text
stringlengths
8
6.88M
#include "rvterrain.h" RVTerrain::RVTerrain(double width) :RVSurface() { m_minS = -width/2; m_maxS = +width/2; m_minT = -width/2; m_maxT = +width/2; m_numSegS = 50; m_numSegT = 50; m_VSFileName = ":/shaders/VS_heightmap.vsh"; } QOpenGLTexture *RVTerrain::heightmap() const { return m_heightmap; } void RVTerrain::setHeightmap(QString textureFilename) { m_heightmap = new QOpenGLTexture(QImage(textureFilename).mirrored()); } void RVTerrain::draw() { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); if (m_wireFrame) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glDisable(GL_CULL_FACE); if (m_heightmap) { glEnable(GL_TEXTURE_2D); glEnable(GL_TEXTURE0); m_heightmap->setWrapMode(QOpenGLTexture::ClampToEdge); m_heightmap->setMinificationFilter(QOpenGLTexture::LinearMipMapLinear); m_heightmap->setMagnificationFilter(QOpenGLTexture::Linear); //Liaison de la texture m_heightmap->bind(); } m_program.bind(); m_vao.bind(); m_program.setUniformValue("u_ModelMatrix", this->modelMatrix()); m_program.setUniformValue("u_ViewMatrix", m_camera->viewMatrix()); m_program.setUniformValue("u_ProjectionMatrix", m_camera->projectionMatrix()); m_program.setUniformValue("u_opacity", m_opacity); m_program.setUniformValue("u_color", m_globalColor); m_program.setUniformValue("texture0", 0); m_program.setUniformValue("light_ambient_color", m_light->ambient()); m_program.setUniformValue("light_diffuse_color", m_light->diffuse()); m_program.setUniformValue("light_specular_color", m_light->specular()); m_program.setUniformValue("light_position", m_light->position()); m_program.setUniformValue("light_specular_strength", this->specStrength()); m_program.setUniformValue("u_height_factor", this->heightFactor); m_program.setUniformValue("eye_position", m_camera->position()); glDrawElements(GL_TRIANGLES, m_numIndices, GL_UNSIGNED_INT, nullptr); m_vao.release(); m_program.release(); if (m_heightmap) { m_heightmap->release(); glDisable(GL_TEXTURE0); glDisable(GL_TEXTURE_2D); } } void RVTerrain::initializeBuffer() { m_numVertices = (m_numSegS + 1) * (m_numSegT + 1); m_numTriangles = 2 * m_numSegS * m_numSegT; m_numIndices = 3 * m_numTriangles; RVVertex * vertexData = new RVVertex [m_numVertices]; uint* indexData = new uint[m_numIndices]; double t = m_minT; double s = m_minS; double deltaT = (m_maxT - m_minT)/m_numSegT; double deltaS = (m_maxS - m_minS)/m_numSegS; uint cptPoint = 0; uint cptIndex = 0; for (int i = 0; i <= m_numSegT; i++, t += deltaT) { s = m_minS; for (int j = 0; j <= m_numSegS; j++, s += deltaS, cptPoint++) { vertexData[cptPoint].position = pos(s,t); vertexData[cptPoint].texCoord = QVector2D(j/float(m_numSegS),-0.0+1.0f*i/float(m_numSegT)); vertexData[cptPoint].normal = normal(s,t); if ((i < m_numSegT) && (j < m_numSegS)) { indexData[cptIndex++] = cptPoint; indexData[cptIndex++] = cptPoint + uint(m_numSegS) + 1; indexData[cptIndex++] = cptPoint + uint(m_numSegS) + 2; indexData[cptIndex++] = cptPoint; indexData[cptIndex++] = cptPoint + uint(m_numSegS) + 2; indexData[cptIndex++] = cptPoint + 1; } } } //Initialisation et remplissage du Vertex Buffer Object m_vbo = QOpenGLBuffer(QOpenGLBuffer::VertexBuffer); m_vbo.create(); m_vbo.bind(); m_vbo.allocate(vertexData, m_numVertices*int(sizeof (RVVertex))); m_vbo.setUsagePattern(QOpenGLBuffer::StaticDraw); m_vbo.release(); //Initialisation et remplissage de l'Index Buffer Object m_ibo = QOpenGLBuffer(QOpenGLBuffer::IndexBuffer); m_ibo.create(); m_ibo.bind(); m_ibo.allocate(indexData, m_numIndices*int(sizeof (uint))); m_ibo.setUsagePattern(QOpenGLBuffer::StaticDraw); m_ibo.release(); } float RVTerrain::x(double s, double t) { return s; } float RVTerrain::y(double s, double t) { return 0; } float RVTerrain::z(double s, double t) { return t; }
#pragma once #include "../ofxDatGui.h" #include "../Controller/File/Settings.h" #include "../Model/Mask.h" #include "../Controller/File/MyFile.h" #include "../Controller/EditShape.h" class DatGui { public: static ofxDatGuiToggle* crosshairToggle; static ofxDatGuiColorPicker* crosshairColor; static int brightness; static bool showAbout; static bool showHelp; static bool showShortcuts; static void init(); static ofRectangle getRect(); static ofxDatGui* myOfxDatGui; private: static void onButtonEvent(ofxDatGuiButtonEvent); static void onSliderEvent(ofxDatGuiSliderEvent); static void onToggleEvent(ofxDatGuiToggleEvent); static void applyWindowSettings(); };
// // Created by dwb on 2019-07-19. // #ifndef SAMPLE_TEACHER_H #define SAMPLE_TEACHER_H #include <iostream> #include <string> using namespace std; class Teacher { public: Teacher(){ cout << "Teacher()" << endl; m_name="Mike"; m_age=20; } Teacher(const string& t_name,int t_age) :m_name(t_name),m_age(t_age){ cout << "Teacher(...)" << endl; } ~Teacher(){ cout << "~Teacher()" << endl; } void print(){ cout << "name->" << m_name << " age->" << m_age << endl; } private: string m_name; int m_age; }; #endif //SAMPLE_TEACHER_H
// http://codeforces.com/problemset/problem/279/B #include<iostream> using namespace std; int main() { long long n, t, b[100000], opti, cur,curCount, optiCount, first; cin >> n >> t; for(int i = 0; i < n; i++) cin >> b[i]; optiCount = cur = curCount = 0; first = 0; b[n] = t + 1; //hacker for(int i = 0; i <= n; i++) { cur += b[i]; if(cur > t) { if(curCount > optiCount) optiCount = curCount; cur -= b[first]; first++; continue; } else curCount += 1; } cout << optiCount; }
/* * @Description: * @Author: Ren Qian * @Date: 2019-07-17 18:25:13 */ #ifndef LIDAR_LOCALIZATION_SENSOR_DATA_GNSS_DATA_HPP_ #define LIDAR_LOCALIZATION_SENSOR_DATA_GNSS_DATA_HPP_ #include <deque> #include "Geocentric/LocalCartesian.hpp" namespace lidar_localization { class GNSSData { public: double time = 0.0; double longitude = 0.0; double latitude = 0.0; double altitude = 0.0; double local_E = 0.0; double local_N = 0.0; double local_U = 0.0; int status = 0; int service = 0; static double origin_longitude; static double origin_latitude; static double origin_altitude; private: static GeographicLib::LocalCartesian geo_converter; static bool origin_position_inited; public: void InitOriginPosition(); void UpdateXYZ(); static bool SyncData(std::deque<GNSSData>& UnsyncedData, std::deque<GNSSData>& SyncedData, double sync_time); }; } #endif
#include "EGameInstance.h" #include "ECore.h" #include "EMovementSystem.h" #include "EInputManager.h" #include "EJobManager.h" #include "Render2DSystem.h" DEFINITION_SINGLE(EGameInstance) EGameInstance::EGameInstance() { } EGameInstance::~EGameInstance() { } void EGameInstance::Tick() { } // // Timer, // Input, // Movement, // Collision, End, Max = 3 bool EGameInstance::Init() { // TODO : ManagerIndex::시스템이름 m_vSystems[EComponentSystemIndex::Render2D] = static_cast<SystemBase*>(GET_SINGLE(Render2DSystem)); return true; }
#include "BattleBase.h" BattleBase::BattleBase() { ReuseInit(); } BattleBase::~BattleBase() { } BattleStatus BattleBase::GetStatus()const { return m_nStatus; } void BattleBase::SetStatus(BattleStatus bs) { m_nStatus = bs; } uint32_t BattleBase::GetRound()const { return m_nRound; } void BattleBase::SetRound(uint32_t nRound) { m_nRound = nRound; } void BattleBase::ReuseInit() { m_nStatus = eBattleStatus_Unknown; m_nRound = 0; } bool BattleBase::BattleInit(BATTLE_ID_TYPE id, const BattleInfo& bi) { m_nMaxRound = bi.nMaxRound; return true; } bool BattleBase::BattleStart() { return true; } bool BattleBase::BattleRun() { //while (!checkBattleFinish()) //{ // initNextActor(); // //处理行动前逻辑 // processBeforeAction(); // //行动前处理完后死亡 // auto pActor = getActor(); // if (pActor->IsDead()) // { // pBattle->SetActor(nullptr); // pBattle->SetSkill(nullptr); // continue; // } // //等待玩家选择 // if (pActor->GetFighterStatus() == FS_WAIT) // { // return waitFighterAction(pBattle); // } // //玩家行动 // auto nRet = processFighterAct(pBattle); // if (nRet == FIGHT_ERROR) // { // RETURN_FIGHT_ERROR("processFighterAct() return FIGHT_ERROR"); // } // else if (nRet == FIGHT_OVER) // { // //pBattle->BattleFinish(true); // break; // } // processAfterAction(pBattle); // //更新死亡状态 // processFighterDead(pBattle); // //清空当前玩家 // pBattle->SetActor(nullptr); // pBattle->SetSkill(nullptr); //} //processAfterBattleFinish(pBattle); //pBattle->SendActionInfo(); //pBattle->BattleFinish(true); //g_pAuraProcessor->EndAura(pBattle); return true; } bool BattleBase::BattleEnd() { return true; } bool BattleBase::BattleErrorEnd() { return true; }
#include "json.hpp" #include "zmqpp/curve.hpp" #include "zmqpp/zmqpp.hpp" #include "cereal/archives/portable_binary.hpp" #include "cereal/cereal.hpp" #include "cereal/types/chrono.hpp" #include "cereal/types/memory.hpp" #include "cereal/types/string.hpp" #include "mqexec_shared.h" int main(int argc, char** argv) { zmqpp::context zmq_ctx; zmqpp::socket sock(zmq_ctx, zmqpp::socket_type::router); sock.set(zmqpp::socket_option::router_mandatory, true); sock.bind(argv[1]); int jobs_to_run = 10; std::this_thread::sleep_for(std::chrono::milliseconds(200)); for (auto i = 0; i < jobs_to_run; i++) { std::stringstream ss; ss << "/bin/echo Hello, world - from " << i; auto scheduled = std::chrono::system_clock::now(); auto expires = scheduled + std::chrono::seconds(10); Job j = {static_cast<uint64_t>(i), "foo", "bar", ss.str(), scheduled, expires, 0, 0, 0.0}; zmqpp::message msg; msg.add(argv[2]); std::ostringstream req_buffer; cereal::PortableBinaryOutputArchive archive(req_buffer); archive(j); msg.add(req_buffer.str()); try { sock.send(msg); } catch (zmqpp::zmq_internal_exception e) { std::cout << "No connection for: " << i << " " << e.what() << std::endl; } catch (std::exception e) { std::cout << "Error " << e.what() << std::endl; } std::cout << "Sent job " << i << std::endl; sock.receive(msg); if (msg.parts() == 0) { continue; } const int last_part = msg.parts() - 1; std::cout << msg.get(0) << std::endl; if (msg.get(last_part).size() == 0) continue; std::istringstream response_buf(msg.get(last_part)); Result res; try { cereal::PortableBinaryInputArchive archive(response_buf); archive(res); } catch (std::exception e) { std::cerr << "Error receiving response: " << e.what(); continue; } std::cout << "Received job result: " << res.output << std::endl; std::cout << "Exit code: " << res.return_code << std::endl; } }
#include <bits/stdc++.h> using namespace std; int main() { int a,i,b,x,y,z; z=0; while(scanf("%d",&a)!=EOF){ if(a==0) break; x=0; y=0; for(i=0;i<a;i++){ scanf("%d",&b); if(b==0)x++; else y++; } cout<<"Case "<<z+1<<": "<<y-x<<endl; z++; } return 0; }
#include "Application.h" #include <stdio.h> int main(int argc, char** argv) { bool success = init_application(); if (!success) { printf("Unable to initialize :("); return -1; } run_application(); quit_application(); return 0; }
#include <iostream> #include <set> #include<cstring> using namespace std; bool setDigits(bool used[], int n) { for (; n > 0; n /= 10) { if (used[n % 10]) return false; used[n % 10] = 1; } return true; } int main() { set<int> s; for (int n = 2; n < 100; n++) { bool used[10] = {1}; if (!setDigits(used, n)) continue; int start = 1000; if (n > 9) start = 100; bool used2[10]; for (int m = start; m * n < 10000; m++) { memcpy(used2, used, 10); if (setDigits(used2, m) && setDigits(used2, m*n)) s.insert(m*n); } } int sum = 0; for (set<int>::iterator iter = s.begin(); iter != s.end(); iter++) sum += *iter; cout << sum << "\n"; }
/******************************** Name: Saiteja Yagni Class: CSCI 689/1 TA Name: Anthony Schroeder Assignment: 10 Due Date: 04/20/2016 *********************************/ #include "Shape2.h" //Includes the class definitons and headers in Shape2.h this will as include headers in Shape2.h #include<iostream> #include<cmath> //For doing to mathematical comptations #define PI (4*atan(1)) //Defining the value of pi using std::cout; using std::cin; using std::endl; /* Name: Rectangle() Arguments:void Return Type:void Class:Rectangle Notes:This is a default constructor for Rectangle clss which sets the values to zero */ Rectangle::Rectangle() { length = 0; width = 0; } /* Name: Rectangle Arguments:double l1,double l2 Return Type:Void Class:Rectangle Notes:This is a parameterised constructor which takes two values and assigns the length and width */ Rectangle::Rectangle(double l1, double w1) { length = l1; width = w1; } /* Name: Rectangle Arguments:const Rectangle &obj Return Type:void Class:Rectangle Notes:This is a copy constructor of Rectangle class which takes a constant reference of a Rectangle instance as an argument and assigns its values to the current instance */ Rectangle::Rectangle(const Rectangle &obj) { length = obj.length; width = obj.width; } /* Name:operator= Arguments:const Rectangle &obj Return Type:Rectangle& Class: Rectangle` Notes:This is an assignment opeator which takes a constant reference to a Rectangle class as an argument and checks if the the instance is same as current instance if yes the returns the current reference as a return type else the current instance is assigned with the values of the passes instance and returns the reference of current instance */ Rectangle& Rectangle::operator=(const Rectangle &obj) { if (this == &obj) return *this; length = obj.length; width = obj.width; return *this; } /* Name: operator+= Arguments:const Rectangle &obj Return Type:Rectangle & Class:Rectangle Notes:This is an overloaded operator which takes a constant reference of rectangle and adds its values to the current instance and returns the reference of the current instance */ Rectangle& Rectangle::operator+=(const Rectangle &obj) { length += obj.length; width += obj.width; return *this; } /* Name: ~Rectangle Arguments:void Return Type:void Class:Rectangle Notes:This is a destructor it frees up any dynamicallly allocated memory */ Rectangle::~Rectangle() { } /* Name: area Arguments: void Return Type:double Class:Rectangle Notes:This is a public member function which calculates the area ofthe rectangle and returns it */ double Rectangle::area() const { return length*width; } /* Name: perimeter Arguments:void Return Type:double Class:Rectangle Notes: This is a public member function which calculates the perimeter of the rectangle and returns it */ double Rectangle::perimeter() const { return 2 * (length + width); } /* Name: print Arguments: void Return Type: void Class: Rectangle Notes: This function displays the dimensions of the rectangle here in this class length and width */ void Rectangle::print() const { cout << " length = " << length << " : width = " << width; } /* Name: Square Arguments:void Return Type:void Class:Square Notes: This is a default constructor which calls the super class constructor and sets the deafult values zero */ Square::Square() { ::Rectangle(); } /* Name: Square Arguments: double s Return Type:void Class:Square Notes: This is a parameterised constructor which takes a double as arguments and sets as the theonly dimension of square i.i square has same length and width */ Square::Square(double s) :Rectangle(s, s) { //sets the values to parameterised constructor of Rectangle } /* Name: area Arguments: void Return Type: double Class: Square Notes: This function calculates the area of square,it actually calls the area function of rectangle and returns it. */ double Square::area () const { return Rectangle::area(); } /* Name: perimeter Arguments: void Return Type: double Class: Square Notes: This function calls the perimeter function of Rectangle and returns it */ double Square::perimeter () const { return Rectangle::perimeter(); } /* Name: print Arguments: void Return Type: void Class: Square Notes: This function displays the dimensions of the square */ void Square::print () const { cout << " length = " << length; } /* Name: Circle Arguments: void Return Type: void Class: Circle Notes:This is a default constr5uctor which sets the value of radius to 0 */ Circle::Circle() { radius = 0; } /* Name: Circle Arguments: double r1 Return Type: void Class: Circle Notes:This is a parameterised constructor which takes a double as argument and assigns it to radius */ Circle::Circle(double r1) { radius = r1; } /* Name: Circle Arguments: const Circle &obj Return Type: void Class: Circle Notes: This is a copy constructor which takes a constant reference to a circle as an object and sets the instance value to the current instance */ Circle::Circle(const Circle &obj) { radius = obj.radius; } /* Name: operator= Arguments:const Circle &obj Return Type:Circle& Class:Circle Notes:This is an assignment operator which takes a constant reference to an instance of Circle class and assigns it to the current instance */ Circle& Circle::operator=(const Circle &obj) { if (this == &obj) return *this; radius = obj.radius; return *this; } /* Name: operator+= Arguments:const Circle &obj Return Type: Circle& Class: Circle Notes: This is an overloaded operator which adds the the reference instance to the current instance and returns the current instance reference */ Circle& Circle::operator+=(const Circle &obj) { radius += obj.radius; return *this; } /* Name:~Circle Arguments:void Return Type: void Class: Circle Notes: This is a destructor which frees the dynamically allocated memory */ Circle::~Circle(void) { } /* Name: area Arguments:void Return Type:double Class: Circle Notes: This is a public member function which calculates the area of the circle and returns it */ double Circle::area() const { return PI*radius*radius; } /* Name: perimeter Arguments: void Return Type: double Class: Circle Notes: This function calcuates the perimeter of circle and returns it */ double Circle::perimeter() const { double k=2*PI*radius; return k; } /* Name: print Arguments: void Return Type:void Class:Circle Notes: prints he radius of the circle */ void Circle::print() const { cout << " radius = " << radius; } /* Name: Triangle Arguments: void Return Type: void Class: Triangle Notes: Default constructor which sets the sides of the triangle to zero */ Triangle::Triangle() { a = b = c = 0; } /* Name: Triangle Arguments: double a1,double b1,double c1 Return Type: void Class:Triangle Notes: Parameterised constructor which takes three parameters and sets them to the three sides of the triangle */ Triangle::Triangle(double a1, double b1, double c1) { a = a1; b = b1; c = c1; } /* Name: Triangle Arguments: const Triangle &obj Return Type: void Class: Triangle Notes: This is a copy constructor which takes a constant reference to a Triangle instance as argument and sets its values to the current instance */ Triangle::Triangle(const Triangle &obj) { a = obj.a; b = obj.b; c = obj.c; } /* Name: operator= Arguments: const Triangle &obj Return Type: Triangle& Class: Triangle Notes: This is an overloaded assignment operator which takes the a constant reference to Triangle as a reference and assign its value to the the current instance and retyurns a reference of current instance */ Triangle& Triangle::operator=(const Triangle &obj) { if (this == &obj) return *this; a = obj.a; b = obj.b; c = obj.c; return *this; } /* Name: operator+= Arguments: const Triangle &obj Return Type: Triangle& Class: Triangle Notes: This is an overloaded operator which takes a constant reference to an instance of triangle and adds its values to the current instance and returns the nreference of the current instance */ Triangle& Triangle::operator+=(const Triangle &obj) { a += obj.a; b += obj.b; c += obj.c; return *this; } /* Name:~Triangle Arguments: void Return Type:void Class: Yriangle Notes: This is a destructor which frees the dynamically allocated memory */ Triangle::~Triangle(void) { } /* Name: area Arguments: void Return Type: double Class: Triangle Notes: Calculates the area of trianlge and returns it */ double Triangle::area() const { double k = (a + b + c)*0.5; //value of semi-perimeter return sqrt(k*(k - a)*(k - b)*(k - c)); } /* Name: perimeter Arguments: void Return Type: double Class: Triangle Notes: Calculates the perimeter of the Triangle */ double Triangle::perimeter() const { return a + b + c; } /* Name: print Arguments: void Return Type: void Class: Triangle Notes: displays the dimensions of the Triangle */ void Triangle::print() const { cout << " a = " << a << " : b = " << b << " : c = " << c; } /* Name: rightTriangle Arguments: void Return Type: void Class: rightTriangle Notes: This is a constructor which call the super class constructor */ rightTriangle::rightTriangle() { ::Triangle();//call to super class constructor } /* Name: rightTriangle Arguments: double a1,double b1 Return Type: void Class: rightTriangle Notes: This parameterised constructor takes two arguments and assigns them to the super class parameterised constructor */ rightTriangle::rightTriangle(double a1, double b1):Triangle(a1,b1,sqrt(pow(a1,2)+pow(b1,2))) { } /* Name: area Arguments: void Return Type: double Class: rightTriangle Notes: Calculates the area of rightTriangle by calling the area of superclass constructor */ double rightTriangle::area() const { return Triangle::area(); } /* Name: perimeter Arguments: void Return Type: double Class: rightTriangle Notes: Calculates the perimeter by calling the perimeter of super class */ double rightTriangle::perimeter() const { return Triangle::perimeter(); } /* Name: print Arguments: void Return Type: void Class: rightTriangle Notes: prints out the dimensions of the rightTriangle */ void rightTriangle::print() const { cout << " length = " << a << " : height = " << b; } /* Name: equTriangle Arguments: void Return Type: void Class: equTriangle Notes:Default constructor which calls the super class constructor */ equTriangle::equTriangle() { ::Triangle(); } /* Name:equTriangle Arguments: double a Return Type: void Class: equTriangle Notes: parameterised constructor which takes a single argument and assigns it to the three variab;e of Trianlge by calling its constructor */ equTriangle::equTriangle(double a) :Triangle(a, a, a) { } /* Name: area Arguments: void Return Type: double Class: equTriangle Notes: Calculates the area of equTriangle by calling the superclass area function */ double equTriangle::area() const { return Triangle::area(); } /* Name: perimeter Arguments: void Return Type: double Class: equTriangle Notes: Calculates the perimeter by calling super class perimeter function */ double equTriangle::perimeter() const { return Triangle::perimeter(); } /* Name: equTriangle Arguments: void Return Type: void Class: equTriangle Notes: Prints the dimensions of equTriangle */ void equTriangle::print() const { cout << " length = " << a; }
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/List.g.uno. // WARNING: Changes might be lost if you edit this file directly. #include <_root.app18_ButtonEntry_icon_Property.h> #include <_root.app18_ButtonEntry_Value_Property.h> #include <_root.ButtonEntry.h> #include <_root.ItemListSelected.h> #include <_root.List.h> #include <_root.List.Template.h> #include <_root.Separator.h> #include <Fuse.Binding.h> #include <Fuse.Node.h> #include <Fuse.NodeGroup.h> #include <Fuse.NodeGroupBase.h> #include <Fuse.Reactive.BindingMode.h> #include <Fuse.Reactive.Data.h> #include <Fuse.Reactive.DataBinding.h> #include <Fuse.Reactive.IExpression.h> #include <Uno.Bool.h> #include <Uno.Collections.ICollection-1.h> #include <Uno.Collections.IList-1.h> #include <Uno.Object.h> #include <Uno.String.h> #include <Uno.UX.FileSource.h> #include <Uno.UX.Property.h> #include <Uno.UX.Property-1.h> #include <Uno.UX.Selector.h> static uString* STRINGS[3]; static uType* TYPES[2]; namespace g{ // public partial sealed class List.Template :50 // { // static Template() :61 static void List__Template__cctor__fn(uType* __type) { ::g::Uno::UX::Selector_typeof()->Init(); List__Template::__selector0_ = ::g::Uno::UX::Selector__op_Implicit(::STRINGS[0/*"icon"*/]); List__Template::__selector1_ = ::g::Uno::UX::Selector__op_Implicit(::STRINGS[1/*"Value"*/]); } static void List__Template_build(uType* type) { ::STRINGS[0] = uString::Const("icon"); ::STRINGS[1] = uString::Const("Value"); ::STRINGS[2] = uString::Const("name"); ::TYPES[0] = ::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Binding_typeof(), NULL); ::TYPES[1] = ::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Node_typeof(), NULL); type->SetFields(2, ::g::List_typeof(), offsetof(List__Template, __parent1), uFieldFlagsWeak, ::g::List_typeof(), offsetof(List__Template, __parentInstance1), uFieldFlagsWeak, ::g::Uno::UX::Property1_typeof()->MakeType(::g::Uno::UX::FileSource_typeof(), NULL), offsetof(List__Template, temp_icon_inst), 0, ::g::Uno::UX::Property1_typeof()->MakeType(::g::Uno::String_typeof(), NULL), offsetof(List__Template, temp_Value_inst), 0, ::g::Uno::UX::Selector_typeof(), (uintptr_t)&List__Template::__selector0_, uFieldFlagsStatic, ::g::Uno::UX::Selector_typeof(), (uintptr_t)&List__Template::__selector1_, uFieldFlagsStatic); } ::g::Uno::UX::Template_type* List__Template_typeof() { static uSStrong< ::g::Uno::UX::Template_type*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::UX::Template_typeof(); options.FieldCount = 8; options.ObjectSize = sizeof(List__Template); options.TypeSize = sizeof(::g::Uno::UX::Template_type); type = (::g::Uno::UX::Template_type*)uClassType::New("List.Template", options); type->fp_build_ = List__Template_build; type->fp_cctor_ = List__Template__cctor__fn; type->fp_New1 = (void(*)(::g::Uno::UX::Template*, uObject**))List__Template__New1_fn; return type; } // public Template(List parent, List parentInstance) :54 void List__Template__ctor_1_fn(List__Template* __this, ::g::List* parent, ::g::List* parentInstance) { __this->ctor_1(parent, parentInstance); } // public override sealed object New() :64 void List__Template__New1_fn(List__Template* __this, uObject** __retval) { ::g::Fuse::NodeGroup* __self1 = ::g::Fuse::NodeGroup::New2(); ::g::ItemListSelected* temp = ::g::ItemListSelected::New6(); __this->temp_icon_inst = ::g::app18_ButtonEntry_icon_Property::New1(temp, List__Template::__selector0_); ::g::Fuse::Reactive::Data* temp1 = ::g::Fuse::Reactive::Data::New1(::STRINGS[0/*"icon"*/]); __this->temp_Value_inst = ::g::app18_ButtonEntry_Value_Property::New1(temp, List__Template::__selector1_); ::g::Fuse::Reactive::Data* temp2 = ::g::Fuse::Reactive::Data::New1(::STRINGS[2/*"name"*/]); ::g::Fuse::Reactive::DataBinding* temp3 = ::g::Fuse::Reactive::DataBinding::New1(__this->temp_icon_inst, (uObject*)temp1, 3); ::g::Fuse::Reactive::DataBinding* temp4 = ::g::Fuse::Reactive::DataBinding::New1(__this->temp_Value_inst, (uObject*)temp2, 3); ::g::Separator* temp5 = ::g::Separator::New4(); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp->Bindings()), ::TYPES[0/*Uno.Collections.ICollection<Fuse.Binding>*/]), temp3); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp->Bindings()), ::TYPES[0/*Uno.Collections.ICollection<Fuse.Binding>*/]), temp4); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(__self1->Nodes()), ::TYPES[1/*Uno.Collections.ICollection<Fuse.Node>*/]), temp); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(__self1->Nodes()), ::TYPES[1/*Uno.Collections.ICollection<Fuse.Node>*/]), temp5); return *__retval = __self1, void(); } // public Template New(List parent, List parentInstance) :54 void List__Template__New2_fn(::g::List* parent, ::g::List* parentInstance, List__Template** __retval) { *__retval = List__Template::New2(parent, parentInstance); } ::g::Uno::UX::Selector List__Template::__selector0_; ::g::Uno::UX::Selector List__Template::__selector1_; // public Template(List parent, List parentInstance) [instance] :54 void List__Template::ctor_1(::g::List* parent, ::g::List* parentInstance) { ctor_(NULL, false); __parent1 = parent; __parentInstance1 = parentInstance; } // public Template New(List parent, List parentInstance) [static] :54 List__Template* List__Template::New2(::g::List* parent, ::g::List* parentInstance) { List__Template* obj1 = (List__Template*)uNew(List__Template_typeof()); obj1->ctor_1(parent, parentInstance); return obj1; } // } } // ::g
// Copyright 2012 Yandex #include "ltr_client/configurator.h" #include <stdexcept> #include <memory> #include <sstream> #include "boost/lexical_cast.hpp" #include "boost/algorithm/string/predicate.hpp" #include "logog/logog.h" #include "ltr/utility/container_utility.h" #include "ltr_client/utility/common_utility.h" #include "ltr_client/utility/parameterized_info.h" #include "ltr_client/utility/tag_handlers.h" #include "tinyxml/tinyxml.h" using std::string; using std::stringstream; using std::logic_error; using std::list; using std::cout; using std::auto_ptr; using std::endl; using ltr::utility::ToString; // ========================== XML tokens ===================================== // =========================== various helpers ================================= // ====================== ConfiguratorPrivate impl ============================= ConfigParser::ConfigParser() { root_ = NULL; general_xml_token_ = new OnGeneralParameterized(this); tag_handlers_[CONFIG] = new OnConfigParser(this); tag_handlers_[DATA] = new TOnDataTag(this); tag_handlers_[LAUNCH] = new OnLaunchTag(this); } ConfigParser::~ConfigParser() { DeleteAllFromUnorderedMap(&tag_handlers_); delete general_xml_token_; } void ConfigParser:: parseConfig(const string& file_name) { document_ = auto_ptr<TiXmlDocument>(new TiXmlDocument(file_name)); if (!document_->LoadFile()) { throw logic_error("not valid config in " + file_name); } root_ = document_->FirstChildElement(ROOT); if (!root_) { throw logic_error("can't find <LTR_experiment>"); } TiXmlElement* config = root_->FirstChildElement(CONFIG); if (!config) { throw logic_error("can't find <config>"); } TiXmlElement* root_dir = config->FirstChildElement(ROOT_DIR); if (!root_dir || !root_dir->GetText()) { throw logic_error("no root directory specified"); } root_path_ = root_dir->GetText(); INFO(" LTR Client. Copyright 2011 Yandex"); INFO(" Experiment started "); GenericParse(tag_handlers_, root_->FirstChildElement(), general_xml_token_); INFO("\n\nEnd of loadConfig. Collected data:\n"); INFO("data_infos_\n%s\n", ToString(dataInfos()).c_str()); INFO("xml_token_specs\n%s\n", ToString(xmlTokenSpecs()).c_str()); INFO("train_infos\n%s\n", ToString(trainInfos()).c_str()); INFO("crossvalidation_infos\n%s\n", ToString(crossvalidationInfos()).c_str()); for (ParameterizedInfos::iterator it = xmlTokenSpecs().begin(); it != xmlTokenSpecs().end(); ++it) { ParametrizedInfo& spec = it->second; spec.fill_dependency_list(xmlTokenSpecs()); } } const ConfigParser::DataInfos& ConfigParser::dataInfos() const { return data_infos_; } ConfigParser::DataInfos& ConfigParser::dataInfos() { return data_infos_; } const ConfigParser::ParameterizedInfos& ConfigParser::xmlTokenSpecs() const { return xml_token_specs; } ConfigParser::ParameterizedInfos& ConfigParser::xmlTokenSpecs() { return xml_token_specs; } const ConfigParser::TrainInfos& ConfigParser::trainInfos() const { return train_infos; } ConfigParser::TrainInfos& ConfigParser::trainInfos() { return train_infos; } const ConfigParser::CrossvalidationInfos& ConfigParser::crossvalidationInfos() const { return crossvalidation_infos; } ConfigParser::CrossvalidationInfos& ConfigParser::crossvalidationInfos() { return crossvalidation_infos; } const ParametrizedInfo& ConfigParser::findParametrized( const string& name) const { for (ParameterizedInfos::const_iterator it = xml_token_specs.begin(); it != xml_token_specs.end(); ++it) { const ParametrizedInfo& spec = it->second; if (spec.get_name() == name) { return spec; } } throw logic_error("Can not find parametrized object!"); } const DataInfo& ConfigParser::findData(const string& name) const { for (DataInfos::const_iterator it = dataInfos().begin(); it != dataInfos().end(); ++it) { const DataInfo& data_info = it->second; if (data_info.name == name) { return data_info; } } throw logic_error("Can not find data!"); } const string& ConfigParser::rootPath() const { return root_path_; }
//kkcckc AhoCorasickDoubleArrayTrie for SS //20171030 #include <iostream> #include <vector> #include <fstream> #include <algorithm> #include <list> using namespace std; class AC { private: vector<vector<string>> output; vector<string> model; vector<char> ch; vector<long> next, fail, check, base, pos; public: explicit AC() { pos.push_back(0); check.push_back(0); ch.push_back(0); fail.push_back(0); } explicit AC(const vector<string> &m) : AC() { model = m; } void trie() { long m = 0, n = 0; vector<vector<long>> tmp; //ch check sort(model.begin(), model.end()); long num = 0; m = static_cast<long>(model.size()); n = static_cast<long>(max_element(begin(model), end(model), [](string a, string b) { return a.size() < b.size(); })->size()); tmp.resize(model.size()); for (auto &i :tmp) i.resize(static_cast<unsigned long>(n), 0); for (long i = 0; i < n; ++i) { for (long j = 0; j < m; ++j) { if (model[j].size() > i) { if (j > 0 && model[j - 1].size() > i && model[j][i] == model[j - 1][i]) { tmp[j][i] = num; } else { tmp[j][i] = ++num; ch.push_back(model[j][i]); check.push_back(i > 0 ? tmp[j][i - 1] : 0); } } } } //next base pos list<long> l; for (long i = 1; i < check.size(); ++i) { l.push_back(i); if (i < check.size() - 1 && check[i] != check[i + 1]) { bool f = true; long t = 1 - ch[l.front()]; while (f) { f = false; for (auto &j:l) { if (t + ch[j] > next.size()) next.resize(static_cast<unsigned long>(t + ch[j] + 1), 0); while (next[t + ch[j]] != 0) { t++; f = true; } } } base.push_back(t - pos[check[i]]); for (auto &j:l) { next[t + ch[j]] = j; pos.push_back(t + ch[j]); } l.clear(); } } //fail for (long i = 1; i < check.size(); ++i) fail.push_back(check[i] == 0 ? 0 : go(fail[check[i]], ch[i])); //output output.resize(check.size() + 1); for (auto i = 0; i < m; ++i) { long x = tmp[i][model[i].size() - 1]; output[x].push_back(model[i]); if (fail[x] != x) for (const auto &j: output[fail[x]]) output[x].push_back(j); } } //match void find(string s) { long q = 0; for (long c = 0; c < s.size(); ++c) { q = go(q, s[c]); if (!output[q].empty()) { for (auto &j: output[q]) { cout << 1 + c - long(j.size()) << ' ' << j << " "; } } } } //goto long go(const long &i, const char &j) { long t = base[i] + pos[i] + j; t = next[t > 0 ? t : 0]; if (i == check[t]) return t; else if (i == 0) return 0; else return go(fail[i], j); } const vector<long> &getNext() const { return next; } const vector<long> &getFail() const { return fail; } const vector<long> &getCheck() const { return check; } const vector<long> &getBase() const { return base; } }; int main() { ifstream fin("1.txt"); long num; fin >> num; string s; vector<string> model; for (long i = 0; i < num; ++i) { fin >> s; model.push_back(s); } AC ac(model); ac.trie(); cout << "check\t"; for (auto &i: ac.getCheck()) cout << i << ' '; cout << "\nbase\t"; for (auto &i: ac.getBase()) cout << i << ' '; cout << "\nnext\t"; auto next = ac.getNext(); for (auto &i: next) cout << i << ' '; num = 0; bool f = false; for (auto &i: next) { if (i != 0) f = true; if (f && i==0) num++; } cout << "\nnext_usage\t"<<double(next.size()-num)/next.size(); cout << "\nfail\t"; for (auto &i: ac.getFail()) cout << i << ' '; cout << "\nresult\t"; getline(fin, s); getline(fin, s); ac.find(s); return 0; }
// testleetcode.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include "pch.h" #include <iostream> #include <vector> #include <string> #include <windows.h> #include <random> using namespace std; class Solution { public: vector<string> generateParenthesis(int n) { vector<string> list; backtrack(list, "", 0, 0, n); return list; } void backtrack(vector<string> &list, string str, int open, int close, int max) { if (str.size() == max * 2) { list.push_back(str); return; } if (open < max) backtrack(list, str + "(", open + 1, close, max); if (close < open) backtrack(list, str + ")", open, close + 1, max); } }; int main() { Solution s; s.generateParenthesis(3); } // 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单 // 调试程序: F5 或调试 >“开始调试”菜单 // 入门提示: // 1. 使用解决方案资源管理器窗口添加/管理文件 // 2. 使用团队资源管理器窗口连接到源代码管理 // 3. 使用输出窗口查看生成输出和其他消息 // 4. 使用错误列表窗口查看错误 // 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目 // 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
#include "ReceiveProto.h" using namespace CPPClient::Net::Cmd; void ReceiveProto::Receive(const char *buffer) { lspb::SrvRes res; res.ParseFromString(buffer); switch (res.methodid()) { case lspb::SrvMsgType::srvEnterRoom: SrvEnterRoom(res.srventerroom(), res.result(), res.errstr()); break; case lspb::SrvMsgType::srvInitOver: SrvInitOver(res.srvinitover(), res.result(), res.errstr()); break; case lspb::SrvMsgType::bGameInit: BGameInit(res.bgameinit(), res.result(), res.errstr()); break; case lspb::SrvMsgType::bGameStart: BGameStart(res.bgamestart(), res.result(), res.errstr()); break; case lspb::SrvMsgType::bGameFrame: BGameFrame(res.bgameframe(), res.result(), res.errstr()); break; default: printf("proto error no %d\n", res.methodid()); break; } } void ReceiveProto::SrvEnterRoom(lspb::SrvEnterRoom msg, lspb::Result result, string errStr) { printf("-----------------------no implements SrvEnterRoom-----------------------\n"); } void ReceiveProto::SrvInitOver(lspb::SrvInitOver msg, lspb::Result result, string errStr) { printf("-----------------------no implements SrvInitOver-----------------------\n"); } void ReceiveProto::BGameInit(lspb::BGameInit msg, lspb::Result result, string errStr) { printf("-----------------------no implements BGameInit-----------------------\n"); } void ReceiveProto::BGameStart(lspb::BGameStart msg, lspb::Result result, string errStr) { printf("-----------------------no implements BGameStart-----------------------\n"); } void ReceiveProto::BGameFrame(lspb::BGameFrame msg, lspb::Result result, string errStr) { printf("-----------------------no implements BGameFrame-----------------------\n"); }
#include "testwindow.h" #include "ui_testwindow.h" TestWindow::TestWindow(QWidget *parent, DataProcessor *processor) : QWidget(parent),dataPro(processor), ui(new Ui::TestWindow) { ui->setupUi(this); testModel.setHorizontalHeaderItem(0, new QStandardItem(QString("动作前功率/KW"))); testModel.setHorizontalHeaderItem(1, new QStandardItem(QString("动作后功率/KW"))); testModel.setHorizontalHeaderItem(2, new QStandardItem(QString("节电比率"))); ui->testTable->setModel(&testModel); } void TestWindow::closeEvent(QCloseEvent *event) { dataPro->openMonitor(); qDebug()<<"test window closed"; event->accept(); } TestWindow::~TestWindow() { delete ui; } void TestWindow::on_beginTest_clicked() { emit testButtonClicked(); qDebug()<<"test button clicked!"; } void TestWindow::on_clearTestRecords_clicked() { testRecords.clear(); testModel.clear(); testModel.setHorizontalHeaderItem(0, new QStandardItem(QString("动作前功率/KW"))); testModel.setHorizontalHeaderItem(1, new QStandardItem(QString("动作后功率/KW"))); testModel.setHorizontalHeaderItem(2, new QStandardItem(QString("节电比率"))); } void TestWindow::on_returnBtn_clicked() { this->hide(); dataPro->openMonitor(); } void TestWindow::getResult(datatype powerBefore, datatype powerAfter, float ratio) { int l=testRecords.length(); qDebug()<<"the lenght of testRecords is "<<l; testModel.setItem(l,0,new QStandardItem(QString("%1").arg(powerBefore,0,'f',3))); testModel.setItem(l,1,new QStandardItem(QString("%1").arg(powerAfter,0,'f',3))); testModel.setItem(l,2,new QStandardItem(QString("%1%").arg(ratio*100,0,'f',1))); TestRecord result; result.before=powerBefore; result.after=powerAfter; result.ratio=ratio; testRecords.append(result); } void TestWindow::on_calculateRatioButton_clicked() { if(testRecords.size()<1) { QMessageBox::warning(this,QString("没有测试结果!"),QString("没有节电测试结果,无法计算平均节电率!")); } else { float sum=0; int len=testRecords.size(); for (int i=0;i<len;i++) { sum+=testRecords[i].ratio; } ui->averageRatioLabel->setText(QString("%1%").arg(100*sum/len,0,'f',1)); } }
#include "FPSCamera.h" #include <iostream> #include <math.h> #include <cmath> #include "Utils.h" #include "Mouse.h" #include "Keyboard.h" #define MOUSE_INTENSIVENESS 0.15f #define WALK_SPEED 0.05f #define PLAYER_SIZE 2.8f #define WALK_AMPLITUDE 0.1f #define WALK_FREQUENCY 0.2f void FPSCamera::update(Terrain terrain) { Camera::update(); speedx = 0; speedy = 0; speedz = 0; float speed = WALK_SPEED; if(keyboard::isKeyPressed(GLFW_KEY_LEFT_SHIFT)) speed *= 3.0f; if(keyboard::isKeyPressed(GLFW_KEY_W))speedz = speed; else if(keyboard::isKeyPressed(GLFW_KEY_S))speedz = -speed; if(keyboard::isKeyPressed(GLFW_KEY_A))speedx = -speed; else if(keyboard::isKeyPressed(GLFW_KEY_D))speedx = speed; if(speedx != 0 && speedz != 0){ speedx /= 2.0f; speedz /= 2.0f; } pitch += mouse::getDeltaMousePositionScreen().y * MOUSE_INTENSIVENESS; yaw += mouse::getDeltaMousePositionScreen().x * MOUSE_INTENSIVENESS; if(pitch > 90) pitch = 90; else if(pitch < -90) pitch = -90; float moveXSide = speedx * cosf(glm::radians(-yaw)); float moveZSide = -speedx * sinf(glm::radians(-yaw)); float moveXForward = speedz * sinf(glm::radians(yaw)); float moveZForward = -speedz * cosf(glm::radians(yaw)); if(speedx != 0 || speedz != 0) walkCounter++; if(speed != WALK_SPEED && (speedx != 0 || speedz != 0)) walkCounter++; float walkOffset = 1.0f * std::sin(1.0f * walkCounter * WALK_FREQUENCY) * WALK_AMPLITUDE; posx += moveXForward + moveXSide; posz += moveZForward + moveZSide; posy = engine::getTerrainHeightAt(posx, posz, &terrain) + PLAYER_SIZE + walkOffset; }
#pragma once #include "SA.hpp" #include <memory> #include <string> namespace MarsColonisation { ref class MainForm; public ref class Series_executor { public: Series_executor(System::Windows::Forms::Label^ gui_series, System::Windows::Forms::Label^ gui_iterations, System::Windows::Forms::ListBox^ gui_best_solution, MainForm^ form) { this->series = gui_series; this->gui_iterations = gui_iterations; this->gui_best_solution = gui_best_solution; this->form = form; } void init(double temperature, double alpha, int x, int y, int amount, System::Drawing::Image^ map_image, int max_slope, int max_range) { init(temperature, alpha, x, y, amount, map_image, max_slope, max_range, "output.txt"); } void init(double temperature, double alpha, int x, int y, int amount, System::Drawing::Image^ map_image, int max_slope, int max_range, std::string file_name) { auto initial_solution = Solution::generate_initial(x, y, amount); this->sa = new SA(temperature, alpha, initial_solution, std::shared_ptr<Graph>(new Graph(map_image, max_slope)), form, max_range, file_name); } MainForm^ form; SA* sa; System::Windows::Forms::Label^ series; System::Windows::Forms::Label^ gui_iterations; System::Windows::Forms::ListBox^ gui_best_solution; long best_achievable_points = 0; char without_improvement = 0; void next_series(); void serie(); ~Series_executor() { this->!Series_executor(); } !Series_executor() { if (sa != nullptr) { delete sa; } } }; }
// Created on: 2014-05-14 // Created by: Denis BOGOLEPOV // Copyright (c) 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 _Graphic3d_RenderingParams_HeaderFile #define _Graphic3d_RenderingParams_HeaderFile #include <Font_Hinting.hxx> #include <Font_NameOfFont.hxx> #include <Graphic3d_AspectText3d.hxx> #include <Graphic3d_TransformPers.hxx> #include <Graphic3d_RenderTransparentMethod.hxx> #include <Graphic3d_RenderingMode.hxx> #include <Graphic3d_StereoMode.hxx> #include <Graphic3d_ToneMappingMethod.hxx> #include <Graphic3d_TypeOfShadingModel.hxx> #include <Graphic3d_Vec4.hxx> //! Helper class to store rendering parameters. class Graphic3d_RenderingParams { public: //! Default pixels density. static const unsigned int THE_DEFAULT_RESOLUTION = 72u; //! Default ray-tracing depth. static const Standard_Integer THE_DEFAULT_DEPTH = 3; //! Anaglyph filter presets. enum Anaglyph { Anaglyph_RedCyan_Simple, //!< simple filter for Red-Cyan glasses (R+GB) Anaglyph_RedCyan_Optimized, //!< optimized filter for Red-Cyan glasses (R+GB) Anaglyph_YellowBlue_Simple, //!< simple filter for Yellow-Blue glasses (RG+B) Anaglyph_YellowBlue_Optimized, //!< optimized filter for Yellow-Blue glasses (RG+B) Anaglyph_GreenMagenta_Simple, //!< simple filter for Green-Magenta glasses (G+RB) Anaglyph_UserDefined //!< use externally specified matrices }; //! Statistics display flags. //! If not specified otherwise, the counter value is computed for a single rendered frame. enum PerfCounters { PerfCounters_NONE = 0x000, //!< no stats PerfCounters_FrameRate = 0x001, //!< Frame Rate, frames per second (number of frames within elapsed time) PerfCounters_CPU = 0x002, //!< CPU utilization as frames per second (number of frames within CPU utilization time (rendering thread)) PerfCounters_Layers = 0x004, //!< count layers (groups of structures) PerfCounters_Structures = 0x008, //!< count low-level Structures (normal unhighlighted Presentable Object is usually represented by 1 Structure) // PerfCounters_Groups = 0x010, //!< count primitive Groups (1 Structure holds 1 or more primitive Group) PerfCounters_GroupArrays = 0x020, //!< count Arrays within Primitive Groups (optimal primitive Group holds 1 Array) // PerfCounters_Triangles = 0x040, //!< count Triangles PerfCounters_Points = 0x080, //!< count Points PerfCounters_Lines = 0x100, //!< count Line segments // PerfCounters_EstimMem = 0x200, //!< estimated GPU memory usage // PerfCounters_FrameTime = 0x400, //!< frame CPU utilization time (rendering thread); @sa Graphic3d_FrameStatsTimer PerfCounters_FrameTimeMax= 0x800, //!< maximum frame times // PerfCounters_SkipImmediate = 0x1000, //!< do not include immediate viewer updates (e.g. lazy updates without redrawing entire view content) //! show basic statistics PerfCounters_Basic = PerfCounters_FrameRate | PerfCounters_CPU | PerfCounters_Layers | PerfCounters_Structures, //! extended (verbose) statistics PerfCounters_Extended = PerfCounters_Basic | PerfCounters_Groups | PerfCounters_GroupArrays | PerfCounters_Triangles | PerfCounters_Points | PerfCounters_Lines | PerfCounters_EstimMem, //! all counters PerfCounters_All = PerfCounters_Extended | PerfCounters_FrameTime | PerfCounters_FrameTimeMax, }; //! State of frustum culling optimization. enum FrustumCulling { FrustumCulling_Off, //!< culling is disabled FrustumCulling_On, //!< culling is active, and the list of culled entities is automatically updated before redraw FrustumCulling_NoUpdate //!< culling is active, but the list of culled entities is not updated }; public: //! Creates default rendering parameters. Graphic3d_RenderingParams() : Method (Graphic3d_RM_RASTERIZATION), ShadingModel (Graphic3d_TypeOfShadingModel_Phong), TransparencyMethod (Graphic3d_RTM_BLEND_UNORDERED), Resolution (THE_DEFAULT_RESOLUTION), FontHinting (Font_Hinting_Off), LineFeather (1.0f), // PBR parameters PbrEnvPow2Size (9), PbrEnvSpecMapNbLevels (6), PbrEnvBakingDiffNbSamples (1024), PbrEnvBakingSpecNbSamples (256), PbrEnvBakingProbability (0.99f), // OitDepthFactor (0.0f), NbOitDepthPeelingLayers (4), NbMsaaSamples (0), RenderResolutionScale (1.0f), ShadowMapResolution (1024), ShadowMapBias (0.005f), ToEnableDepthPrepass (Standard_False), ToEnableAlphaToCoverage (Standard_True), // ray tracing parameters IsGlobalIlluminationEnabled (Standard_False), SamplesPerPixel(0), RaytracingDepth (THE_DEFAULT_DEPTH), IsShadowEnabled (Standard_True), IsReflectionEnabled (Standard_False), IsAntialiasingEnabled (Standard_False), IsTransparentShadowEnabled (Standard_False), UseEnvironmentMapBackground (Standard_False), ToIgnoreNormalMapInRayTracing (Standard_False), CoherentPathTracingMode (Standard_False), AdaptiveScreenSampling (Standard_False), AdaptiveScreenSamplingAtomic(Standard_False), ShowSamplingTiles (Standard_False), TwoSidedBsdfModels (Standard_False), RadianceClampingValue (30.0), RebuildRayTracingShaders (Standard_False), RayTracingTileSize (32), NbRayTracingTiles (16 * 16), CameraApertureRadius (0.0f), CameraFocalPlaneDist (1.0f), FrustumCullingState (FrustumCulling_On), ToneMappingMethod (Graphic3d_ToneMappingMethod_Disabled), Exposure (0.f), WhitePoint (1.f), // stereoscopic parameters StereoMode (Graphic3d_StereoMode_QuadBuffer), HmdFov2d (30.0f), AnaglyphFilter (Anaglyph_RedCyan_Optimized), ToReverseStereo (Standard_False), ToSmoothInterlacing (Standard_True), ToMirrorComposer (Standard_True), // StatsPosition (new Graphic3d_TransformPers (Graphic3d_TMF_2d, Aspect_TOTP_LEFT_UPPER, Graphic3d_Vec2i (20, 20))), ChartPosition (new Graphic3d_TransformPers (Graphic3d_TMF_2d, Aspect_TOTP_RIGHT_UPPER, Graphic3d_Vec2i (20, 20))), ChartSize (-1, -1), StatsTextAspect (new Graphic3d_AspectText3d()), StatsUpdateInterval (1.0), StatsTextHeight (16), StatsNbFrames (1), StatsMaxChartTime (0.1f), CollectedStats (PerfCounters_Basic), ToShowStats (Standard_False) { const Graphic3d_Vec4 aZero (0.0f, 0.0f, 0.0f, 0.0f); AnaglyphLeft .SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f)); AnaglyphLeft .SetRow (1, aZero); AnaglyphLeft .SetRow (2, aZero); AnaglyphLeft .SetRow (3, aZero); AnaglyphRight.SetRow (0, aZero); AnaglyphRight.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f)); AnaglyphRight.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f)); AnaglyphRight.SetRow (3, aZero); StatsTextAspect->SetColor (Quantity_NOC_WHITE); StatsTextAspect->SetColorSubTitle (Quantity_NOC_BLACK); StatsTextAspect->SetFont (Font_NOF_ASCII_MONO); StatsTextAspect->SetDisplayType (Aspect_TODT_SHADOW); StatsTextAspect->SetTextZoomable (Standard_False); StatsTextAspect->SetTextFontAspect (Font_FA_Regular); } //! Returns resolution ratio. Standard_ShortReal ResolutionRatio() const { return Resolution / static_cast<Standard_ShortReal> (THE_DEFAULT_RESOLUTION); } //! Dumps the content of me into the stream Standard_EXPORT void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const; public: //! @name general parameters Graphic3d_RenderingMode Method; //!< specifies rendering mode, Graphic3d_RM_RASTERIZATION by default Graphic3d_TypeOfShadingModel ShadingModel; //!< specified default shading model, Graphic3d_TypeOfShadingModel_Phong by default Graphic3d_RenderTransparentMethod TransparencyMethod; //!< specifies rendering method for transparent graphics unsigned int Resolution; //!< Pixels density (PPI), defines scaling factor for parameters like text size //! (when defined in screen-space units rather than in 3D) to be properly displayed //! on device (screen / printer). 72 is default value. //! Note that using difference resolution in different Views in same Viewer //! will lead to performance regression (for example, text will be recreated every time). Font_Hinting FontHinting; //!< enables/disables text hinting within textured fonts, Font_Hinting_Off by default; //! hinting improves readability of thin text on low-resolution screen, //! but adds distortions to original font depending on font family and font library version Standard_ShortReal LineFeather; //!< line feather width in pixels (> 0.0), 1.0 by default; //! high values produce blurred results, small values produce sharp (aliased) edges public: //! @name rendering resolution parameters Standard_Integer PbrEnvPow2Size; //!< size of IBL maps side can be calculated as 2^PbrEnvPow2Size (> 0), 9 by default Standard_Integer PbrEnvSpecMapNbLevels; //!< number of levels used in specular IBL map (> 1), 6 by default Standard_Integer PbrEnvBakingDiffNbSamples; //!< number of samples used in Monte-Carlo integration during diffuse IBL map's //! spherical harmonics coefficients generation (> 0), 1024 by default Standard_Integer PbrEnvBakingSpecNbSamples; //!< number of samples used in Monte-Carlo integration during specular IBL map's generation (> 0), 256 by default Standard_ShortReal PbrEnvBakingProbability; //!< controls strength of samples reducing strategy during specular IBL map's generation //! (see 'SpecIBLMapSamplesFactor' function for detail explanation) [0.0, 1.0], 0.99 by default Standard_ShortReal OitDepthFactor; //!< scalar factor [0-1] controlling influence of depth of a fragment to its final coverage (Graphic3d_RTM_BLEND_OIT), 0.0 by default Standard_Integer NbOitDepthPeelingLayers; //!< number of depth peeling (Graphic3d_RTM_DEPTH_PEELING_OIT) layers, 4 by default Standard_Integer NbMsaaSamples; //!< number of MSAA samples (should be within 0..GL_MAX_SAMPLES, power-of-two number), 0 by default Standard_ShortReal RenderResolutionScale; //!< rendering resolution scale factor, 1 by default; //! incompatible with MSAA (e.g. NbMsaaSamples should be set to 0) Standard_Integer ShadowMapResolution; //!< shadow texture map resolution, 1024 by default Standard_ShortReal ShadowMapBias; //!< shadowmap bias, 0.005 by default; Standard_Boolean ToEnableDepthPrepass; //!< enables/disables depth pre-pass, False by default Standard_Boolean ToEnableAlphaToCoverage; //!< enables/disables alpha to coverage, True by default public: //! @name Ray-Tracing/Path-Tracing parameters Standard_Boolean IsGlobalIlluminationEnabled; //!< enables/disables global illumination effects (path tracing) Standard_Integer SamplesPerPixel; //!< number of samples per pixel (SPP) Standard_Integer RaytracingDepth; //!< maximum ray-tracing depth, 3 by default Standard_Boolean IsShadowEnabled; //!< enables/disables shadows rendering, True by default Standard_Boolean IsReflectionEnabled; //!< enables/disables specular reflections, False by default Standard_Boolean IsAntialiasingEnabled; //!< enables/disables adaptive anti-aliasing, False by default Standard_Boolean IsTransparentShadowEnabled; //!< enables/disables light propagation through transparent media, False by default Standard_Boolean UseEnvironmentMapBackground; //!< enables/disables environment map background Standard_Boolean ToIgnoreNormalMapInRayTracing; //!< enables/disables normal map ignoring during path tracing; FALSE by default Standard_Boolean CoherentPathTracingMode; //!< enables/disables 'coherent' tracing mode (single RNG seed within 16x16 image blocks) Standard_Boolean AdaptiveScreenSampling; //!< enables/disables adaptive screen sampling mode for path tracing, FALSE by default Standard_Boolean AdaptiveScreenSamplingAtomic;//!< enables/disables usage of atomic float operations within adaptive screen sampling, FALSE by default Standard_Boolean ShowSamplingTiles; //!< enables/disables debug mode for adaptive screen sampling, FALSE by default Standard_Boolean TwoSidedBsdfModels; //!< forces path tracing to use two-sided versions of original one-sided scattering models Standard_ShortReal RadianceClampingValue; //!< maximum radiance value used for clamping radiance estimation. Standard_Boolean RebuildRayTracingShaders; //!< forces rebuilding ray tracing shaders at the next frame Standard_Integer RayTracingTileSize; //!< screen tile size, 32 by default (adaptive sampling mode of path tracing); Standard_Integer NbRayTracingTiles; //!< maximum number of screen tiles per frame, 256 by default (adaptive sampling mode of path tracing); //! this parameter limits the number of tiles to be rendered per redraw, increasing Viewer interactivity, //! but also increasing the time for achieving a good quality; -1 means no limit Standard_ShortReal CameraApertureRadius; //!< aperture radius of perspective camera used for depth-of-field, 0.0 by default (no DOF) (path tracing only) Standard_ShortReal CameraFocalPlaneDist; //!< focal distance of perspective camera used for depth-of field, 1.0 by default (path tracing only) FrustumCulling FrustumCullingState; //!< state of frustum culling optimization; FrustumCulling_On by default Graphic3d_ToneMappingMethod ToneMappingMethod; //!< specifies tone mapping method for path tracing, Graphic3d_ToneMappingMethod_Disabled by default Standard_ShortReal Exposure; //!< exposure value used for tone mapping (path tracing), 0.0 by default Standard_ShortReal WhitePoint; //!< white point value used in filmic tone mapping (path tracing), 1.0 by default public: //! @name VR / stereoscopic parameters Graphic3d_StereoMode StereoMode; //!< stereoscopic output mode, Graphic3d_StereoMode_QuadBuffer by default Standard_ShortReal HmdFov2d; //!< sharp field of view range in degrees for displaying on-screen 2D elements, 30.0 by default; Anaglyph AnaglyphFilter; //!< filter for anaglyph output, Anaglyph_RedCyan_Optimized by default Graphic3d_Mat4 AnaglyphLeft; //!< left anaglyph filter (in normalized colorspace), Color = AnaglyphRight * theColorRight + AnaglyphLeft * theColorLeft; Graphic3d_Mat4 AnaglyphRight; //!< right anaglyph filter (in normalized colorspace), Color = AnaglyphRight * theColorRight + AnaglyphLeft * theColorLeft; Standard_Boolean ToReverseStereo; //!< flag to reverse stereo pair, FALSE by default Standard_Boolean ToSmoothInterlacing; //!< flag to smooth output on interlaced displays (improves text readability / reduces line aliasing), TRUE by default Standard_Boolean ToMirrorComposer; //!< if output device is an external composer - mirror rendering results in window in addition to sending frame to composer, TRUE by default public: //! @name on-screen display parameters Handle(Graphic3d_TransformPers) StatsPosition; //!< location of stats, upper-left position by default Handle(Graphic3d_TransformPers) ChartPosition; //!< location of stats chart, upper-right position by default Graphic3d_Vec2i ChartSize; //!< chart size in pixels, (-1, -1) by default which means that chart will occupy a portion of viewport Handle(Graphic3d_AspectText3d) StatsTextAspect; //!< stats text aspect Standard_ShortReal StatsUpdateInterval; //!< time interval between stats updates in seconds, 1.0 second by default; //! too often updates might impact performance and will smear text within widgets //! (especially framerate, which is better averaging); //! 0.0 interval will force updating on each frame Standard_Integer StatsTextHeight; //!< stats text size; 16 by default Standard_Integer StatsNbFrames; //!< number of data frames to collect history; 1 by default Standard_ShortReal StatsMaxChartTime; //!< upper time limit within frame chart in seconds; 0.1 seconds by default (100 ms or 10 FPS) PerfCounters CollectedStats; //!< performance counters to collect, PerfCounters_Basic by default; //! too verbose options might impact rendering performance, //! because some counters might lack caching optimization (and will require expensive iteration through all data structures) Standard_Boolean ToShowStats; //!< display performance statistics, FALSE by default; //! note that counters specified within CollectedStats will be updated nevertheless //! of visibility of widget managed by ToShowStats flag (e.g. stats can be retrieved by application for displaying using other methods) }; #endif // _Graphic3d_RenderingParams_HeaderFile
#pragma once #include <string> #include <vector> #include <GL/glew.h> #include "Color.h" static std::vector<unsigned int> textures; namespace engine{ unsigned int loadTextureFile(std::string file, bool genMipmap, int filtering); unsigned int createEmptyTexture(unsigned int width, unsigned int height, std::vector<GLubyte> &imageData); void updateImageData(unsigned int textureId, unsigned int width, unsigned int height, std::vector<GLubyte> &imageData); void storePixelInBuffer(unsigned int x, unsigned int y, unsigned int width, Color color, std::vector<GLubyte> &imageData); Color getPixelInBuffer(unsigned int x, unsigned int y, unsigned int width, std::vector<GLubyte> &imageData); unsigned int loadHeightMap(std::string fileName, std::vector<std::vector<float>> &heights); unsigned int loadHeightMap(unsigned int heightMap, std::vector<std::vector<float>> &heights); unsigned int loadCubeMap(std::string right, std::string left, std::string top, std::string bottom, std::string back, std::string front); void cleanUpTextures(); }
#include <stdio.h> #include <string.h> #include <opencv2/opencv.hpp> #define GRAY 0 #define INV 1 #define THRESH 2 #define EDGE 3 #define BYTE 8 #define MAX_RGB 765 #define MAX_GRAY 255 using namespace cv; typedef struct { uchar blue; uchar green; uchar red; } pixel; // ----- FUNCTION HEADERS ----- // uint pixelValue(pixel p); void getSurroundingRGB(pixel ret[8], Mat img, ulong curPixel); uint edgeValue(pixel* pixels); // ---------------------------- // int main (int argc, char** argv) { Mat image; Mat output[3]; uchar highest = 0; bool flags[] = {false, false, false, false}; uint maxThresh = MAX_RGB, threshold, edge, pixelSize = 3; size_t option; pixel p = {0, 0, 0}; pixel edgeArray[8]; for (option = 1; option < argc && argv[option][0] == '-'; option++) { switch (argv[option][1]) { case 'g': flags[GRAY] = true; pixelSize = 1; maxThresh = MAX_GRAY; break; case 'i': flags[INV] = true; break; case 't': flags[THRESH] = true; if (sscanf(argv[++option], "%ud", &threshold) < 1) { fprintf(stderr, "Invalid argument for -t\n"); return -1; } fprintf(stderr, "Value received for -t: %d\n", threshold); break; case 'e': flags[EDGE] = true; if (sscanf(argv[++option], "%ud", &edge) < 1) { fprintf(stderr, "Invalid argument for -e\n"); return -1; } break; default: fprintf(stderr, "Incorrect usage\n"); exit(EXIT_FAILURE); } } if (threshold > maxThresh) { threshold = maxThresh; } if (edge > maxThresh) { edge = maxThresh; } if (flags[GRAY]) image = imread("./mona-lisa.jpg", CV_LOAD_IMAGE_GRAYSCALE); else image = imread("./mona-lisa.jpg", CV_LOAD_IMAGE_COLOR); if (!image.data) { fprintf(stderr, "No image data\n"); return -1; } if (flags[GRAY]) { output[0].create(Size(image.cols, image.rows), CV_8UC1); output[1].create(Size(image.cols, image.rows), CV_8UC1); output[2].create(Size(image.cols, image.rows), CV_8UC1); } else { output[0].create(Size(image.cols, image.rows), CV_8UC3); output[1].create(Size(image.cols, image.rows), CV_8UC3); output[2].create(Size(image.cols, image.rows), CV_8UC3); } printf("------ Input Image Data ------\n"); printf("Rows: %d Columns: %d\n", image.rows, image.cols); printf("Number of dimensions: %d\n", image.dims); printf("First byte of image data: %d\n", image.data[0]); // Inverted image if (flags[INV]) { for (int i = 0; i < image.rows*image.cols*pixelSize; i++) { if (image.data[i] > highest) highest = image.data[i]; output[0].data[i] = 255 - image.data[i]; } printf("Highest data value: %d\n", highest); printf("------ Inverted Image Data ------\n"); printf("Rows: %d Columns: %d\n", output[0].rows, output[0].cols); printf("Number of dimensions: %d\n", output[0].dims); printf("First byte of output data: %d\n", output[0].data[0]); namedWindow("Inverted Image", WINDOW_NORMAL); imshow("Inverted Image", output[0]); } // Thresholded image if (flags[THRESH]) { for (int i = 0; i < image.rows*image.cols*pixelSize; i += pixelSize) { // Reset pixel data p = {0, 0, 0}; // Copy image.data (1 or 3 bytes) into a pixel memcpy(&p, (image.data + i), pixelSize); if (pixelValue(p) >= threshold) { // Higher than threshold -> white p.blue = 255; p.green = 255; p.red = 255; } else { // Lower than threshold -> black p.blue = 0; p.green = 0; p.red = 0; } // Put the new pixel (black or white) into output.data memcpy((output[1].data + i), &p, pixelSize); } namedWindow("Thresholded Image", WINDOW_NORMAL); imshow("Thresholded Image", output[1]); } // Edge-detected image if (flags[EDGE]) { if (flags[GRAY]) { fprintf(stderr, "Please only use edge-detection with RGB images\n"); return -1; } for (int i = 0; i < image.rows*image.cols*pixelSize; i += pixelSize) { // Reset pixel data p = {0, 0, 0}; // Find the pixels around the current one getSurroundingRGB(edgeArray, image, i/3); if (edgeValue(edgeArray) > edge) { // Higher than threshold -> white p.blue = 255; p.green = 255; p.red = 255; } else { // Lower than threshold -> black p.blue = 0; p.green = 0; p.red = 0; } // Put the new pixel (black or white) into output.data memcpy((output[2].data + i), &p, pixelSize); } namedWindow("Edge-detected Image", WINDOW_NORMAL); imshow("Edge-detected Image", output[2]); } namedWindow("Original Image", WINDOW_NORMAL); imshow("Original Image", image); waitKey(0); return 0; } uint pixelValue(pixel p) { uint val; val = p.blue + p.green + p.red; return val; } // Returns an array of the RGB pixels surround the one at the given point in the given Mat img void getSurroundingRGB(pixel ret[8], Mat img, ulong curPixel) { Vec3b pixels[8]; uint curRow, curCol, i; // Row = pixel# / # of cols, rounded down curRow = curPixel / img.cols; // Col = pixel# - (row# * # of cols) curCol = curPixel - (curRow * img.cols); if (curRow == 0 || curCol == 0 || curRow >= (img.rows - 1) || curCol >= (img.cols - 1)) { for (i = 0; i < 8; i++) { ret[i].blue = 0; ret[i].green = 0; ret[i].red = 0; } } else { pixels[0] = img.at<Vec3b>(curRow - 1, curCol - 1); pixels[1] = img.at<Vec3b>(curRow - 1, curCol); pixels[2] = img.at<Vec3b>(curRow - 1, curCol + 1); pixels[3] = img.at<Vec3b>(curRow, curCol + 1); pixels[4] = img.at<Vec3b>(curRow + 1, curCol + 1); pixels[5] = img.at<Vec3b>(curRow + 1, curCol); pixels[6] = img.at<Vec3b>(curRow + 1, curCol - 1); pixels[7] = img.at<Vec3b>(curRow, curCol - 1); for (i = 0; i < 8; i++) { ret[i].blue = pixels[i].val[0]; ret[i].green = pixels[i].val[1]; ret[i].red = pixels[i].val[2]; //fprintf(stderr, "--- OBTAINED PIXEL VALUE %3d %3d %3d ---\n", ret[i].blue, ret[i].green, ret[1].red); } } return; } uint edgeValue(pixel* pixels) { uint ret, high = 0, low = 765, tmp, i; // Get min/max pixel values for (i = 0; i < 8; i++) { tmp = pixelValue(pixels[i]); if (tmp > high) high = tmp; if (tmp < low) low = tmp; } // Calculate edge value: high - low ret = high - low; //fprintf(stderr, "--- OBTAINED EDGE VALUE %3d ---\n", ret); return ret; }
#include "pch.h" #include "ShadowMapInstance.h" #include "Camera.h" using namespace SimpleMath; ShadowMapInstance::ShadowMapInstance() { m_deviceContext = nullptr; m_width = 0; m_height = 0; } ShadowMapInstance::~ShadowMapInstance() {} VS_VP_MATRICES_CBUFFER ShadowMapInstance::getLightMatrices() const { return m_lightMatrices; } DirectX::BoundingOrientedBox ShadowMapInstance::getLightBoundingBox(float distanceMultipler) const { BoundingOrientedBox obb; obb.Center = m_worldBoundingSphere.Center; float distance = m_worldBoundingSphere.Radius * distanceMultipler; obb.Extents = XMFLOAT3(distance * 6.f, distance, distance); XMFLOAT3 directionF3 = pMath::F3Multiply(m_lightDirection, m_worldBoundingSphere.Radius); XMFLOAT3 lookAtF3 = pMath::F3Add(obb.Center, directionF3); XMVECTOR lookAt = XMLoadFloat3(&lookAtF3); XMFLOAT3 positionF3 = pMath::F3Subtract(obb.Center, directionF3); XMVECTOR position = XMLoadFloat3(&positionF3); XMVECTOR up = DirectX::XMVectorSet(0.f, 1.f, 0.f, 0.f); XMMATRIX rotationMatrix = DirectX::XMMatrixLookAtLH(position, lookAt, up); XMStoreFloat4(&obb.Orientation, DirectX::XMQuaternionRotationMatrix(rotationMatrix)); return obb; } void ShadowMapInstance::initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, UINT width, UINT height) { // Device m_deviceContext = deviceContext; // Dimensions m_width = width; m_height = height; // Viewport m_viewport.TopLeftX = 0.f; m_viewport.TopLeftY = 0.f; m_viewport.Width = (float)m_width; m_viewport.Height = (float)m_height; m_viewport.MinDepth = 0.f; m_viewport.MaxDepth = 1.f; // Resources // Texture 2D D3D11_TEXTURE2D_DESC textureDesc; textureDesc.Width = m_width; textureDesc.Height = m_height; textureDesc.MipLevels = 1; textureDesc.ArraySize = 1; textureDesc.Format = DXGI_FORMAT_R24G8_TYPELESS; textureDesc.SampleDesc.Count = 1; textureDesc.SampleDesc.Quality = 0; textureDesc.Usage = D3D11_USAGE_DEFAULT; textureDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE; textureDesc.CPUAccessFlags = 0; textureDesc.MiscFlags = 0; ID3D11Texture2D* depthMap; ZeroMemory(&depthMap, sizeof(depthMap)); HRESULT hr = device->CreateTexture2D(&textureDesc, 0, &depthMap); assert(SUCCEEDED(hr) && "Error, failed to create shadow map texture!"); // Depth Stencil View D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc; depthStencilViewDesc.Flags = 0; depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; depthStencilViewDesc.Texture2D.MipSlice = 0; hr = device->CreateDepthStencilView(depthMap, &depthStencilViewDesc, m_shadowMapDSV.GetAddressOf()); assert(SUCCEEDED(hr) && "Error, failed to create shadow map depth stencil view!"); // Shader Resource View D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc; shaderResourceViewDesc.Format = DXGI_FORMAT_R24_UNORM_X8_TYPELESS; shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; shaderResourceViewDesc.Texture2D.MipLevels = textureDesc.MipLevels; shaderResourceViewDesc.Texture2D.MostDetailedMip = 0; hr = device->CreateShaderResourceView(depthMap, &shaderResourceViewDesc, m_shadowMapSRV.GetAddressOf()); assert(SUCCEEDED(hr) && "Error, failed to create shadow map shader resource view!"); depthMap->Release(); // Pipeline States // Depth Stencil State D3D11_DEPTH_STENCIL_DESC dsDesc; ZeroMemory(&dsDesc, sizeof(D3D11_DEPTH_STENCIL_DESC)); dsDesc.DepthEnable = true; dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK::D3D11_DEPTH_WRITE_MASK_ALL; dsDesc.DepthFunc = D3D11_COMPARISON_FUNC::D3D11_COMPARISON_LESS_EQUAL; // Stencil test parameters dsDesc.StencilEnable = true; dsDesc.StencilReadMask = 0xFF; dsDesc.StencilWriteMask = 0xFF; // Stencil operations if pixel is front-facing dsDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; dsDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; dsDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; dsDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; // Stencil operations if pixel is back-facing dsDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; dsDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; dsDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; dsDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; hr = device->CreateDepthStencilState(&dsDesc, &m_depthStencilState); assert(SUCCEEDED(hr) && "Error, failed to create shadow map depth stencil state!"); // Rasterizer D3D11_RASTERIZER_DESC rasterizerDesc; ZeroMemory(&rasterizerDesc, sizeof(rasterizerDesc)); rasterizerDesc.DepthBias = 1000; rasterizerDesc.DepthBiasClamp = 0.f; rasterizerDesc.SlopeScaledDepthBias = 0.f; rasterizerDesc.FillMode = D3D11_FILL_SOLID; rasterizerDesc.CullMode = D3D11_CULL_BACK; rasterizerDesc.FrontCounterClockwise = false; rasterizerDesc.DepthClipEnable = true; hr = device->CreateRasterizerState(&rasterizerDesc, m_rasterizerState.GetAddressOf()); assert(SUCCEEDED(hr) && "Error, failed to create shadow map rasterizer state!"); // Sampler D3D11_SAMPLER_DESC comparisonSamplerDesc; ZeroMemory(&comparisonSamplerDesc, sizeof(D3D11_SAMPLER_DESC)); comparisonSamplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_BORDER; comparisonSamplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_BORDER; comparisonSamplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_BORDER; comparisonSamplerDesc.BorderColor[0] = 1.f; comparisonSamplerDesc.BorderColor[1] = 1.f; comparisonSamplerDesc.BorderColor[2] = 1.f; comparisonSamplerDesc.BorderColor[3] = 1.f; comparisonSamplerDesc.MinLOD = 0.f; comparisonSamplerDesc.MaxLOD = D3D11_FLOAT32_MAX; comparisonSamplerDesc.MipLODBias = 0.f; comparisonSamplerDesc.MaxAnisotropy = 0; comparisonSamplerDesc.ComparisonFunc = D3D11_COMPARISON_LESS_EQUAL; comparisonSamplerDesc.Filter = D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT; hr = device->CreateSamplerState(&comparisonSamplerDesc, m_comparisonSampler.GetAddressOf()); assert(SUCCEEDED(hr) && "Error when creating shadow map sampler state!"); // World Bounding Sphere m_worldBoundingSphere.Center = { 0.f, 0.f, 0.f }; m_worldBoundingSphere.Radius = 100.f; // Shader ShaderFiles shaderFiles; shaderFiles.vs = L"Shader Files\\ShadowVS.hlsl"; m_shader.initialize(device, deviceContext, shaderFiles); // Constant Buffer m_lightMatrixCBuffer.init(device, deviceContext); } void ShadowMapInstance::buildLightMatrix(XMFLOAT3 lightDirection, XMFLOAT3 position) { // Light View Matrix m_lightDirection = lightDirection; m_worldBoundingSphere.Center = position; XMVECTOR lightDirectionVec = XMLoadFloat3(&m_lightDirection); XMVECTOR lookAt = XMLoadFloat3(&position); lookAt = DirectX::XMVectorSetW(lookAt, 1.f); XMVECTOR lightPosition = DirectX::XMVectorAdd(DirectX::XMVectorScale(lightDirectionVec, m_worldBoundingSphere.Radius), lookAt); XMVECTOR up = DirectX::XMVectorSet(0.f, 1.f, 0.f, 0.f); XMVECTOR eyeDirection = DirectX::XMVectorSubtract(lookAt, lightPosition); if (DirectX::XMVector3Equal(eyeDirection, DirectX::XMVectorZero())) { lookAt = DirectX::XMVectorAdd(lookAt, DirectX::XMVectorSet(0.f, 0.f, 1.f, 0.f)); } m_lightMatrices.viewMatrix = DirectX::XMMatrixLookAtLH(lightPosition, lookAt, up); // Transform World Bounding Sphere to Light Local View Space XMFLOAT3 worldSphereCenterLightSpace; XMStoreFloat3(&worldSphereCenterLightSpace, DirectX::XMVector3TransformCoord(lookAt, m_lightMatrices.viewMatrix)); // Construct Orthographic Frustum in Light View Space float l = worldSphereCenterLightSpace.x - m_worldBoundingSphere.Radius; float b = worldSphereCenterLightSpace.y - m_worldBoundingSphere.Radius; //float n = worldSphereCenterLightSpace.z - m_worldBoundingSphere.Radius; float n = 0.f; float r = worldSphereCenterLightSpace.x + m_worldBoundingSphere.Radius; float t = worldSphereCenterLightSpace.y + m_worldBoundingSphere.Radius; //float f = worldSphereCenterLightSpace.z + m_worldBoundingSphere.Radius; float f = m_worldBoundingSphere.Radius * 6.f; // Local Projection Matrix m_lightMatrices.projMatrix = DirectX::XMMatrixOrthographicOffCenterLH(l, r, b, t, n, f); // Update data m_lightMatrixCBuffer.upd(&m_lightMatrices); } void ShadowMapInstance::buildCascadeLightMatrix(XMFLOAT3 lightDirection, Camera* camera) { Vector3 frustomCorners[8] = { Vector3(-1.f, 1.f, 0.f), Vector3( 1.f, 1.f, 0.f), Vector3( 1.f,-1.f, 0.f), Vector3(-1.f,-1.f, 0.f), Vector3(-1.f, 1.f, 1.f), Vector3( 1.f, 1.f, 1.f), Vector3( 1.f,-1.f, 1.f), Vector3(-1.f,-1.f, 1.f) }; XMMATRIX cameraViewProjMatrix = camera->getViewMatrix(); cameraViewProjMatrix *= camera->getProjectionMatrix(); XMMATRIX invViewProj = DirectX::XMMatrixInverse(nullptr, cameraViewProjMatrix); Vector3 frustomCenter = Vector3::Zero; for (uint32_t i = 0; i < 8; i++) { frustomCorners[i] = pMath::TransformTransposed(frustomCorners[i], invViewProj); frustomCenter = frustomCenter + frustomCorners[i]; } frustomCenter = frustomCenter * (1.f / 8.f); } void ShadowMapInstance::update() { } ID3D11ShaderResourceView* ShadowMapInstance::getShadowMapSRV() { return m_shadowMapSRV.Get(); } ID3D11ShaderResourceView* const* ShadowMapInstance::getShadowMapSRVConstPtr() { return m_shadowMapSRV.GetAddressOf(); } void ShadowMapInstance::clearShadowmap() { m_deviceContext->ClearDepthStencilView(m_shadowMapDSV.Get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); } void ShadowMapInstance::setComparisonSampler() { m_deviceContext->PSSetSamplers(1, 1, m_comparisonSampler.GetAddressOf()); } void ShadowMapInstance::bindViewsAndRenderTarget() { ID3D11ShaderResourceView* shaderResourceNullptr = nullptr; m_deviceContext->PSSetShaderResources(3, 1, &shaderResourceNullptr); m_deviceContext->OMSetRenderTargets(1, m_rendertarget, m_shadowMapDSV.Get()); m_deviceContext->ClearDepthStencilView(m_shadowMapDSV.Get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); m_deviceContext->RSSetState(m_rasterizerState.Get()); m_deviceContext->RSSetViewports(1, &m_viewport); m_deviceContext->OMSetDepthStencilState(m_depthStencilState.Get(), 0); m_deviceContext->VSSetConstantBuffers(1, 1, m_lightMatrixCBuffer.GetAddressOf()); // GetAddressOf XD m_shader.setShaders(); }
/// Legati prin linii fiecare element din coloana Constructia de elementul corespunzator din coloana Reprezinta /// Constructia: /// 1.alfa /// 2."alfa' /// 3.'10"' /// 4.'20"" /// 5.'alfa' /// 6.5000 /// 7."alfa" /// 8.'500' /// 9."120" /// Reprezinta: /// a.Identificator data elementara /// b.Constanta de tip sir de caractere /// c.Constanta de tip numeric /// d.Constructie gresita // Raspunsuri: // 1.a // 2.d // 3.d // 4.d // 5.d // 6.c // 7.b // 8.d // 9.b //Program evaluator pentru exercitiu //Desi e corect in cele mai multe cazuri, s-ar putea sa aiba probleme cu cateva caractere speciale #include <iostream> #include <string> #include <windows.h> ; int verifica(const std::string &input) { bool doarspatii = true; for (int i = 0; i < input.size(); i++) if (input[i] != ' ') doarspatii = false; if (input[0] != '"' && strchr("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYZ", input[0])) //identificator de data { bool eok = true; // nu poate sa aiba space/caracterele in "body": @&$(%! etc.. for (unsigned i = 1; i < input.size(); i++) { if (!strchr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYZ", input[i])) { eok = false; break; } } return eok ? 0 : 4; } else if (input[input.size() - 1] == '"' && input[0] == '"') //sir de caractere { bool eok = true; for (unsigned i = 1; i < input.size() - 1; i++) { //!(strchr("\n" ,input[i]))) //toate caracterele posibile if (input[i-1] == '\\' && !strchr("abfnrtv?\"\\", input[i])) { eok = false; break; } } return eok ? 1 : 4; } else if (input[input.size() - 1] == '\'' && input[0] == '\'') //un singur caracter { bool eok = true; if ((input.size() > 4) || // are prea multe caractere (input.size() <= 3 && strchr("'\\", input[1])) || // are caracterele ' sau / inauntru (input.size() == 4 && !(input[1] == '\\' && strchr("'abfnrtv?\\", input[2])))) //are combinatie de caractere nerecunoscuta { eok = false; } return eok ? 2 : 4; } else // constanta de tip numeric { bool eok = true; for (unsigned i = 0; i < input.size(); i++) { if (!strchr("0123456789", input[i])) { eok = false; break; } } return eok ? 3 : 4; } } int main() { //declaratii //constanta - nu se schimba const std::string raspunsuri[5] = { "Identificator data elementara" , "Constanta de tip sir de caractere", "Constanta de tip de caracter", "Constanta de tip numeric", "Constructie gresita" }; std::string constructia; std::cout << "Scrie constructia care trebuie verificata: " << std::endl; //pentru verificarea unui constructii //citeste constructia care trebuie verificat //std::getline(std::cin, constructia); //std::cout << raspunsuri[verifica(constructia)] << std::endl; //pentru verificarea mai multor constructii while (std::getline(std::cin, constructia)) { std::cout << raspunsuri[verifica(constructia)] << std::endl; std::cout << std::endl; } std::cout << std::endl; system("pause"); return 0; }
#include "quitwindow.h" #include "ui_quitwindow.h" #include <QDialog> quitWindow::quitWindow(QWidget *parent) : QDialog(parent), ui(new Ui::quitWindow) { ui->setupUi(this); exampleDialog = new QDialog; closeButton = ui->closeButton; cancelButton = ui->pushButton_2; connect(closeButton, SIGNAL(clicked()), this, SLOT(quitButtonClicked())); connect(cancelButton, SIGNAL(clicked()), this, SLOT(hide())); } quitWindow::~quitWindow() { delete ui; delete closeButton; delete cancelButton; delete exampleDialog; } void quitWindow::quitButtonClicked() { QApplication::quit(); }
#include <Q2HX711.h> const byte HX711_DATA_PIN = A2; const byte HX711_CLOCK_PIN = A3; Q2HX711 HX711(HX711_DATA_PIN, HX711_CLOCK_PIN); double output = 0; long t; void setup() { Serial.begin(9600); Serial.println("Starting setup"); HX711.startSensorSetup(); } void loop() { // Start weight sensor setup if (!HX711.isSetupComplete()) { HX711.read(); // fill up averaging array } if (millis() > t + 500) { if (HX711.readyToSend()) { Serial.print(HX711.read()); Serial.println(" grams"); t = millis(); } } }
#include "SQLiteHelper.hh" #include <filesystem> #include <utility> namespace SQLiteWrapper { using namespace std; const int SQLiteHelper::SQLiteBinder::bind(const sqlite3_stmt& _stmt) { const int ret = bind_cnt; bind_cnt = 1; return ret; } SQLiteHelper::SQLiteHelper() { auto deleter = [](sqlite3 * _conn) { if (_conn) sqlite3_close(_conn); }; conn = unique_ptr<sqlite3, function<void(sqlite3*)>>{ nullptr, deleter }; } void SQLiteHelper::open(const string& _dbfile) { PRECONDITION(!_dbfile.empty(), "Need to provide database filepath"); sqlite3* conn_{ nullptr }; if( !filesystem::exists(_dbfile) ) throw runtime_error(string("Database file doesnt exist: ") + _dbfile); caller->invoke<int>(sqlite3_open, _dbfile.c_str(), &conn_); conn.reset(conn_); POSTCONDITION(conn_ != nullptr, "Database couldnt be opened"); } void SQLiteHelper::close() { caller->invoke<int>(sqlite3_close, conn.get()); conn.reset(nullptr); } const bool SQLiteHelper::isConnected() const noexcept { return conn.get(); } sqlite3* SQLiteHelper::getConn() const noexcept { return conn.get(); } const bool SQLiteHelper::isReturnCodeAnErrorCode(const int _rc) const noexcept { return _rc > SQLITE_OK && _rc < SQLITE_NOTICE; } const bool SQLiteHelper::isQueryParseable(const std::string& _query) const { PRECONDITION(!_query.empty(), "Query cannot be empty!"); try { sqlite3_stmt* stmt = prepareStmt(_query); finalizeStmt(*stmt); return true; } catch( const std::exception& ) { return false; } } sqlite3_stmt* SQLiteHelper::prepareStmt(const string& _query) const { sqlite3_stmt* stmt{ nullptr }; caller->invoke<int>(sqlite3_prepare_v2, conn.get(), _query.c_str(), -1, &stmt, nullptr); caller->invoke<int>(sqlite3_exec, conn.get(), "BEGIN TRANSACTION", nullptr, nullptr, nullptr); POSTCONDITION(stmt != nullptr, "Statement couldnt be prepared"); return stmt; } void SQLiteHelper::finalizeStmt(const sqlite3_stmt& _stmt) const { caller->invoke<int>(sqlite3_exec, conn.get(), "END TRANSACTION", nullptr, nullptr, nullptr); caller->invoke<int>(sqlite3_finalize, &_stmt); } const ResultSet SQLiteHelper::createResultSet(const sqlite3_stmt& _stmt) const { vector<Row> rows; const int column_count = caller->invoke<int>(sqlite3_column_count, &_stmt); while( caller->invoke<int>(sqlite3_step, &_stmt) == SQLITE_ROW ) { Row r{ static_cast<unsigned int>(rows.size()) }; for (int i = 0; i < column_count; ++i) r.columns.emplace_back(getColumnFromStatement(_stmt, i)); rows.emplace_back(r); } return ResultSet(rows); } Column SQLiteHelper::getColumnFromStatement(const sqlite3_stmt& _stmt, const int _col) const { const string name{ caller->invoke<const char*>(sqlite3_column_name, &_stmt, _col) }; const int bytes { caller->invoke<int>(sqlite3_column_bytes, &_stmt, _col) }; const string value{ bytes ? caller->invoke<const char*>(sqlite3_column_text, &_stmt, _col) : "" }; const int type{ caller->invoke<int>(sqlite3_column_type, &_stmt, _col) }; return Column{ name, value, type }; } }
#include <bits/stdc++.h> using namespace std; int i,j,t,a,arr[100],temp,co; int swap(int arr[],int b){ co=0; for(i=1;i<=b-1;i++){ for(j=i+1;j<=b;j++){ if(arr[i]>arr[j]){ temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; co++; } } } return co; } int main() { int k; scanf("%d",&t); while(t--){ scanf("%d",&a); for(i=1;i<=a;i++){ scanf("%d",&arr[i]); } k= swap(arr,a); printf("Optimal train swapping takes %d swaps.\n",k); } return 0; }
// Fill out your copyright notice in the Description page of Project Settings. #include "TopDownCharacter.h" #include "Camera/CameraComponent.h" #include "Kismet/GameplayStatics.h" #include "GameFramework/CharacterMovementComponent.h" #include "GameFramework/SpringArmComponent.h" // Sets default values ATopDownCharacter::ATopDownCharacter() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; // Setting up the spring arm for the camera. CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom")); CameraBoom->SetupAttachment(RootComponent); CameraBoom->bAbsoluteRotation = true; CameraBoom->TargetArmLength = 1250.f; CameraBoom->bEnableCameraLag = true; CameraBoom->bEnableCameraRotationLag = true; CameraBoom->CameraLagSpeed = 10.f; CameraBoom->RelativeRotation = FRotator(-10.f, 0.f, 0.f); CameraBoom->bDoCollisionTest = false; // Attach the camera to the boom. Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraComponent")); Camera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); Camera->bUsePawnControlRotation = false; GetCharacterMovement()->JumpZVelocity = 600.f; } // Called when the game starts or when spawned void ATopDownCharacter::BeginPlay() { Super::BeginPlay(); } // Called every frame void ATopDownCharacter::Tick(float DeltaTime) { Super::Tick(DeltaTime); } // Called to bind functionality to input void ATopDownCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); PlayerInputComponent->BindAxis("MoveForward", this, &ATopDownCharacter::MoveForward); // PlayerInputComponent->BindAxis("MoveRight", this, &ATopDownCharacter::MoveRight); PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ATopDownCharacter::StartJump); PlayerInputComponent->BindAction("Jump", IE_Released, this, &ATopDownCharacter::StopJump); } void ATopDownCharacter::MoveForward(float Delta) { FVector Direction = FRotationMatrix(GetControlRotation()).GetScaledAxis(EAxis::X); AddMovementInput(Direction, Delta); } void ATopDownCharacter::MoveRight(float Delta) { FVector Direction = FRotationMatrix(GetControlRotation()).GetScaledAxis(EAxis::Y); AddMovementInput(Direction, Delta); } void ATopDownCharacter::StartJump() { bPressedJump = true; } void ATopDownCharacter::StopJump() { bPressedJump = false; }
// // main.cpp // DistinctSubsequences // // Created by Russell Lowry on 11/17/17. // Copyright © 2017 Russell Lowry. All rights reserved. // #include<cstdio> #include<string.h> #include <algorithm> using namespace std; void add(char str1[], char str2[], char res[]){ int len1 = strlen(str1); int len2 = strlen(str2); int reslen = max(len1, len2) + 1; for(int i = 0; i < reslen; i++) { res[i]='0'; } res[reslen]='\0'; int i = len1 - 1; int j = len2 - 1; int k = reslen - 1; int carry = 0; int tmp = 0; for(i, j, k, tmp, carry; i >= 0 || j >= 0; k--){ tmp = 0; if(i >= 0) { tmp+=str1[i--] - '0'; } if(j >= 0) { tmp+=str2[j--] - '0'; } tmp += carry; if(tmp>=10) { carry=1; tmp-=10; } else { carry = 0; } res[k] = tmp + '0'; } res[0]='0'+carry; if(res[0]=='0') { for(int i=0;i<reslen;i++) { res[i]=res[i+1]; } } } int main(int argc, const char * argv[]) { int n; scanf("%d",&n); while(n--){ char S[10001],T[101]; char DP[101][10000]; scanf("%s%s", S, T); int len = strlen(T); for(int x = 1; x <= 100; x++) { DP[x][0]='0'; DP[x][1]='\0'; } DP[0][0]='1'; DP[0][1]='\0'; for(int x = 0; S[x] != '\0'; x++) { for(int y = len - 1; y >= 0; y--) { if(S[x] == T[y]) { char res[10000]; add(DP[y + 1], DP[y], res); strcpy(DP[y + 1], res); } } } printf("%s\n",DP[len]); } }
#ifndef STRINGLISTMODEL_H #define STRINGLISTMODEL_H /** * @brief stringlistmodel.h * This is the header file for object class meant for instantiation of the QObject type * Add this header to be able to use this class functions. */ #include <QObject> #include <QtQml> //Macro declaration #define MAXWIDTH 20 class StringListModel : public QObject { Q_OBJECT //declaration of properties Q_PROPERTY(QAbstractItemModel *listModel READ getListModel NOTIFY modelChanged) public: explicit StringListModel(void); //Constructor QStringListModel* getListModel()const; //Function for reading and returning the listmodel property bool fetchCPUInfoList(QString fileName); //Function for reading the cpuinfo file and constructing the Qstringlistmodel object signals: void modelChanged(); //notify signal for the lisModel property private: QStringListModel* m_cpuInfoList; //member variable to be used as the model to be exported to QML }; #endif // STRINGLISTMODEL_H
#include "../headers/JsonReader.h" JsonReader* JsonReader::pInstance = 0; bool JsonReader::load() { const char* path = "config.json"; file.open(path,std::fstream::in); if (!file.is_open()) { std::cout << "Error abriendo el archivo de configuración" << std::endl; return false; } bool parsingSuccessful = reader.parse(file, root); if (!parsingSuccessful) { std::cout << "Error leyendo el archivo de configuración: " << file << std::endl; return false; } /* * Al agregar nuevas configuraciones al config.json, crear métodos para levantarlos como loadWindowConfig() */ loadWindowConfig(); loadStageConfig(); file.close(); } void JsonReader::loadStageConfig() { int stage_width = root["stage"].get("width",640).asInt(); int stage_height = root["stage"].get("height",480).asInt(); int stage_x = root["stage"].get("x",0).asInt(); int stage_y = root["stage"].get("y",0).asInt(); stageConfig["width"] = stage_width; stageConfig["height"] = stage_height; stageConfig["x"] = stage_x; stageConfig["y"] = stage_y; } void JsonReader::loadWindowConfig() { int window_width = root["window"].get("width",640).asInt(); int window_height = root["window"].get("height",480).asInt(); windowConfig["width"] = window_width; windowConfig["height"] = window_height; } int JsonReader::getStageValue(std::string property) { if ( stageConfig.find(property) == stageConfig.end()) { std::cout << "No se encuentra el valor de configuración para " << property << std::endl; // Debería encontrar algún valor por defecto } return stageConfig[property]; } int JsonReader::getWindowValue(std::string property) { if ( windowConfig.find(property) == windowConfig.end()) { std::cout << "No se encuentra el valor de configuración para " << property << std::endl; // Debería encontrar algún valor por defecto } return windowConfig[property]; }
#include <iostream> int main(){ freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); long long a, b, c; std::cin >> a >> b >> c; if (a >= b+c) std::cout << "YES"; else std::cout << "NO"; }
#ifndef SubExtra_HPP #define SubExtra_HPP #include <QObject> class SubExtraPrivate; class SubExtra : public QObject { Q_OBJECT public: SubExtra(); ~SubExtra(); private: SubExtraPrivate* const d; }; #endif
#pragma once #include "utils.h" #include "Light.h" #include <stdio.h> #include <string> #include <vector> #include <glad/glad.h> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> class ShaderProgram { public: GLuint Id; ShaderProgram(const char * vertexShaderSource, const char * fragmentShaderSource); void Use(); void SetUniform(const char * uniform, const int value) const; void SetUniform(const char * uniform, const float value) const; void SetUniform(const char * uniform, const glm::vec3& value) const; void SetUniform(const char * uniform, const glm::mat4& value) const; void SetUniform(const char * uniform, const Light& light) const; void SetUniform(const char * uniform, const std::vector<Light>& lights) const; private: void CompileShader(GLuint id, const char * shaderSource); };
#include "Core.h" #include "Input.h" #include "World.h" #include "Object.h" #include "Screen.h" #include "Resources.h" #include "Camera.h" #include "GUI.h" #include "Exception.h" #include <glm/glm.hpp> #include <AL/al.h> #include <AL/alc.h> //! The AudioCore class. This initialises the audio software. struct AudioCore { AudioCore() { device = alcOpenDevice(NULL); // Open up the OpenAL device if (device == NULL) { throw Exception("unable to open device"); } context = alcCreateContext(device, NULL); // Create audio context if (context == NULL) { alcCloseDevice(device); throw Exception("Unable to create context"); } // Set as current context if (!alcMakeContextCurrent(context)) { alcDestroyContext(context); alcCloseDevice(device); throw Exception("Unable to make context current"); } } ~AudioCore() { alcMakeContextCurrent(NULL); alcDestroyContext(context); alcCloseDevice(device); } private: ALCdevice* device; ALCcontext* context; }; Core::Core(glm::vec2 _screenSize) { screen = std::make_shared<Screen>(_screenSize); context = rend::Context::initialize(); audioCore = std::make_shared<AudioCore>(); world = std::make_shared<World>(); } Core::~Core() { } std::shared_ptr<Core> Core::Initialize(glm::vec2 _screenSize) { std::shared_ptr<Core> rtn(new Core(_screenSize)); rtn->self = rtn; rtn->input = std::make_shared<Input>(rtn); rtn->resources = std::make_shared<Resources>(rtn); rtn->gui = std::make_shared<GUI>(rtn); return rtn; } std::shared_ptr<Object> Core::AddObject() { std::shared_ptr<Object> obj = std::make_shared<Object>(); obj->SetSelf(obj); obj->SetCore(self); objects.push_front(obj); return obj; } void Core::Start() { playing = true; for (std::list<std::shared_ptr<Object>>::iterator it = objects.begin(); it != objects.end(); it++) { (*it)->Start(); } while (playing) { world->SetTime(); screen->Clear(); SDL_Event event = { 0 }; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { playing = false; } } for (std::list<std::shared_ptr<Object>>::iterator it = objects.begin(); it != objects.end(); it++) { if ((*it)->isActive) { (*it)->Update(); (*it)->Display(); } } for (std::list<std::shared_ptr<Object>>::iterator it = objects.begin(); it != objects.end(); it++) { if ((*it)->isActive) { (*it)->GUI(); } } screen->Display(); } } void Core::Finish() { playing = false; } std::shared_ptr<Input> Core::GetInput() { return input; } std::shared_ptr<World> Core::GetWorld() { return world; } std::shared_ptr<Screen> Core::GetScreen() { return screen; } std::shared_ptr<Resources> Core::GetResources() { return resources; } std::shared_ptr<rend::Context> Core::GetContext() { return context; } std::shared_ptr<Camera> Core::GetCamera() { return mainCamera.lock(); } std::shared_ptr<Light> Core::GetLights() { return *lights.begin(); } std::shared_ptr<GUI> Core::GetGUI() { return gui; }
// // Class AliRsnCutEventUtils // // It works with ESD and AOD events. // // authors: F. Bellini (fbellini@cern.ch) #ifndef ALIRSNCUTEVENTUTILS_H #define ALIRSNCUTEVENTUTILS_H #include "AliRsnCut.h" class AliVVertex; class AliAnalysisUtils; class AliRsnCutEventUtils : public AliRsnCut { public: AliRsnCutEventUtils(const char *name = "cutEventUtils", Bool_t rmFirstEvInChunck = kFALSE, Bool_t checkPileUppA2013 = kTRUE); AliRsnCutEventUtils(const AliRsnCutEventUtils &copy); AliRsnCutEventUtils &operator=(const AliRsnCutEventUtils &copy); virtual ~AliRsnCutEventUtils() {;}; void SetRemovePileUppA2013(Bool_t doit = kTRUE) {fCheckPileUppA2013 = doit;} void SetRemoveFirstEvtInChunk(Bool_t doit = kTRUE) {fIsRmFirstEvInChunck = doit;} void SetUseMVPlpSelection(Bool_t useMVPlpSelection = kFALSE) { fUseMVPlpSelection = useMVPlpSelection;} void SetUseVertexSelection2013pA(Bool_t vtxpA2013 = kTRUE, Double_t maxVtxZ = 10.0) {fUseVertexSelection2013pA = vtxpA2013; fMaxVtxZ = maxVtxZ;} void SetUseVertexSelection2013pAIDspectra(Bool_t enable = kTRUE, Double_t maxVtxZ = 10.0) {fUseVertexSelection2013pAspectra = enable; fUseVertexSelection2013pA = kFALSE; fMaxVtxZ = maxVtxZ;} Bool_t IsSelected(TObject *object); AliAnalysisUtils* GetAnalysisUtils() { return fUtils; } void SetAnalysisUtils(AliAnalysisUtils* utils){ fUtils = utils; } void SetMinPlpContribMV(Int_t minPlpContribMV) { fMinPlpContribMV = minPlpContribMV;} void SetMinPlpContribSPD(Int_t minPlpContribSPD) { fMinPlpContribSPD = minPlpContribSPD;} void SetFilterNSDeventsDPMJETpA2013(Bool_t doit = kFALSE) {fFilterNSDeventsDPMJETpA2013 = doit;} Bool_t IsVertexSelected2013pAIDspectra(AliVEvent *event); void SetCheckIncompleteDAQ(Bool_t doit = kFALSE) {fCheckIncompleteDAQ = doit;} private: Bool_t fIsRmFirstEvInChunck; // if kTRUE, remove the first event in the chunk (pA2013) Bool_t fCheckPileUppA2013; // check and reject pileupped events (pA2013) Bool_t fUseMVPlpSelection; // check for pile-up from multiple vtx Int_t fMinPlpContribMV; // min. n. of MV pile-up contributors Int_t fMinPlpContribSPD; // min. n. of pile-up contributors from SPD Bool_t fUseVertexSelection2013pA;// check and reject vertex of events for pA2013 Bool_t fUseVertexSelection2013pAspectra;// check and reject vertex of events for pA2013 Double_t fMaxVtxZ;//max selected z_vtx Bool_t fFilterNSDeventsDPMJETpA2013;//enable filter for NSD events in DPMJET MC for pA Bool_t fCheckIncompleteDAQ;// check if DAQ has set the incomplete event attributes (pp 13 TeV) AliAnalysisUtils * fUtils; //pointer to the AliAnalysisUtils object ClassDef(AliRsnCutEventUtils, 5) }; #endif
#include <blinklib.h> #include <shared/blinkbios_shared_functions.h> #include <string.h> #include "message_handlers.h" #include "src/blinks-broadcast/manager.h" #include "src/blinks-broadcast/message.h" #include "src/blinks-debug/debug.h" broadcast::Message count_blinks; broadcast::Message report_blinks; void setup() { broadcast::message::Initialize(&count_blinks, MESSAGE_COUNT_BLINKS, false); memcpy(count_blinks.payload, message_payload, BROADCAST_MESSAGE_PAYLOAD_BYTES); broadcast::message::Initialize(&report_blinks, MESSAGE_REPORT_BLINKS_COUNT, true); } bool reported_blinks = false; byte step = 0; broadcast::Message result; byte count = 0; void loop() { broadcast::manager::Process(); if (buttonSingleClicked()) { step = 1; count = 1; } switch (step) { case 0: return; case 1: if (!broadcast::manager::Send(&count_blinks)) return; break; case 2: if (!broadcast::manager::Receive(&result)) return; break; case 3: LOGF("Number of blinks (counted): "); LOGLN(result.payload[0]); break; case 4: report_blinks.payload[0] = result.payload[0]; if (!broadcast::manager::Send(&report_blinks)) return; break; } step++; if (step > 4) { count++; if (count > 3) { step = 0; count = 0; } else { step = 1; } } }
/* * LSST Data Management System * Copyright 2014-2015 AURA/LSST. * * This product includes software developed by the * LSST Project (http://www.lsst.org/). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the LSST License Statement and * the GNU General Public License along with this program. If not, * see <https://www.lsstcorp.org/LegalNotices/>. */ /// \file /// \brief This file contains the ConvexPolygon class implementation. #include "ConvexPolygon.h" #include <ostream> #include "Box.h" #include "Circle.h" #include "Ellipse.h" #include "Orientation.h" #include "Utils.h" namespace lsst { namespace sg { namespace { char const * const FOUND_ANTIPODAL_POINT = "The convex hull of the given point set is the " "entire unit sphere"; char const * const NOT_ENOUGH_POINTS = "The convex hull of a point set containing less than " "3 distinct, non-coplanar points is not a convex polygon"; struct Vector3dLessThan { bool operator()(Vector3d const & v0, Vector3d const & v1) const { if (v0.x() == v1.x()) { if (v0.y() == v1.y()) { return v0.z() < v1.z(); } return v0.y() < v1.y(); } return v0.x() < v1.x(); } }; // `findPlane` rearranges the entries of `points` such that the first two // entries are distinct. If it is unable to do so, or if it encounters any // antipodal points in the process, an exception is thrown. It returns an // iterator to the first point in the input that was not consumed during // the search. std::vector<UnitVector3d>::iterator findPlane( std::vector<UnitVector3d> & points) { if (points.empty()) { throw std::invalid_argument(NOT_ENOUGH_POINTS); } // Starting with the first point v0, find a distinct second point v1. UnitVector3d & v0 = points[0]; UnitVector3d & v1 = points[1]; std::vector<UnitVector3d>::iterator const end = points.end(); std::vector<UnitVector3d>::iterator v = points.begin() + 1; for (; v != end; ++v) { if (v0 == -*v) { throw std::invalid_argument(FOUND_ANTIPODAL_POINT); } if (v0 != *v) { break; } } if (v == end) { throw std::invalid_argument(NOT_ENOUGH_POINTS); } v1 = *v; return ++v; } // `findTriangle` rearranges the entries of `points` such that the first // three entries have counter-clockwise orientation. If it is unable to do so, // or if it encounters any antipodal points in the process, an exception is // thrown. It returns an iterator to the first point in the input that was not // consumed during the search. std::vector<UnitVector3d>::iterator findTriangle( std::vector<UnitVector3d> & points) { std::vector<UnitVector3d>::iterator v = findPlane(points); std::vector<UnitVector3d>::iterator const end = points.end(); UnitVector3d & v0 = points[0]; UnitVector3d & v1 = points[1]; // Note that robustCross() gives a non-zero result for distinct, // non-antipodal inputs, and that normalization never maps a non-zero // vector to the zero vector. UnitVector3d n(v0.robustCross(v1)); for (; v != end; ++v) { int ccw = orientation(v0, v1, *v); if (ccw > 0) { // We found a counter-clockwise triangle. break; } else if (ccw < 0) { // We found a clockwise triangle. Swap the first two vertices to // flip its orientation. std::swap(v0, v1); break; } // v, v0 and v1 are coplanar. if (*v == v0 || *v == v1) { continue; } if (*v == -v0 || *v == -v1) { throw std::invalid_argument(FOUND_ANTIPODAL_POINT); } // At this point, v, v0 and v1 are distinct and non-antipodal. // If v is in the interior of the great circle segment (v0, v1), // discard v and continue. int v0v = orientation(n, v0, *v); int vv1 = orientation(n, *v, v1); if (v0v == vv1) { continue; } int v0v1 = orientation(n, v0, v1); // If v1 is in the interior of (v0, v), replace v1 with v and continue. if (v0v1 == -vv1) { v1 = *v; continue; } // If v0 is in the interior of (v, v1), replace v0 with v and continue. if (-v0v == v0v1) { v0 = *v; continue; } // Otherwise, (v0, v1) ∪ (v1, v) and (v, v0) ∪ (v0, v1) both span // more than π radians of the great circle defined by the v0 and v1, // so there is a pair of antipodal points in the corresponding great // circle segment. throw std::invalid_argument(FOUND_ANTIPODAL_POINT); } if (v == end) { throw std::invalid_argument(NOT_ENOUGH_POINTS); } points[2] = *v; return ++v; } void computeHull(std::vector<UnitVector3d> & points) { typedef std::vector<UnitVector3d>::iterator VertexIterator; VertexIterator hullEnd = points.begin() + 3; VertexIterator const end = points.end(); // Start with a triangular hull. for (VertexIterator v = findTriangle(points); v != end; ++v) { // Compute the hull of the current hull and v. // // Notice that if v is in the current hull, v can be ignored. If // -v is in the current hull, then the hull of v and the current hull // is not a convex polygon. // // Otherwise, let i and j be the first and second end-points of an edge // in the current hull. We define the orientation of vertex j with // respect to vertex v as orientation(v, i, j). When neither v or -v // is in the current hull, there must be a sequence of consecutive // hull vertices that do not have counter-clockwise orientation with // respect to v. Insert v before the first vertex in this sequence // and remove all vertices in the sequence except the last to obtain // a new, larger convex hull. VertexIterator i = hullEnd - 1; VertexIterator j = points.begin(); // toCCW is the vertex before the transition to counter-clockwise // orientation with respect to v. VertexIterator toCCW = hullEnd; // fromCCW is the vertex at which orientation with respect to v // changes from counter-clockwise to clockwise or coplanar. It may // equal toCCW. VertexIterator fromCCW = hullEnd; // Compute the orientation of the first point in the current hull // with respect to v. bool const firstCCW = orientation(*v, *i, *j) > 0; bool prevCCW = firstCCW; // Compute the orientation of points in the current hull with respect // to v, starting with the second point. Update toCCW / fromCCW when // we transition to / from counter-clockwise orientation. for (i = j, ++j; j != hullEnd; i = j, ++j) { if (orientation(*v, *i, *j) > 0) { if (!prevCCW) { toCCW = i; prevCCW = true; } } else if (prevCCW) { fromCCW = j; prevCCW = false; } } // Now that we know the orientation of the last point in the current // hull with respect to v, consider the first point in the current hull. if (firstCCW) { if (!prevCCW) { toCCW = i; } } else if (prevCCW) { fromCCW = points.begin(); } // Handle the case where there is never a transition to / from // counter-clockwise orientation. if (toCCW == hullEnd) { // If all vertices are counter-clockwise with respect to v, // v is inside the current hull and can be ignored. if (firstCCW) { continue; } // Otherwise, no vertex is counter-clockwise with respect to v, // so that -v is inside the current hull. throw std::invalid_argument(FOUND_ANTIPODAL_POINT); } // Insert v into the current hull at fromCCW, and remove // all vertices between fromCCW and toCCW. if (toCCW < fromCCW) { if (toCCW != points.begin()) { fromCCW = std::copy(toCCW, fromCCW, points.begin()); } *fromCCW++ = *v; hullEnd = fromCCW; } else if (toCCW > fromCCW) { *fromCCW++ = *v; if (toCCW != fromCCW) { hullEnd = std::copy(toCCW, hullEnd, fromCCW); } } else { if (fromCCW == points.begin()) { *hullEnd = *v; } else { std::copy_backward(fromCCW, hullEnd, hullEnd + 1); *fromCCW = *v; } ++hullEnd; } } points.erase(hullEnd, end); // Since the points in the hull are distinct, there is a unique minimum // point - rotate the points vector to make it the first one. This allows // operator== for ConvexPolygon to be implemented simply by comparing // vertices. VertexIterator minVertex = points.begin(); Vector3dLessThan lessThan; for (VertexIterator v = minVertex + 1, e = points.end(); v != e; ++v) { if (lessThan(*v, *minVertex)) { minVertex = v; } } std::rotate(points.begin(), minVertex, points.end()); } // TODO(smm): for all of this to be fully rigorous, we must prove that no two // UnitVector3d objects u and v are exactly colinear unless u == v or u == -v. // It's not clear that this is true. For example, (1, 0, 0) and (1 + ε, 0, 0) // are colinear. This means that UnitVector3d should probably always normalize // on construction. Currently, it does not normalize when created from a LonLat, // and also contains some escape-hatches for performance. The normalize() // function implementation may also need to be revisited. // TODO(smm): This implementation is quadratic. It would be nice to implement // a fast hull merging algorithm, which could then be used to implement Chan's // algorithm. } // unnamed namespace ConvexPolygon::ConvexPolygon(std::vector<UnitVector3d> const & points) : _vertices(points) { computeHull(_vertices); } bool ConvexPolygon::operator==(ConvexPolygon const & p) const { if (this == &p) { return true; } if (_vertices.size() != p._vertices.size()) { return false; } VertexIterator i = _vertices.begin(); VertexIterator j = p._vertices.begin(); VertexIterator const end = _vertices.end(); for (; i != end; ++i, ++j) { if (*i != *j) { return false; } } return true; } UnitVector3d ConvexPolygon::getCentroid() const { // The center of mass is obtained via trivial generalization of // the formula for spherical triangles from: // // The centroid and inertia tensor for a spherical triangle // John E. Brock // 1974, Naval Postgraduate School, Monterey Calif. Vector3d cm; VertexIterator const end = _vertices.end(); VertexIterator i = end - 1; VertexIterator j = _vertices.begin(); for (; j != end; i = j, ++j) { Vector3d v = (*i).robustCross(*j); double s = 0.5 * v.normalize(); double c = (*i).dot(*j); double a = (s == 0.0 && c == 0.0) ? 0.0 : std::atan2(s, c); cm += v * a; } return UnitVector3d(cm); } Circle ConvexPolygon::getBoundingCircle() const { UnitVector3d c = getCentroid(); // Compute the maximum squared chord length between the centroid and // all vertices. VertexIterator const end = _vertices.end(); VertexIterator i = end - 1; VertexIterator j = _vertices.begin(); double cl2 = 0.0; for (; j != end; i = j, ++j) { cl2 = std::max(cl2, (*j - *i).getSquaredNorm()); } // Add double the maximum squared-chord-length error, so that the // bounding circle we return also reliably CONTAINS this polygon. return Circle(c, cl2 + 2.0 * MAX_SCL_ERROR); } Box ConvexPolygon::getBoundingBox() const { Angle const eps(5.0e-10); // ~ 0.1 milli-arcseconds Box bbox; VertexIterator const end = _vertices.end(); VertexIterator i = end - 1; VertexIterator j = _vertices.begin(); bool haveCW = false; bool haveCCW = false; // Compute the bounding box for each vertex. When converting a Vector3d // to a LonLat, the relative error on the longitude is about 4*2^-53, // and the relative error on the latitude is about twice that (assuming // std::atan2 and std::sqrt accurate to within 1 ulp). We convert each // vertex to a conservative bounding box for its spherical coordinates, // and compute a bounding box for the union of all these boxes. // // Furthermore, the latitude range of an edge can be greater than the // latitude range of its endpoints - this occurs when the minimum or // maximum latitude point on the great circle defined by the edge vertices // lies in the edge interior. for (; j != end; i = j, ++j) { LonLat p(*j); bbox.expandTo(Box(p, eps, eps)); if (!haveCW || !haveCCW) { // TODO(smm): This orientation call in particular is likely to be // useful in other contexts, and may warrant a specialized // implementation. int o = orientation(UnitVector3d::Z(), *i, *j); haveCCW = haveCCW || (o > 0); haveCW = haveCW || (o < 0); } // Compute the plane normal for edge i, j. Vector3d n = (*i).robustCross(*j); // Compute a vector v with positive z component that lies on both the // edge plane and on the plane defined by the z axis and the edge plane // normal. This is the direction of maximum latitude for the great // circle containing the edge, and -v is the direction of minimum // latitude. // // TODO(smm): Do a proper error analysis. Vector3d v(-n.x() * n.z(), -n.y() * n.z(), n.x() * n.x() + n.y() * n.y()); if (v != Vector3d()) { // The plane defined by the z axis and n has normal // (-n.y(), n.x(), 0.0). Compute the dot product of this plane // normal with vertices i and j. double zni = i->y() * n.x() - i->x() * n.y(); double znj = j->y() * n.x() - j->x() * n.y(); // Check if v or -v is in the edge interior. if (zni > 0.0 && znj < 0.0) { bbox = Box(bbox.getLon(), bbox.getLat().expandedTo( LonLat::latitudeOf(v) + eps)); } else if (zni < 0.0 && znj > 0.0) { bbox = Box(bbox.getLon(), bbox.getLat().expandedTo( LonLat::latitudeOf(-v) - eps)); } } } // If this polygon contains a pole, its bounding box must contain all // longitudes. if (!haveCW) { Box northPole(Box::allLongitudes(), AngleInterval(Angle(0.5 * PI))); bbox.expandTo(northPole); } else if (!haveCCW) { Box southPole(Box::allLongitudes(), AngleInterval(Angle(-0.5 * PI))); bbox.expandTo(southPole); } return bbox; } bool ConvexPolygon::contains(UnitVector3d const & v) const { VertexIterator const end = _vertices.end(); VertexIterator i = end - 1; VertexIterator j = _vertices.begin(); for (; j != end; i = j, ++j) { if (orientation(v, *i, *j) < 0) { return false; } } return true; } int ConvexPolygon::relate(Box const & b) const { // TODO(smm): be more accurate when computing box relations. return getBoundingBox().relate(b) & (WITHIN | INTERSECTS | DISJOINT); } int ConvexPolygon::relate(Circle const & c) const { if (c.isEmpty()) { return CONTAINS | DISJOINT; } if (c.isFull()) { return INTERSECTS | WITHIN; } // Determine whether or not the circle and polygon boundaries intersect. // If the polygon vertices are not all inside or all outside of c, then the // boundaries cross. bool inside = false; for (VertexIterator v = _vertices.begin(), e = _vertices.end(); v != e; ++v) { double d = (*v - c.getCenter()).getSquaredNorm(); if (std::fabs(d - c.getSquaredChordLength()) < MAX_SCL_ERROR) { // A polygon vertex is close to the circle boundary. return INTERSECTS; } bool b = d < c.getSquaredChordLength(); if (v == _vertices.begin()) { inside = b; } else if (inside != b) { // There are box vertices both inside and outside of c. return INTERSECTS; } } if (inside) { // All polygon vertices are inside c. Look for points in the polygon // edge interiors that are outside c. for (VertexIterator a = _vertices.end(), b = _vertices.begin(), e = a; b != e; a = b, ++b) { Vector3d n = a->robustCross(*b); double d = getMaxSquaredChordLength(c.getCenter(), *a, *b, n); if (d > c.getSquaredChordLength() - MAX_SCL_ERROR) { return INTERSECTS; } } // The polygon boundary is conclusively inside c. It may still be the // case that the circle punches a hole in the polygon. We check that // the polygon does not contain the complement of c by testing whether // or not it contains the anti-center of c. if (contains(-c.getCenter())) { return INTERSECTS; } return INTERSECTS | WITHIN; } // All polygon vertices are outside c. Look for points in the polygon edge // interiors that are inside c. for (VertexIterator a = _vertices.end(), b = _vertices.begin(), e = a; b != e; a = b, ++b) { Vector3d n = a->robustCross(*b); double d = getMinSquaredChordLength(c.getCenter(), *a, *b, n); if (d < c.getSquaredChordLength() + MAX_SCL_ERROR) { return INTERSECTS; } } // The polygon boundary is conclusively outside of c. If the polygon // contains the circle center, then the polygon contains c. Otherwise, the // polygon and circle are disjoint. if (contains(c.getCenter())) { return CONTAINS | INTERSECTS; } return DISJOINT; } int ConvexPolygon::relate(ConvexPolygon const &) const { // TODO(smm): Implement this. It should be possible to determine whether // the boundaries intersect by adapting the following method to the sphere: // // A new linear algorithm for intersecting convex polygons // Computer Graphics and Image Processing, Volume 19, Issue 1, May 1982, Page 92 // Joseph O'Rourke, Chi-Bin Chien, Thomas Olson, David Naddor // // http://www.sciencedirect.com/science/article/pii/0146664X82900235 throw std::runtime_error("Not implemented"); } int ConvexPolygon::relate(Ellipse const & e) const { return relate(e.getBoundingCircle()) & (CONTAINS | INTERSECTS | DISJOINT); } std::ostream & operator<<(std::ostream & os, ConvexPolygon const & p) { typedef std::vector<UnitVector3d>::const_iterator VertexIterator; os << "ConvexPolygon(\n" " "; VertexIterator v = p.getVertices().begin(); VertexIterator const end = p.getVertices().end(); for (; v != end; ++v) { if (v != p.getVertices().begin()) { os << ",\n" " "; } os << *v; } os << "\n" ")"; return os; } }} // namespace lsst::sg
// Redirector.h : Declaration of the CRedirector // reference MSDN : http://msdn.microsoft.com/en-us/library/bb250489.aspx // and : http://msdn.microsoft.com/en-us/library/bb250436.aspx for more details. // and : http://msdn.microsoft.com/en-us/library/aa768283.aspx #ifndef __REDIRECTOR_H_ #define __REDIRECTOR_H_ #include "resource.h" // main symbols #include <shlguid.h> // IID_IWebBrowser2, DIID_DWebBrowserEvents2, etc. #include <exdispid.h> // DISPID_DOCUMENTCOMPLETE, etc. #include <mshtml.h> // IID_IHTMLDocument2 #include <shlwapi.h> #include "Socket.h" #include "HttpRequest.h" #include "ClientDaemon.h" ///////////////////////////////////////////////////////////////////////////// // CRedirector class ATL_NO_VTABLE CRedirector : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CRedirector, &CLSID_Redirector>, public IObjectWithSiteImpl<CRedirector>, public IDispatchImpl<IRedirector, &IID_IRedirector, &LIBID_BROWSERHOOKERLib>, public IDispEventImpl<1, CRedirector, &DIID_DWebBrowserEvents2, &LIBID_SHDocVw, 1, 1> { public: CRedirector(){}; ~CRedirector(){}; DECLARE_REGISTRY_RESOURCEID(IDR_REDIRECTOR) DECLARE_NOT_AGGREGATABLE(CRedirector) DECLARE_PROTECT_FINAL_CONSTRUCT() BEGIN_COM_MAP(CRedirector) COM_INTERFACE_ENTRY(IRedirector) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(IObjectWithSite) END_COM_MAP() // IRedirector public: STDMETHOD(SetSite)(IUnknown *pUnkSite); BEGIN_SINK_MAP(CRedirector) SINK_ENTRY_EX(1, DIID_DWebBrowserEvents2, DISPID_DOCUMENTCOMPLETE, OnDocumentComplete) SINK_ENTRY_EX(1, DIID_DWebBrowserEvents2, DISPID_BEFORENAVIGATE2, OnBeforeNavigate2) SINK_ENTRY_EX(1, DIID_DWebBrowserEvents2, DISPID_DOWNLOADBEGIN, OnDownloadBegin) SINK_ENTRY_EX(1, DIID_DWebBrowserEvents2, DISPID_DOWNLOADCOMPLETE, OnDownloadComplete) SINK_ENTRY_EX(1, DIID_DWebBrowserEvents2, DISPID_NAVIGATECOMPLETE2, OnNavigateComplete2) END_SINK_MAP() // DWebBrowserEvents2 // DocumentComplete事件响应函数 void STDMETHODCALLTYPE OnDocumentComplete(IDispatch *pDisp, VARIANT *pvarURL); // BeforeNavigate2事件响应函数 void STDMETHODCALLTYPE OnBeforeNavigate2(IDispatch *pDisp, VARIANT *url, VARIANT *Flags, VARIANT *TargetFrameName, VARIANT *PostData, VARIANT *Headers, VARIANT_BOOL *Cancel ); void STDMETHODCALLTYPE OnDownloadBegin(void); void STDMETHODCALLTYPE OnDownloadComplete(void); void STDMETHODCALLTYPE OnNavigateComplete2(IDispatch *pDisp, VARIANT *URL ); private: CComPtr<IWebBrowser2> m_spWebBrowser; HWND m_ParentWindow; BOOL m_fAdvised; BSTR m_origUrl; BSTR m_oldUrl; BSTR m_replacedUrl; BOOL m_bMainWindow; BOOL m_bLocationUrlChanged; BOOL m_bReplaced; CHttpRequest *m_pHttpRequest; string m_sServerAddr; UINT m_uServerPort; map<string, string> m_replaceUrlMap; string m_replacePageContent; public: //static CClientDaemon *m_pClientDaemon; // because need access from static member function. private: int MyStrToOleStrN(LPOLESTR pwsz, int cchWideChar, LPCSTR psz); BOOL isSameRootDomain(BSTR url, BSTR domain); int ReplacePageWithUrl(IHTMLDocument2 *iDoc, const char* pszurl); int ReplacePageWithHtml(IHTMLDocument2 *iDoc, BSTR htmlContent); void WriteHTMLToDoc_OLD(IHTMLDocument2* iDoc, string url); void StartClientDaemon(HWND hMainWnd); public: //static void CALLBACK GetCommandFromServer(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime); }; #endif //__REDIRECTOR_H_
// // Auto.h // Apuntadores // // Created by Daniel on 22/09/14. // Copyright (c) 2014 Gotomo. All rights reserved. // #ifndef __Apuntadores__Auto__ #define __Apuntadores__Auto__ #include <iostream> class Auto { public: Auto() {} virtual void Corre(); friend std::ostream & operator << (std::ostream &, Auto &); }; #endif /* defined(__Apuntadores__Auto__) */
#include <bits/stdc++.h> using namespace std; #define TESTC "" #define PROBLEM "13187" #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) int main(int argc, char const *argv[]) { #ifdef DBG freopen("uva" PROBLEM TESTC ".in", "r", stdin); freopen("uva" PROBLEM ".out", "w", stdout); #endif int CASE; scanf("%d",&CASE); long long num; while( CASE-- ){ scanf("%lld",&num); printf("%lld\n", (num+1)*(num+1)-1 ); } return 0; }
#ifndef __AASFILE_H__ #define __AASFILE_H__ /* =============================================================================== AAS File =============================================================================== */ #define AAS_FILEID "DewmAAS" #define AAS_FILEVERSION "1.08" // travel flags #define TFL_INVALID BIT(0) // not valid #define TFL_WALK BIT(1) // walking #define TFL_CROUCH BIT(2) // crouching #define TFL_WALKOFFLEDGE BIT(3) // walking of a ledge #define TFL_BARRIERJUMP BIT(4) // jumping onto a barrier #define TFL_JUMP BIT(5) // jumping #define TFL_LADDER BIT(6) // climbing a ladder #define TFL_SWIM BIT(7) // swimming #define TFL_WATERJUMP BIT(8) // jump out of the water #define TFL_TELEPORT BIT(9) // teleportation #define TFL_ELEVATOR BIT(10) // travel by elevator #define TFL_FLY BIT(11) // fly #define TFL_SPECIAL BIT(12) // special #define TFL_WATER BIT(21) // travel through water #define TFL_AIR BIT(22) // travel through air // face flags #define FACE_SOLID BIT(0) // solid at the other side #define FACE_LADDER BIT(1) // ladder surface #define FACE_FLOOR BIT(2) // standing on floor when on this face #define FACE_LIQUID BIT(3) // face seperating two areas with liquid #define FACE_LIQUIDSURFACE BIT(4) // face seperating liquid and air // area flags #define AREA_FLOOR BIT(0) // AI can stand on the floor in this area #define AREA_GAP BIT(1) // area has a gap #define AREA_LEDGE BIT(2) // if entered the AI bbox partly floats above a ledge #define AREA_LADDER BIT(3) // area contains one or more ladder faces #define AREA_LIQUID BIT(4) // area contains a liquid #define AREA_CROUCH BIT(5) // AI cannot walk but can only crouch in this area #define AREA_REACHABLE_WALK BIT(6) // area is reachable by walking or swimming #define AREA_REACHABLE_FLY BIT(7) // area is reachable by flying // area contents flags #define AREACONTENTS_SOLID BIT(0) // solid, not a valid area #define AREACONTENTS_WATER BIT(1) // area contains water #define AREACONTENTS_CLUSTERPORTAL BIT(2) // area is a cluster portal #define AREACONTENTS_OBSTACLE BIT(3) // area contains (part of) a dynamic obstacle #define AREACONTENTS_TELEPORTER BIT(4) // area contains (part of) a teleporter trigger // bits for different bboxes #define AREACONTENTS_BBOX_BIT 24 // RAVEN BEGIN // cdr: AASTactical // feature bits #define FEATURE_COVER BIT(0) // provides cover #define FEATURE_LOOK_LEFT BIT(1) // attack by leaning left #define FEATURE_LOOK_RIGHT BIT(2) // attack by leaning right #define FEATURE_LOOK_OVER BIT(3) // attack by leaning over the cover #define FEATURE_CORNER_LEFT BIT(4) // is a left corner #define FEATURE_CORNER_RIGHT BIT(5) // is a right corner #define FEATURE_PINCH BIT(6) // is a tight area connecting two larger areas #define FEATURE_VANTAGE BIT(7) // provides a good view of the sampled area as a whole // forward reference of sensor object struct rvAASTacticalSensor; struct rvMarker; // RAVEN END #define MAX_REACH_PER_AREA 256 #define MAX_AAS_TREE_DEPTH 128 #define MAX_AAS_BOUNDING_BOXES 4 typedef enum { RE_WALK, RE_WALKOFFLEDGE, RE_FLY, RE_SWIM, RE_WATERJUMP, RE_BARRIERJUMP, RE_SPECIAL }; // reachability to another area class idReachability { public: int travelType; // type of travel required to get to the area short toAreaNum; // number of the reachable area short fromAreaNum; // number of area the reachability starts idVec3 start; // start point of inter area movement idVec3 end; // end point of inter area movement int edgeNum; // edge crossed by this reachability unsigned short travelTime; // travel time of the inter area movement byte number; // reachability number within the fromAreaNum (must be < 256) byte disableCount; // number of times this reachability has been disabled idReachability * next; // next reachability in list idReachability * rev_next; // next reachability in reversed list unsigned short * areaTravelTimes; // travel times within the fromAreaNum from reachabilities that lead towards this area }; class idReachability_Walk : public idReachability { }; class idReachability_BarrierJump : public idReachability { }; class idReachability_WaterJump : public idReachability { }; class idReachability_WalkOffLedge : public idReachability { }; class idReachability_Swim : public idReachability { }; class idReachability_Fly : public idReachability { }; class idReachability_Special : public idReachability { friend class idAASFileLocal; private: idDict dict; }; // index typedef int aasIndex_t; // vertex typedef idVec3 aasVertex_t; // edge typedef struct aasEdge_s { int vertexNum[2]; // numbers of the vertexes of this edge } aasEdge_t; // area boundary face typedef struct aasFace_s { unsigned short planeNum; // number of the plane this face is on unsigned short flags; // face flags int numEdges; // number of edges in the boundary of the face int firstEdge; // first edge in the edge index short areas[2]; // area at the front and back of this face } aasFace_t; // area with a boundary of faces typedef struct aasArea_s { int numFaces; // number of faces used for the boundary of the area int firstFace; // first face in the face index used for the boundary of the area idBounds bounds; // bounds of the area idVec3 center; // center of the area an AI can move towards float ceiling; // top of the area unsigned short flags; // several area flags unsigned short contents; // contents of the area short cluster; // cluster the area belongs to, if negative it's a portal short clusterAreaNum; // number of the area in the cluster int travelFlags; // travel flags for traveling through this area idReachability * reach; // reachabilities that start from this area idReachability * rev_reach; // reachabilities that lead to this area // RAVEN BEGIN // cdr: AASTactical unsigned short numFeatures; // number of features in this area unsigned short firstFeature; // first feature in the feature index within this area // cdr: Obstacle Avoidance rvMarker* firstMarker; // first obstacle avoidance threat in this area (0 if none) // RAVEN END } aasArea_t; // nodes of the bsp tree typedef struct aasNode_s { unsigned short planeNum; // number of the plane that splits the subspace at this node int children[2]; // child nodes, zero is solid, negative is -(area number) } aasNode_t; // cluster portal typedef struct aasPortal_s { short areaNum; // number of the area that is the actual portal short clusters[2]; // number of cluster at the front and back of the portal short clusterAreaNum[2]; // number of this portal area in the front and back cluster unsigned short maxAreaTravelTime; // maximum travel time through the portal area } aasPortal_t; // cluster typedef struct aasCluster_s { int numAreas; // number of areas in the cluster int numReachableAreas; // number of areas with reachabilities int numPortals; // number of cluster portals int firstPortal; // first cluster portal in the index } aasCluster_t; // RAVEN BEGIN // cdr: AASTactical typedef struct aasFeature_s { short x; // 2 Bytes short y; // 2 Bytes short z; // 2 Bytes unsigned short flags; // 2 Bytes unsigned char normalx; // 1 Byte unsigned char normaly; // 1 Byte unsigned char height; // 1 Byte unsigned char weight; // 1 Byte idVec3& Normal(); idVec3& Origin(); void DrawDebugInfo( int index=-1 ); int GetLookPos( idVec3& lookPos, const idVec3& aimAtOrigin, const float leanDistance=16.0f ); } aasFeature_t; //-------------------------------- // 12 Bytes // RAVEN END // trace through the world typedef struct aasTrace_s { // parameters int flags; // areas with these flags block the trace int travelFlags; // areas with these travel flags block the trace int maxAreas; // size of the 'areas' array int getOutOfSolid; // trace out of solid if the trace starts in solid // output float fraction; // fraction of trace completed idVec3 endpos; // end position of trace int planeNum; // plane hit int lastAreaNum; // number of last area the trace went through int blockingAreaNum; // area that could not be entered int numAreas; // number of areas the trace went through int * areas; // array to store areas the trace went through idVec3 * points; // points where the trace entered each new area aasTrace_s( void ) { areas = NULL; points = NULL; getOutOfSolid = false; flags = travelFlags = maxAreas = 0; } } aasTrace_t; // settings class idAASSettings { public: // collision settings int numBoundingBoxes; idBounds boundingBoxes[MAX_AAS_BOUNDING_BOXES]; bool usePatches; bool writeBrushMap; bool playerFlood; bool noOptimize; bool allowSwimReachabilities; bool allowFlyReachabilities; // RAVEN BEGIN // bkreimeier bool generateAllFaces; // cdr: AASTactical bool generateTacticalFeatures; // scork: AASOnly numbers int iAASOnly; // 0, else 32,48,96,250 or -1 for all // RAVEN END idStr fileExtension; // physics settings idVec3 gravity; idVec3 gravityDir; idVec3 invGravityDir; float gravityValue; float maxStepHeight; float maxBarrierHeight; float maxWaterJumpHeight; float maxFallHeight; float minFloorCos; // fixed travel times int tt_barrierJump; int tt_startCrouching; int tt_waterJump; int tt_startWalkOffLedge; // RAVEN BEGIN // rjohnson: added more debug drawing idVec4 debugColor; bool debugDraw; // RAVEN END public: idAASSettings( void ); bool FromFile( const idStr &fileName ); // RAVEN BEGIN // jsinger: changed to be Lexer instead of idLexer so that we have the ability to read binary files bool FromParser( Lexer &src ); // RAVEN END bool FromDict( const char *name, const idDict *dict ); bool WriteToFile( idFile *fp ) const; bool ValidForBounds( const idBounds &bounds ) const; bool ValidEntity( const char *classname, bool* needFlyReachabilities=NULL ) const; // RAVEN BEGIN float Radius( float scale=1.0f ) const; // RAVEN END private: // RAVEN BEGIN // jsinger: changed to be Lexer instead of idLexer so that we have the ability to read binary files bool ParseBool( Lexer &src, bool &b ); bool ParseInt( Lexer &src, int &i ); bool ParseFloat( Lexer &src, float &f ); bool ParseVector( Lexer &src, idVec3 &vec ); bool ParseBBoxes( Lexer &src ); // RAVEN END }; /* - when a node child is a solid leaf the node child number is zero - two adjacent areas (sharing a plane at opposite sides) share a face this face is a portal between the areas - when an area uses a face from the faceindex with a positive index then the face plane normal points into the area - the face edges are stored counter clockwise using the edgeindex - two adjacent convex areas (sharing a face) only share One face this is a simple result of the areas being convex - the areas can't have a mixture of ground and gap faces other mixtures of faces in one area are allowed - areas with the AREACONTENTS_CLUSTERPORTAL in the settings have the cluster number set to the negative portal number - edge zero is a dummy - face zero is a dummy - area zero is a dummy - node zero is a dummy - portal zero is a dummy - cluster zero is a dummy */ typedef struct sizeEstimate_s { int numEdgeIndexes; int numFaceIndexes; int numAreas; int numNodes; } sizeEstimate_t; class idAASFile { public: virtual ~idAASFile( void ) {} // RAVEN BEGIN // jscott: made pure virtual virtual class idAASFile * CreateNew( void ) = 0; virtual class idAASSettings * CreateAASSettings( void ) = 0; virtual class idReachability * CreateReachability( int type ) = 0; // RAVEN BEGIN // jsinger: changed to be Lexer instead of idLexer so that we have the ability to read binary files virtual bool FromParser( class idAASSettings *edit, Lexer &src ) = 0; // RAVEN END virtual const char * GetName( void ) const = 0; virtual unsigned int GetCRC( void ) const = 0; virtual void SetSizes( sizeEstimate_t size ) = 0; virtual int GetNumPlanes( void ) const = 0; virtual idPlane & GetPlane( int index ) = 0; virtual int FindPlane( const idPlane &plane, const float normalEps, const float distEps ) = 0; virtual int GetNumVertices( void ) const = 0; virtual aasVertex_t & GetVertex( int index ) = 0; virtual int AppendVertex( aasVertex_t &vert ) = 0; virtual int GetNumEdges( void ) const = 0; virtual aasEdge_t & GetEdge( int index ) = 0; virtual int AppendEdge( aasEdge_t &edge ) = 0; virtual int GetNumEdgeIndexes( void ) const = 0; virtual aasIndex_t & GetEdgeIndex( int index ) = 0; virtual int AppendEdgeIndex( aasIndex_t &edgeIdx ) = 0; virtual int GetNumFaces( void ) const = 0; virtual aasFace_t & GetFace( int index ) = 0; virtual int AppendFace( aasFace_t &face ) = 0; virtual int GetNumFaceIndexes( void ) const = 0; virtual aasIndex_t & GetFaceIndex( int index ) = 0; virtual int AppendFaceIndex( aasIndex_t &faceIdx ) = 0; virtual int GetNumAreas( void ) const = 0; virtual aasArea_t & GetArea( int index ) = 0; virtual int AppendArea( aasArea_t &area ) = 0; virtual int GetNumNodes( void ) const = 0; virtual aasNode_t & GetNode( int index ) = 0; virtual int AppendNode( aasNode_t &node ) = 0; virtual void SetNumNodes( int num ) = 0; virtual int GetNumPortals( void ) const = 0; virtual aasPortal_t & GetPortal( int index ) = 0; virtual int AppendPortal( aasPortal_t &portal ) = 0; virtual int GetNumPortalIndexes( void ) const = 0; virtual aasIndex_t & GetPortalIndex( int index ) = 0; virtual int AppendPortalIndex( aasIndex_t &portalIdx, int clusterNum ) = 0; virtual int GetNumClusters( void ) const = 0; virtual aasCluster_t & GetCluster( int index ) = 0; virtual int AppendCluster( aasCluster_t &cluster ) = 0; // RAVEN BEGIN // cdr: AASTactical virtual void ClearTactical( void ) = 0; virtual int GetNumFeatureIndexes( void ) const = 0; virtual aasIndex_t & GetFeatureIndex( int index ) = 0; virtual int AppendFeatureIndex( aasIndex_t &featureIdx ) = 0; virtual int GetNumFeatures( void ) const = 0; virtual aasFeature_t & GetFeature( int index ) = 0; virtual int AppendFeature( aasFeature_t &cluster ) = 0; // RAVEN END virtual idAASSettings & GetSettings( void ) = 0; virtual void SetSettings( const idAASSettings &in ) = 0; virtual void SetPortalMaxTravelTime( int index, int time ) = 0; virtual void SetAreaTravelFlag( int index, int flag ) = 0; virtual void RemoveAreaTravelFlag( int index, int flag ) = 0; // RAVEN END virtual idVec3 EdgeCenter( int edgeNum ) const = 0; virtual idVec3 FaceCenter( int faceNum ) const = 0; virtual idVec3 AreaCenter( int areaNum ) const = 0; virtual idBounds EdgeBounds( int edgeNum ) const = 0; virtual idBounds FaceBounds( int faceNum ) const = 0; virtual idBounds AreaBounds( int areaNum ) const = 0; virtual int PointAreaNum( const idVec3 &origin ) const = 0; virtual int PointReachableAreaNum( const idVec3 &origin, const idBounds &searchBounds, const int areaFlags, const int excludeTravelFlags ) const = 0; virtual int BoundsReachableAreaNum( const idBounds &bounds, const int areaFlags, const int excludeTravelFlags ) const = 0; virtual void PushPointIntoAreaNum( int areaNum, idVec3 &point ) const = 0; virtual bool Trace( aasTrace_t &trace, const idVec3 &start, const idVec3 &end ) const = 0; virtual void PrintInfo( void ) const = 0; // RAVEN BEGIN // jscott: added virtual size_t GetMemorySize( void ) = 0; virtual void Init( void ) = 0; virtual bool Load( const idStr &fileName, unsigned int mapFileCRC ) = 0; virtual bool Write( const idStr &fileName, unsigned int mapFileCRC ) = 0; virtual void Clear( void ) = 0; virtual void FinishAreas( void ) = 0; virtual void ReportRoutingEfficiency( void ) const = 0; virtual void LinkReversedReachability( void ) = 0; virtual void DeleteReachabilities( void ) = 0; virtual void DeleteClusters( void ) = 0; virtual void Optimize( void ) = 0; virtual bool IsDummyFile( unsigned int mapFileCRC ) = 0; // RAVEN END virtual const idDict & GetReachabilitySpecialDict( idReachability *reach ) const = 0; virtual void SetReachabilitySpecialDictKeyValue( idReachability *reach, const char *key, const char *value ) = 0; }; // RAVEN BEGIN extern idAASFile *AASFile; // RAVEN END #endif /* !__AASFILE_H__ */
class Category_644 { duplicate = 622; }; class Category_610 { duplicate = 622; };
#include <iostream> using namespace std; #define LONGUITUD 1002 /*** 3 4 6 .... .T.. .... */ char mapa[7][7]; // tabla para indicar terreno int R,C,K; // tamaño del terreno, renglon y columna int Caminos=0; void buscar(int r, int c , int k){ if (k>0){ if (mapa[r][c]!='x'){ /// no visitado if (mapa[r][c]!='T'){ /// que no es arbol if (r>=1 and r<=R and c>=1 and c<=C){///que sea una posicion valida if (r==1 and c==C){ /// llege al establo Caminos=Caminos+1; return ; } mapa[r][c]='x'; /// marco como visitado buscar(r+1,c,k-1); buscar(r-1,c,k-1); buscar(r,c+1,k-1); buscar(r,c-1,k-1); mapa[r][c]='.'; /// desmarco visitados para hacer busqueda exaustiva } } } } } int main() { cin >> R>> C>> K; for (int i=1; i<=R;i++){ for (int j=1; j<=C;j++){ cin >> mapa[i][j]; } } buscar(R,1, K); // dejando en miTerrreno el tamaño de mi terreno cout << Caminos<< endl; return 0; }
#include <iostream> using namespace std; int str2int(const char *str) { const char *p = str; int tmp=0; if(*str == '-'||*str == '+') { str++; } while(*str != 0) { if(*str<'0'||*str>'9') { break; } tmp = tmp*10+*str-'0'; str++; } if(*p == '-') { tmp = -tmp; } return tmp; } int main() { int n=0; char p[10]=""; cin.getline(p,10); n=str2int(p); cout<<n<<endl; char str_int[33] = "54325431"; char str_double[33]="68322.34323"; int num_int; int num_double; num_int = atoi(str_int); num_double = atof(str_double); cout<<"str2int:"<<num_int<<endl; cout<<"str2double:"<<num_double<<endl; return 0; }
/*********************************************************\ * 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. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include "VulkanRenderer/RenderTarget/RenderPass.h" #include "VulkanRenderer/VulkanRenderer.h" #include "VulkanRenderer/VulkanContext.h" #include "VulkanRenderer/Mapping.h" #include <Renderer/ILog.h> #include <Renderer/IAllocator.h> // Disable warnings in external headers, we can't fix them PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(4365) // warning C4365: 'argument': conversion from 'long' to 'unsigned int', signed/unsigned mismatch PRAGMA_WARNING_DISABLE_MSVC(4571) // warning C4571: Informational: catch(...) semantics changed since Visual C++ 7.1; structured exceptions (SEH) are no longer caught #include <vector> PRAGMA_WARNING_POP //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace VulkanRenderer { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] RenderPass::RenderPass(VulkanRenderer& vulkanRenderer, uint32_t numberOfColorAttachments, const Renderer::TextureFormat::Enum* colorAttachmentTextureFormats, Renderer::TextureFormat::Enum depthStencilAttachmentTextureFormat, uint8_t numberOfMultisamples) : IRenderPass(vulkanRenderer), mVkRenderPass(VK_NULL_HANDLE), mNumberOfColorAttachments(numberOfColorAttachments), mDepthStencilAttachmentTextureFormat(depthStencilAttachmentTextureFormat), mVkSampleCountFlagBits(Mapping::getVulkanSampleCountFlagBits(vulkanRenderer.getContext(), numberOfMultisamples)) { const bool hasDepthStencilAttachment = (Renderer::TextureFormat::Enum::UNKNOWN != depthStencilAttachmentTextureFormat); // Vulkan attachment descriptions std::vector<VkAttachmentDescription> vkAttachmentDescriptions; vkAttachmentDescriptions.resize(mNumberOfColorAttachments + (hasDepthStencilAttachment ? 1u : 0u)); uint32_t currentVkAttachmentDescriptionIndex = 0; // Handle color attachments typedef std::vector<VkAttachmentReference> VkAttachmentReferences; VkAttachmentReferences colorVkAttachmentReferences; if (mNumberOfColorAttachments > 0) { colorVkAttachmentReferences.resize(mNumberOfColorAttachments); for (uint32_t i = 0; i < mNumberOfColorAttachments; ++i) { { // Setup Vulkan color attachment references VkAttachmentReference& vkAttachmentReference = colorVkAttachmentReferences[currentVkAttachmentDescriptionIndex]; vkAttachmentReference.attachment = currentVkAttachmentDescriptionIndex; // attachment (uint32_t) vkAttachmentReference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; // layout (VkImageLayout) } { // Setup Vulkan color attachment description VkAttachmentDescription& vkAttachmentDescription = vkAttachmentDescriptions[currentVkAttachmentDescriptionIndex]; vkAttachmentDescription.flags = 0; // flags (VkAttachmentDescriptionFlags) vkAttachmentDescription.format = Mapping::getVulkanFormat(colorAttachmentTextureFormats[i]); // format (VkFormat) vkAttachmentDescription.samples = mVkSampleCountFlagBits; // samples (VkSampleCountFlagBits) vkAttachmentDescription.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; // loadOp (VkAttachmentLoadOp) vkAttachmentDescription.storeOp = VK_ATTACHMENT_STORE_OP_STORE; // storeOp (VkAttachmentStoreOp) vkAttachmentDescription.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; // stencilLoadOp (VkAttachmentLoadOp) vkAttachmentDescription.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; // stencilStoreOp (VkAttachmentStoreOp) vkAttachmentDescription.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; // initialLayout (VkImageLayout) vkAttachmentDescription.finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; // finalLayout (VkImageLayout) } // Advance current Vulkan attachment description index ++currentVkAttachmentDescriptionIndex; } } // Handle depth stencil attachments const VkAttachmentReference depthVkAttachmentReference = { currentVkAttachmentDescriptionIndex, // attachment (uint32_t) VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL // layout (VkImageLayout) }; if (hasDepthStencilAttachment) { // Setup Vulkan depth attachment description VkAttachmentDescription& vkAttachmentDescription = vkAttachmentDescriptions[currentVkAttachmentDescriptionIndex]; vkAttachmentDescription.flags = 0; // flags (VkAttachmentDescriptionFlags) vkAttachmentDescription.format = Mapping::getVulkanFormat(depthStencilAttachmentTextureFormat); // format (VkFormat) vkAttachmentDescription.samples = mVkSampleCountFlagBits; // samples (VkSampleCountFlagBits) vkAttachmentDescription.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; // loadOp (VkAttachmentLoadOp) vkAttachmentDescription.storeOp = VK_ATTACHMENT_STORE_OP_STORE; // storeOp (VkAttachmentStoreOp) vkAttachmentDescription.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; // stencilLoadOp (VkAttachmentLoadOp) vkAttachmentDescription.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; // stencilStoreOp (VkAttachmentStoreOp) vkAttachmentDescription.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; // initialLayout (VkImageLayout) vkAttachmentDescription.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; // finalLayout (VkImageLayout) // ++currentVkAttachmentDescriptionIndex; // Not needed since we're the last } // Create Vulkan create render pass const VkSubpassDescription vkSubpassDescription = { 0, // flags (VkSubpassDescriptionFlags) VK_PIPELINE_BIND_POINT_GRAPHICS, // pipelineBindPoint (VkPipelineBindPoint) 0, // inputAttachmentCount (uint32_t) nullptr, // pInputAttachments (const VkAttachmentReference*) mNumberOfColorAttachments, // colorAttachmentCount (uint32_t) (mNumberOfColorAttachments > 0) ? colorVkAttachmentReferences.data() : nullptr, // pColorAttachments (const VkAttachmentReference*) nullptr, // pResolveAttachments (const VkAttachmentReference*) hasDepthStencilAttachment ? &depthVkAttachmentReference : nullptr, // pDepthStencilAttachment (const VkAttachmentReference*) 0, // preserveAttachmentCount (uint32_t) nullptr // pPreserveAttachments (const uint32_t*) }; const std::array<VkSubpassDependency, 2> vkSubpassDependencies = {{ { VK_SUBPASS_EXTERNAL, // srcSubpass (uint32_t) 0, // dstSubpass (uint32_t) VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, // srcStageMask (VkPipelineStageFlags) VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, // dstStageMask (VkPipelineStageFlags) VK_ACCESS_MEMORY_READ_BIT, // srcAccessMask (VkAccessFlags) VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // dstAccessMask (VkAccessFlags) VK_DEPENDENCY_BY_REGION_BIT // dependencyFlags (VkDependencyFlags) }, { 0, // srcSubpass (uint32_t) VK_SUBPASS_EXTERNAL, // dstSubpass (uint32_t) VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, // srcStageMask (VkPipelineStageFlags) VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, // dstStageMask (VkPipelineStageFlags) VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // srcAccessMask (VkAccessFlags) VK_ACCESS_MEMORY_READ_BIT, // dstAccessMask (VkAccessFlags) VK_DEPENDENCY_BY_REGION_BIT // dependencyFlags (VkDependencyFlags) } }}; const VkRenderPassCreateInfo vkRenderPassCreateInfo = { VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, // sType (VkStructureType) nullptr, // pNext (const void*) 0, // flags (VkRenderPassCreateFlags) static_cast<uint32_t>(vkAttachmentDescriptions.size()), // attachmentCount (uint32_t) vkAttachmentDescriptions.data(), // pAttachments (const VkAttachmentDescription*) 1, // subpassCount (uint32_t) &vkSubpassDescription, // pSubpasses (const VkSubpassDescription*) static_cast<uint32_t>(vkSubpassDependencies.size()), // dependencyCount (uint32_t) vkSubpassDependencies.data() // pDependencies (const VkSubpassDependency*) }; const VkDevice vkDevice = vulkanRenderer.getVulkanContext().getVkDevice(); const Renderer::Context& context = vulkanRenderer.getContext(); if (vkCreateRenderPass(vkDevice, &vkRenderPassCreateInfo, vulkanRenderer.getVkAllocationCallbacks(), &mVkRenderPass) != VK_SUCCESS) { RENDERER_LOG(context, CRITICAL, "Failed to create Vulkan render pass") } } RenderPass::~RenderPass() { // Destroy Vulkan render pass instance if (VK_NULL_HANDLE != mVkRenderPass) { const VulkanRenderer& vulkanRenderer = static_cast<VulkanRenderer&>(getRenderer()); vkDestroyRenderPass(vulkanRenderer.getVulkanContext().getVkDevice(), mVkRenderPass, vulkanRenderer.getVkAllocationCallbacks()); } } //[-------------------------------------------------------] //[ Protected virtual Renderer::RefCount methods ] //[-------------------------------------------------------] void RenderPass::selfDestruct() { RENDERER_DELETE(getRenderer().getContext(), RenderPass, this); } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // VulkanRenderer
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2009-2011 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ /** * @file OpenSSLSocket.cpp * * SSL-capable socket implementation. * * @author Alexei Khlebnikov <alexeik@opera.com> * */ #include "core/pch.h" #ifdef EXTERNAL_SSL_OPENSSL_IMPLEMENTATION #include "modules/externalssl/src/openssl_impl/OpenSSLSocket.h" #include "modules/externalssl/src/openssl_impl/OpenSSLCertificate.h" #include "modules/externalssl/src/openssl_impl/OpenSSLLibrary.h" #include "modules/hardcore/mh/mh.h" #include "modules/libopeay/openssl/cryptlib.h" #include "modules/libopeay/openssl/err.h" #include "modules/url/url_socket_wrapper.h" OpenSSLSocket::OpenSSLSocket(OpSocketListener* listener, BOOL secure) : m_socket(0) , m_listener(listener) , m_secure(secure) , m_ciphers(0) , m_cipher_count(0) , m_ssl_cert_errors(CERT_BAD_CERTIFICATE) , m_ssl_ctx(0) , m_rbio(0) , m_wbio(0) , m_ssl(0) , m_peer_cert(0) , m_ssl_state(SSL_STATE_NOSSL) , m_socket_data_ready(false) , m_rbuf_pos(m_rbuf) , m_wbuf_pos(m_wbuf) , m_rbuf_len(0) , m_wbuf_len(0) { } OP_STATUS OpenSSLSocket::Init() { // Create the platform socket. OP_STATUS status = SocketWrapper::CreateTCPSocket(&m_socket, this, SocketWrapper::ALLOW_ALL_WRAPPERS); RETURN_IF_ERROR(status); // Set message callbacks. g_main_message_handler->SetCallBack(this, MSG_OPENSSL_HANDLE_BIOS, Id()); g_main_message_handler->SetCallBack(this, MSG_OPENSSL_HANDLE_NONBLOCKING, Id()); // Get library. OP_ASSERT(g_opera); void* global_data = g_opera->externalssl_module.GetGlobalData(); OP_ASSERT(global_data); OpenSSLLibrary* library = reinterpret_cast <OpenSSLLibrary*> (global_data); OP_ASSERT(library); // Get CTX. m_ssl_ctx = library->Get_SSL_CTX(); OP_ASSERT(m_ssl_ctx); return OpStatus::OK; } OpenSSLSocket::~OpenSSLSocket() { g_main_message_handler->UnsetCallBacks(this); if (m_ssl) { // These asserts must be changed to ifs if they become able to be triggered // If part of the expression starting with "||" is true - // it's probably a bug in OpenSSL. OP_ASSERT(SSL_get_wbio(m_ssl) == m_wbio || (m_ssl->bbio && m_ssl->bbio->next_bio == m_wbio)); m_wbio = 0; OP_ASSERT(SSL_get_rbio(m_ssl) == m_rbio); m_rbio = 0; // Should free BIOs as well SSL_free(m_ssl); m_ssl = 0; } // Deallocation if m_ssl failed to be created if (m_wbio) { BIO_free(m_wbio); m_wbio = 0; } if (m_rbio) { BIO_free(m_rbio); m_rbio = 0; } // Will deallocate m_peer_cert. UpdatePeerCert(); if (m_socket) { delete m_socket; m_socket = 0; } } OP_STATUS OpenSSLSocket::Connect(OpSocketAddress* socket_address) { OP_ASSERT(m_socket); return m_socket->Connect(socket_address); } OP_STATUS OpenSSLSocket::Send(const void* data, UINT length) { OP_ASSERT(m_socket); if (!m_secure) return m_socket->Send(data, length); if (!data) return OpStatus::ERR; OP_ASSERT(m_ssl); OP_ASSERT(m_listener); // No graceful handling so far when in other states. // Also prevents reentrancy. if (m_ssl_state != SSL_STATE_CONNECTED) { Unimplemented(); return OpStatus::ERR; } m_ssl_state = SSL_STATE_WRITING; // SSL_write() takes signed int. Let's check for int overflow. // When calling SSL_write() with 0 bytes to be sent, the behaviour is undefined. OP_ASSERT((int)length > 0); ERR_clear_error(); int status = SSL_write(m_ssl, data, length); OP_STATUS op_status = HandleOpenSSLReturnCode(status); if (status > 0) { OP_ASSERT(status == (int)length); m_listener->OnSocketDataSent(this, length); } return op_status; } OP_STATUS OpenSSLSocket::Recv(void* buffer, UINT length, UINT* bytes_received) { OP_ASSERT(m_socket); if (!m_secure) return m_socket->Recv(buffer, length, bytes_received); if (!buffer || !bytes_received) return OpStatus::ERR; OP_ASSERT(m_ssl); // No graceful handling so far when in other states. // Also prevents reentrancy. if (m_ssl_state != SSL_STATE_CONNECTED) { Unimplemented(); return OpStatus::ERR; } m_ssl_state = SSL_STATE_READING; // SSL_read() takes signed int. Let's check for int overflow. // When calling SSL_read() with 0 buffer size, the behaviour is undefined. OP_ASSERT((int)length > 0); ERR_clear_error(); int status = SSL_read(m_ssl, buffer, length); OP_STATUS op_status = HandleOpenSSLReturnCode(status); if (status > 0) *bytes_received = status; else *bytes_received = 0; return op_status; } void OpenSSLSocket::Close() { OP_ASSERT(m_socket); if (!m_secure) { m_socket->Close(); return; } OP_ASSERT(m_ssl); m_ssl_state = SSL_STATE_SHUTTING_DOWN; g_main_message_handler->PostMessage(MSG_OPENSSL_HANDLE_NONBLOCKING, Id(), 0); } #ifdef OPSOCKET_PAUSE_DOWNLOAD OP_STATUS OpenSSLSocket::PauseRecv() { OP_ASSERT(m_socket); return m_socket->PauseRecv(); } OP_STATUS OpenSSLSocket::ContinueRecv() { OP_ASSERT(m_socket); return m_socket->ContinueRecv(); } #endif // OPSOCKET_PAUSE_DOWNLOAD OP_STATUS OpenSSLSocket::GetSocketAddress(OpSocketAddress* socket_address) { OP_ASSERT(m_socket); return m_socket->GetSocketAddress(socket_address); } #ifdef OPSOCKET_OPTIONS OP_STATUS OpenSSLSocket::SetSocketOption(OpSocketBoolOption option, BOOL value) { OP_ASSERT(m_socket); return m_socket->SetSocketOption(option, value); } OP_STATUS OpenSSLSocket::GetSocketOption(OpSocketBoolOption option, BOOL& out_value) { OP_ASSERT(m_socket); return m_socket->GetSocketOption(option, out_value); } #endif // OPSOCKET_OPTIONS OP_STATUS OpenSSLSocket::UpgradeToSecure() { OP_ASSERT(m_ssl_ctx); m_secure = TRUE; // RBIO if (!m_rbio) m_rbio = BIO_new(BIO_s_mem()); if (!m_rbio) return OpStatus::ERR; // WBIO if (!m_wbio) m_wbio = BIO_new(BIO_s_mem()); if (!m_wbio) return OpStatus::ERR; // SSL if (!m_ssl) m_ssl = SSL_new(m_ssl_ctx); if (!m_ssl) return OpStatus::ERR; // Clear state if the socket is reused, no-op otherwise ClearSSL(); // Connect objects to each other SSL_set_bio(m_ssl, m_rbio, m_wbio); // Handshaking SSL_set_connect_state(m_ssl); m_ssl_state = SSL_STATE_HANDSHAKING; g_main_message_handler->PostMessage(MSG_OPENSSL_HANDLE_NONBLOCKING, Id(), 0); return OpStatus::OK; } OP_STATUS OpenSSLSocket::SetSecureCiphers(const cipherentry_st* ciphers, UINT cipher_count) { m_ciphers = ciphers; m_cipher_count = cipher_count; return OpStatus::OK; } OP_STATUS OpenSSLSocket::AcceptInsecureCertificate(OpCertificate* cert) { //Force hitting the breakpoint. Unimplemented(); if (m_ssl_state != SSL_STATE_ASKING_USER || !cert || !m_peer_cert) return OpStatus::ERR; unsigned int length; const char* cert_hash = cert->GetCertificateHash(length); OP_ASSERT(cert_hash); OP_ASSERT(length == SHA_DIGEST_LENGTH); // Compare hashes. int res = op_memcmp(cert_hash, m_peer_cert->sha1_hash, SHA_DIGEST_LENGTH); // Main decision. if (res == 0) { m_ssl_state = SSL_STATE_CONNECTED; return OpStatus::OK; } else { m_ssl_cert_errors = CERT_DIFFERENT_CERTIFICATE; return OpStatus::ERR; } } OP_STATUS OpenSSLSocket::GetCurrentCipher(cipherentry_st* used_cipher, BOOL* tls_v1_used, UINT32* pk_keysize) { if (!used_cipher || !tls_v1_used || !pk_keysize || !m_ciphers) return OpStatus::ERR_NULL_POINTER; if (m_ssl_state != SSL_STATE_CONNECTED) return OpStatus::ERR; OP_ASSERT(m_cipher_count > 0); OP_ASSERT(m_secure); OP_ASSERT(m_ssl); const SSL_CIPHER* ssl_cipher = SSL_get_current_cipher(m_ssl); OP_ASSERT(ssl_cipher); // m_ssl owns ssl_cipher. // Get 2-byte cipher id cipherentry_st id; id.id[0] = (ssl_cipher->id >> 8) & 0xFF; id.id[1] = ssl_cipher->id & 0xFF; // Search for the used cipher UINT cipher_num = 0; for (; cipher_num < m_cipher_count; cipher_num++) { const cipherentry_st& cipher = m_ciphers[cipher_num]; if (cipher.id[0] == id.id[0] && cipher.id[1] == id.id[1]) { // Found used_cipher->id[0] = id.id[0]; used_cipher->id[1] = id.id[1]; break; } } // Cipher is unknown - set used_cipher to zeros if (cipher_num == m_cipher_count) { used_cipher->id[0] = 0; used_cipher->id[1] = 0; } // Detect if TLSv1 is used const char* ssl_protocol_version = SSL_get_version(m_ssl); OP_ASSERT(ssl_protocol_version); // ssl_protocol_version is not owned, it's a pointer to a string literal. if (!op_strcmp(ssl_protocol_version, "TLSv1")) *tls_v1_used = TRUE; else *tls_v1_used = FALSE; // Detect key size *pk_keysize = 0; // m_peer_cert should be filled now because UpdatePeerCert() // should have been called just after the handshake. if (m_peer_cert) { EVP_PKEY* peer_pubkey = X509_get_pubkey(m_peer_cert); if (peer_pubkey) { // We own peer_pubkey. // Get public key size in bits. *pk_keysize = EVP_PKEY_bits(peer_pubkey); EVP_PKEY_free(peer_pubkey); } } return OpStatus::OK; } OP_STATUS OpenSSLSocket::SetServerName(const uni_char* server_name) { OP_STATUS status = m_server_name.Set(server_name); return status; } OpCertificate* OpenSSLSocket::ExtractCertificate() { // Will gracefully fail and return 0 if m_peer_cert == 0. OpCertificate* op_cert = OpenSSLCertificate::Create(m_peer_cert); if (!op_cert) m_ssl_cert_errors = CERT_BAD_CERTIFICATE; return op_cert; } OpAutoVector<OpCertificate>* OpenSSLSocket::ExtractCertificateChain() { if (!m_ssl) return 0; // Get certificate chain. STACK_OF(X509)* x509_stack = SSL_get_peer_cert_chain(m_ssl); if (!x509_stack) return 0; // m_ssl owns x509_stack. int x509_count = sk_X509_num(x509_stack); OP_ASSERT(x509_count >= 0); OpAutoVector<OpCertificate>* chain = OP_NEW(OpAutoVector<OpCertificate>, (x509_count)); if (!chain) return 0; for (int i = 0; i < x509_count; i++) { X509* x509 = sk_X509_value(x509_stack, i); OP_ASSERT(x509); // x509_stack owns x509. OpCertificate* op_cert = OpenSSLCertificate::Create(x509); if (!op_cert) { OP_DELETE(chain); return 0; } OP_STATUS status = chain->Add(op_cert); if (status != OpStatus::OK) { OP_DELETE(op_cert); OP_DELETE(chain); return 0; } } return chain; } void OpenSSLSocket::OnSocketConnected(OpSocket* socket) { OP_ASSERT(socket == m_socket); OP_ASSERT(m_listener); if (!m_secure) { m_listener->OnSocketConnected(this); return; } UpgradeToSecure(); } void OpenSSLSocket::OnSocketDataReady(OpSocket* socket) { OP_ASSERT(socket == m_socket); OP_ASSERT(m_listener); if (!m_secure) { m_listener->OnSocketDataReady(this); return; } m_socket_data_ready = true; g_main_message_handler->PostMessage(MSG_OPENSSL_HANDLE_BIOS, Id(), 0); } void OpenSSLSocket::OnSocketDataSent(OpSocket* socket, UINT bytes_sent) { OP_ASSERT(socket == m_socket); OP_ASSERT(m_listener); if (!m_secure) { m_listener->OnSocketDataSent(this, bytes_sent); return; } switch (m_ssl_state) { case SSL_STATE_HANDSHAKING: case SSL_STATE_SHUTTING_DOWN: // Do nothing break; case SSL_STATE_CONNECTED: // 0 because the amount of data is already accounted // in OpenSSLSocket::Send() m_listener->OnSocketDataSent(this, 0); g_main_message_handler->PostMessage(MSG_OPENSSL_HANDLE_BIOS, Id(), 0); break; default: // Shouldn't happen Unimplemented(); } return; } void OpenSSLSocket::OnSocketClosed(OpSocket* socket) { OP_ASSERT(socket == m_socket); OP_ASSERT(m_listener); if (m_secure) ClearSSL(); m_listener->OnSocketClosed(this); } void OpenSSLSocket::OnSocketConnectError(OpSocket* socket, OpSocket::Error error) { OP_ASSERT(socket == m_socket); OP_ASSERT(m_listener); OP_ASSERT(m_ssl_state == SSL_STATE_NOSSL); m_listener->OnSocketConnectError(this, error); } void OpenSSLSocket::OnSocketReceiveError(OpSocket* socket, OpSocket::Error error) { OP_ASSERT(socket == m_socket); OP_ASSERT(m_listener); m_listener->OnSocketReceiveError(this, error); } void OpenSSLSocket::OnSocketSendError(OpSocket* socket, OpSocket::Error error) { OP_ASSERT(socket == m_socket); OP_ASSERT(m_listener); m_listener->OnSocketSendError(this, error); } void OpenSSLSocket::OnSocketCloseError(OpSocket* socket, OpSocket::Error error) { OP_ASSERT(socket == m_socket); OP_ASSERT(m_listener); m_listener->OnSocketCloseError(this, error); } void OpenSSLSocket::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { switch (msg) { case MSG_OPENSSL_HANDLE_BIOS: HandleOpenSSLBIOs(); break; case MSG_OPENSSL_HANDLE_NONBLOCKING: HandleOpenSSLNonBlocking(); break; default: Unimplemented(); } } OP_STATUS OpenSSLSocket::HandleOpenSSLReturnCode(int status) { OP_ASSERT(m_ssl); int err = SSL_get_error(m_ssl, status); OP_STATUS opst = OpStatus::ERR; if (status > 0) { // Something good OP_ASSERT(err == SSL_ERROR_NONE); opst = HandleOpenSSLPositiveReturnCode(status); } else { // Something bad or operation in progress OP_ASSERT(err != SSL_ERROR_NONE); opst = HandleOpenSSLNegativeReturnCode(status, err); } ERR_clear_error(); return opst; } OP_STATUS OpenSSLSocket::HandleOpenSSLPositiveReturnCode(int status) { OP_ASSERT(status > 0); OP_ASSERT(g_main_message_handler); OP_ASSERT(m_listener); OP_ASSERT(m_socket); OP_ASSERT(m_ssl); switch (m_ssl_state) { case SSL_STATE_HANDSHAKING: OP_ASSERT(status == 1); // It will also get the verification info. UpdatePeerCert(); // Based on the verification info, decide if handshaking // can be finished. { if (m_ssl_cert_errors == SSL_NO_ERROR) { m_ssl_state = SSL_STATE_CONNECTED; m_listener->OnSocketConnected(this); } else { m_ssl_state = SSL_STATE_ASKING_USER; m_listener->OnSocketConnectError(this, SECURE_CONNECTION_FAILED); } } break; case SSL_STATE_READING: case SSL_STATE_WRITING: g_main_message_handler->PostMessage(MSG_OPENSSL_HANDLE_BIOS, Id(), 0); m_ssl_state = SSL_STATE_CONNECTED; break; case SSL_STATE_SHUTTING_DOWN: OP_ASSERT(status == 1); m_ssl_state = SSL_STATE_NOSSL; UpdatePeerCert(); m_socket->Close(); break; default: // Shouldn't happen Unimplemented(); } return OpStatus::OK; } OP_STATUS OpenSSLSocket::HandleOpenSSLNegativeReturnCode(int status, int err) { OP_ASSERT(status <= 0); OP_ASSERT(g_main_message_handler); OP_ASSERT(m_listener); OP_ASSERT(m_socket); OP_ASSERT(m_ssl); switch (err) { case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: { // Need an operation on a non-blocking socket g_main_message_handler->PostMessage(MSG_OPENSSL_HANDLE_BIOS, Id(), 0); switch (m_ssl_state) { case SSL_STATE_HANDSHAKING: case SSL_STATE_SHUTTING_DOWN: // Do nothing, let BIOs be handled break; case SSL_STATE_READING: m_listener->OnSocketReceiveError(this, SOCKET_BLOCKING); m_ssl_state = SSL_STATE_CONNECTED; break; case SSL_STATE_WRITING: m_listener->OnSocketSendError(this, SOCKET_BLOCKING); m_ssl_state = SSL_STATE_CONNECTED; break; default: // Shouldn't happen Unimplemented(); } break; } // Graceful SSL shutdown case SSL_ERROR_ZERO_RETURN: { OP_ASSERT(status == 0); switch (m_ssl_state) { case SSL_STATE_HANDSHAKING: m_listener->OnSocketConnectError(this, SECURE_CONNECTION_FAILED); break; case SSL_STATE_READING: m_listener->OnSocketReceiveError(this, SOCKET_BLOCKING); break; default: // Shouldn't happen Unimplemented(); } m_ssl_state = SSL_STATE_SHUTTING_DOWN; g_main_message_handler->PostMessage(MSG_OPENSSL_HANDLE_NONBLOCKING, Id(), 0); break; } case SSL_ERROR_SSL: case SSL_ERROR_SYSCALL: { switch (m_ssl_state) { case SSL_STATE_HANDSHAKING: m_listener->OnSocketConnectError(this, SECURE_CONNECTION_FAILED); break; case SSL_STATE_READING: m_listener->OnSocketReceiveError(this, NETWORK_ERROR); break; case SSL_STATE_WRITING: m_listener->OnSocketSendError(this, NETWORK_ERROR); break; case SSL_STATE_SHUTTING_DOWN: // Do nothing, ignore unsuccessful SSL shutdown break; default: // Shouldn't happen Unimplemented(); } // Do not leak resources - do abortive close m_socket->Close(); break; } default: { // An unhandled error occured Unimplemented(); switch (m_ssl_state) { // Do not leak resources - do abortive close case SSL_STATE_SHUTTING_DOWN: m_socket->Close(); break; } } } return OpStatus::ERR; } void OpenSSLSocket::HandleOpenSSLBIOs() { HandleOpenSSLRBIO(); HandleOpenSSLWBIO(); OP_ASSERT(m_rbio); int rbio_pending = BIO_pending(m_rbio); if (m_ssl_state == SSL_STATE_CONNECTED && rbio_pending > 0) m_listener->OnSocketDataReady(this); } void OpenSSLSocket::PrepareBuffer(char* buf, char* buf_pos, int buf_len, char*& buf_end, char*& buf_free_pos, int& buf_free_len) { OP_ASSERT(buf); OP_ASSERT(buf_pos); OP_ASSERT(buf_pos >= buf); OP_ASSERT(buf_len >= 0); // Pointer to the first byte after the buffer buf_end = buf + OPENSSL_SOCKET_BUFFER_SIZE; OP_ASSERT(buf_pos <= buf_end); // Pointer to the first "free" byte of the buffer buf_free_pos = buf_pos + buf_len; OP_ASSERT(buf_free_pos <= buf_end); // Length of "free" buffer space buf_free_len = buf_end - buf_free_pos; OP_ASSERT(buf_free_len >= 0); } void OpenSSLSocket::HandleOpenSSLRBIO() { OP_ASSERT(m_rbio); OP_ASSERT(m_socket); if (m_socket_data_ready) { // Prepare buffer char* rbuf_end = 0; char* rbuf_free_pos = 0; int rbuf_free_len = 0; PrepareBuffer(m_rbuf, m_rbuf_pos, m_rbuf_len, rbuf_end, rbuf_free_pos, rbuf_free_len); if (rbuf_free_len > 0) { UINT bytes_read = 0; // Read from socket OP_STATUS status = m_socket->Recv(rbuf_free_pos, rbuf_free_len, &bytes_read); if (status == OpStatus::OK) { if (bytes_read > 0) m_rbuf_len += bytes_read; else m_socket_data_ready = false; } OP_ASSERT(m_rbuf_pos + m_rbuf_len == rbuf_free_pos + bytes_read); } OP_ASSERT(m_rbuf_pos + m_rbuf_len <= rbuf_end); if (m_rbuf_len > 0) { // Buffer space available // Write to BIO int bytes_written = BIO_write(m_rbio, m_rbuf_pos, m_rbuf_len); OP_ASSERT(bytes_written <= m_rbuf_len); if (bytes_written > 0) { m_rbuf_pos += bytes_written; m_rbuf_len -= bytes_written; OP_ASSERT(m_rbuf_len >= 0); OP_ASSERT(m_rbuf_pos + m_rbuf_len <= rbuf_end); if (m_rbuf_len == 0) // Buffer is empty m_rbuf_pos = m_rbuf; g_main_message_handler->PostMessage( MSG_OPENSSL_HANDLE_NONBLOCKING, Id(), 0); m_listener->OnSocketDataReady(this); } } } } void OpenSSLSocket::HandleOpenSSLWBIO() { OP_ASSERT(m_wbio); OP_ASSERT(m_socket); int wbio_pending = BIO_pending(m_wbio); if (wbio_pending > 0) { // Prepare buffer char* wbuf_end = 0; char* wbuf_free_pos = 0; int wbuf_free_len = 0; PrepareBuffer(m_wbuf, m_wbuf_pos, m_wbuf_len, wbuf_end, wbuf_free_pos, wbuf_free_len); if (wbuf_free_len > 0) { // Buffer space available if (wbio_pending > wbuf_free_len) wbio_pending = wbuf_free_len; // Read from BIO int bytes_read = BIO_read(m_wbio, wbuf_free_pos, wbio_pending); OP_ASSERT(bytes_read <= wbio_pending); if (bytes_read > 0) m_wbuf_len += bytes_read; OP_ASSERT(m_wbuf_pos + m_wbuf_len == wbuf_free_pos + bytes_read); } OP_ASSERT(m_wbuf_pos + m_wbuf_len <= wbuf_end); if (m_wbuf_len) { // Write to socket OP_STATUS status = m_socket->Send(m_wbuf_pos, m_wbuf_len); if (status == OpStatus::OK) { // Buffer is empty m_wbuf_pos = m_wbuf; m_wbuf_len = 0; g_main_message_handler->PostMessage( MSG_OPENSSL_HANDLE_NONBLOCKING, Id(), 0); } } } } void OpenSSLSocket::HandleOpenSSLNonBlocking() { OP_ASSERT(m_ssl); switch (m_ssl_state) { case SSL_STATE_HANDSHAKING: { ERR_clear_error(); int status = SSL_do_handshake(m_ssl); HandleOpenSSLReturnCode(status); break; } case SSL_STATE_NOSSL: case SSL_STATE_CONNECTED: case SSL_STATE_READING: case SSL_STATE_WRITING: // Do nothing break; case SSL_STATE_SHUTTING_DOWN: { ERR_clear_error(); int status = SSL_shutdown(m_ssl); HandleOpenSSLReturnCode(status); break; } default: Unimplemented(); } } void OpenSSLSocket::UpdatePeerCert() { // This function relies on the fact that the peer certificate pointer // inside m_ssl remains unchanged for the whole time of SSL/TLS session. X509* peer_cert = 0; if(m_ssl) peer_cert = SSL_get_peer_certificate(m_ssl); if (peer_cert == m_peer_cert) // Already up-to-date, including the case when both pointers are 0. return; if (m_peer_cert) // m_peer_cert is a leftover from the previous SSL session. X509_free(m_peer_cert); // Updating the pointer. Correct behaviour in (peer_cert == 0) case. m_peer_cert = peer_cert; // Set to CERT_BAD_CERTIFICATE until the opposite is proven. m_ssl_cert_errors = CERT_BAD_CERTIFICATE; if (!m_peer_cert) return; // Update certificate hash. unsigned int len = 0; int res = X509_digest(m_peer_cert, EVP_sha1(), m_peer_cert->sha1_hash, &len); if (res == 0) { // Hash calculation failure. It's probably an OOM problem. // In this case it will probably not be enough memory // for normal further work. Cert comparison can't work. // This case is very rare. m_peer_cert = 0; return; } // Hash calculation successful. OP_ASSERT(res == 1); OP_ASSERT(len == SHA_DIGEST_LENGTH); UpdatePeerCertVerification(); } void OpenSSLSocket::UpdatePeerCertVerification() { // Hack: always allow the connection, because the dialog asking for // bad certificate confirmation is still not implemented. // Ifdef out these lines if you want to perform certificate verification. #if 1 m_ssl_cert_errors = SSL_NO_ERROR; return; #endif // Called only from UpdatePeerCert(). Thus the following must be true: OP_ASSERT(m_ssl); OP_ASSERT(m_peer_cert); OP_ASSERT(m_ssl_cert_errors == CERT_BAD_CERTIFICATE); // Check cert name. // Get subject from cert. X509_NAME* x509_name = X509_get_subject_name(m_peer_cert); OP_ASSERT(x509_name); // m_peer_cert owns x509_name. // Max hostname length is 255, according to RFC 2181. const int MAX_HOSTNAME_LENGTH = 255; char data[MAX_HOSTNAME_LENGTH + 1]; /* ARRAY OK 2009-10-05 alexeik */ // Get CN from subject. int res = X509_NAME_get_text_by_NID(x509_name, NID_commonName, data, MAX_HOSTNAME_LENGTH + 1); if (res <= 0) // No CN or empty CN. return; // Compare server name with CN. OP_ASSERT(m_server_name.HasContent()); OP_ASSERT(res <= MAX_HOSTNAME_LENGTH); if (m_server_name.CompareI(data, res) != 0) // CN is not the same as the server name. return; // Get verification result and update m_ssl_cert_errors. long verify_result = SSL_get_verify_result(m_ssl); switch (verify_result) { case X509_V_OK: // The following 7 codes are unused according to man verify(1ssl). // These are CRL issues. They do not necessary invalidate the certificate. case X509_V_ERR_UNABLE_TO_GET_CRL: case X509_V_ERR_CRL_SIGNATURE_FAILURE: case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE: case X509_V_ERR_CRL_NOT_YET_VALID: case X509_V_ERR_CRL_HAS_EXPIRED: case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD: case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD: m_ssl_cert_errors = SSL_NO_ERROR; break; case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY: case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: case X509_V_ERR_CERT_CHAIN_TOO_LONG: case X509_V_ERR_INVALID_CA: case X509_V_ERR_CERT_UNTRUSTED: case X509_V_ERR_CERT_REJECTED: case X509_V_ERR_SUBJECT_ISSUER_MISMATCH: case X509_V_ERR_AKID_SKID_MISMATCH: case X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH: case X509_V_ERR_KEYUSAGE_NO_CERTSIGN: m_ssl_cert_errors = CERT_INCOMPLETE_CHAIN; break; case X509_V_ERR_CERT_NOT_YET_VALID: case X509_V_ERR_CERT_HAS_EXPIRED: case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: m_ssl_cert_errors = CERT_EXPIRED; break; case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE: case X509_V_ERR_CERT_SIGNATURE_FAILURE: case X509_V_ERR_OUT_OF_MEM: case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: case X509_V_ERR_CERT_REVOKED: case X509_V_ERR_PATH_LENGTH_EXCEEDED: case X509_V_ERR_INVALID_PURPOSE: case X509_V_ERR_APPLICATION_VERIFICATION: default: // Already set. OP_ASSERT(m_ssl_cert_errors == CERT_BAD_CERTIFICATE); //m_ssl_cert_errors = CERT_BAD_CERTIFICATE; break; } } void OpenSSLSocket::ClearSSL() { OP_ASSERT(m_secure); OP_ASSERT(m_ssl); OP_ASSERT(m_rbio); OP_ASSERT(m_wbio); int err = SSL_clear(m_ssl); OP_ASSERT(err == 1); err = BIO_reset(m_rbio); OP_ASSERT(err == 1); err = BIO_reset(m_wbio); OP_ASSERT(err == 1); // Suppress warning about unused variable. (void)err; m_rbuf_len = 0; m_wbuf_len = 0; m_ssl_state = SSL_STATE_NOSSL; UpdatePeerCert(); } void OpenSSLSocket::Unimplemented() { // Set breakpoint here OP_ASSERT(!"OpenSSLSocket::Unimplemented() called! Get the stack trace and see what's not implemented."); } #endif // EXTERNAL_SSL_OPENSSL_IMPLEMENTATION
#include <bits/stdc++.h> using namespace std; int main() { int a,c,b,d; while(scanf("%d %d",&a,&b)!=EOF){ if(a==0 && b==0) break; c=sqrt(a); d=sqrt(b); //if(c*c==a) // printf("%d\n",c); // else if(c*c==a) printf("%d\n",d-c+1); else printf("%d\n",d-c); } return 0; }
/* This class is the master ancestor class. Anything that is brought into existance by the resource * manager class. The resource manager will maintain UUIDs that can be used for global reference of * any object. so this includes Meshes, materials, cameras, buffers, etc. It is worth noteing that * some objects may have more than one object in them. any time there is an object that has a HAS-A * relationship with another object, then it will have sub objects. some IS-A relationships will * also have subobjects. I can't actually think of an example of that right now, so I'm going to * for now assume that the only something can have a subobject is in a HAS-A relationship, like how * a mesh HAS-A material. */ #ifndef OBJECT_CPP #define OBJECT_CPP #include "Object.h" Object::Object() { ID = 0; } Object::~Object() { ID = 0; } UID Object::getID() { return ID; } bool Object::onEvent(const Event& event) { TRACE(5); return false;//there isn't anything I can really think an object can do by itself. //it kind of needs to know about the resource manager to be able to self destruct. //so I'm just going to say that object never handles anything. } /*.S.D.G.*/ #endif
// Created on: 1996-06-06 // Created by: Philippe MANGIN // Copyright (c) 1996-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 _GeomConvert_CompBezierSurfacesToBSplineSurface_HeaderFile #define _GeomConvert_CompBezierSurfacesToBSplineSurface_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Integer.hxx> #include <TColStd_HArray1OfInteger.hxx> #include <TColStd_HArray1OfReal.hxx> #include <TColgp_HArray2OfPnt.hxx> #include <TColGeom_Array2OfBezierSurface.hxx> #include <TColStd_Array1OfReal.hxx> #include <GeomAbs_Shape.hxx> //! An algorithm to convert a grid of adjacent //! non-rational Bezier surfaces (with continuity CM) into a //! BSpline surface (with continuity CM). //! A CompBezierSurfacesToBSplineSurface object //! provides a framework for: //! - defining the grid of adjacent Bezier surfaces //! which is to be converted into a BSpline surface, //! - implementing the computation algorithm, and //! - consulting the results. //! Warning //! Do not attempt to convert rational Bezier surfaces using such an algorithm. //! Input is array of Bezier patch //! 1 2 3 4 -> VIndex [1, NbVPatches] -> VDirection //! ----------------------- //! 1 | | | | | //! ----------------------- //! 2 | | | | | //! ----------------------- //! 3 | | | | | //! ----------------------- //! UIndex [1, NbUPatches] Udirection //! //! Warning! Patches must have compatible parametrization class GeomConvert_CompBezierSurfacesToBSplineSurface { public: DEFINE_STANDARD_ALLOC //! Computes all the data needed to build a "C0" //! continuous BSpline surface equivalent to the grid of //! adjacent non-rational Bezier surfaces Beziers. //! Each surface in the Beziers grid becomes a natural //! patch, limited by knots values, on the BSpline surface //! whose data is computed. Surfaces in the grid must //! satisfy the following conditions: //! - Coincident bounding curves between two //! consecutive surfaces in a row of the Beziers grid //! must be u-isoparametric bounding curves of these two surfaces. //! - Coincident bounding curves between two //! consecutive surfaces in a column of the Beziers //! grid must be v-isoparametric bounding curves of these two surfaces. //! The BSpline surface whose data is computed has the //! following characteristics: //! - Its degree in the u (respectively v) parametric //! direction is equal to that of the Bezier surface //! which has the highest degree in the u //! (respectively v) parametric direction in the Beziers grid. //! - It is a "Piecewise Bezier" in both u and v //! parametric directions, i.e.: //! - the knots are regularly spaced in each //! parametric direction (i.e. the difference between //! two consecutive knots is a constant), and //! - all the multiplicities of the surface knots in a //! given parametric direction are equal to //! Degree, which is the degree of the BSpline //! surface in this parametric direction, except for //! the first and last knots for which the multiplicity is //! equal to Degree + 1. //! - Coincident bounding curves between two //! consecutive columns of Bezier surfaces in the //! Beziers grid become u-isoparametric curves, //! corresponding to knots values of the BSpline surface. //! - Coincident bounding curves between two //! consecutive rows of Bezier surfaces in the Beziers //! grid become v-isoparametric curves //! corresponding to knots values of the BSpline surface. //! Use the available consultation functions to access the //! computed data. This data may be used to construct the BSpline surface. //! Warning //! The surfaces in the Beziers grid must be adjacent, i.e. //! two consecutive Bezier surfaces in the grid (in a row //! or column) must have a coincident bounding curve. In //! addition, the location of the parameterization on each //! of these surfaces (i.e. the relative location of u and v //! isoparametric curves on the surface) is of importance //! with regard to the positioning of the surfaces in the //! Beziers grid. Care must be taken with respect to the //! above, as these properties are not checked and an //! error may occur if they are not satisfied. //! Exceptions //! Standard_NotImplemented if one of the Bezier //! surfaces of the Beziers grid is rational. Standard_EXPORT GeomConvert_CompBezierSurfacesToBSplineSurface(const TColGeom_Array2OfBezierSurface& Beziers); //! Build an Ci uniform (Rational) BSpline surface //! The highest Continuity Ci is imposed, like the //! maximal deformation is lower than <Tolerance>. //! Warning: The Continuity C0 is imposed without any check. Standard_EXPORT GeomConvert_CompBezierSurfacesToBSplineSurface(const TColGeom_Array2OfBezierSurface& Beziers, const Standard_Real Tolerance, const Standard_Boolean RemoveKnots = Standard_True); //! Computes all the data needed to construct a BSpline //! surface equivalent to the adjacent non-rational //! Bezier surfaces Beziers grid. //! Each surface in the Beziers grid becomes a natural //! patch, limited by knots values, on the BSpline surface //! whose data is computed. Surfaces in the grid must //! satisfy the following conditions: //! - Coincident bounding curves between two //! consecutive surfaces in a row of the Beziers grid //! must be u-isoparametric bounding curves of these two surfaces. //! - Coincident bounding curves between two //! consecutive surfaces in a column of the Beziers //! grid must be v-isoparametric bounding curves of these two surfaces. //! The BSpline surface whose data is computed has the //! following characteristics: //! - Its degree in the u (respectively v) parametric //! direction is equal to that of the Bezier surface //! which has the highest degree in the u //! (respectively v) parametric direction in the Beziers grid. //! - Coincident bounding curves between two //! consecutive columns of Bezier surfaces in the //! Beziers grid become u-isoparametric curves //! corresponding to knots values of the BSpline surface. //! - Coincident bounding curves between two //! consecutive rows of Bezier surfaces in the Beziers //! grid become v-isoparametric curves //! corresponding to knots values of the BSpline surface. //! Knots values of the BSpline surface are given in the two tables: //! - UKnots for the u parametric direction (which //! corresponds to the order of Bezier surface columns in the Beziers grid), and //! - VKnots for the v parametric direction (which //! corresponds to the order of Bezier surface rows in the Beziers grid). //! The dimensions of UKnots (respectively VKnots) //! must be equal to the number of columns (respectively, //! rows) of the Beziers grid, plus 1 . //! UContinuity and VContinuity, which are both //! defaulted to GeomAbs_C0, specify the required //! continuity on the BSpline surface. If the required //! degree of continuity is greater than 0 in a given //! parametric direction, a deformation is applied locally //! on the initial surface (as defined by the Beziers grid) //! to satisfy this condition. This local deformation is not //! applied however, if it is greater than Tolerance //! (defaulted to 1.0 e-7). In such cases, the //! continuity condition is not satisfied, and the function //! IsDone will return false. A small tolerance value //! prevents any modification of the surface and a large //! tolerance value "smoothes" the surface. //! Use the available consultation functions to access the //! computed data. This data may be used to construct the BSpline surface. //! Warning //! The surfaces in the Beziers grid must be adjacent, i.e. //! two consecutive Bezier surfaces in the grid (in a row //! or column) must have a coincident bounding curve. In //! addition, the location of the parameterization on each //! of these surfaces (i.e. the relative location of u and v //! isoparametric curves on the surface) is of importance //! with regard to the positioning of the surfaces in the //! Beziers grid. Care must be taken with respect to the //! above, as these properties are not checked and an //! error may occur if they are not satisfied. //! Exceptions //! Standard_DimensionMismatch: //! - if the number of knots in the UKnots table (i.e. the //! length of the UKnots array) is not equal to the //! number of columns of Bezier surfaces in the //! Beziers grid plus 1, or //! - if the number of knots in the VKnots table (i.e. the //! length of the VKnots array) is not equal to the //! number of rows of Bezier surfaces in the Beziers grid, plus 1. //! Standard_ConstructionError: //! - if UContinuity and VContinuity are not equal to //! one of the following values: GeomAbs_C0, //! GeomAbs_C1, GeomAbs_C2 and GeomAbs_C3; or //! - if the number of columns in the Beziers grid is //! greater than 1, and the required degree of //! continuity in the u parametric direction is greater //! than that of the Bezier surface with the highest //! degree in the u parametric direction (in the Beziers grid), minus 1; or //! - if the number of rows in the Beziers grid is //! greater than 1, and the required degree of //! continuity in the v parametric direction is greater //! than that of the Bezier surface with the highest //! degree in the v parametric direction (in the Beziers grid), minus 1 . //! Standard_NotImplemented if one of the Bezier //! surfaces in the Beziers grid is rational. Standard_EXPORT GeomConvert_CompBezierSurfacesToBSplineSurface(const TColGeom_Array2OfBezierSurface& Beziers, const TColStd_Array1OfReal& UKnots, const TColStd_Array1OfReal& VKnots, const GeomAbs_Shape UContinuity = GeomAbs_C0, const GeomAbs_Shape VContinuity = GeomAbs_C0, const Standard_Real Tolerance = 1.0e-4); //! Returns the number of knots in the U direction //! of the BSpline surface whose data is computed in this framework. Standard_Integer NbUKnots() const; //! Returns number of poles in the U direction //! of the BSpline surface whose data is computed in this framework. Standard_Integer NbUPoles() const; //! Returns the number of knots in the V direction //! of the BSpline surface whose data is computed in this framework. Standard_Integer NbVKnots() const; //! Returns the number of poles in the V direction //! of the BSpline surface whose data is computed in this framework. Standard_Integer NbVPoles() const; //! Returns the table of poles of the BSpline surface //! whose data is computed in this framework. const Handle(TColgp_HArray2OfPnt)& Poles() const; //! Returns the knots table for the u parametric //! direction of the BSpline surface whose data is computed in this framework. const Handle(TColStd_HArray1OfReal)& UKnots() const; //! Returns the degree for the u parametric //! direction of the BSpline surface whose data is computed in this framework. Standard_Integer UDegree() const; //! Returns the knots table for the v parametric //! direction of the BSpline surface whose data is computed in this framework. const Handle(TColStd_HArray1OfReal)& VKnots() const; //! Returns the degree for the v parametric //! direction of the BSpline surface whose data is computed in this framework. Standard_Integer VDegree() const; //! Returns the multiplicities table for the u //! parametric direction of the knots of the BSpline //! surface whose data is computed in this framework. const Handle(TColStd_HArray1OfInteger)& UMultiplicities() const; //! -- Returns the multiplicities table for the v //! parametric direction of the knots of the BSpline //! surface whose data is computed in this framework. const Handle(TColStd_HArray1OfInteger)& VMultiplicities() const; //! Returns true if the conversion was successful. //! Unless an exception was raised at the time of //! construction, the conversion of the Bezier surface //! grid assigned to this algorithm is always carried out. //! IsDone returns false if the constraints defined at the //! time of construction cannot be respected. This occurs //! when there is an incompatibility between a required //! degree of continuity on the BSpline surface, and the //! maximum tolerance accepted for local deformations //! of the surface. In such a case the computed data //! does not satisfy all the initial constraints. Standard_EXPORT Standard_Boolean IsDone() const; protected: private: //! It used internally by the constructors. Standard_EXPORT void Perform (const TColGeom_Array2OfBezierSurface& Beziers); Standard_Integer myUDegree; Standard_Integer myVDegree; Handle(TColStd_HArray1OfInteger) myVMults; Handle(TColStd_HArray1OfInteger) myUMults; Handle(TColStd_HArray1OfReal) myUKnots; Handle(TColStd_HArray1OfReal) myVKnots; Handle(TColgp_HArray2OfPnt) myPoles; Standard_Boolean isrational; Standard_Boolean myDone; }; #include <GeomConvert_CompBezierSurfacesToBSplineSurface.lxx> #endif // _GeomConvert_CompBezierSurfacesToBSplineSurface_HeaderFile
// 0922_7.cpp : 定义控制台应用程序的入口点。 //求平均成绩 //假设一个班有n(n<=50)个学生,每人考m(m<=5)门课, //求每个学生的平均成绩和每门课的平均成绩,并输出各科成绩均大于等于平均成绩的学生数量。 //n和m,分别表示学生数和课程数。然后是n行数据,每行包括m个整数(即:考试分数)。 #include <iostream> using namespace std; int main() { int n, m;//n个学生m科课程 const int size = 100; while (cin >> n>> m) { if (n > 50 || m > 5 || n <= 0 || m <= 0) break; double score[size][size]; double averProject[size], averStudent[size];//课程平均成绩,学生平均成绩 int i, j; int flag; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { cin >> score[i][j];//依次输入第i个学生的第j门课程成绩 } } double sum; flag = 0; //计算n个学生的平均成绩 for (i = 0; i < n; i++) { sum = 0; for (j = 0; j < m; j++) { sum += score[i][j]; if (j == (m - 1)) { if (flag) printf(" %.2f", sum / m); else { printf("%.2f", sum / m); flag = 1; } averStudent[i] = sum / m; break; } } } cout << endl; //计算m门课程的平均成绩 flag = 0; for (j = 0; j < m; j++) { sum = 0; for (i = 0; i < n; i++) { sum += score[i][j]; if (i == (n - 1)) { if (flag) printf(" %.2f", sum / n); else { printf("%.2f", sum / n); flag = 1; } averProject[j] = sum / n; break; } } } cout << endl; //计算该班中各科成绩均大于等于这门课平均成绩的人数 int num = 0; for ( i= 0; i < n; i++) { flag = 0; for (j = 0; j < m; j++) { if (score[i][j] >= averProject[j]) flag++; if (flag == m) num++; } } cout << num << endl << endl; } return 0; }
#include "mpu9250.h" uint8_t mpu_id, ak_id; // variable to hold register addresses uint8_t a_scale = AFS_2G, g_scale = GFS_250DPS, m_scale=MFS_16BITS; // define scales for return values float a_res, g_res, m_res; //variables to store resolution uint8_t a_rate = 0x04; //sets to 200Hz float mag_calibration[3] = {0, 0, 0}; //vector for storing x,y,z magnetometer sensitivity adjustment values uint8_t m_rate=0x06; //0010(0x02)=8hz, 0110(0x06)=100hz sample rate //used for accel/gyro (mpu) calibration - output biases and scale recorded from calibration functions float a_bias[3] = {-0.0221812, 0.015564, -0.030273}, g_bias[3] = {-1.6504434, 0.847328, 0.244275}; float m_bias[3] = {557.109741, 212.527557, -340.863892}, mag_scale[3] = {1.054201, 0.960494, 0.989822}; const int room_offset = 0; int16_t mag_data[3] = {0}; //for reading raw ak8963s std::vector<int16_t> mpu_data(7); //for reading raw mpu values std::vector<float> accel_data(6); //for publishing acceleration values std_msgs::Float32MultiArray list; geometry_msgs::Accel acc; ir_odom::Euler ang; ir_odom::Magnet mag; //varaibles for filtering w/ madgewick double del_t=0, now=0, last_update=0; //variables for getting angles and filtering w/ low pass float theta_a=0, theta_af=0, theta_g=0, phi_a=0, phi_af=0, phi_g=0, psi_g=0, psi_m=0; float theta=0, phi=0, psi=0; //final euler angles float cf_alpha=0.97, lp_alpha=0.4, m_alpha=0.2; //alpha coefs for low pass int count=1; float ax=0, ay=0, az=0, gx=0, gy=0, gz=0, mx=0, my=0, mz=0, tc=0, tf=0; //holds original values float ax_f=0, ay_f=0, az_f=0, mx_f=0, my_f=0, mz_f=0; //holds filtered values std::vector<float> avg_accel(3), total_accel(3), avg_gyro(3), total_gyro(3), avg_mag(3), total_mag(3);//for averaging std::vector<float> comp_mag(3); /*..........................miscellaneous functions to help processing data ...................................*/ //get delta t float getTime(){ now = ros::Time::now().toSec(); if(last_update>0){ del_t = (now - last_update); // set integration time by time elapsed since last filter update } last_update = now; //MadgwickQuaternionUpdate(-ax, ay, az, gx*PI/180, -gy*PI/180, -gz*PI/180, -mx, my, mz, del_t, q); return del_t; } void getAverages(float ax, float ay, float az, float gx, float gy, float gz, float mx, float my, float mz, const int ss){ //reset if larger than sample size if(count>(ss)){ count=1; total_accel[0]=avg_accel[0], total_accel[1]=avg_accel[1], total_accel[2]=avg_accel[2]; total_gyro[0]=avg_gyro[0], total_gyro[1]=avg_gyro[1], total_gyro[2]=avg_gyro[2]; total_mag[0]=avg_mag[0], total_mag[1]=avg_mag[1], total_mag[2]=avg_mag[2]; } avg_accel[0]=total_accel[0]/count, avg_accel[1]=total_accel[1]/count, avg_accel[2]=total_accel[2]/count; avg_gyro[0]=total_gyro[0]/count, avg_gyro[1]=total_gyro[1]/count, avg_gyro[2]=total_gyro[2]/count; avg_mag[0]=total_mag[0]/count, avg_mag[1]=total_mag[1]/count, avg_mag[2]=total_mag[2]/count; total_accel[0]+=ax, total_accel[1]+=ay, total_accel[2]+=az; total_gyro[0]+=gx, total_gyro[1]+=gy, total_gyro[2]+=gz; total_mag[0]+=mx, total_mag[1]+=my, total_mag[2]+=mz; } /*..........................................setup communication.................................................*/ adc::mpu9250::mpu9250(){ fd = 0; //initialize variable to store imu address for reading/writing imuInit(); //begin i2c communication //initialize publishers accel_pub=nh.advertise<geometry_msgs::Accel>("/accel",30); ang_pub=nh.advertise<ir_odom::Euler>("/angles", 30); mag_pub=nh.advertise<ir_odom::Magnet>("/mag_fields", 30); if(idMPU9250()==0x71){ reset(); a_res = getAres(a_scale), g_res = getGres(g_scale), m_res = getMres(m_scale); //get resolutions //calibrateMPU(g_bias, a_bias); //calibrate accel and gyro delay(1000); mpuInit(g_scale, a_scale, a_rate); //initialize MPU9250 for accel and gyro data if(idAK8963()==0x48){ initAKslave(m_scale, m_rate, mag_calibration); //calibrateMag(m_bias, mag_scale); //uncomment if needing to recalibrate and collect necessary values } } } /*.......................................main conversions and processing........................................*/ void adc::mpu9250::convert(){ //read temp, gyro, and accelerometer data mpu9250ReadAll(mpu_data); tc = ((float)mpu_data[3]-room_offset)/333.87 + 21; //convert to temp deg celsius tf = (tc*1.8)+32.0; //convert to fareheight //get change in time since last loops getTime(); ROS_INFO("dt=%3f", del_t); ax = ((float)mpu_data[0]*a_res)-a_bias[0]; //convert acceleration readings to Gs ay = ((float)mpu_data[1]*a_res); az = ((float)mpu_data[2]*a_res)-a_bias[2]; gx = ((float)mpu_data[4]*g_res)-g_bias[0]; //convert gyroscope readings to deg/sec gy = ((float)mpu_data[5]*g_res)-g_bias[1]; gz = ((float)mpu_data[6]*g_res)-g_bias[2]; //read data from magnetometer returns in milliGauss magRead(mag_data); mx = ((float)mag_data[0]*m_res*mag_calibration[0]-m_bias[0]); my = ((float)mag_data[1]*m_res*mag_calibration[1]-m_bias[1]); mz = ((float)mag_data[2]*m_res*mag_calibration[2]-m_bias[2]); mx *= mag_scale[0]; my *= mag_scale[1]; mz *= mag_scale[2]; //get update of averages at sample size set below getAverages(ax, ay, az, gx, gy, gz, mx, my, mz, 10); //low pass filter on accel and mag data mx_f=(1-m_alpha)*mx_f+m_alpha*avg_mag[0]; my_f=(1-m_alpha)*my_f+m_alpha*avg_mag[1]; mz_f=(1-m_alpha)*mz_f+m_alpha*avg_mag[2]; ax_f = (1-lp_alpha)*ax_f +lp_alpha*avg_accel[0]; ay_f = (1-lp_alpha)*ay_f +lp_alpha*avg_accel[1]; phi_a = atan2f(ay_f, sqrtf(pow(ax_f,2)+pow(avg_accel[2],2))); //pitch and roll from accelorometer values theta_a = atan2f(ax_f, sqrtf(pow(ay_f,2)+pow(avg_accel[2],2))); phi_g += gx*del_t; //pitch roll and yaw from gyro and convert to radians theta_g -= gy*del_t; psi_g -= gz*del_t; //yaw from gyro drifts ~0.08 deg/sec //complimentary filter for angle smoothing (only good for pitch angle) phi = (1-cf_alpha)*(phi-phi_g) + (cf_alpha*phi_a); theta = (1-cf_alpha)*(theta-theta_g) + (cf_alpha*theta_a); //compensate mag readings for tilt in x/y directions using angles calculated from gyro comp_mag[0] = avg_mag[0]*cos(phi) + avg_mag[1]*sin(theta)*sin(phi) - avg_mag[2]*cos(theta)*sin(phi); comp_mag[1] = avg_mag[1]*cos(phi) - avg_mag[2]*sin(phi); psi_m = atan2f(-comp_mag[1], comp_mag[0]); //yaw from magnetometer //publish to ros for plotting with rqt_plot ang.aPitch = phi_a*180/PI; ang.gPitch = phi_g; ang.Pitch = phi; ang.aRoll = theta_a*180/PI; ang.gRoll = theta_g; ang.Roll = theta; ang.gYaw = psi_g; ang.mYaw = (psi_m*180/PI)-9.22; ang_pub.publish(ang); //store values from accelerometer m/s/s = linear rate of accereation acc.linear.x = ax_f; acc.linear.y = ay_f; acc.linear.z = az; //store filtered values from gyroscope deg/sec = ang rate velocity acc.angular.x = gx; acc.angular.y = gy; acc.angular.z = gz; accel_pub.publish(acc); //store filtered values from magnetometer in mG mag.magX = mx_f; mag.magY = my_f; mag.magZ = mz_f; mag_pub.publish(mag); count++; } int main(int argc, char* argv[]){ ros::init(argc, argv, "imu_accel_data"); adc::mpu9250 imu1; //create imu object //ros::Rate lr(100); while(ros::ok()){ imu1.convert(); // lr.sleep(); ros::spinOnce(); } return 0; }
#include <iostream> #include <vector> #include <iterator> using namespace std; void product(vector<int> input, vector<string> &output){ int N = (int)input.size(); int *left = new int[N], *right = new int[N]; left[0] = right[N-1] = 1; for (int i = 1;i<N;i++){ left[i] = left[i-1]*input.at(i-1); right[N-i-1] = right[N-i]*input.at(N-i); } for (int i = 0;i<N;i++){ output.push_back(to_string(left[i]*right[i])); } delete[] left; delete[] right; } int main(int argc, char **argv){ vector<int> input; vector<string> output; if (argc <= 2) { cout<<"Wrong input"<<endl; return 1; } for(int i=1;i<argc;i++) input.push_back(stoi(argv[i])); product(input, output); copy(output.begin(),output.end(),ostream_iterator<string>(cout, " ")); return 0; }
#include <bits/stdc++.h> using namespace std; const int maxn = 30; int t, n, k, a[maxn], b[maxn], c[maxn]; int main() { scanf("%d%d", &t, &n); while(t--) { memset(a, 0, sizeof(a)); memset(b, 0, sizeof(b)); memset(c, 0, sizeof(c)); int ans = 0; for (int i = 1; i <= n; i++) { scanf("%d%d", &a[i], &k); if (a[i] == 0) a[i] = 14; else a[i] = (a[i] + 10) % 13 + 1; } for (int i = 1; i <= n; i++) b[a[i]]++; // for (int i = 1; i <= 14; i++) // cout << b[i]; // cout << endl; for (int i = 1; i <= 14 - 6; i++) if (b[i] && b[i + 1] && b[i + 2] && b[i + 3] && b[i + 4]) { for (int j = i; j <= 14; j++) if (b[j]) b[j] -= 1; else break; ans++; } for (int i = 1; i <= 14 - 4; i++) if (b[i] >= 3 && b[i + 1] >= 3 && b[i + 2] >= 3) { for (int j = i; j <= 14; j++) if (b[j] >= 3) b[j] -= 3; else break; ans++; } for (int i = 1; i <= 14 - 4; i++) if (b[i] >= 2 && b[i + 1] >= 2 && b[i + 2] >= 2) { for (int j = i; j <= 14; j++) if (b[j] >= 2) b[j] -= 2; else break; ans++; } // for (int i = 1; i <= 14; i++) // cout << b[i]; // cout << endl; // cout << ans << endl; for (int i = 1; i <= 14; i++) c[b[i]]++; // for (int i = 1; i <= 5; i++) // cout << c[i]; // cout << endl; while (c[4] >= 1 && c[2] >= 2) { c[4] -= 1; c[2] -= 2; ans ++; } while (c[4] >= 1 && c[1] >= 2) { c[4] -= 1; c[1] -= 2; ans ++; } while (c[3] && c[2]) { c[3] -= 1; c[2] -= 1; ans ++; } while (c[3] && c[1]) { c[3] -= 1; c[2] -= 1; ans ++; } // cout << ans << endl; // for (int i = 1; i <= 5; i++) // cout << c[i]; // cout << endl; for (int i = 1; i <= 10; i++) ans += c[i]; cout << ans << endl; } return 0; }
// a4_q1.cpp : This file contains the 'main' function. Program execution begins and ends there. //***************************************************************************** // Student Names: Chaitya Patel and Mayurah Omkararuban // // SYDE 121 Assignment: 4 // Filename: a4_q1 // // We hereby declare that this code, submitted for credit for the course SYDE121, is a product of our own efforts. // This coded solution has not been plagiarized from other sources and has not been knowingly plagiarized by others. // // Due Date: Friday, November 6, 2020 //************************************************************** /*Testing and Debugging: To test the code the game was played realistically with two outside players and more planned testing included playing the game in such a pattern that would test the different possible win or tie patterns by the two players. Scenarios were played out so that both players won through different patterns. Also, sometimes a repetitive location was entered intentionally to check for reprompting and then game was sometimes played for onyl one round and sometimes multiple to check to make sure that those scenarious worked as well. Different winners and scores were intentionally played out to check for accurate game stats.*/ #include <iostream> #include <string> using namespace std; void tic_tac_toe(); // PURPOSE: to initiate a tic tac toe game // INPUTS: none // OUTPUTS: none void print_game_board(string board[][4], int board_size); // PURPOSE: to print the original configuration of the game board // INPUTS: board[][4] - a string array of game board elements to be modified during game play with a max of 4 columns // board_size - size of the game board string array // OUTPUTS: none void player_turn(); // PURPOSE: to alternate between player turns in the game // INPUTS: none // OUTPUTS: none bool continue_game(string board[][4], int board_size, bool& game_finished); // PURPOSE: check after every round to make sure the players want to contine their game // INPUTS: board[][4] - a string array of game board elements to be modified during game play with a max of 4 columns // board_size - size of the game board string array // game_finished - // OUTPUTS: true - if players want game to be continued // false - if players do not want to continue the game void game_stats(int round_counter, int player1_win_counter, int player2_win_counter, int tie_counter); // PURPOSE: to print out the stats of the game at the end of game play when the players do not want to continue the game // INPUTS: round_counter - counts the number of rounds that the players have played // player1_win_counter - number of games won by player 1 // player2_win_counter - number of games qwon by player 2 // tie_counter - number of tie games // OUTPUTS: none void player1(char player, string board[][4], int board_size); // PURPOSE: to go through player 1's turn (X) // INPUTS: player - the character that will be used as a placeholder for that player in the tic-tac-toe game // board[][4] - a string array of game board elements to be modified during game play with a max of 4 columns // board_size - size of the game board string array // OUTPUTS: none void player2(char player, string board[][4], int board_size); // PURPOSE: to go through player 2's turn (O) // INPUTS: player - the character that will be used as a placeholder for that player in the tic-tac-toe game // board[][4] - a string array of game board elements to be modified during game play with a max of 4 columns // board_size - size of the game board string array // OUTPUTS: none bool check_win(string board[][4], int board_size, bool& game_finished, int& player1_win_counter, int& player2_win_counter, int& tie_counter); // PURPOSE: to check for a winning pattern of X's or O's vertically, diagonally, or horizontally, or a tie // INPUTS: board[][4] - a string array of game board elements to be modified during game play with a max of 4 columns // board_size - size of the game board string array // game_finished - to change to true if there is a win or tie to indicate end of the round // player1_win_counter - number of games won by player 1 // player2_win_counter - number of games won by player 2 // tie_counter - number of games tied // OUTPUTS: true - if a someone won the game or the game is tied in this round // false - if there is no winner or tie yet bool check_taken(char player, int entry, string board[][4], int board_size, int location1, int location2); // PURPOSE: to check if the desired index of entry is already filled with and X or O // INPUTS: player - the character that will be used as a placeholder for that player in the tic-tac-toe game // entry - the desired place of entry by the player // board[][4] - a string array of game board elements to be modified during game play with a max of 4 columns // board_size - size of the game board string array // location1 - the row that the player wants to place their token in // location2 - the column that the player wants to place their token in // OUTPUTS: true - in the cases that the originally intended place of token was already filled by an X or O void update_board(char player, int entry, string board[][4], int board_size); // PURPOSE: to update and fill the game board with player tokens // INPUTS: player - the character that will be used as a placeholder for that player in the tic-tac-toe game // entry - the desired place of entry by the player // board[][4] - a string array of game board elements to be modified during game play with a max of 4 columns // board_size - size of the game board string array // OUTPUTS: none void tic_tac_toe() { // [SETUP] step0. declare and initialize variables char play; // a character to be entered if the game wants to be played //[PROCESSING] step1. ask the user if they want to play and lay out some rules cout << "4-SQUARED TIC-TAC-TOE" << endl << "Enter the letter P to play: "; cin >> play; if (play == 'p') { cout << "P1 (Player 1) will be X and will start, and P2 (Player 2) will be O" << endl; player_turn(); // to alternate between player turns in the game } } void player_turn() { //[SETUP]step0. declare and initialize variables and arrays int player1_win_counter = 0; int player2_win_counter = 0; int tie_counter = 0; char player_x = 'X'; char player_o = 'O'; int round_counter = 0; bool game_finished = false; // is the game still being played or is the round finished string board[4][4] = { {"1", "2", "3", "4"}, {"5", "6", "7", "8"}, {"9", "10", "11", "12"}, {"13", "14", "15", "16"} }; // game board configuration //[OUTPUT]step1. to show the player the game board configuration print_game_board(board, 4); //[PROCESSING]step2. to start with player 1 (X) and alterate starting player as more than one round is played do { if (round_counter % 2 == 0) { // if round is even, then player 1 goes first, if odd then player 2 goes first while (game_finished == false) { if (check_win(board, 4, game_finished, player1_win_counter, player2_win_counter, tie_counter) != true) { // to check for winning/tie patterns to be undetected before continuing game player1(player_x, board, 4); // initiation of player 1's turn } if (game_finished == false) { if (check_win(board, 4, game_finished, player1_win_counter, player2_win_counter, tie_counter) != true) { // to check for winning/tie patterns to be undetected before continuing game player2(player_o, board, 4); // initiation of player 2's turn } } } } else { while (game_finished == false) { if (check_win(board, 4, game_finished, player1_win_counter, player2_win_counter, tie_counter) != true) { // to check for winning/tie patterns to be undetected before continuing game player2(player_o, board, 4); // initiation of player 2's turn } if (game_finished == false) { if (check_win(board, 4, game_finished, player1_win_counter, player2_win_counter, tie_counter) != true) { // to check for winning/tie patterns to be undetected before continuing game player1(player_x, board, 4); // initiation of player 1's turn } } } } round_counter += 1; // to count a completed round } while (continue_game(board, 4, game_finished) == true); // keep playing while the players wants the game to continue //[OUTPUT]step3. output game stats at the end of the game game_stats(round_counter, player1_win_counter, player2_win_counter, tie_counter); // function to print the stats of the game after it is ended } void print_game_board(string board[][4], int board_size) { //[OUTPUT] print game board cout << " " << board[0][0] << " " << board[0][1] << " " << board[0][2] << " " << board[0][3] << endl << " " << board[1][0] << " " << board[1][1] << " " << board[1][2] << " " << board[1][3] << endl << " " << board[2][0] << " " << board[2][1] << " " << board[2][2] << " " << board[2][3] << endl << " " << board[3][0] << " " << board[3][1] << " " << board[3][2] << " " << board[3][3] << endl; } void player1(char player, string board[][4], int board_size) { //[SETUP]step0. declare and initialize variables int entry_x; // location that player 1 wants to put their X //[INPUT]step1. retrieve location where player 1 wants to put their piece cout << "P1, enter the number where you would like to place an X: "; cin >> entry_x; //[PROCESSING]step2. pass on location to update the game board update_board(player, entry_x, board, 4); } void player2(char player, string board[][4], int board_size) { //[SETUP]step0. declare and initialize variables int entry_o; // location that player 2 wants to put their O //[INPUT]step1. retrieve location where player 1 wants to put their piece cout << "P2, enter the number where you would like to place an O: "; cin >> entry_o; //[PROCESSING]step2. pass on location to update the game board update_board(player, entry_o, board, 4); } void update_board(char player, int entry, string board[][4], int board_size) { //[PROCESSING] based on the user entry, go to that location on the game board, check if place is taken, if not update and print game board switch (entry) { case 1: if (check_taken(player, entry, board, 4, 0, 0) != true) { board[0][0] = player; print_game_board(board, 4); } break; case 2: if (check_taken(player, entry, board, 4, 0, 1) != true) { board[0][1] = player; print_game_board(board, 4); } break; case 3: if (check_taken(player, entry, board, 4, 0, 2) != true) { board[0][2] = player; print_game_board(board, 4); } break; case 4: if (check_taken(player, entry, board, 4, 0, 3) != true) { board[0][3] = player; print_game_board(board, 4); } break; case 5: if (check_taken(player, entry, board, 4, 1, 0) != true) { board[1][0] = player; print_game_board(board, 4); } break; case 6: if (check_taken(player, entry, board, 4, 1, 1) != true) { board[1][1] = player; print_game_board(board, 4); } break; case 7: if (check_taken(player, entry, board, 4, 1, 2) != true) { board[1][2] = player; print_game_board(board, 4); } break; case 8: if (check_taken(player, entry, board, 4, 1, 3) != true) { board[1][3] = player; print_game_board(board, 4); } break; case 9: if (check_taken(player, entry, board, 4, 2, 0) != true) { board[2][0] = player; print_game_board(board, 4); } break; case 10: if (check_taken(player, entry, board, 4, 2, 1) != true) { board[2][1] = player; print_game_board(board, 4); } break; case 11: if (check_taken(player, entry, board, 4, 2, 2) != true) { board[2][2] = player; print_game_board(board, 4); } break; case 12: if (check_taken(player, entry, board, 4, 2, 3) != true) { board[2][3] = player; print_game_board(board, 4); } break; case 13: if (check_taken(player, entry, board, 4, 3, 0) != true) { board[3][0] = player; print_game_board(board, 4); } break; case 14: if (check_taken(player, entry, board, 4, 3, 1) != true) { board[3][1] = player; print_game_board(board, 4); } break; case 15: if (check_taken(player, entry, board, 4, 3, 2) != true) { board[3][2] = player; print_game_board(board, 4); } break; case 16: if (check_taken(player, entry, board, 4, 3, 3) != true) { board[3][3] = player; print_game_board(board, 4); } break; } } bool check_taken(char player, int entry, string board[][4], int board_size, int location1, int location2) { //[PROCESSING]step1. check if the desired input location by the player is already occupied by a game piece if (board[location1][location2] == "X") { // check if there is an X in the location cout << "This spot is already taken." << endl; // if place taken, reprompt user to enter a different location if (player == 'X') player1(player, board, 4); else if (player == 'O') player2(player, board, 4); return true; // return true if place is taken } if (board[location1][location2] == "O") { // check if there is an O in the location cout << "This spot is already taken." << endl; // if place taken, reprompt user to enter a different location if (player == 'X') player1(player, board, 4); else if (player == 'O') player2(player, board, 4); return true; // return true if place is taken } } bool check_win(string board[][4], int board_size, bool& game_finished, int& player1_win_counter, int& player2_win_counter, int& tie_counter) { //[SETUP]step0. declare and initialize variables int alpha_counter = 0; // to count the number of letters already entered in the game board // [PROCESSING]step1. check for win vertically, horizontally or diagonally and update win counter for corresponding player // also set game_finished to truet to indicate the round has finished and return true to indicate that there has been a win if (board[0][0] == board[1][0] && board[1][0] == board[2][0] && board[2][0] == board[3][0]) { if (board[0][0] == "X") { player1_win_counter += 1; cout << "Player 1 wins the round!" << endl; game_finished = true; return true; } if (board[0][0] == "O") { player2_win_counter += 1; cout << "Player 2 wins the round!" << endl; game_finished = true; return true; } } if (board[0][1] == board[1][1] && board[1][1] == board[2][1] && board[2][1] == board[3][1]) { if (board[0][1] == "X") { player1_win_counter += 1; cout << "Player 1 wins the round!" << endl; game_finished = true; return true; } if (board[0][1] == "O") { player2_win_counter += 1; cout << "Player 2 wins the round!" << endl; game_finished = true; return true; } } if (board[0][2] == board[1][2] && board[1][2] == board[2][2] && board[2][2] == board[3][2]) { if (board[0][2] == "X") { player1_win_counter += 1; cout << "Player 1 wins the round!" << endl; game_finished = true; return true; } if (board[0][2] == "O") { player2_win_counter += 1; cout << "Player 2 wins the round!" << endl; game_finished = true; return true; } } if (board[0][3] == board[1][3] && board[1][3] == board[2][3] && board[2][3] == board[3][3]) { if (board[0][3] == "X") { player1_win_counter += 1; cout << "Player 1 wins the round!" << endl; game_finished = true; return true; } if (board[0][3] == "O") { player2_win_counter += 1; cout << "Player 2 wins the round!" << endl; game_finished = true; return true; } } if (board[0][0] == board[0][1] && board[0][1] == board[0][2] && board[0][2] == board[0][3]) { if (board[0][0] == "X") { player1_win_counter += 1; cout << "Player 1 wins the round!" << endl; game_finished = true; return true; } if (board[0][0] == "O") { player2_win_counter += 1; cout << "Player 2 wins the round!" << endl; game_finished = true; return true; } } if (board[1][0] == board[1][1] && board[1][1] == board[1][2] && board[1][2] == board[1][3]) { if (board[1][0] == "X") { player1_win_counter += 1; cout << "Player 1 wins the round!" << endl; game_finished = true; return true; } if (board[1][0] == "O") { player2_win_counter += 1; cout << "Player 2 wins the round!" << endl; game_finished = true; return true; } } if (board[2][0] == board[2][1] && board[2][1] == board[2][2] && board[2][2] == board[2][3]) { if (board[2][0] == "X") { player1_win_counter += 1; cout << "Player 1 wins the round!" << endl; game_finished = true; return true; } if (board[2][0] == "O") { player2_win_counter += 1; cout << "Player 2 wins the round!" << endl; game_finished = true; return true; } } if (board[3][0] == board[3][1] && board[3][1] == board[3][2] && board[3][2] == board[3][3]) { if (board[3][0] == "X") { player1_win_counter += 1; cout << "Player 1 wins the round!" << endl; game_finished = true; return true; } if (board[3][0] == "O") { player2_win_counter += 1; cout << "Player 2 wins the round!" << endl; game_finished = true; return true; } } if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[2][2] == board[3][3]) { if (board[0][0] == "X") { player1_win_counter += 1; cout << "Player 1 wins the round!" << endl; game_finished = true; return true; } if (board[0][0] == "O") { player2_win_counter += 1; cout << "Player 2 wins the round!" << endl; game_finished = true; return true; } } if (board[3][0] == board[2][1] && board[2][1] == board[1][2] && board[1][2] == board[0][3]) { if (board[3][0] == "X") { player1_win_counter += 1; cout << "Player 1 wins the round!" << endl; game_finished = true; return true; } if (board[3][0] == "O") { player2_win_counter += 1; cout << "Player 2 wins the round!" << endl; game_finished = true; return true; } } //step2. check if all indices in the board array are filled with letters, in that case there is a tie and the round is finished for (int index1 = 0; index1 < 4; index1++) { for (int index2 = 0; index2 < 4; index2++) { if (board[index1][index2] == "X" || board[index1][index2] == "O") { alpha_counter += 1; // count every X or O in the array if (alpha_counter == 16) { // if total is 16 that means array is filled with X's and O's tie_counter += 1; // count the tie to keep score cout << "This round is a tie!" << endl; game_finished = true; // indicates that game has finished for this round return true; // return true to indicate that a win/tie has been detected } } } } } bool continue_game(string board[][4], int board_size, bool& game_finished) { //[SETUP]step0. declare and initialize variables char play; // a character entered by the user to indicate whether they want to continue playing //[INPUT]step1. retrieve user input for decision on continuing the game cout << "Do you want to play again? Enter the letter Y to continue, if you want to exit press any other key:"; cin >> play; //[PROCESSING]step2. if players want to continue then restart game config and continue playing if (play == 'y') { int board_number = 0; // declare and initialize to fill the game board array with numbered locations for (int index1 = 0; index1 < 4; index1++) { for (int index2 = 0; index2 < 4; index2++) { board_number += 1; board[index1][index2] = to_string(board_number); } } game_finished = false; // inidicate that game is not finished yet print_game_board(board, 4); // reprint the game board configuration return true; // continue game play } //step3. if players don't want to continue then return false to indicate end of game else { return false; } } void game_stats(int round_counter, int player1_win, int player2_win, int tie) { //[OUTPUT] print the game stats cout << "END OF GAME STATS:" << endl; cout << "Rounds Played: " << round_counter << endl; cout << "Number of Rounds Won by Player 1: " << player1_win << endl; cout << "Number of Rounds Won by Player 2: " << player2_win << endl; cout << "Number of Rounds Tied: " << tie << endl; // indicate the winner or game conclusion if (player1_win > player2_win) cout << "Player 1 Wins! Better Luck Next Time Player 2 :)" << endl; else if (player1_win < player2_win) cout << "Player 2 Wins! Better Luck Next Time Player 1 :)" << endl; else cout << "Tie Game!" << endl; cout << "Thank You for Playing! See You Next Time!" << endl; } int main() { tic_tac_toe(); // initiate a 4x4 game of 2 player tic-tac-toe }
#include <stdio.h> int main() { double sales_tax = 0.04; double purchase = 52; double tax = purchase*sales_tax; double total = purchase+tax; printf("%f\n", total); return 0; }
// Created on: 1993-01-09 // Created by: CKY / Contract Toubro-Larsen ( SIVA ) // Copyright (c) 1993-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 _IGESSolid_EdgeList_HeaderFile #define _IGESSolid_EdgeList_HeaderFile #include <Standard.hxx> #include <IGESData_HArray1OfIGESEntity.hxx> #include <IGESSolid_HArray1OfVertexList.hxx> #include <TColStd_HArray1OfInteger.hxx> #include <IGESData_IGESEntity.hxx> #include <Standard_Integer.hxx> class IGESSolid_VertexList; class IGESSolid_EdgeList; DEFINE_STANDARD_HANDLE(IGESSolid_EdgeList, IGESData_IGESEntity) //! defines EdgeList, Type <504> Form <1> //! in package IGESSolid //! EdgeList is defined as a segment joining two vertices //! It contains one or more edge tuples. class IGESSolid_EdgeList : public IGESData_IGESEntity { public: Standard_EXPORT IGESSolid_EdgeList(); //! This method is used to set the fields of the class //! EdgeList //! - curves : the model space curves //! - startVertexList : the vertex list that contains the //! start vertices //! - startVertexIndex : the index of the vertex in the //! corresponding vertex list //! - endVertexList : the vertex list that contains the //! end vertices //! - endVertexIndex : the index of the vertex in the //! corresponding vertex list //! raises exception if size of curves,startVertexList,startVertexIndex, //! endVertexList and endVertexIndex do no match Standard_EXPORT void Init (const Handle(IGESData_HArray1OfIGESEntity)& curves, const Handle(IGESSolid_HArray1OfVertexList)& startVertexList, const Handle(TColStd_HArray1OfInteger)& startVertexIndex, const Handle(IGESSolid_HArray1OfVertexList)& endVertexList, const Handle(TColStd_HArray1OfInteger)& endVertexIndex); //! returns the number of edges in the edge list Standard_EXPORT Standard_Integer NbEdges() const; //! returns the num'th model space curve //! raises Exception if num <= 0 or num > NbEdges() Standard_EXPORT Handle(IGESData_IGESEntity) Curve (const Standard_Integer num) const; //! returns the num'th start vertex list //! raises Exception if num <= 0 or num > NbEdges() Standard_EXPORT Handle(IGESSolid_VertexList) StartVertexList (const Standard_Integer num) const; //! returns the index of num'th start vertex in //! the corresponding start vertex list //! raises Exception if num <= 0 or num > NbEdges() Standard_EXPORT Standard_Integer StartVertexIndex (const Standard_Integer num) const; //! returns the num'th end vertex list //! raises Exception if num <= 0 or num > NbEdges() Standard_EXPORT Handle(IGESSolid_VertexList) EndVertexList (const Standard_Integer num) const; //! returns the index of num'th end vertex in //! the corresponding end vertex list //! raises Exception if num <= 0 or num > NbEdges() Standard_EXPORT Standard_Integer EndVertexIndex (const Standard_Integer num) const; DEFINE_STANDARD_RTTIEXT(IGESSolid_EdgeList,IGESData_IGESEntity) protected: private: Handle(IGESData_HArray1OfIGESEntity) theCurves; Handle(IGESSolid_HArray1OfVertexList) theStartVertexList; Handle(TColStd_HArray1OfInteger) theStartVertexIndex; Handle(IGESSolid_HArray1OfVertexList) theEndVertexList; Handle(TColStd_HArray1OfInteger) theEndVertexIndex; }; #endif // _IGESSolid_EdgeList_HeaderFile
/* Copyright (c) 2005-2022 Xavier Leclercq Released under the MIT License See https://github.com/ishiko-cpp/test-framework/blob/main/LICENSE.txt */ #include "TestNumber.hpp" namespace Ishiko { TestNumber::TestNumber() { } TestNumber::TestNumber(int major) { m_number.push_back(major); } TestNumber::TestNumber(int major, int minor) { m_number.push_back(major); m_number.push_back(minor); } size_t TestNumber::depth() const { return m_number.size(); } int TestNumber::part(size_t i) const { return m_number[i]; } bool TestNumber::operator ==(const TestNumber& other) const { return (m_number == other.m_number); } bool TestNumber::operator !=(const TestNumber& other) const { return (m_number != other.m_number); } TestNumber& TestNumber::operator ++() { if (!m_number.empty()) { ++m_number.back(); } return *this; } TestNumber TestNumber::operator ++(int) { TestNumber result(*this); if (!m_number.empty()) { ++m_number.back(); } return result; } TestNumber TestNumber::getDeeperNumber() const { TestNumber result = *this; result.m_number.push_back(1); return result; } }
/** * Tomer Rahamim 203717475 * Roi Peretz 203258041 */ //main.cpp #include <vector> #include <string> #include <iostream> #include <iterator> #include <sstream> #include "MoviesSystem.h" #include "Server.h" #include "UDPServer.h" #include "TCPServer.h" #include <pthread.h> using namespace std; int main(int argc, char* argv[]) { TCPServer* server; int status; if(argc-1 != 2){ cout<<"Missing arguments - exit"<<endl; return 0; } int port = atoi(argv[2]); int type = atoi(argv[1]); if(port< 1024 || port>65536){ cout<<"invalid port number - exit"<<endl; return 0; } // creating a connection (TCP). server = new TCPServer(port); MoviesSystem::getInstance()->setServer(server); //MoviesSystem::getInstance()->load(MoviesSystem::getInstance()); server->threadFactory(); return 0; }
#ifndef VnaCwSweep_H #define VnaCwSweep_H // RsaToolbox #include "Definitions.h" // Etc // Qt #include <QObject> #include <QScopedPointer> namespace RsaToolbox { class Vna; class VnaChannel; class VnaCwSweep : public QObject { Q_OBJECT public: explicit VnaCwSweep(QObject *parent = 0); VnaCwSweep(VnaCwSweep &other); VnaCwSweep(Vna *vna, VnaChannel *channel, QObject *parent = 0); VnaCwSweep(Vna *vna, uint channelIndex, QObject *parent = 0); ~VnaCwSweep(); uint points(); void setPoints(uint numberOfPoints); double frequency_Hz(); void setFrequency(double frequency, SiPrefix prefix = SiPrefix::None); double power_dBm(); void setPower(double power_dBm); double ifBandwidth_Hz(); void setIfBandwidth(double bandwidth, SiPrefix prefix = SiPrefix::None); uint sweepTime_ms(); void operator=(VnaCwSweep const &other); // void moveToThread(QThread *thread); private: Vna *_vna; QScopedPointer<Vna> placeholder; QScopedPointer<VnaChannel> _channel; uint _channelIndex; bool isFullyInitialized() const; }; } #endif // VnaCwSweep_H
#include "../../headers.h" #include "Log.h" #include "SettingsReader.h" //------------------------------------------------------------------------------------------------- SettingsReader::SettingsReader(const std::string& path) { path_ = path; mtim_.tv_nsec = 0; mtim_.tv_sec = 0; } //------------------------------------------------------------------------------------------------- SettingsReader::~SettingsReader() { } //------------------------------------------------------------------------------------------------- bool SettingsReader::checkAndReload(Settings* out) { if (!check()) return false; PLOG_INFO << "Reading settings: " << StreamColors(termcolor::magenta, true) << path_; // file has been changed (or never read), so read it. YAML::Node config = YAML::LoadFile(path_); out->GridResolution = config["GridResolution"].as<int>(); out->GridWorldSize = config["GridWorldSize"].as<float>(); out->GridOrigin = config["GridOrigin"].as<glm::vec2>(); out->Size = config["Size"].as<float>(); out->UsePhillips = config["UsePhillips"].as<bool>(); out->A = config["A"].as<float>(); out->WindSpeed = config["WindSpeed"].as<float>(); out->WindAlignment = config["WindAlignment"].as<float>(); out->MinWaveLength = config["MinWaveLength"].as<float>(); out->WindDirection = glm::normalize(config["WindDirection"].as<glm::vec2>()); out->Choppiness = config["Choppiness"].as<float>(); out->DisplacementFactor = config["DisplacementFactor"].as<float>(); out->RenderSky = config["RenderSky"].as<bool>(); out->SkyboxName = config["SkyboxName"].as<std::string>(); out->SkyboxHalfSize = config["SkyboxHalfSize"].as<float>(); out->SmoothNormals = config["SmoothNormals"].as<float>(); out->OceanColor = readColor(config, "OceanColor"); out->LightColor = readColor(config, "LightColor"); out->SkyColor = readColor(config, "SkyColor"); out->LightDir = glm::normalize(config["LightDir"].as<glm::vec3>()); out->Kr = config["Kr"].as<float>(); out->Kt = config["Kt"].as<float>(); out->Ks = config["Ks"].as<float>(); out->PhongFactor = config["PhongFactor"].as<float>(); return true; } //------------------------------------------------------------------------------------------------- bool SettingsReader::check() { int fd = open(path_.c_str(), O_RDONLY); if (fd < -1) return false; struct stat fileStat; if (fstat(fd, &fileStat) < 0) return false; close(fd); if (fileStat.st_mtim.tv_nsec != mtim_.tv_nsec) { mtim_.tv_nsec = fileStat.st_mtim.tv_nsec; return true; } return false; } //------------------------------------------------------------------------------------------------- glm::vec3 SettingsReader::readColor(const YAML::Node& config, const std::string& name) { glm::vec3 color = config[name].as<glm::vec3>(); return color / 255.0f; }
#include <cstdio> int main() { int a,b,c; scanf("%d %d %d", &a, &b, &c); if(a<b) { a=b; } if(a<c) { a=c; } printf("%d eh o maior\n", a); }
/* TESTS/basic/microstep/main.cpp Check that Pololu2968 microstep() works */ #include "mbed.h" #include "rtos.h" #include "stdio.h" #include "Pololu2968.h" #include "unity.h" Pololu2968 foo(p22,p21,p23,NC,p30); int main(void){ pc.printf("Pololu2968 version "); pc.printf(POLOLU2968_VERSION); pc.printf("\r\nmicrostep() test\r\n"); pc.printf("Setup for this test: step p22, dir p21, i1 p23, i2 NC, nsleep p30\r\n"); for (int i=0; i<10; i++){ pc.pritnf("microstep(10);\r\n"); foo.microstep(10); } return(0); }
/*********************************************************\ * 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" //[-------------------------------------------------------] //[ Forward declarations ] //[-------------------------------------------------------] namespace Renderer { class ILog; class IAssert; class IAllocator; } #ifdef LINUX // Copied from "Xlib.h" struct _XDisplay; // Copied from "wayland-client.h" struct wl_display; struct wl_surface; #endif //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace Renderer { //[-------------------------------------------------------] //[ Classes ] //[-------------------------------------------------------] /** * @brief * Context class encapsulating all embedding related wirings */ class Context { //[-------------------------------------------------------] //[ Public definitions ] //[-------------------------------------------------------] public: enum class ContextType { WINDOWS, X11, WAYLAND }; //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] log * Log instance to use, the log instance must stay valid as long as the renderer instance exists * @param[in] assert * Assert instance to use, the assert instance must stay valid as long as the renderer instance exists * @param[in] allocator * Allocator instance to use, the allocator instance must stay valid as long as the renderer instance exists * @param[in] nativeWindowHandle * Native window handle * @param[in] useExternalContext * Indicates if an external renderer context is used; in this case the renderer itself has nothing to do with the creation/managing of an renderer context * @param[in] contextType * The type of the context */ inline Context(ILog& log, IAssert& assert, IAllocator& allocator, handle nativeWindowHandle = 0, bool useExternalContext = false, ContextType contextType = Context::ContextType::WINDOWS); /** * @brief * Destructor */ inline virtual ~Context(); /** * @brief * Return the log instance * * @return * The log instance */ inline ILog& getLog() const; /** * @brief * Return the assert instance * * @return * The assert instance */ inline IAssert& getAssert() const; /** * @brief * Return the allocator instance * * @return * The allocator instance */ inline IAllocator& getAllocator() const; /** * @brief * Return the native window handle * * @return * The native window handle */ inline handle getNativeWindowHandle() const; /** * @brief * Return whether or not an external context is used * * @return * "true" if an external context is used, else "false" */ inline bool isUsingExternalContext() const; /** * @brief * Return the type of the context * * @return * The context type */ inline ContextType getType() const; /** * @brief * Return a handle to the renderer API shared library * * @return * The handle to the renderer API shared library */ inline void* getRendererApiSharedLibrary() const; /** * @brief * Set the handle for the renderer API shared library to use instead of let it load by the renderer instance * * @param[in] rendererApiSharedLibrary * A handle to the renderer API shared library; the renderer will use this handle instead of loading the renderer API shared library itself */ inline void setRendererApiSharedLibrary(void* rendererApiSharedLibrary); //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit Context(const Context&) = delete; Context& operator=(const Context&) = delete; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: ILog& mLog; IAssert& mAssert; IAllocator& mAllocator; handle mNativeWindowHandle; bool mUseExternalContext; ContextType mContextType; void* mRendererApiSharedLibrary; ///< A handle to the renderer API shared library (e.g. obtained via "dlopen()" and co) }; // TODO(sw) Hide it via an define for non Linux builds? This definition doesn't use any platform specific headers #ifdef LINUX /** * @brief * X11 version of the context class */ class X11Context final : public Context { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] log * Log instance to use, the log instance must stay valid as long as the renderer instance exists * @param[in] assert * Assert instance to use, the assert instance must stay valid as long as the renderer instance exists * @param[in] allocator * Allocator instance to use, the allocator instance must stay valid as long as the renderer instance exists * @param[in] display * The X11 display connection * @param[in] nativeWindowHandle * Native window handle * @param[in] useExternalContext * Indicates if an external renderer context is used; in this case the renderer itself has nothing to do with the creation/managing of an renderer context */ inline X11Context(ILog& log, IAssert& assert, IAllocator& allocator, _XDisplay* display, handle nativeWindowHandle = 0, bool useExternalContext = false); /** * @brief * Return the x11 display connection * * @return * The x11 display connection */ inline _XDisplay* getDisplay() const; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: _XDisplay* mDisplay; }; /** * @brief * Wayland version of the context class */ class WaylandContext final : public Context { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] log * Log instance to use, the log instance must stay valid as long as the renderer instance exists * @param[in] assert * Assert instance to use, the assert instance must stay valid as long as the renderer instance exists * @param[in] allocator * Allocator instance to use, the allocator instance must stay valid as long as the renderer instance exists * @param[in] display * The Wayland display connection * @param[in] surface * The Wayland surface * @param[in] useExternalContext * Indicates if an external renderer context is used; in this case the renderer itself has nothing to do with the creation/managing of an renderer context */ inline WaylandContext(ILog& log, IAssert& assert, IAllocator& allocator, wl_display* display, wl_surface* surface = 0, bool useExternalContext = false); /** * @brief * Return the Wayland display connection * * @return * The Wayland display connection */ inline wl_display* getDisplay() const; /** * @brief * Return the Wayland surface * * @return * The Wayland surface */ inline wl_surface* getSurface() const; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: wl_display* mDisplay; wl_surface* mSurface; }; #endif //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // Renderer //[-------------------------------------------------------] //[ Implementation ] //[-------------------------------------------------------] #include "Renderer/Context.inl"
#pragma once #include "widget.h" namespace sge{ namespace graphics { namespace gui { class Component: public Widget { protected: std::vector<Widget*> m_Widgets; math::mat4 m_TransformationMatrix; public: Component(const math::Rectangle& bounds); ~Component(); void addTransformation(math::mat4 transform); void resetTransformation(); Widget* add(Widget *widget); void remove(Widget *widget); void clear(); void onUpdate() override; void onEvent(events::Event& event) override; void submit(Renderer2D *renderer) const override; inline const std::vector<Widget*>& GetWidgets() const { return m_Widgets; } }; } } }
/* * @Description: matching 模块任务管理, 放在类里使代码更清晰 * @Author: Ren Qian * @Date: 2020-02-10 08:31:22 */ #ifndef LIDAR_LOCALIZATION_MATCHING_MATCHING_FLOW_HPP_ #define LIDAR_LOCALIZATION_MATCHING_MATCHING_FLOW_HPP_ #include <ros/ros.h> // subscriber #include "lidar_localization/subscriber/cloud_subscriber.hpp" #include "lidar_localization/subscriber/odometry_subscriber.hpp" // publisher #include "lidar_localization/publisher/cloud_publisher.hpp" #include "lidar_localization/publisher/odometry_publisher.hpp" #include "lidar_localization/publisher/tf_broadcaster.hpp" // matching #include "lidar_localization/matching/matching.hpp" namespace lidar_localization { class MatchingFlow { public: MatchingFlow(ros::NodeHandle& nh); bool Run(); private: bool ReadData(); bool HasData(); bool ValidData(); bool UpdateMatching(); bool PublishData(); private: // subscriber std::shared_ptr<CloudSubscriber> cloud_sub_ptr_; std::shared_ptr<OdometrySubscriber> gnss_sub_ptr_; // publisher std::shared_ptr<CloudPublisher> global_map_pub_ptr_; std::shared_ptr<CloudPublisher> local_map_pub_ptr_; std::shared_ptr<CloudPublisher> current_scan_pub_ptr_; std::shared_ptr<OdometryPublisher> laser_odom_pub_ptr_; std::shared_ptr<TFBroadCaster> laser_tf_pub_ptr_; // matching std::shared_ptr<Matching> matching_ptr_; std::deque<CloudData> cloud_data_buff_; std::deque<PoseData> gnss_data_buff_; CloudData current_cloud_data_; PoseData current_gnss_data_; Eigen::Matrix4f laser_odometry_ = Eigen::Matrix4f::Identity(); }; } #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #ifdef ENCODINGS_HAVE_TABLE_DRIVEN #include "modules/encodings/tablemanager/tablemanager.h" #include "modules/encodings/tablemanager/table_decompressor.h" #ifdef TABLEMANAGER_DYNAMIC_REV_TABLES #include "modules/encodings/tablemanager/reverse_table_builder.h" #endif #ifndef ENCODINGS_REGTEST # include "modules/hardcore/mem/mem_man.h" # include "modules/util/opfile/opfile.h" # include "modules/pi/OpSystemInfo.h" #endif // Table bit flags #define TABLE_PADDED 0x80 /**< Table length contains one padding byte. */ #define TABLE_COMPRESSED 0x01 /**< Table is compressed. */ #define TABLE_FORMAT 0x7F /**< Bit mask for table storage format. */ // ===== Module implementation TableCacheManager::TableCacheManager() : OpTableManager(), m_encoding_headers(NULL), m_encoding_headers_size(0), m_delete_encoding_headers_on_exit(FALSE), m_tables(NULL), m_table_count(0) { #if !defined ENCODINGS_HAVE_ROM_TABLES || defined TABLEMANAGER_COMPRESSED_TABLES || defined TABLEMANAGER_DYNAMIC_REV_TABLES for (int ix = 0; ix < ENCODINGS_LRU_SIZE; ix ++) m_lru[ix] = -1; #endif } TableCacheManager::~TableCacheManager() { int tbl_count = m_table_count; if (m_tables) { for (int ix = 0; ix < tbl_count; ix ++) { #ifdef ENCODINGS_REGTEST # if !defined ENCODINGS_HAVE_ROM_TABLES || defined TABLEMANAGER_COMPRESSED_TABLES || defined TABLEMANAGER_DYNAMIC_REV_TABLES assert(0 == m_tables[ix].ref_count); # endif #endif //Delete table_name if it is allocated by itself, and not as part of the m_encoding_headers if (m_tables[ix].table_name && (m_tables[ix].table_name<reinterpret_cast<const char*>(m_encoding_headers) || m_tables[ix].table_name>=reinterpret_cast<const char*>(m_encoding_headers+m_encoding_headers_size)) ) { OP_DELETEA(const_cast<char*>(m_tables[ix].table_name)); } #if !defined ENCODINGS_HAVE_ROM_TABLES || defined TABLEMANAGER_COMPRESSED_TABLES || defined TABLEMANAGER_DYNAMIC_REV_TABLES if (m_tables[ix].table_was_allocated) OP_DELETEA(const_cast<UINT8*>(m_tables[ix].table)); #endif } OP_DELETEA(m_tables); } if (m_delete_encoding_headers_on_exit) OP_DELETEA(const_cast<UINT8*>(m_encoding_headers)); } const void *TableCacheManager::Get(const char *table_name, long &byte_count) { byte_count = 0; int ix = GetIndex(table_name); TableDescriptor *table = (ix >= 0) ? GetTableDescriptor(ix) : NULL; if (-1 == ix || !table) { return NULL; } if (table->table == NULL) // Table not yet loaded { #ifdef TABLEMANAGER_DYNAMIC_REV_TABLES if (-1 == table->start_offset) { // We know about the table, but haven't got it stored, so we need // to create it. We try two times. ReverseTableBuilder::BuildTable(this, table); if (table->table == NULL) { g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY); return NULL; } } else #endif { #if !defined ENCODINGS_HAVE_ROM_TABLES || defined TABLEMANAGER_COMPRESSED_TABLES || defined TABLEMANAGER_DYNAMIC_REV_TABLES OP_ASSERT(0 == table->ref_count); #endif OP_STATUS rc = LoadRawTable(ix); if (rc == OpStatus::ERR_NO_MEMORY) { #ifndef ENCODINGS_REGTEST g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY); #endif return NULL; } if (OpStatus::IsError(rc)) { return NULL; } #ifdef TABLEMANAGER_COMPRESSED_TABLES else { //Compressed? if (OpStatus::IsSuccess(rc) && table->table_info & TABLE_COMPRESSED) { TableDecompressor decompressor; rc = decompressor.Init(); if (OpStatus::IsSuccess(rc)) { const UINT8 *compressed_table = table->table; const UINT8 *decompress_ptr = compressed_table; BOOL compressed_table_was_allocated = table->table_was_allocated; table->table = OP_NEWA(UINT8, table->final_byte_count); table->table_was_allocated = table->table!=NULL; if (!table->table) { //Revert changes and return error table->table = compressed_table; table->table_was_allocated = compressed_table_was_allocated; rc = OpStatus::ERR_NO_MEMORY; } else { int src_len = table->byte_count; if (table->table_info & TABLE_PADDED && table->byte_count>0) src_len--; int read = 0; int written, total_written = 0; do { written = decompressor.Decompress(decompress_ptr, src_len, const_cast<UINT8*>(table->table + total_written), table->final_byte_count - total_written, &read); if (written == -1) { OP_DELETEA(const_cast<UINT8*>(table->table)); table->table = NULL; table->table_was_allocated = FALSE; rc = OpStatus::ERR; break; } total_written += written; decompress_ptr += read; src_len -= read; } while (src_len>0 && read!=0); OP_ASSERT(OpStatus::IsError(rc) || (src_len==0 && total_written==table->final_byte_count)); if (compressed_table_was_allocated) OP_DELETEA(const_cast<UINT8*>(compressed_table)); } } } } #endif // TABLEMANAGER_COMPRESSED_TABLES } } if (!table->table) return NULL; #if !defined ENCODINGS_HAVE_ROM_TABLES || defined TABLEMANAGER_COMPRESSED_TABLES || defined TABLEMANAGER_DYNAMIC_REV_TABLES if (1 == ++table->ref_count) { RemoveFromLRU(ix); } #endif byte_count = table->final_byte_count; return table->table; } void TableCacheManager::Release(const void *table) { if (!table) return; #if !defined ENCODINGS_HAVE_ROM_TABLES || defined TABLEMANAGER_COMPRESSED_TABLES || defined TABLEMANAGER_DYNAMIC_REV_TABLES int i; for (i=0; i < m_table_count; i++) { if (m_tables[i].table == table) { if (0 == --m_tables[i].ref_count) { // We can now safely discard this table. AddToLRU(i); } break; } } #endif } BOOL TableCacheManager::Has(const char* table_name) { if (GetIndex(table_name) != -1) return TRUE; return FALSE; } /** * Retrieve the number of a named table. * * @param table_name Name of the table to find in the index. * @return The index of the table, or -1 if not found. */ int TableCacheManager::GetIndex(const char *table_name) { if (m_tables && m_table_count) { TableDescriptor search = { table_name, 0, 0, 0, 0, NULL, #if !defined ENCODINGS_HAVE_ROM_TABLES || defined TABLEMANAGER_COMPRESSED_TABLES || defined TABLEMANAGER_DYNAMIC_REV_TABLES FALSE, 0 #endif }; TableDescriptor *found = reinterpret_cast<TableDescriptor *> (op_bsearch(&search, m_tables, m_table_count, sizeof(TableDescriptor), tablenamecmp)); if (found) { OP_ASSERT(op_stricmp(found->table_name, table_name) == 0); OP_ASSERT(op_stricmp(m_tables[found - m_tables].table_name, table_name) == 0); return found - m_tables; } #ifdef TABLEMANAGER_DYNAMIC_REV_TABLES if (ReverseTableBuilder::HasReverse(this, table_name)) return GetIndex(table_name); #endif } // Table not found or no tables loaded return -1; } #ifdef OUT_OF_MEMORY_POLLING void TableCacheManager::Flush() { # if !defined ENCODINGS_HAVE_ROM_TABLES || defined TABLEMANAGER_COMPRESSED_TABLES || defined TABLEMANAGER_DYNAMIC_REV_TABLES for (int ix = 0; ix < ENCODINGS_LRU_SIZE; ix ++) { if (m_lru[ix] != -1) { OP_ASSERT(0 == m_tables[m_lru[ix]].ref_count); if (m_tables[m_lru[ix]].table_was_allocated) OP_DELETEA(const_cast<UINT8 *>(m_tables[m_lru[ix]].table)); m_tables[m_lru[ix]].table = NULL; m_tables[m_lru[ix]].table_was_allocated = FALSE; m_lru[ix] = -1; } } # endif } #endif // OUT_OF_MEMORY_POLLING OP_STATUS TableCacheManager::ParseRawHeaders(const UINT8 *encoding_headers, UINT16 headers_size, BOOL delete_on_exit) { OP_ASSERT(encoding_headers!=NULL && headers_size>=8); //Don't try to parse before raw headers are allocated and read (at least 8 bytes..) if (!encoding_headers || headers_size<8) { if (delete_on_exit) OP_DELETEA(const_cast<UINT8*>(encoding_headers)); m_encoding_headers = NULL; m_encoding_headers_size = 0; m_delete_encoding_headers_on_exit = FALSE; return OpStatus::OK; //Nothing to do } OP_ASSERT(!m_tables && m_table_count==0); if (m_tables || m_table_count>0) return OpStatus::ERR; m_encoding_headers = encoding_headers; m_encoding_headers_size = headers_size; m_delete_encoding_headers_on_exit = delete_on_exit; UINT16 magic = *(reinterpret_cast<const UINT16*>(m_encoding_headers)); #ifdef ENCODINGS_OPPOSITE_ENDIAN magic = ENCDATA16(magic); #endif if (magic == 0xFE01) //Magic number for what is considered version 1 of encoding.bin { //File format: //UINT16 magic (For version 1, this should be 0xFE01) //UINT16 headers_size (size of all data before tables, including magic and headers_size, in bytes) //UINT16 number_of_tables //UINT16 reserved (should be set to 0) // //UINT32 table_data[number_of_tables+1] (offset from beginning of file to table data (last item is a placeholder, and should equal to filelength)) //UINT32 final_size[number_of_tables] (number of bytes for uncompressed table) //UINT16 table_name[number_of_tables] (offset from beginning of file to table name (which is zero-terminated)) //UINT8 table_info[number_of_tables] (bitmask. bit7=table data includes one padding byte, bit6..1=reserved, bit0=table data is compressed) //char names[<just-enough-bytes, including zero-terminators>] (All table names, with a zero-terminator after each name) //char padding[0..1] (padding, if needed. Should be set to 0) //table data.. m_table_count = *(reinterpret_cast<const UINT16*>(m_encoding_headers+4)); #ifdef _DEBUG UINT16 headers_size = *(reinterpret_cast<const UINT16*>(m_encoding_headers+2)); UINT16 reserved = *(reinterpret_cast<const UINT16*>(m_encoding_headers+6)); OP_ASSERT(reserved == 0); #endif #ifdef ENCODINGS_OPPOSITE_ENDIAN m_table_count = ENCDATA16(m_table_count); #ifdef _DEBUG headers_size = ENCDATA16(headers_size); reserved = ENCDATA16(reserved); #endif // _DEBUG #endif // ENCODINGS_OPPOSITE_ENDIAN // Allocate m_tables = OP_NEWA(TableDescriptor, m_table_count); if (!m_tables) { m_table_count = 0; return OpStatus::ERR_NO_MEMORY; } const UINT8 *table_data_ptr = m_encoding_headers + 8/*headers*/; const UINT8 *final_size_ptr = table_data_ptr + 4*(m_table_count+1)/*table_data*/; const UINT8 *table_name_ptr = final_size_ptr + 4*m_table_count/*final_size*/; const UINT8 *table_info_ptr = table_name_ptr + 2*m_table_count/*table_name*/; if (table_info_ptr+m_table_count >= m_encoding_headers+m_encoding_headers_size) //Fail if last table_info entry is outside buffer { OP_DELETEA(m_tables); m_tables = NULL; m_table_count = 0; return OpStatus::ERR_PARSING_FAILED; } int i; for (i=0; i<m_table_count; i++) { m_tables[i].start_offset = *(reinterpret_cast<const UINT32*>(table_data_ptr + 4*i)); UINT32 next_table_start_offset = *(reinterpret_cast<const UINT32*>(table_data_ptr + 4*(i+1))); m_tables[i].final_byte_count = *(reinterpret_cast<const UINT32*>(final_size_ptr + 4*i)); m_tables[i].table_name = reinterpret_cast<const char*>(m_encoding_headers + *(reinterpret_cast<const UINT16*>(table_name_ptr + 2*i))); //This points directly into the headers m_tables[i].table_info = *(reinterpret_cast<const UINT8*>(table_info_ptr + i)); m_tables[i].table = NULL; #if !defined ENCODINGS_HAVE_ROM_TABLES || defined TABLEMANAGER_COMPRESSED_TABLES || defined TABLEMANAGER_DYNAMIC_REV_TABLES m_tables[i].table_was_allocated = FALSE; m_tables[i].ref_count = 0; #endif #ifdef ENCODINGS_OPPOSITE_ENDIAN m_tables[i].start_offset = ENCDATA32(m_tables[i].start_offset); next_table_start_offset = ENCDATA32(next_table_start_offset); m_tables[i].final_byte_count = ENCDATA32(m_tables[i].final_byte_count); m_tables[i].table_name = reinterpret_cast<const char*>(m_encoding_headers + ENCDATA16(*(reinterpret_cast<const UINT16*>(table_name_ptr + 2*i)))); #endif m_tables[i].byte_count = next_table_start_offset - m_tables[i].start_offset; if (m_tables[i].table_info & TABLE_PADDED && m_tables[i].byte_count>0) //table_data includes one byte padding { m_tables[i].table_info &= TABLE_FORMAT; m_tables[i].byte_count--; } #ifndef TABLEMANAGER_COMPRESSED_TABLES OP_ASSERT(m_tables[i].table_info == 0 || !"Compressed table support disabled in this build"); #endif } OP_ASSERT(m_table_count>0 && headers_size==m_tables[0].start_offset); } if (m_tables && m_table_count>1) { //Don't worry about LRU here, it should not have any entries yet op_qsort(m_tables, m_table_count, sizeof(TableDescriptor), tablenamecmp); } return OpStatus::OK; } #ifdef TABLEMANAGER_DYNAMIC_REV_TABLES /** * Add information about a table to TableCacheManager's list of known tables. * This is used by the reverse table builder to insert tables at run-time. * Only the fields table_name, byte_count and table are used from the data * supplied. The inherting class must implement the BuildTable() class for * any tables it inserts here, so that they can be rebuilt after having been * flushed. * * @param new_table Meta data for the new table * @return Status of the operation */ OP_STATUS TableCacheManager::AddTable(const TableDescriptor& new_table) { // Reallocate TableDescriptor *new_table_list = OP_NEWA(TableDescriptor, m_table_count + 1); if (!new_table_list) { return OpStatus::ERR_NO_MEMORY; } // Shuffle old stuff into the new list op_memcpy(new_table_list, m_tables, sizeof (TableDescriptor) * m_table_count); new_table_list[m_table_count] = new_table; // Initialize the new entry new_table_list[m_table_count].ref_count = 0; new_table_list[m_table_count].start_offset = -1; op_qsort(new_table_list, ++ m_table_count, sizeof(TableDescriptor), tablenamecmp); // Update LRU queue for (int ix = 0; ix < ENCODINGS_LRU_SIZE; ix ++) { if (m_lru[ix] != -1) { // We've inserted exactly one table, so unless the sorting // is unstable, it should not have moved away more than one // step. const UINT8 *old_table = m_tables[m_lru[ix]].table; for (int iy = m_lru[ix]; iy < m_table_count; iy ++) { if (new_table_list[iy].table == old_table) { m_lru[ix] = iy; break; } } } } OP_DELETEA(m_tables); m_tables = new_table_list; return OpStatus::OK; } #endif // TABLEMANAGER_DYNAMIC_REV_TABLES #if !defined ENCODINGS_HAVE_ROM_TABLES || defined TABLEMANAGER_COMPRESSED_TABLES || defined TABLEMANAGER_DYNAMIC_REV_TABLES void TableCacheManager::AddToLRU(UINT16 index) { // If there is an entry pending deletion, kill it. if (m_lru[0] != -1) { OP_ASSERT(0 == m_tables[m_lru[0]].ref_count); if (m_tables[m_lru[0]].table_was_allocated) OP_DELETEA(const_cast<UINT8*>(m_tables[m_lru[0]].table)); m_tables[m_lru[0]].table = NULL; m_tables[m_lru[0]].table_was_allocated = FALSE; } // Put it in the LRU queue. int i; for (i=0; i < ENCODINGS_LRU_SIZE - 1; i++) { m_lru[i] = m_lru[i+1]; } m_lru[ENCODINGS_LRU_SIZE-1] = index; } #endif // !ENCODINGS_HAVE_ROM_TABLES || TABLEMANAGER_COMPRESSED_TABLES || TABLEMANAGER_DYNAMIC_REV_TABLES #if !defined ENCODINGS_HAVE_ROM_TABLES || defined TABLEMANAGER_COMPRESSED_TABLES || defined TABLEMANAGER_DYNAMIC_REV_TABLES void TableCacheManager::RemoveFromLRU(UINT16 index) { // Remove from LRU buffer if it is listed there int i; for (i=0; i < ENCODINGS_LRU_SIZE; i++) { if (index == m_lru[i]) { // Push any previous entries forward int j; for (j=i; j > 0; j--) { m_lru[j] = m_lru[j-1]; } m_lru[0] = -1; break; } } } #endif // !ENCODINGS_HAVE_ROM_TABLES || TABLEMANAGER_COMPRESSED_TABLES || TABLEMANAGER_DYNAMIC_REV_TABLES /** Comparison function for qsort and bsearch. */ int TableCacheManager::tablenamecmp(const void *p1, const void *p2) { const TableDescriptor *d1 = reinterpret_cast<const TableDescriptor *>(p1); const TableDescriptor *d2 = reinterpret_cast<const TableDescriptor *>(p2); return op_stricmp(d1->table_name, d2->table_name); } #endif // ENCODINGS_HAVE_TABLE_DRIVEN
#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; const double eps = 1e-9; double equ[100][300]; int fri[100]; vector<double> a; bool vis[10]; int dcmp(double x) { if (abs(x) < eps) return 0; return x > 0?1:-1; } long long dfs() { if (!a.size()) return 2; int ans = 0,k = a.size(); for (int i = 0; i < (1 << k); i++) { int f = 0; for (int j = 0;j < k; j++) { f += a[j]*(((i >> j) & 1)?1:-1); } if (!dcmp(f)) ans++; } return ans; } int main() { int t; scanf("%d",&t); while (t--) { int n,m; int from,to; scanf("%d%d",&n,&m); for (int i = 1;i <= n; i++) for (int j = 1;j <= m; j++) equ[i][j] = 0; for (int i = 1;i <= m; i++) { scanf("%d%d",&from,&to); fri[from]++;fri[to]++; equ[from][i] = 1; equ[to][i] = 1; } bool has = true; for (int i = 1;i <= n; i++) if (fri[i]%2) { has = false; break; } if (has) { memset(vis,false,sizeof(vis)); int now = 1; for (int cou = 1;cou < n; cou++) { int loc = 0,aloc,next; vis[now] = true; for (int i = 1;i <= m; i++) if (dcmp(equ[now][i])) { loc = i; aloc = equ[now][i]; break; } for (int i = loc+1;i <= m; i++) { //cout << equ[now][i] << " " << aloc << endl; equ[now][i] = -equ[now][i]/aloc; } for (int i = 1;i <= n; i++) if (!vis[i] && dcmp(equ[i][loc])) { next = i; break; } for (int i = 1;i <= m; i++) equ[next][i] += equ[now][i]; equ[next][loc] = 0; now = next; } a.clear(); long long ans = 1; for (int i = 1;i <= m; i++) { //cout << equ[now][i] << " "; if (dcmp(equ[now][i])) a.push_back(equ[now][i]); } //cout << endl; printf("%lld\n",dfs()); } else { printf("0\n"); } } return 0; }
#include <iostream> #include <cstdlib> #include <fstream> #include <chrono> #include <unistd.h> #include <string> #include <vector> #include <sstream> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <windows.h> #include <winsock2.h> #include <ws2tcpip.h> #include <iphlpapi.h> #include <dir.h> #include <dirent.h> #include <conio.h> #include <ctype.h> #define PATH "C:\\MinGW\\bin\\Networking\\" // PATH #define DUMP "DUMP" // Dump folder #define QBANK "QBANK" // folder where questions are stored in .txt files #define LBOARD "LBOARD" // Leaderboard entries are stored in LBOARD.dat #define DATA "DATA" #define DAT ".DAT" #define TXT ".TXT" #define SERVER_PORT 12345 #define QUEUE_SIZE 5 #define LOOPBACK_IP "127.0.0.1" #define DELIM "|" #define SUCCESS 0 #define ESC 27 #define ABORTED -1 #define BADFILE -6 #define REQUEST_LBE "pls" // Magic word #define ENTRY_ADDED "Leaderboard has been updated" #define MAX_LBE_DISPLAY 3 // Max entries displayed by view leaderboards typedef struct { int qtotal,qright,qwrong; } QResult; typedef struct { char uname[50], date[30]; int score; float accuracy, speed; long duration; QResult qresult; } LeaderboardEntry; typedef struct { char uname[50]; // char password[20]; } Player; typedef struct { char question[1000]; char option[4][1000]; int answer; } Question; int ReadTextFiles(); Player login(); void Newgame(Player); int GameUI (LeaderboardEntry&, Player); Question fetchquestion(char*, int); void displayquestion(int, Question); int GetAnswer(); int SendLeaderboardEntry (LeaderboardEntry); std::string ldb_struct_to_string(LeaderboardEntry); int sendall(int, char*, int&); void PostGame (LeaderboardEntry); int view_leaderboards(); int fetch_leaderboards(LeaderboardEntry*); int string_to_ldb_struct(LeaderboardEntry*, std::string); int retrieve_lbe(LeaderboardEntry*); int AddLeaderboardEntry(LeaderboardEntry); void swap(int*, int, int); void FisherYates(int*, int); void DeleteFolder(char*); void DeletWork_dat(); char* pathof(char*, char*, char*, char*); int countinfile(char*, char*, char*, int);
#include <iostream> using std::cout; using std::endl; using std::cin; #include <string> using std::string; bool has_upper(const string& s) { for(auto c : s) { if(isupper(c)) return true; } return false; } void to_upper(string& s) { for(auto& c : s) { c = toupper(c); } return; } int main() { string s; cin >> s; cout << "has upper char? " << has_upper(s) << endl; to_upper(s); cout << "to upper: " << s << endl; return 0; }
#ifndef _MSG_0X82_UPDATESIGN_TW_H_ #define _MSG_0X82_UPDATESIGN_TW_H_ #include "mcprotocol_base.h" namespace MC { namespace Protocol { namespace Msg { class UpdateSign : public BaseMessage { public: UpdateSign(); UpdateSign(int32_t _x, int16_t _y, int32_t _z, const String16& _text1, const String16& _text2, const String16& _text3, const String16& _text4); size_t serialize(Buffer& _dst, size_t _offset); size_t deserialize(const Buffer& _src, size_t _offset); int32_t getX() const; int16_t getY() const; int32_t getZ() const; const String16& getText1() const; const String16& getText2() const; const String16& getText3() const; const String16& getText4() const; void setX(int32_t _val); void setY(int16_t _val); void setZ(int32_t _val); void setText1(const String16& _val); void setText2(const String16& _val); void setText3(const String16& _val); void setText4(const String16& _val); private: int32_t _pf_x; int16_t _pf_y; int32_t _pf_z; String16 _pf_text1; String16 _pf_text2; String16 _pf_text3; String16 _pf_text4; }; } // namespace Msg } // namespace Protocol } // namespace MC #endif // _MSG_0X82_UPDATESIGN_TW_H_
// Created on: 1993-05-07 // Created by: Jean Yves LEBEY // Copyright (c) 1993-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 _TopOpeBRep_VPointInterIterator_HeaderFile #define _TopOpeBRep_VPointInterIterator_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <TopOpeBRep_PLineInter.hxx> #include <Standard_Integer.hxx> class TopOpeBRep_VPointInter; class TopOpeBRep_VPointInterIterator { public: DEFINE_STANDARD_ALLOC Standard_EXPORT TopOpeBRep_VPointInterIterator(); Standard_EXPORT TopOpeBRep_VPointInterIterator(const TopOpeBRep_LineInter& LI); Standard_EXPORT void Init (const TopOpeBRep_LineInter& LI, const Standard_Boolean checkkeep = Standard_False); Standard_EXPORT void Init(); Standard_EXPORT Standard_Boolean More() const; Standard_EXPORT void Next(); Standard_EXPORT const TopOpeBRep_VPointInter& CurrentVP(); Standard_EXPORT Standard_Integer CurrentVPIndex() const; Standard_EXPORT TopOpeBRep_VPointInter& ChangeCurrentVP(); Standard_EXPORT TopOpeBRep_PLineInter PLineInterDummy() const; protected: private: TopOpeBRep_PLineInter myLineInter; Standard_Integer myVPointIndex; Standard_Integer myVPointNb; Standard_Boolean mycheckkeep; }; #endif // _TopOpeBRep_VPointInterIterator_HeaderFile
#include <bits/stdc++.h> using namespace std; int N; vector<long long> bit; void upd(int i, int x) { while (i <= N) { bit[i] += x; i += i & (-i); } } int query(int i) { long long s = 0; while (i > 0) { s += bit[i]; i -= i & (-i); } return s; } int main() { cin >> N; vector<int> breeds(N + 1); bit.resize(N + 1); for (int i = 1; i <= N; i++) { cin >> breeds[i]; } long long ans = 0; vector<int> exist(N + 1); for (int i = 1; i <= N; i++) { if (exist[breeds[i]] != 0) { upd(exist[breeds[i]], -1); } ans += query(i) - query(exist[breeds[i]]); upd(i, 1); exist[breeds[i]] = i; } cout << ans << endl; }
#include "utils.hpp" #include "origin_ptts.hpp" namespace pd = proto::data; namespace pcs = proto::config; namespace nora { namespace config { origin_ptts& origin_ptts_instance() { static origin_ptts inst; return inst; } void origin_ptts_set_funcs() { } } }
//Probar ya que esta versión no la probe. Debería andar con la aplicación #include <Adafruit_CC3000.h> #include <SPI.h> #include "utility/debug.h" #include "utility/socket.h" //WiFi Shield #define led13 13 #define ADAFRUIT_CC3000_IRQ 3 #define ADAFRUIT_CC3000_VBAT 5 #define ADAFRUIT_CC3000_CS 10 #define WLAN_SSID "WIFIMobile" #define WLAN_PASS "123456789" #define WLAN_SSID1 "SpeedyHidden" #define WLAN_PASS1 "qpWOeiRUty" #define WLAN_SSID2 "WIFI4940" #define WLAN_PASS2 "12345678" #define WLAN_SECURITY WLAN_SEC_WPA2 #define LISTEN_PORT 8888 //Motor driver #define ENA 9 #define IN1 8 #define IN2 7 #define IN3 6 #define IN4 4 #define ENB 2 #define LUCES 23 Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIV2); Adafruit_CC3000_Server server(LISTEN_PORT); char m; boolean adelante=true; int velocidad=20; void setup() { pinMode(led13, OUTPUT); pinMode(ENA, OUTPUT); pinMode(ENB, OUTPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT); pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT); pinMode(LUCES, OUTPUT); digitalWrite(led13, LOW); Serial.begin(115200); inicializarMotoresPositivo(); delay(500); Serial.println("Inicializando servidor..."); if(!cc3000.begin()) { Serial.println("No se puede inicializar la placa"); while(1) { error(); } } Serial.println("Intentando conectar a la red"); if(cc3000.connectToAP(WLAN_SSID1, WLAN_PASS1, WLAN_SECURITY, 2)) { Serial.println("Se conecto correctamente a la red"); digitalWrite(led13, HIGH); while(!cc3000.checkDHCP()) { delay(100); } while(!mostrarDatosDeConexion()) delay(1000); server.begin(); Serial.println("Esperando una nueva conexion..."); Serial.println(); } else { Serial.println("No se puede conectar a la red"); while(1) error(); } } void loop() { Adafruit_CC3000_ClientRef cliente = server.available(); //Apenas se conecta el sistema android debe enviar un caracter if(cliente.available()) { digitalWrite(LUCES, HIGH); m=cliente.read(); switch(m){ case 'm': Serial.println(m); comprobarProtocolo(m, cliente); break; case 'a': Serial.println(m); aumentarVelocidad(); break; case 'd': Serial.println(m); disminuirVelocidad(); break; case 'p': Serial.println(m); parar(); break; case 'b': Serial.println(); acelerar(); break; case 'r': Serial.println(); marchaAtras(); break; default: Serial.println("No se reconoce el comando"); break; } } } //Funciones de usuario void comprobarProtocolo(char m, Adafruit_CC3000_ClientRef cliente) { if(m=='m') Serial.println("Se cumple el protocolo... Esperando comandos"); else { Serial.println("No se cumple el protocolo, intente conectar nuevamente"); cliente.stop(); cliente.flush(); } } boolean mostrarDatosDeConexion() { uint32_t dirIP, netMask, gateway, dhcpserv, dnsserv; if(!cc3000.getIPAddress(&dirIP, &netMask, &gateway, &dhcpserv, &dnsserv)) { Serial.println("No se puede mostrar los detalles"); return false; } else { Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(dirIP); Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netMask); Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway); Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv); Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv); Serial.println(); return true; } } void inicializarMotoresPositivo() { digitalWrite(IN1, LOW); digitalWrite(IN2, HIGH); digitalWrite(IN3, LOW); digitalWrite(IN4, HIGH); } void inicializarMotoresNegativo() { digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW); } void aumentarVelocidad() { digitalWrite(LUCES, LOW); if(adelante) //Si está yendo para adelante { if(velocidad<255) //Si la velocidad no es la mayor { velocidad+=5; //Aumento velocidad Serial.println("Aumento velocidad con sentido para adelante"); Serial.println(velocidad); } } else //Sino, Osea, si esta yendo para atras { if(velocidad>20) //Si la velocidada es mayor a 19 { digitalWrite(LUCES, HIGH); velocidad-=5; //Disminuyo velocidad Serial.println("Disminuyo velocidad intentando ir para adelante"); Serial.println(velocidad); } else //Sino, si la velocidad es igual a 19 { adelante=true; //Entonces voy a ir para adelante inicializarMotoresPositivo(); //Inicialializo el motor con el sentido positivo velocidad+=5; delay(500); Serial.println("Cambio el sentido para adelante e inicializo el motor positivo"); Serial.println(velocidad); } } actualizarVelocidad(velocidad); } void disminuirVelocidad() { digitalWrite(LUCES, HIGH); if(adelante) { if(velocidad>19) { velocidad-=5; Serial.println("Bajo velocidad con sentido para adelante"); Serial.println(velocidad); } else { adelante=false; inicializarMotoresNegativo(); velocidad+=5; delay(500); Serial.println("Cambio el sentido para atras, inicializo motor negativo"); Serial.println(velocidad); } } else { if(velocidad<255) { velocidad+=5; Serial.println("Aumento velocidad con sentido para atras"); Serial.println(velocidad); } } actualizarVelocidad(velocidad); } void parar() { digitalWrite(LUCES, HIGH); velocidad=0; actualizarVelocidad(velocidad); Serial.println("El robot se detuvo"); } void acelerar() { digitalWrite(LUCES, LOW); if(velocidad<=40 || adelante == false) { parar(); inicializarMotoresPositivo(); adelante = true; velocidad=100; digitalWrite(LUCES, LOW); actualizarVelocidad(velocidad); Serial.println("Acelerando el robot"); Serial.println(velocidad); } } void marchaAtras() { digitalWrite(LUCES, HIGH); if(velocidad <= 40 || adelante==true) { parar(); inicializarMotoresNegativo(); adelante = false; velocidad=100; actualizarVelocidad(velocidad); Serial.println("Auto corriendo en marcha atrás"); Serial.println(velocidad); } } void actualizarVelocidad(int velocidad) { analogWrite(ENA, velocidad); analogWrite(ENB, velocidad); //Acá envió la velocidad server.write(velocidad); } void error(){ delay(1000); digitalWrite(led13, HIGH); delay(1000); digitalWrite(led13, LOW); }
#include <iostream> #include "base.hpp" #include "op.hpp" #include "rand.hpp" #include "mult.hpp" #include "div.hpp" #include "add.hpp" #include "sub.hpp" #include "pow.hpp" #include "factory.hpp" int main(int argv, char** argc) { factory* f = new factory(); Base* res = f->parse(argc, argv); if(res == nullptr) { std::cout << "Invalid input" << std::endl; } std::cout << "Number result is: " << res->evaluate() << std::endl; std::cout << "String result is: " << res->stringify() << std::endl; return 0; }
// Created on: 1995-10-26 // Created by: Yves FRICAUD // Copyright (c) 1995-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 _BRepAlgo_Image_HeaderFile #define _BRepAlgo_Image_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <TopTools_ListOfShape.hxx> #include <TopTools_DataMapOfShapeShape.hxx> #include <TopTools_DataMapOfShapeListOfShape.hxx> #include <Standard_Boolean.hxx> #include <TopAbs_ShapeEnum.hxx> class TopoDS_Shape; //! Stores link between a shape <S> and a shape <NewS> //! obtained from <S>. <NewS> is an image of <S>. class BRepAlgo_Image { public: DEFINE_STANDARD_ALLOC Standard_EXPORT BRepAlgo_Image(); Standard_EXPORT void SetRoot (const TopoDS_Shape& S); //! Links <NewS> as image of <OldS>. Standard_EXPORT void Bind (const TopoDS_Shape& OldS, const TopoDS_Shape& NewS); //! Links <NewS> as image of <OldS>. Standard_EXPORT void Bind (const TopoDS_Shape& OldS, const TopTools_ListOfShape& NewS); //! Add <NewS> to the image of <OldS>. Standard_EXPORT void Add (const TopoDS_Shape& OldS, const TopoDS_Shape& NewS); //! Add <NewS> to the image of <OldS>. Standard_EXPORT void Add (const TopoDS_Shape& OldS, const TopTools_ListOfShape& NewS); Standard_EXPORT void Clear(); //! Remove <S> to set of images. Standard_EXPORT void Remove (const TopoDS_Shape& S); //! Removes the root <theRoot> from the list of roots and up and down maps. Standard_EXPORT void RemoveRoot (const TopoDS_Shape& Root); //! Replaces the <OldRoot> with the <NewRoot>, so all images //! of the <OldRoot> become the images of the <NewRoot>. //! The <OldRoot> is removed. Standard_EXPORT void ReplaceRoot (const TopoDS_Shape& OldRoot, const TopoDS_Shape& NewRoot); Standard_EXPORT const TopTools_ListOfShape& Roots() const; Standard_EXPORT Standard_Boolean IsImage (const TopoDS_Shape& S) const; //! Returns the generator of <S> Standard_EXPORT const TopoDS_Shape& ImageFrom (const TopoDS_Shape& S) const; //! Returns the upper generator of <S> Standard_EXPORT const TopoDS_Shape& Root (const TopoDS_Shape& S) const; Standard_EXPORT Standard_Boolean HasImage (const TopoDS_Shape& S) const; //! Returns the Image of <S>. //! Returns <S> in the list if HasImage(S) is false. Standard_EXPORT const TopTools_ListOfShape& Image (const TopoDS_Shape& S) const; //! Stores in <L> the images of images of...images of <S>. //! <L> contains only <S> if HasImage(S) is false. Standard_EXPORT void LastImage (const TopoDS_Shape& S, TopTools_ListOfShape& L) const; //! Keeps only the link between roots and lastimage. Standard_EXPORT void Compact(); //! Deletes in the images the shape of type <ShapeType> //! which are not in <S>. //! Warning: Compact() must be call before. Standard_EXPORT void Filter (const TopoDS_Shape& S, const TopAbs_ShapeEnum ShapeType); protected: private: TopTools_ListOfShape roots; TopTools_DataMapOfShapeShape up; TopTools_DataMapOfShapeListOfShape down; }; #endif // _BRepAlgo_Image_HeaderFile
#include <stdio.h> #include <conio.h> #include <stdlib.h> #include <time.h> main() { int array[10],x,i,n,k=0,h=0,j; int loopc=10; srand(time(NULL)); do { printf("\n1. Generate and display a random array of size 10\n\twith values between 1 and 100 \n"); printf("2. Find the first occurrence of a given number\n"); printf("3. Find the last occurrence of a given number\n"); printf("4. Delete a given number from the array.\n"); printf("5. Find Minimum\n"); printf("6. Print the current contents of the array.\n"); printf("7. Add a number to the array.\n"); printf("8. Quit\n"); printf("enter your choice: "); scanf("%d",&x); if(x==1) for(i=0;i<10;i++) { array[i]=(rand()%100)+1; printf("%d\t",array[i]); loopc=10; } if(x==2) //first occur { printf("enter number: "); scanf("%d",&n); for(i=0;i<loopc;i++) if(n==array[i]) { printf("number found at slot#%d\n",i+1); break; } if(i==loopc) printf("\nElement not present in the array\n\n"); } if(x==3) //last occur { printf("enter number: "); scanf("%d",&n); for(i=loopc-1; i>=0;i--) { if(n==array[i]) { printf("number found at slot#%d\n",i+1); break; } if(i==0) printf("\nElement not present in the array\n\n"); } } if(x==4) //delete array { printf("enter number: "); scanf("%d",&n); for(i=0; i<loopc;i++) { if(n==array[i]) { for(j=i; j<(loopc);j++) array[j]=array[j+1] ; printf("\nsuccessfully deleted\n\n"); loopc=loopc-1; for(int i=0; i<loopc; i++) printf("%d\t",array[i]); printf("\n\n"); break; } } if(i==loopc) printf("\nnot in array\n\n"); } if(x==6) for(i=0;i<10;i++) printf("%d\t",array[i]); // if(x==7) }while(x!=8); }
/********************************************************* * Copyright (C) 2017 Daniel Enriquez (camus_mm@hotmail.com) * All Rights Reserved * * You may use, distribute and modify this code under the * following terms: * ** Do not claim that you wrote this software * ** A mention would be appreciated but not needed * ** I do not and will not provide support, this software is "as is" * ** Enjoy, learn and share. *********************************************************/ #ifndef UAD_UTILS_GL_H #define UAD_UTILS_GL_H #include "Config.h" #include <stdio.h> // //#include <GLES2/gl2.h> //#include <GLES2/gl2ext.h> #include <AlgebraLib.h> #include <string> #include <GL\glew.h> // void checkcompilederrors(GLuint shader, GLenum type); GLuint createShader(GLenum type, char* pSource); char *file2string(const char *path); //Busca el salto de linea e ignora todos los espacios despues de este void SkipEndLineAndWhiteSpaces(char* const buffer, char* const end, char** it); //Busca una cadena y revisa si en la misma linea no se encuentra la palabra "template" bool SearchStringAndJump(char* const buffer, char* const end, char** it, const char* string); //Extrae el numero que se encuentre antes del caracter especificado double GetNumberBeforeChar(char* const buffer, char* const end, char** it, char c); void SkipTemplates(char* const buffer, char* const end, char** it); std::string GetNextPath(char* const buffer, char* const end, char** it); Mat4D::CVector4D IntToColor(int Color); #endif
#pragma once namespace texture { class DXTexture; }; namespace mesh { class Mesh; class MeshEntry { public: MeshEntry() {}; MeshEntry(D3DXMATRIX& transform, Mesh* mesh) { this->transform = transform ; this->mesh = mesh; }; D3DXMATRIX transform; Mesh* mesh; }; typedef vector<MeshEntry> MeshList; class MeshSystem { public: MeshSystem(); ~MeshSystem(); void acquire(); void release(); bool acquired; string name; int refcount; // rendered geometry MeshList meshes; // collision geometry, etc. }; };
#ifndef _DX11_RENDERABLE_H_ #define _DX11_RENDERABLE_H_ #include "Renderable.h" #include "d3d11.h" namespace HW{ class DX11RenderSystem; class DX11Renderable : public Renderable{ public: DX11Renderable(RenderSystem* renderSystem); virtual ~DX11Renderable(); virtual void createInternalRes(); virtual void releaseInternalRes(); virtual GpuVertexData* GetGpuAttrData(InputLayout* layout); private: // A quick access to render system DX11RenderSystem* m_pSystem; }; } #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*- ** ** Copyright (C) 2009-2012 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #ifdef DOM_WEBWORKERS_SUPPORT #include "modules/dom/src/domenvironmentimpl.h" #include "modules/dom/src/domcore/node.h" #include "modules/dom/src/domevents/domeventlistener.h" #include "modules/dom/src/domcore/domerror.h" #include "modules/dom/src/domcore/domexception.h" #include "modules/dom/src/domwebworkers/domwebworkers.h" #include "modules/dom/src/domwebworkers/domwworker.h" #include "modules/dom/src/domwebworkers/domcrossmessage.h" #include "modules/dom/src/domwebworkers/domcrossutils.h" #include "modules/dom/src/domwebworkers/domwwutils.h" #include "modules/dom/src/domwebworkers/domwwloader.h" #include "modules/dom/src/domevents/domeventsource.h" #include "modules/dom/src/domfile/domfileerror.h" #include "modules/dom/src/domfile/domfileexception.h" #include "modules/dom/src/domfile/domfilereadersync.h" #include "modules/dom/src/opera/domhttp.h" #include "modules/dom/src/opera/domformdata.h" #include "modules/dom/src/js/js_console.h" #include "modules/dom/src/js/location.h" #include "modules/dom/src/js/navigat.h" #include "modules/dom/src/js/dombase64.h" #ifdef CANVAS_SUPPORT # include "modules/dom/src/canvas/domcontext2d.h" #endif // CANVAS_SUPPORT #ifdef WEBSOCKETS_SUPPORT #include "modules/prefs/prefsmanager/collections/pc_doc.h" #include "modules/dom/src/websockets/domwebsocket.h" #endif // WEBSOCKETS_SUPPORT #ifdef DOM_WEBWORKERS_WORKER_STAT_SUPPORT #include "modules/dom/src/domwebworkers/domwwinfo.h" #endif // DOM_WEBWORKERS_WORKER_STAT_SUPPORT #ifdef PROGRESS_EVENTS_SUPPORT #include "modules/dom/src/domevents/domprogressevent.h" #endif // PROGRESS_EVENTS_SUPPORT #include "modules/prefs/prefsmanager/collections/pc_js.h" #include "modules/dom/src/domglobaldata.h" DOM_DedicatedWorkerGlobalScope::DOM_DedicatedWorkerGlobalScope() #ifdef DOM_NO_COMPLEX_GLOBALS : DOM_Prototype(g_DOM_globalData->DOM_DedicatedWorkerGlobalScope_functions, g_DOM_globalData->DOM_DedicatedWorkerGlobalScope_functions_with_data) #else // DOM_NO_COMPLEX_GLOBALS : DOM_Prototype(DOM_DedicatedWorkerGlobalScope_functions, DOM_DedicatedWorkerGlobalScope_functions_with_data) #endif // DOM_NO_COMPLEX_GLOBALS { } /* virtual */ void DOM_DedicatedWorkerGlobalScope::GCTrace() { GetEnvironment()->GCTrace(); DOM_Prototype::GCTrace(); } DOM_SharedWorkerGlobalScope::DOM_SharedWorkerGlobalScope() #ifdef DOM_NO_COMPLEX_GLOBALS : DOM_Prototype(g_DOM_globalData->DOM_SharedWorkerGlobalScope_functions, g_DOM_globalData->DOM_SharedWorkerGlobalScope_functions_with_data) #else // DOM_NO_COMPLEX_GLOBALS : DOM_Prototype(DOM_SharedWorkerGlobalScope_functions, DOM_SharedWorkerGlobalScope_functions_with_data) #endif // DOM_NO_COMPLEX_GLOBALS { } /* virtual */ void DOM_SharedWorkerGlobalScope::GCTrace() { GetEnvironment()->GCTrace(); DOM_Prototype::GCTrace(); } /*-------------------------------------------------------------------------------------- */ DOM_WebWorker::DOM_WebWorker(BOOL is_dedicated) : parent(NULL), domain(NULL), worker_name(NULL), port(NULL), is_dedicated(is_dedicated), is_closed(FALSE), is_enabled(FALSE), connect_handler(NULL), keep_alive_counter(1024) { } /** Initialise the global scope for a Worker. @param proto The prototype of the worker's global object. @param worker The worker being created. @return No result, but method will leave with OpStatus::ERR_NO_MEMORY on OOM. */ /* static */ void DOM_WebWorker::SetupGlobalScopeL(DOM_Prototype *worker_prototype, DOM_WebWorker *worker) { worker_prototype->InitializeL(); DOM_Runtime *runtime = worker_prototype->GetRuntime(); DOM_BuiltInConstructor *constructor = OP_NEW(DOM_BuiltInConstructor, (worker_prototype)); LEAVE_IF_ERROR(DOM_Object::DOMSetFunctionRuntime(constructor, runtime, "WorkerGlobalScope")); ES_Value value; DOM_Object::DOMSetObject(&value, constructor); worker_prototype->PutL("WorkerGlobalScope", value, PROP_DONT_ENUM); worker_prototype->PutL(worker->IsDedicated() ? "DedicatedWorkerGlobalScope" : "SharedWorkerGlobalScope", value, PROP_DONT_ENUM); worker_prototype->PutL("constructor", value, PROP_DONT_ENUM); DOM_Event::ConstructEventObjectL(*worker->PutConstructorL("Event", DOM_Runtime::EVENT_PROTOTYPE), runtime); worker->PutConstructorL("ErrorEvent", DOM_Runtime::ERROREVENT_PROTOTYPE); DOM_DOMException::ConstructDOMExceptionObjectL(*worker->PutConstructorL("DOMException", DOM_Runtime::DOMEXCEPTION_PROTOTYPE, TRUE), runtime); DOM_Object *object; worker->PutObjectL("DOMError", object = OP_NEW(DOM_Object, ()), "DOMError", PROP_DONT_ENUM); DOM_DOMError::ConstructDOMErrorObjectL(*object, runtime); #ifdef DOM_HTTP_SUPPORT DOM_XMLHttpRequest_Constructor *xhr_constructor = OP_NEW_L(DOM_XMLHttpRequest_Constructor, ()); worker->PutFunctionL("XMLHttpRequest", xhr_constructor, "XMLHttpRequest", NULL); DOM_XMLHttpRequest::ConstructXMLHttpRequestObjectL(*xhr_constructor, runtime); DOM_AnonXMLHttpRequest_Constructor *anon_xhr_constructor = OP_NEW_L(DOM_AnonXMLHttpRequest_Constructor, ()); worker->PutFunctionL("AnonXMLHttpRequest", anon_xhr_constructor, "AnonXMLHttpRequest", NULL); worker->PutFunctionL("FormData", OP_NEW(DOM_FormData_Constructor, ()), "FormData", NULL); # ifdef PROGRESS_EVENTS_SUPPORT worker->PutFunctionL("XMLHttpRequestUpload", OP_NEW(DOM_Object, ()), "XMLHttpRequestUpload"); # endif // PROGRESS_EVENTS_SUPPORT #endif // DOM_HTTP_SUPPORT #ifdef CANVAS_SUPPORT worker->PutConstructorL("ImageData", DOM_Runtime::CANVASIMAGEDATA_PROTOTYPE); #endif // CANVAS_SUPPORT worker->PutFunctionL("FileReader", OP_NEW(DOM_FileReaderSync_Constructor, ()), "FileReader"); DOM_FileError::ConstructFileErrorObjectL(*worker->PutConstructorL("FileError", DOM_Runtime::FILEERROR_PROTOTYPE), runtime); worker->PutFunctionL("FileReaderSync", OP_NEW(DOM_FileReaderSync_Constructor, ()), "FileReaderSync"); DOM_FileException::ConstructFileExceptionObjectL(*worker->PutConstructorL("FileException", DOM_Runtime::FILEEXCEPTION_PROTOTYPE), runtime); worker->PutConstructorL("File", DOM_Runtime::FILE_PROTOTYPE); worker->PutFunctionL("Blob", OP_NEW(DOM_Blob_Constructor, ()), "Blob"); // Console object. Mirror Window, and provide it inside Workers too. DOM_Object::DOMSetObjectRuntimeL(object = OP_NEW(JS_Console, ()), runtime, runtime->GetPrototype(DOM_Runtime::CONSOLE_PROTOTYPE), "Console"); DOM_Object::DOMSetObject(&value, object); worker->PutL("console", value); DOM_Object::DOMSetObjectRuntimeL(object = OP_NEW(JS_Location_Worker, ()), runtime, runtime->GetPrototype(DOM_Runtime::WEBWORKERS_LOCATION_PROTOTYPE), "WorkerLocation"); worker->PutPrivateL(DOM_PRIVATE_location, object); DOM_Object::DOMSetObjectRuntimeL(object = OP_NEW(JS_Navigator_Worker, ()), runtime, runtime->GetPrototype(DOM_Runtime::WEBWORKERS_NAVIGATOR_PROTOTYPE), "WorkerNavigator"); worker->PutPrivateL(DOM_PRIVATE_navigator, object); worker->PutFunctionL("Worker", OP_NEW(DOM_DedicatedWorkerObject_Constructor,()),"Worker","s"); worker->PutFunctionL("SharedWorker", OP_NEW(DOM_SharedWorkerObject_Constructor,()),"SharedWorker","ss-"); #ifdef DOM_CROSSDOCUMENT_MESSAGING_SUPPORT worker->PutFunctionL("MessageChannel", OP_NEW(DOM_MessageChannel_Constructor,()),"MessageChannel", NULL); worker->PutFunctionL("MessageEvent", OP_NEW(DOM_MessageEvent_Constructor,()),"MessageEvent","-O"); worker->PutConstructorL("MessagePort", DOM_Runtime::CROSSDOCUMENT_MESSAGEPORT_PROTOTYPE); #endif // DOM_CROSSDOCUMENT_MESSAGING_SUPPORT #ifdef EVENT_SOURCE_SUPPORT worker->PutFunctionL("EventSource", OP_NEW(DOM_EventSource_Constructor, ()), "EventSource", "s{withCredentials:b}-"); #endif // EVENT_SOURCE_SUPPORT #ifdef PROGRESS_EVENTS_SUPPORT DOM_ProgressEvent_Constructor::AddConstructorL(worker); #endif // PROGRESS_EVENTS_SUPPORT /* Known interface object omissions: ApplicationCache, EventTarget, Database, FileList. */ #ifdef WEBSOCKETS_SUPPORT if (g_pcdoc->GetIntegerPref(PrefsCollectionDoc::EnableWebSockets, runtime->GetOriginURL())) { DOM_WebSocket_Constructor::AddConstructorL(worker); DOM_CloseEvent_Constructor::AddConstructorL(worker); } #endif // WEBSOCKETS_SUPPORT } /* static */ OP_STATUS DOM_WebWorker::ConstructGlobalScope(BOOL is_dedicated, DOM_Runtime *runtime) { DOM_WebWorker *worker; if (is_dedicated) worker = OP_NEW(DOM_DedicatedWorker, ()); else worker = OP_NEW(DOM_SharedWorker, ()); if (!worker) return OpStatus::ERR_NO_MEMORY; DOM_Prototype *worker_prototype; if (is_dedicated) worker_prototype = OP_NEW(DOM_DedicatedWorkerGlobalScope, ()); else worker_prototype = OP_NEW(DOM_SharedWorkerGlobalScope, ()); if (!worker_prototype) { OP_DELETE(worker); return OpStatus::ERR_NO_MEMORY; } RETURN_IF_ERROR(runtime->SetHostGlobalObject(worker, worker_prototype)); runtime->GetEnvironment()->GetWorkerController()->SetWorkerObject(worker); RETURN_IF_LEAVE(DOM_WebWorker::SetupGlobalScopeL(worker_prototype, worker)); return OpStatus::OK; } DOM_WebWorker::~DOM_WebWorker() { /* If OOM hits before this (host) global object has been attached, nothing to do. */ if (!GetRuntime()) return; /* Drop the connection to any _remaining_ connected workers; when a controllern shuts down * this DOM_WebWorker, the connected DOM_WebWorkerObject that it has registered will be let * go of first & deleted, which will cause them to unregister with this worker. Hence, any * remaining ones are still alive and can be safely closed off here. */ DetachConnectedWorkers(); RemoveActiveLoaders(); DropEntangledPorts(); is_closed = TRUE; port = NULL; if (worker_name) OP_DELETEA(worker_name); while (DOM_EventListener *listener = static_cast<DOM_EventListener*>(delayed_listeners.First())) { listener->Out(); DOM_EventListener::DecRefCount(listener); } processing_exceptions.Clear(); DOM_Object::DOMFreeValue(loader_return_value); if (GetEnvironment()->GetWorkerController() && GetEnvironment()->GetWorkerController()->GetWorkerObject() == this) GetEnvironment()->GetWorkerController()->SetWorkerObject(NULL); } DOM_DedicatedWorkerObject* DOM_WebWorker::GetDedicatedWorker() { if (!is_dedicated || connected_workers.Empty()) return NULL; else return static_cast<DOM_DedicatedWorkerObject*>(connected_workers.First()); } /* static */ OP_STATUS DOM_WebWorker::AddChildWorker(DOM_WebWorker *parent, DOM_WebWorker *w) { AsListElement<DOM_WebWorker> *element = OP_NEW(AsListElement<DOM_WebWorker>, (w)); if (!element) return OpStatus::ERR_NO_MEMORY; element->Into(&parent->child_workers); return OpStatus::OK; } /* static */ BOOL DOM_WebWorker::RemoveChildWorker(DOM_WebWorker *parent, DOM_WebWorker *worker) { for (AsListElement<DOM_WebWorker> *element = parent->child_workers.First(); element; element = element->Suc()) if (element->ref == worker) { element->Out(); OP_DELETE(element); return TRUE; } return FALSE; } OP_STATUS DOM_WebWorker::PushActiveLoader(DOM_WebWorker_Loader *l) { DOM_WebWorker_Loader_Element *element = OP_NEW(DOM_WebWorker_Loader_Element, (l)); if (!element) return OpStatus::ERR_NO_MEMORY; element->IntoStart(&active_loaders); return OpStatus::OK; } void DOM_WebWorker::PopActiveLoader() { if (DOM_WebWorker_Loader_Element *element = active_loaders.First()) { element->loader->Shutdown(); element->Out(); OP_DELETE(element); } } void DOM_WebWorker::RemoveActiveLoaders() { while (DOM_WebWorker_Loader_Element *element = active_loaders.First()) { element->loader->Shutdown(); element->Out(); OP_DELETE(element); } } void DOM_WebWorker::DOM_WebWorker_Loader_Element::GCTrace(DOM_Runtime *runtime) { runtime->GCMark(loader); } OP_STATUS DOM_WebWorker::SetParentWorker(DOM_WebWorker *p) { OP_STATUS status = OpStatus::OK; if (p) { parent = p; /* ..and back again; maintain a connection from the parent (e.g., for termination requests.) */ if (OpStatus::IsError(status = AddChildWorker(p, this))) /* Failure, reset attachment. */ parent = NULL; } return status; } OP_STATUS DOM_WebWorker::AddKeepAlive(DOM_Object *object, int *id) { RETURN_IF_ERROR(PutPrivate(keep_alive_counter, *object)); if (id) *id = keep_alive_counter; ++keep_alive_counter; return OpStatus::OK; } void DOM_WebWorker::RemoveKeepAlive(int id) { OpStatus::Ignore(DeletePrivate(id)); } OP_STATUS DOM_WebWorker::AddConnectedWorker(DOM_WebWorkerObject *worker) { /* "There can only be one." Clear out previous. */ if (is_dedicated) connected_workers.RemoveAll(); worker->Into(&connected_workers); return OpStatus::OK; } void DOM_WebWorker::ClearOtherWorker(DOM_WebWorkerObject *w) { OP_ASSERT(w && connected_workers.HasLink(w)); w->Out(); w->ClearWorker(); } /* static */ OP_STATUS DOM_WebWorker::NewExecutionContext(DOM_Object *this_object, DOM_WebWorker *&inner, DOM_WebWorkerDomain *&worker_domain, DOM_WebWorker *parent, DOM_WebWorkerObject *worker_object, const URL &origin, const uni_char *name, ES_Value *return_value) { OP_STATUS status; BOOL is_dedicated = (name == NULL); worker_domain = NULL; BOOL existing_worker = FALSE; inner = NULL; /* Create worker in some execution context/domain (worker_domain.) */ RETURN_IF_ERROR(DOM_WebWorker::Construct(this_object, inner, worker_domain, existing_worker, origin, is_dedicated, name, return_value)); RETURN_IF_ERROR(inner->AddConnectedWorker(worker_object)); DOM_EnvironmentImpl *worker_exec_env = worker_domain->GetEnvironment(); worker_exec_env->GetRuntime()->SetErrorHandler(inner); worker_exec_env->GetWorkerController()->SetWorkerObject(inner); /* For a shared worker, we simply share the running worker instance and won't reload any scripts or * perform other initialisation actions. The connection of a new 'user' of the worker is announced * to the worker instance by firing a 'connect' event. * (see the creation of the worker object in DOM_WebWorker::Make() for how this is done.) */ if (existing_worker) return OpStatus::OK; inner->SetLocationURL(origin); inner->port = NULL; inner->is_dedicated = is_dedicated; if (!is_dedicated) inner->worker_name = UniSetNewStr(name); /* And the incoming parent for the (outer) instance. */ RETURN_IF_ERROR(inner->SetParentWorker(parent)); /* Create the port that resides inside the shared worker */ if (!is_dedicated) { DOM_MessagePort *port = NULL; RETURN_IF_ERROR(DOM_MessagePort::Make(port, worker_exec_env->GetDOMRuntime())); inner->port = port; } /* Kick off the new worker and its instance by issuing a load/import of its script; followed by evaluation. */ status = OpStatus::OK; URL *resolved_url = NULL; OpAutoVector<URL> *import_urls = NULL; /* Attach the Web Worker to the controlling domain + configure its toplevel scope/execution context. */ RETURN_IF_ERROR(worker_domain->AddWebWorker(inner)); resolved_url = OP_NEW(URL, ()); if (!resolved_url) { status = OpStatus::ERR_NO_MEMORY; goto failed_import_script; } if (!DOM_WebWorker_Utils::CheckImportScriptURL(origin)) { OP_DELETE(resolved_url); status = OpStatus::ERR; goto failed_import_script; } else *resolved_url = origin; import_urls = OP_NEW(OpAutoVector<URL>, ()); if (!import_urls) { OP_DELETE(resolved_url); status = OpStatus::ERR_NO_MEMORY; goto failed_import_script; } if (OpStatus::IsError(status = import_urls->Add(resolved_url))) { OP_DELETE(resolved_url); OP_DELETE(import_urls); goto failed_import_script; } if (OpStatus::IsError(status = DOM_WebWorker_Loader::LoadScripts(this_object, inner, worker_object, import_urls, return_value, NULL/*interrupt_thread*/))) { failed_import_script: inner->TerminateWorker(); return status; } /* Enable the processing of listener registration -- the spec is in two minds here, * stating in one place (4.7.3, step 12/13) that message queues are enabled as the last step in * initialising a Worker object, while in another (4.5, step 8) stating that message queues * are only enabled after the script has finished processing its toplevel. * * => taking height for the situation that the spec may go either way, we keep around the notion * of enabling a worker (cf. EnableWorker()), but turn on the enabled state right away here. * If the spec goes with the other option, simply uncomment the next line. */ inner->is_enabled = TRUE; return OpStatus::OK; } /* virtual */ void DOM_WebWorker::GCTrace() { DOM_Runtime *runtime = GetRuntime(); if (port && runtime->IsSameHeap(port->GetRuntime())) runtime->GCMark(port); for (DOM_WebWorker_Loader_Element *loader = active_loaders.First(); loader; loader = loader->Suc()) loader->GCTrace(runtime); GCMark(loader_return_value); for (AsListElement<DOM_WebWorker> *element = child_workers.First(); element; element = element->Suc()) if (runtime->IsSameHeap(element->ref->GetRuntime())) runtime->GCMark(element->ref); for (DOM_MessagePort *p = entangled_ports.First(); p; p = p->Suc()) { OP_ASSERT(runtime->IsSameHeap(p->GetRuntime())); runtime->GCMark(p); } for (AsListElement<DOM_ErrorEvent> *error_event = processing_exceptions.First(); error_event; error_event = error_event->Suc()) if (runtime->IsSameHeap(error_event->ref->GetRuntime())) runtime->GCMark(error_event->ref); for (DOM_EventListener *listener = static_cast<DOM_EventListener*>(delayed_listeners.First()); listener; listener = static_cast<DOM_EventListener*>(listener->Suc())) listener->GCTrace(runtime); message_event_queue.GCTrace(runtime); error_event_queue.GCTrace(runtime); connect_event_queue.GCTrace(runtime); GCMark(FetchEventTarget()); } /* static */ OP_STATUS DOM_WebWorker::Construct(DOM_Object *this_object, DOM_WebWorker *&worker_instance, DOM_WebWorkerDomain *&domain_instance, BOOL &existing_worker, const URL &origin, BOOL is_dedicated, const uni_char *name, ES_Value *return_value) { worker_instance = NULL; if (!g_webworkers->FindWebWorkerDomain(domain_instance, origin, name)) { if (!g_webworkers->CanCreateWorker()) { RETURN_IF_ERROR(DOM_WebWorker_Utils::ReportQuotaExceeded(this_object, FALSE, g_webworkers->GetMaxWorkersPerSession())); this_object->CallDOMException(QUOTA_EXCEEDED_ERR, return_value); // ignore ES_EXCEPTION; return OpStatus::ERR; } RETURN_IF_ERROR(DOM_WebWorkerDomain::Make(domain_instance, this_object, origin, is_dedicated, return_value)); worker_instance = domain_instance->GetEnvironment()->GetWorkerController()->GetWorkerObject(); g_webworkers->AddWorkerDomain(domain_instance); } if (is_dedicated) { worker_instance = domain_instance->GetEnvironment()->GetWorkerController()->GetWorkerObject(); return OpStatus::OK; } if (DOM_WebWorker *shared_worker = domain_instance->FindSharedWorker(origin, name)) { /* a shared worker instance's already active, attach to it. */ worker_instance = shared_worker; DOM_EnvironmentImpl *owner = this_object->GetEnvironment(); domain_instance = worker_instance->GetWorkerDomain(); /* Register new shared worker connection/reuse with its domain + record it with the instatiating environment's controller, so that we can unregister upon closing down. */ RETURN_IF_ERROR(domain_instance->AddDomainOwner(owner)); RETURN_IF_ERROR(owner->GetWorkerController()->AddWebWorkerDomain(domain_instance)); existing_worker = TRUE; } return (worker_instance ? OpStatus::OK : OpStatus::ERR); } OP_STATUS DOM_WebWorker::InvokeErrorListeners(DOM_ErrorEvent *exception, BOOL propagate_if_not_handled) { DOM_ErrorEvent *event = NULL; RETURN_IF_ERROR(DOM_ErrorException_Utils::CopyErrorEvent(this, event, exception, GetLocationURL(), propagate_if_not_handled)); /* Sigh - we want onerror handlers _at the worker global scope_ to be of the same shape (i.e., taking three arguments) as window.onerror, so flag this error event as a window event to have the event delivery code do the necessary unbundling. We _only_ do this when firing the event at the object representing the worker inside its execution context. If not, it's handled like a normal ErrorEvent. */ event->SetWindowEvent(); return DeliverError(this, event); } /* virtual */ OP_STATUS DOM_WebWorker::HandleException(DOM_ErrorEvent *exception) { if (error_handler) /* Handle the error by firing a local error event; none is already in flight */ return InvokeErrorListeners(exception, TRUE); else /* Either there are no local listeners or we are already processing an unhandled exception/error: how do we know if the exception happened as a result of processing it? We don't really (until we figure out how to inject an exception handler around 'onerror' executions..), so all subsequent exceptions are treated as stemming from within these exception handlers. */ return PropagateErrorException(exception); } OP_STATUS DOM_WebWorker::ProcessingException(DOM_ErrorEvent *error_event) { AsListElement<DOM_ErrorEvent> *element = OP_NEW(AsListElement<DOM_ErrorEvent>, (error_event)); if (!element) return OpStatus::ERR_NO_MEMORY; element->Into(&processing_exceptions); return OpStatus::OK; } void DOM_WebWorker::ProcessedException(DOM_ErrorEvent *exception) { for (AsListElement<DOM_ErrorEvent> *element = processing_exceptions.First(); element; element = element->Suc()) { DOM_ErrorEvent *error = element->ref; if (error == exception || exception->GetMessage() && error->GetMessage() && uni_str_eq(error->GetMessage(), exception->GetMessage())) { element->Out(); OP_DELETE(element); return; } } } BOOL DOM_WebWorker::IsProcessingException(const uni_char *message, unsigned line_number, const uni_char *url_str) { OP_ASSERT(message && url_str); for (AsListElement<DOM_ErrorEvent> *element = processing_exceptions.First(); element; element = element->Suc()) { DOM_ErrorEvent *error = element->ref; if (error->GetMessage() && uni_str_eq(error->GetMessage(), message) && error->GetResourceLineNumber() == line_number && uni_str_eq(error->GetResourceUrl(), url_str)) return TRUE; } return FALSE; } #ifdef ECMASCRIPT_DEBUGGER OP_STATUS DOM_WebWorker::GetWindows(OpVector<Window> &windows) { DOM_WebWorker *worker = this; /* If this is a child webworker, move all the way up the parent chain until we reach a worker instantiated by a real browsing context. */ while (worker->parent) worker = worker->parent; if (worker->GetWorkerDomain()) return worker->GetWorkerDomain()->GetWindows(windows); return OpStatus::OK; } #endif // ECMASCRIPT_DEBUGGER /* virtual */ OP_STATUS DOM_WebWorker::PropagateErrorException(DOM_ErrorEvent *exception) { /* If this worker is shared, then the error should be reported to the user (Section 4.7, second para.) */ if (!IsDedicated()) { /* Reset exception handling flags; we're done. */ ProcessedException(exception); return DOM_ErrorException_Utils::ReportErrorEvent(exception, GetLocationURL(), GetEnvironment()); } else { /* Check if parent is receptive.. */ DOM_WebWorker* parent_worker = GetParentWorker(); if (parent_worker && !parent_worker->IsDedicated()) { /* Parent is shared, report to user (Section 4.7, 4th para.) */ ProcessedException(exception); return DOM_ErrorException_Utils::ReportErrorEvent(exception, parent_worker->GetLocationURL(), parent_worker->GetEnvironment()); } else if (parent_worker) { /* Hand off the exception to the parent. */ ProcessedException(exception); return parent_worker->InvokeErrorListeners(exception, TRUE); } else if (GetDedicatedWorker() && GetDedicatedWorker()->GetEventTarget() && GetDedicatedWorker()->GetEventTarget()->HasListeners(ONERROR, UNI_L("error"), ES_PHASE_ANY)) { /* Fire the event at Worker object on the other side */ ProcessedException(exception); return GetDedicatedWorker()->InvokeErrorListeners(exception, TRUE); } else { /* All else failed (for dedicated worker.); report to user...but also queue it up for delivery at both worker sites. Either may have an .onerror listener registration queued up, so be helpful and notify them of prev. error when/if they come online. */ OpStatus::Ignore(InvokeErrorListeners(exception, FALSE)); if (GetDedicatedWorker()) OpStatus::Ignore(GetDedicatedWorker()->InvokeErrorListeners(exception, FALSE)); ProcessedException(exception); return DOM_ErrorException_Utils::ReportErrorEvent(exception, GetLocationURL(), GetEnvironment()); } } } /* virtual */ OP_STATUS DOM_WebWorker::HandleError(ES_Runtime *runtime, const ES_Runtime::ErrorHandler::ErrorInformation *information, const uni_char *message, const uni_char *url, const ES_SourcePosition &position, const ES_ErrorData *data) { unsigned line_number = position.GetAbsoluteLine(); if (!url) url = UNI_L(""); if (information->type == ES_Runtime::ErrorHandler::RUNTIME_ERROR && !IsProcessingException(message, line_number, url)) { DOM_ErrorEvent *event = NULL; RETURN_IF_ERROR(DOM_ErrorException_Utils::BuildErrorEvent(this, event, url, message, line_number, TRUE/*propagate, if needs be*/)); RETURN_IF_ERROR(ProcessingException(event)); RETURN_IF_ERROR(HandleException(event)); } if (data) runtime->IgnoreError(data); return OpStatus::OK; } /* static */ OP_STATUS DOM_WebWorker::HandleWorkerError(const ES_Value &exception) { /* This is the exception case of ES_AsyncCallback::HandleCallback() */ ES_Value message_value; unsigned line_number = 1; const uni_char *msg = UNI_L(""); /* Extrapolate the arguments required by HandleException() */ if (exception.type == VALUE_STRING) msg = exception.value.string; else if (exception.type == VALUE_OBJECT) { DOM_Object *host_object = DOM_HOSTOBJECT(exception.value.object, DOM_Object); if (host_object && host_object->IsA(DOM_TYPE_ERROREVENT)) { DOM_ErrorEvent *error_event = static_cast<DOM_ErrorEvent*>(host_object); msg = error_event->GetMessage(); line_number = error_event->GetResourceLineNumber(); } else if (host_object) { ES_Runtime *runtime = host_object->GetEnvironment()->GetRuntime(); /* Arguably trying way too hard... Q: is there a DOM_TYPE for DOMExceptions? */ if (OpStatus::IsSuccess(host_object->GetName(OP_ATOM_message, &message_value, runtime)) && message_value.type == VALUE_STRING) msg = message_value.value.string; else if (OpStatus::IsSuccess(host_object->Get(UNI_L("message"), &message_value)) && message_value.type == VALUE_STRING) msg = message_value.value.string; if (OpStatus::IsSuccess(host_object->GetName(OP_ATOM_lineno, &message_value, runtime)) && message_value.type == VALUE_NUMBER) line_number = static_cast<unsigned>(message_value.value.number); else if (OpStatus::IsSuccess(host_object->Get(UNI_L("lineno"), &message_value)) && message_value.type == VALUE_NUMBER) line_number = static_cast<unsigned>(message_value.value.number); else if (OpStatus::IsSuccess(host_object->Get(UNI_L("code"), &message_value)) && message_value.type == VALUE_NUMBER) line_number = static_cast<unsigned>(message_value.value.number); } else { ES_Object *error_object = exception.value.object; ES_Runtime *runtime = GetRuntime(); /* For Carakan friendliness; may elicit a warning about non-ref'ed variable w/ Futhark. */ if (OpStatus::IsSuccess(runtime->GetName(error_object, UNI_L("message"), &message_value)) && message_value.type == VALUE_STRING) msg = message_value.value.string; if (OpStatus::IsSuccess(runtime->GetName(error_object, UNI_L("lineno"), &message_value)) && message_value.type == VALUE_NUMBER) line_number = static_cast<unsigned>(message_value.value.number); } } DOM_ErrorEvent *event = NULL; OpString url_str; RETURN_IF_ERROR(GetLocationURL().GetAttribute(URL::KUniName_With_Fragment, url_str)); RETURN_IF_ERROR(DOM_ErrorException_Utils::BuildErrorEvent(this, event, url_str.CStr(), msg, line_number, TRUE/*propagate, if needs be*/)); return HandleException(event); } /* virtual */ OP_STATUS DOM_WebWorker::HandleCallback(ES_AsyncOperation operation, ES_AsyncStatus status, const ES_Value &result) { if (DOM_WebWorker_Loader_Element *element = active_loaders.First()) OpStatus::Ignore(element->loader->HandleCallback(status, result)); switch(status) { case ES_ASYNC_SUCCESS: /* If we've reached the end of evaluation and "enable" the worker (=> start message reception.) */ OpStatus::Ignore(EnableWorker()); return OpStatus::OK; case ES_ASYNC_EXCEPTION: return HandleWorkerError(result/*this is the exception object*/); /* 'result' is of an undefined nature for these; propagate an internal error event for now. */ case ES_ASYNC_FAILURE: case ES_ASYNC_NO_MEMORY: { DOM_ErrorEvent *event = NULL; const uni_char *msg; if (status == ES_ASYNC_FAILURE) msg = UNI_L("Internal error"); else msg = UNI_L("Out of memory"); unsigned line_number = 0; OpString url_str; RETURN_IF_ERROR(GetLocationURL().GetAttribute(URL::KUniName_With_Fragment, url_str)); RETURN_IF_ERROR(DOM_ErrorException_Utils::BuildErrorEvent(this, event, url_str.CStr(), msg, line_number, TRUE/*propagate, if needs be*/)); return HandleException(event); } case ES_ASYNC_CANCELLED: default: return OpStatus::OK; } } static BOOL IsEventHandlerFor(DOM_EventTarget *target, DOM_EventListener *listener, DOM_EventType event_type, const uni_char *event_name) { ES_Object *handler; return (target->HasListeners(event_type, event_name, ES_PHASE_ANY) && target->FindOldStyleHandler(event_type, &handler) == OpBoolean::IS_TRUE && listener->GetNativeHandler() == handler); } void DOM_WebWorker::UpdateEventHandlers(DOM_EventListener *l) { DOM_EventTarget *target = GetEventTarget(); /* Did we just add an .onXXX handler, and didn't have one before? */ if (!error_handler && IsEventHandlerFor(target, l, ONERROR, UNI_L("error"))) error_handler = l; if (!message_handler && IsEventHandlerFor(target, l, ONMESSAGE, UNI_L("message"))) message_handler = l; if (!connect_handler && IsEventHandlerFor(target, l, ONCONNECT, UNI_L("connect"))) connect_handler = l; } /* Terminate/close distinction - the former is from the outside, the latter triggered by explicit Worker call to "close()" */ void DOM_WebWorker::CloseChildren() { /* Summarily inform the children */ while (AsListElement<DOM_WebWorker> *element = child_workers.First()) element->ref->TerminateWorker(); child_workers.Clear(); } /* virtual */ OP_STATUS DOM_WebWorker::DrainEventQueues() { return DOM_WebWorkerBase::DrainEventQueues(this); } /* virtual */ OP_STATUS DOM_SharedWorker::DrainEventQueues() { if (!connect_event_queue.HaveDrainedEvents() && GetEventTarget() && GetEventTarget()->HasListeners(ONCONNECT, UNI_L("connect"), ES_PHASE_ANY)) OpStatus::Ignore(connect_event_queue.DrainEventQueue(GetEnvironment())); return DOM_WebWorkerBase::DrainEventQueues(this); } /* virtual */ ES_PutState DOM_SharedWorker::PutName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime) { switch(property_name) { case OP_ATOM_applicationCache: case OP_ATOM_location: case OP_ATOM_name: case OP_ATOM_self: return PUT_SUCCESS; case OP_ATOM_onconnect: PUT_FAILED_IF_ERROR(DOM_Object::CreateEventTarget()); return DOM_CrossMessage_Utils::PutEventHandler(this, UNI_L("connect"), ONCONNECT, connect_handler, &connect_event_queue, value, origining_runtime); default: return DOM_WebWorker::PutName(property_name, value, origining_runtime); } } /* virtual */ ES_PutState DOM_DedicatedWorker::PutName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime) { switch(property_name) { case OP_ATOM_location: case OP_ATOM_self: return PUT_SUCCESS; case OP_ATOM_onmessage: PUT_FAILED_IF_ERROR(DOM_Object::CreateEventTarget()); return DOM_CrossMessage_Utils::PutEventHandler(this, UNI_L("message"), ONMESSAGE, message_handler, &message_event_queue, value, origining_runtime); case OP_ATOM_onerror: PUT_FAILED_IF_ERROR(DOM_Object::CreateEventTarget()); return DOM_CrossMessage_Utils::PutEventHandler(this, UNI_L("error"), ONERROR, error_handler, &error_event_queue, value, origining_runtime); default: return DOM_WebWorker::PutName(property_name, value, origining_runtime); } } /* virtual */ ES_PutState DOM_WebWorker::PutName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime) { switch(property_name) { case OP_ATOM_onerror: PUT_FAILED_IF_ERROR(DOM_Object::CreateEventTarget()); return DOM_CrossMessage_Utils::PutEventHandler(this, UNI_L("error"), ONERROR, error_handler, &error_event_queue, value, origining_runtime); default: return DOM_Object::PutName(property_name, value, origining_runtime); } } OP_STATUS DOM_WebWorker::DeliverMessage(DOM_MessageEvent *message_event, BOOL is_message) { if (is_message) RETURN_IF_ERROR(message_event_queue.DeliverEvent(message_event, GetEnvironment())); else RETURN_IF_ERROR(connect_event_queue.DeliverEvent(message_event, GetEnvironment())); /* Somewhat unfortunate place, but do check that we haven't got a * a listener set up after all.. this can happen behind our back for * toplevel assignments to "onmessage = ..." for dedicated workers. */ return DrainEventQueues(); } OP_STATUS DOM_WebWorker::RegisterConnection(DOM_MessagePort *port_out) { DOM_MessageEvent *connect_event; RETURN_IF_ERROR(DOM_MessageEvent::MakeConnect(connect_event, TRUE, GetLocationURL(), this, port_out, TRUE/* with .ports alias */, this)); AddEntangledPort(port_out->GetTarget()); return DeliverMessage(connect_event, FALSE); } void DOM_WebWorker::TerminateWorker() { /* Perform termination of a Worker and its execution environment; extends to its progeny */ error_handler = NULL; message_handler = NULL; connect_handler = NULL; CloseWorker(); } void DOM_WebWorker::DetachConnectedWorkers() { for (DOM_WebWorkerObject *worker = connected_workers.First(); worker; worker = worker->Suc()) worker->ClearWorker(); connected_workers.RemoveAll(); } void DOM_WebWorker::CloseWorker() { is_closed = TRUE; /* Note: this includes handling downward termination notifications to children */ CloseChildren(); if (parent) RemoveChildWorker(parent, this); DetachConnectedWorkers(); DropEntangledPorts(); RemoveActiveLoaders(); if (domain) domain->RemoveWebWorker(this); domain = NULL; } /* virtual */ OP_STATUS DOM_WebWorker::EnableWorker() { if (is_closed || is_enabled) return OpStatus::OK; is_enabled = TRUE; RETURN_IF_ERROR(DOM_Object::CreateEventTarget()); while (DOM_EventListener *listener = static_cast<DOM_EventListener*>(delayed_listeners.First())) { listener->Out(); GetEventTarget()->AddListener(listener); UpdateEventHandlers(listener); } OpStatus::Ignore(connect_event_queue.DrainEventQueue(GetEnvironment())); OpStatus::Ignore(message_event_queue.DrainEventQueue(GetEnvironment())); OpStatus::Ignore(error_event_queue.DrainEventQueue(GetEnvironment())); return OpStatus::OK; } /* static */ int DOM_WebWorker::close(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime) { DOM_THIS_OBJECT(worker, DOM_TYPE_WEBWORKERS_WORKER, DOM_WebWorker); worker->is_closed = TRUE; /* Summarily inform the children - a close is a termination event for them. */ worker->CloseChildren(); return ES_FAILED; } OP_STATUS DOM_WebWorker::SetLoaderReturnValue(const ES_Value &value) { DOM_Object::DOMFreeValue(loader_return_value); return DOM_Object::DOMCopyValue(loader_return_value, value); } /* static */ int DOM_WebWorker::importScripts(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime) { DOM_THIS_OBJECT(worker, DOM_TYPE_WEBWORKERS_WORKER, DOM_WebWorker); if (argc < 0) { CALL_FAILED_IF_ERROR(DOM_Object::DOMCopyValue(*return_value, worker->loader_return_value)); int result = (worker->loader_return_value.type == VALUE_UNDEFINED ? ES_FAILED : ES_EXCEPTION); DOM_Object::DOMFreeValue(worker->loader_return_value); DOM_Object::DOMSetUndefined(&worker->loader_return_value); worker->PopActiveLoader(); return result; } else if (argc == 0) return ES_FAILED; else { DOM_CHECK_ARGUMENTS("s"); URL base_url = worker->GetLocationURL(); OP_STATUS status; OpAutoVector<URL> *import_urls = OP_NEW(OpAutoVector<URL>, ()); if (!import_urls) return ES_FAILED; for (int i = 0 ; i < argc; i++) { URL *resolved_url = OP_NEW(URL, ()); if (!resolved_url) return ES_FAILED; if (OpStatus::IsError(status = import_urls->Add(resolved_url))) { OP_DELETE(resolved_url); OP_DELETE(import_urls); CALL_FAILED_IF_ERROR(status); } BOOL is_import_url_ok = FALSE; BOOL type_mismatch = argv[i].type != VALUE_STRING; if (!type_mismatch) { URL effective_url = g_url_api->GetURL(base_url, argv[i].value.string); is_import_url_ok = DOM_WebWorker_Utils::CheckImportScriptURL(effective_url); if (is_import_url_ok) *resolved_url = effective_url; } if (type_mismatch || !is_import_url_ok) { OpString error_message; const uni_char *error_header = (type_mismatch ? UNI_L("Expecting string argument") : (!is_import_url_ok ? UNI_L("Security error importing script: ") : UNI_L("Unable to import script: "))); if (OpStatus::IsError(status = error_message.Append(error_header)) || !type_mismatch && OpStatus::IsError(status = error_message.Append(argv[i].value.string))) { OP_DELETE(import_urls); CALL_FAILED_IF_ERROR(status); } OpString url_str; CALL_FAILED_IF_ERROR(worker->GetLocationURL().GetAttribute(URL::KUniName_With_Fragment, url_str)); DOM_ErrorEvent *error_event = NULL; CALL_FAILED_IF_ERROR(DOM_ErrorException_Utils::BuildErrorEvent(worker, error_event, url_str.CStr(), error_message.CStr(), 0, FALSE)); DOM_Object::DOMSetObject(return_value, error_event); OP_DELETE(import_urls); return ES_EXCEPTION; } } ES_Thread *interrupt_thread = origining_runtime->GetESScheduler()->GetCurrentThread(); if (OpStatus::IsError(DOM_WebWorker_Loader::LoadScripts(this_object, worker, NULL, import_urls, return_value, interrupt_thread))) { const uni_char *header = UNI_L("Unable to import script"); OpString url_str; if (worker) CALL_FAILED_IF_ERROR(worker->GetLocationURL().GetAttribute(URL::KUniName_With_Fragment, url_str)); DOM_ErrorEvent *error_event = NULL; CALL_FAILED_IF_ERROR(DOM_ErrorException_Utils::BuildErrorEvent(worker, error_event, url_str.CStr(), header, 0, FALSE)); DOM_Object::DOMSetObject(return_value, error_event); return ES_EXCEPTION; } return (ES_RESTART | ES_SUSPEND); } } /* virtual */ ES_GetState DOM_DedicatedWorker::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime) { switch(property_name) { case OP_ATOM_onmessage: DOMSetObject(value, message_handler); return GET_SUCCESS; default: return DOM_WebWorker::GetName(property_name, value, origining_runtime); } } /* virtual */ ES_GetState DOM_SharedWorker::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime) { switch(property_name) { case OP_ATOM_name: OP_ASSERT(GetWorkerName()); DOMSetString(value, GetWorkerName()); return GET_SUCCESS; case OP_ATOM_applicationCache: // FIXME: Once AppCache is integrated with Web Workers; integrate and hook up here. DOMSetNull(value); return GET_SUCCESS; case OP_ATOM_onconnect: DOMSetObject(value, connect_handler); return GET_SUCCESS; default: return DOM_WebWorker::GetName(property_name, value, origining_runtime); } } /* virtual */ ES_GetState DOM_WebWorker::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime) { switch (property_name) { case OP_ATOM_self: DOMSetObject(value, this); return GET_SUCCESS; case OP_ATOM_location: return DOMSetPrivate(value, DOM_PRIVATE_location); case OP_ATOM_navigator: return DOMSetPrivate(value, DOM_PRIVATE_navigator); case OP_ATOM_onerror: /* Implement the HTML5-prescribed event target behaviour of giving back a 'null' rather than 'undefined' for targets without any listeners. We don't yet have a consistent story throughout dom/ for these event targets, hence local "hack". */ DOMSetObject(value, error_handler); return GET_SUCCESS; default: return DOM_Object::GetName(property_name, value, origining_runtime); } } /* static */ int DOM_DedicatedWorker::postMessage(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime) { DOM_THIS_OBJECT(worker, DOM_TYPE_WEBWORKERS_WORKER_DEDICATED, DOM_DedicatedWorker); if (argc < 0) return ES_FAILED; else if (argc == 0) return DOM_CALL_DOMEXCEPTION(NOT_SUPPORTED_ERR); else { DOM_WebWorkerObject *target_worker = worker->GetDedicatedWorker(); if (!target_worker) return ES_FAILED; if (worker->IsClosed()) { OpString url_str; CALL_FAILED_IF_ERROR(worker->GetLocationURL().GetAttribute(URL::KUniName_With_Fragment, url_str)); DOM_ErrorEvent *error_event = NULL; const uni_char* exception_string = UNI_L("postMessage() on closed worker"); CALL_FAILED_IF_ERROR(DOM_ErrorException_Utils::BuildErrorEvent(worker, error_event, url_str.CStr(), exception_string, 0, FALSE)); DOM_Object::DOMSetObject(return_value, error_event); return ES_EXCEPTION; } DOMSetNull(return_value); URL url = worker->GetLocationURL(); ES_Value message_argv[2]; message_argv[0] = argv[0]; if (argc == 1) DOMSetNull(&message_argv[1]); else message_argv[1] = argv[1]; ES_Value message_event_value; DOM_MessageEvent *message_event; int result; if ((result = DOM_MessageEvent::Create(message_event, worker, target_worker->GetEnvironment()->GetDOMRuntime(), NULL, NULL, url, message_argv, ARRAY_SIZE(message_argv), &message_event_value)) != ES_FAILED) { if (return_value) *return_value = message_event_value; return result; } message_event->SetTarget(target_worker); message_event->SetSynthetic(); CALL_FAILED_IF_ERROR(target_worker->DeliverMessage(message_event)); /* Have postMessage() suspend and restart as a way of giving the receiving context a chance to service the message right away. Not doing so leads to worker code that pumps out messages to run full-on for their timeslice, clogging up the system with messages that the listeners on the other side won't be able to drain. Laggy code and increased memory usage is the result. Hence, we force a context-switch here. It'll all be different when there are multiple threads of control running... (same comment re: restarting applies to DOM_DedicatedWorker::postMessage()) */ return (ES_RESTART | ES_SUSPEND); } } /* static */ int DOM_WebWorker::accessEventListener(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime, int data) { DOM_THIS_OBJECT(worker, DOM_TYPE_WEBWORKERS_WORKER, DOM_WebWorker); OP_ASSERT(origining_runtime == worker->GetEnvironment()->GetRuntime()); int status = DOM_Node::accessEventListener(this_object, argv, argc, return_value, origining_runtime, data); /* Check if adding a listener on the Worker object may allow us to drain queued-up events. */ if (argc >= 1 && (data == 0 || data == 2)) OpStatus::Ignore(worker->DrainEventQueues()); return status; } FramesDocument * DOM_WebWorker::GetWorkerOwnerDocument() { return DOM_WebWorker_Utils::GetWorkerFramesDocument(this, NULL); } #ifdef DOM_WEBWORKERS_WORKER_STAT_SUPPORT OP_STATUS DOM_WebWorker::GetStatistics(DOM_WebWorkerInfo *&info) { info->is_dedicated = is_dedicated; info->worker_name = worker_name; if (GetWorkerDomain()) info->worker_url = &GetOriginURL(); info->ports_active = entangled_ports.Cardinal(); if (GetDedicatedWorker()) { DOM_WebWorkerInfo *other_wwi = OP_NEW(DOM_WebWorkerInfo, ()); if (!other_wwi) { OP_DELETE(info); info = NULL; return OpStatus::ERR_NO_MEMORY; } other_wwi->is_dedicated = is_dedicated; other_wwi->worker_name = GetWorkerName(); other_wwi->ports_active = 0; other_wwi->worker_url = info->worker_url; other_wwi->Into(&info->clients); } else if (!connected_workers.Empty()) { DOM_WebWorkerInfo *other_wwi = OP_NEW(DOM_WebWorkerInfo, ()); if (!other_wwi) return OpStatus::ERR_NO_MEMORY; other_wwi->Into(&info->clients); for (DOM_WebWorkerObject *worker = connected_workers.First(); worker; worker = worker->Suc()) { if (worker->GetWorker()) { other_wwi->is_dedicated = IsDedicated(); other_wwi->worker_name = GetWorkerName(); other_wwi->ports_active = 0; other_wwi->worker_url = &worker->GetOriginURL(); } if (worker->Suc()) { DOM_WebWorkerInfo *nxt = OP_NEW(DOM_WebWorkerInfo, ()); if (!nxt) { OP_DELETE(info); info = NULL; return OpStatus::ERR_NO_MEMORY; } nxt->Follow(other_wwi); } } } if (!child_workers.Empty()) { DOM_WebWorkerInfo *child = OP_NEW(DOM_WebWorkerInfo, ()); if (!child) { OP_DELETE(info); info = NULL; return OpStatus::ERR_NO_MEMORY; } DOM_WebWorkerInfo *current_wi = child; child->Into(&info->children); OP_STATUS status; for (AsListElement<DOM_WebWorker> *element = child_workers.First(); element; element = element->Suc()) { DOM_WebWorker *w = element->ref; if (OpStatus::IsError(status = w->GetStatistics(current_wi))) { OP_DELETE(info); info = NULL; return status; } if (element->Suc()) { DOM_WebWorkerInfo *nxt = OP_NEW(DOM_WebWorkerInfo, ()); if (!nxt) { OP_DELETE(info); info = NULL; return OpStatus::ERR_NO_MEMORY; } nxt->Follow(current_wi); current_wi = nxt; } } } return OpStatus::OK; } #endif // DOM_WEBWORKERS_WORKER_STAT_SUPPORT #include "modules/dom/src/domglobaldata.h" /* Global functions / toplevel methods on the dedicated Worker global scope object: */ DOM_FUNCTIONS_START(DOM_DedicatedWorkerGlobalScope) DOM_FUNCTIONS_FUNCTION(DOM_DedicatedWorkerGlobalScope, DOM_DedicatedWorker::postMessage, "postMessage", NULL) DOM_FUNCTIONS_FUNCTION(DOM_DedicatedWorkerGlobalScope, DOM_WebWorker::close, "close", NULL) DOM_FUNCTIONS_FUNCTION(DOM_DedicatedWorkerGlobalScope, DOM_WebWorker::importScripts, "importScripts", "s-") DOM_FUNCTIONS_FUNCTION(DOM_DedicatedWorkerGlobalScope, DOM_Node::dispatchEvent, "dispatchEvent", NULL) #ifdef URL_UPLOAD_BASE64_SUPPORT DOM_FUNCTIONS_FUNCTION(DOM_DedicatedWorkerGlobalScope, DOM_Base64::atob, "atob", "Z-") DOM_FUNCTIONS_FUNCTION(DOM_DedicatedWorkerGlobalScope, DOM_Base64::btoa, "btoa", "Z-") #endif // URL_UPLOAD_BASE64_SUPPORT DOM_FUNCTIONS_END(DOM_DedicatedWorkerGlobalScope) DOM_FUNCTIONS_WITH_DATA_START(DOM_DedicatedWorkerGlobalScope) DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_DedicatedWorkerGlobalScope, JS_Window::setIntervalOrTimeout, 0, "setTimeout", "-n-") DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_DedicatedWorkerGlobalScope, JS_Window::setIntervalOrTimeout, 1, "setInterval", "-n-") DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_DedicatedWorkerGlobalScope, JS_Window::clearIntervalOrTimeout, 0, "clearInterval", "n-") DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_DedicatedWorkerGlobalScope, JS_Window::clearIntervalOrTimeout, 1, "clearTimeout", "n-") DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_DedicatedWorkerGlobalScope, DOM_WebWorker::accessEventListener, 0, "addEventListener", "s-b-") DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_DedicatedWorkerGlobalScope, DOM_WebWorker::accessEventListener, 1, "removeEventListener", "s-b-") DOM_FUNCTIONS_WITH_DATA_END(DOM_DedicatedWorkerGlobalScope) /* Global functions / toplevel methods on the shared Worker global scope object: */ DOM_FUNCTIONS_START(DOM_SharedWorkerGlobalScope) DOM_FUNCTIONS_FUNCTION(DOM_SharedWorkerGlobalScope, DOM_WebWorker::close, "close", NULL) DOM_FUNCTIONS_FUNCTION(DOM_SharedWorkerGlobalScope, DOM_WebWorker::importScripts, "importScripts", "s-") DOM_FUNCTIONS_FUNCTION(DOM_SharedWorkerGlobalScope, DOM_Node::dispatchEvent, "dispatchEvent", NULL) #ifdef URL_UPLOAD_BASE64_SUPPORT DOM_FUNCTIONS_FUNCTION(DOM_SharedWorkerGlobalScope, DOM_Base64::atob, "atob", "Z-") DOM_FUNCTIONS_FUNCTION(DOM_SharedWorkerGlobalScope, DOM_Base64::btoa, "btoa", "Z-") #endif // URL_UPLOAD_BASE64_SUPPORT DOM_FUNCTIONS_END(DOM_SharedWorkerGlobalScope) DOM_FUNCTIONS_WITH_DATA_START(DOM_SharedWorkerGlobalScope) DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_SharedWorkerGlobalScope, JS_Window::setIntervalOrTimeout, 0, "setTimeout", "-n-") DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_SharedWorkerGlobalScope, JS_Window::setIntervalOrTimeout, 1, "setInterval", "-n-") DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_SharedWorkerGlobalScope, JS_Window::clearIntervalOrTimeout, 0, "clearInterval", "n-") DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_SharedWorkerGlobalScope, JS_Window::clearIntervalOrTimeout, 1, "clearTimeout", "n-") DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_SharedWorkerGlobalScope, DOM_WebWorker::accessEventListener, 0, "addEventListener", "s-b-") DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_SharedWorkerGlobalScope, DOM_WebWorker::accessEventListener, 1, "removeEventListener", "s-b-") DOM_FUNCTIONS_WITH_DATA_END(DOM_SharedWorkerGlobalScope) #endif // DOM_WEBWORKERS_SUPPORT
#include "comn.h" #include "http-deal.h" int main() { CInternetSession session(_T("Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6")); Fun_InternetGetConnectedState(); }
#ifndef Model_h__ #define Model_h__ #include "../../middleware/includes/glm/glm.hpp" #include <vector> #include "../../middleware/includes/gl/glew.h" class Model { public: //VAO GLuint mVertexArrayObjectID; //VBOs GLuint mVertexDataBufferID; GLuint mColorDataBufferID; GLuint mIndicesDataBufferID; GLuint mUVDataBufferID; GLuint mNormalsBufferID; Model(); ~Model(); std::vector<glm::vec3> VertexData; std::vector<glm::vec3> ColorData; std::vector<glm::vec2> UVData; std::vector<glm::vec3> NormalsData; std::vector<unsigned short> IndicesData; void Initialize(); virtual void Update(); virtual void Draw(); virtual void DrawStrip(); virtual void DrawWireFrame(); void Cleanup(); }; #endif // Model_h__
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*- */ /** Typed Arrays - as specified Khronos (WebGL being the main motivator); http://www.khronos.org/registry/typedarray/specs/latest/ (a variant may end up as a EcmaScript TC39 specification at some point.) ArrayBuffer is the basic byte array view, with <Type>Array providing a uniformly typed view on top of it (instantiated at an integral or floating point type.) Or if a dynamic, heterogeneous view is required of the buffer, DataView is provided. It lets you index the array buffer at any of the above basic types. An ArrayBuffer can be shared by multiple DataViews and TypeArrays. */ #ifndef ES_TYPEDARRAY_H #define ES_TYPEDARRAY_H class ES_ArrayBuffer; class ES_DataView; class ES_TypedArray : public ES_Object { public: enum Kind { Int8Array = 0, Int16Array, Int32Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, Float32Array, Float64Array, DataViewArray, ES_TypedArrayCount }; static ES_TypedArray *Make(ES_Execution_Context *context, Kind kind, unsigned argc, ES_Value_Internal* argv); static ES_TypedArray *Make(ES_Context *context, ES_Global_Object *global_object, Kind kind, ES_ArrayBuffer* array_buffer, unsigned view_byte_offset = 0, unsigned view_byte_length = 0); Kind GetKind() { return kind; } ES_ArrayBuffer *GetArrayBuffer() { return array_buffer; } static unsigned GetElementSizeInBytes(Kind k); static const char *GetKindClassName(Kind k); void *GetStorage(); /**< Returns the storage (ES_ArrayBuffer::GetStorage() + offset) for this typed array. */ unsigned GetSize(); /**< Returns the size, in bytes, of the storage for this typed array. */ unsigned GetOffset(); /**< Returns the view byte offset for this typed array. */ void Neuter(); /**< Render this typed array unusable after transfer of its underlying ArrayBuffer. */ private: friend class ESMM; friend class ES_DataViewBuiltins; friend class ES_TypedArrayBuiltins; friend class ES_ArrayBuffer; static void Initialize(ES_TypedArray *typed_array, ES_Class *klass, Kind kind, ES_Object *buffer); static void Destroy(ES_TypedArray *typed_array); Kind kind; ES_ArrayBuffer *array_buffer; ES_TypedArray *next; ES_TypedArray *prev; /**< Typed arrays sharing the same ArrayBuffer are chained together. */ }; class ES_ArrayBuffer : public ES_Object { public: enum ByteOrder { LittleEndian = 0, BigEndian }; static ES_ArrayBuffer *Make(ES_Execution_Context *context, ES_Global_Object *global_object, unsigned argc, ES_Value_Internal *argv); static ES_ArrayBuffer *Make(ES_Context *context, ES_Global_Object *global_object, unsigned byte_length, unsigned char *bytes = NULL, BOOL initialize_to_zero = TRUE); /**< Create a new ArrayBuffer in the given execution context, optionally initializing it to hold an external buffer. @param context The execution context. @param global_object The global object. @param byte_length The requested length of this buffer. @param bytes If non-NULL, the external buffer that holds the storage and initial contents for this ArrayBuffer. Must be least 'byte_length' bytes large. If the allocation of the ArrayBuffer object is successful, ownership of 'bytes' is transferred to the object and further buffer accesses should not be performed. The buffer must have been allocated using the system allocator (op_malloc() / op_realloc()),, and will be released using that allocator's destructor (op_free) upon destruction of the ES_ArrayBuffer object. @param initialize_to_zero If TRUE, zero initialize the ArrayBuffer's storage. Passing in FALSE is appropriate if the buffer is created from external storage ('bytes' is non-NULL) or the storage will be initialized just after creation. @return If successful, returns the ArrayBuffer instance. If allocating the external buffer encounters OOM, a TypeError is thrown and NULL is returned. Callers are obliged to NULL check the return value. */ static void Transfer(ES_ArrayBuffer *source, ES_ArrayBuffer *target); /**< Transfer an ArrayBuffer to another. Transferring entails re-assigning the underlying storage to the other, leaving the source as empty. */ GetResult GetIndex(ES_Execution_Context *context, unsigned index, ES_Value_Internal &value, ES_TypedArray::Kind kind, ByteOrder byte_order); PutResult PutIndex(ES_Execution_Context *context, unsigned byte_index, const ES_Value_Internal &value, ES_TypedArray::Kind kind, ByteOrder byte_order); unsigned char *GetStorage() { return static_cast<ES_Byte_Array_Indexed *>(GetIndexedProperties())->Storage(); } unsigned GetSize() { return static_cast<ES_Byte_Array_Indexed *>(GetIndexedProperties())->Capacity(); } void RegisterTypedArray(ES_Context *context, ES_TypedArray *typed_array); /**< Register the given typed array as having a view of this ArrayBuffer. Needed for invalidation of the different views in case the ArrayBuffer is transferred (and, so-called, neutered in the process.) */ void RemoveTypedArray(ES_TypedArray *typed_array); /**< Upon destruction of a typed array, diassociate from its ArrayBuffer. */ private: friend class ESMM; static void Initialize(ES_ArrayBuffer *array_buffer, ES_Class *klass) { ES_Object::Initialize(array_buffer, klass); array_buffer->ChangeGCTag(GCTAG_ES_Object_ArrayBuffer); array_buffer->typed_array_view = NULL; } ES_TypedArray *typed_array_view; /**< Head of list of dependent typed array views, iterated over when neutering the array buffer upon transfer. @see RegisterTypedArray(). */ }; /** ES_DataView is a utility class for the DataView builtins, allowing reads and writes with a given byte order. Typed Arrays do not use this, but operate on the indexed representation directly. */ class ES_DataView { public: static GetResult GetIndex(ES_Execution_Context *context, ES_Object *this_object, unsigned index, ES_Value_Internal &value, ES_TypedArray::Kind kind, ES_ArrayBuffer::ByteOrder byte_order); static PutResult PutIndex(ES_Execution_Context *context, ES_Object *this_object, unsigned index, const ES_Value_Internal &value, ES_TypedArray::Kind kind, ES_ArrayBuffer::ByteOrder byte_order); }; #endif // ES_TYPEDARRAY_H
// Created on: 2007-07-06 // Created by: Pavel TELKOV // Copyright (c) 2007-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. // Original implementation copyright (c) RINA S.p.A. #ifndef Message_StatusType_HeaderFile #define Message_StatusType_HeaderFile //! Definition of types of execution status supported by //! the class Message_ExecStatus enum Message_StatusType { Message_DONE = 0x00000100, Message_WARN = 0x00000200, Message_ALARM = 0x00000400, Message_FAIL = 0x00000800 }; #endif
#include "application.h" namespace sge { using namespace graphics; App* App::s_Instance = nullptr; App::App(const std::string &name, const WindowProperties& properties) :m_FramesPerSecond(0), m_UpdatesPerSecond(0), m_Name(name){ window = new Window(name, properties); s_Instance = this; std::cout << window->getWidth() << std::endl; window->setEventCallback(std::bind(&App::onEvent, this, std::placeholders::_1)); } App::~App() { delete window; delete m_Timer; for(int i=0; i<m_LayerStack.size(); i++) delete m_LayerStack[i]; } void App::pushLayer(Layer* layer){ m_LayerStack.push_back(layer); } Layer* App::popLayer() { Layer* layer = m_LayerStack.back(); m_LayerStack.pop_back(); return layer; } Layer* App::popLayer(Layer* layer) { for (uint i = 0; i < m_LayerStack.size(); i++) { if (m_LayerStack[i] == layer) { m_LayerStack.erase(m_LayerStack.begin() + i); break; } } return layer; } void App::init() { } void App::start(){ init(); m_Running = true; m_Suspended = false; run(); } void App::suspend() { m_Suspended = true; } void App::resume() { m_Suspended = false; } void App::stop() { m_Running = false; } void App::onRender(){ for (uint i = 0; i < m_LayerStack.size(); i++){ m_LayerStack[i]->onRender(); } } void App::run(){ m_Timer = new Timer(); float time = 0.0f; float updateTimer = 0.0f; float updateTick = 1.0f / 60.0f; unsigned int frames = 0; unsigned int updates = 0; while(!window->closed()){ window->clear(); if (m_Timer->elapsed() - updateTimer > updateTick) { onUpdate(); updates++; updateTimer += updateTick; } onRender(); frames++; window->update(); if (m_Timer->elapsed() - time > 1.0f) { time += 1.0f; m_FramesPerSecond = frames; m_UpdatesPerSecond = updates; frames = 0; updates = 0; onTick(); } } } void App::onEvent(events::Event& event) { for (int i = m_LayerStack.size() - 1; i >= 0; i--) { m_LayerStack[i]->onEvent(event); if (event.isHandled()) return; } } }
#include "core/pch.h" #ifdef M2_SUPPORT #include "modules/util/simset.h" #include <ctype.h> #include "nntprange.h" #include "nntpmodule.h" NNTPRangeItem::NNTPRangeItem() : m_from(-1), m_to(-1) { } NNTPRange::NNTPRange() : m_availablerange_from(-1), m_availablerange_to(-1) { } NNTPRange::~NNTPRange() { range_list.Clear(); } OP_STATUS NNTPRange::SetReadRange(const OpStringC8& string) { range_list.Clear(); return AddRange(string); } void NNTPRange::SetAvailableRange(INT32 from, INT32 to) { m_availablerange_from = MIN(from,to); m_availablerange_to = MAX(from, to); } OP_STATUS NNTPRange::SetAvailableRange(const OpStringC8& available_range) { OP_STATUS ret; INT32 from=0, to=0; char* range_ptr = (char*)(available_range.CStr()); if (range_ptr) { if ((ret=ParseNextRange(range_ptr, from, to)) != OpStatus::OK) return ret; } SetAvailableRange(from, to); return OpStatus::OK; } OP_STATUS NNTPRange::GetReadRange(OpString8& string) const { OP_STATUS ret; string.Empty(); char temp_string[22]; NNTPRangeItem* item = (NNTPRangeItem*)(range_list.First()); while (item) { if (!string.IsEmpty() && (ret=string.Append(","))!=OpStatus::OK) return ret; if (item->m_from<0 || item->m_to<0) { temp_string[0] = 0; } else { if (item->m_to <= item->m_from) { sprintf(temp_string, "%d", item->m_from); } else { sprintf(temp_string, "%d-%d", item->m_from, item->m_to); } } if ((ret=string.Append(temp_string)) != OpStatus::OK) return ret; item = (NNTPRangeItem*)(item->Suc()); } return OpStatus::OK; } BOOL NNTPRange::IsRead(INT32 index) const { NNTPRangeItem* item = (NNTPRangeItem*)(range_list.First()); while (item) { if (item->m_from<=index && item->m_to>=index) { return TRUE; } else if (item->m_from > index) { return FALSE; } item = (NNTPRangeItem*)(item->Suc()); } return FALSE; } INT32 NNTPRange::GetUnreadCount() const { if (m_availablerange_from<0 || m_availablerange_to<0) return 0; INT32 unread = m_availablerange_to - m_availablerange_from + 1; NNTPRangeItem* item = (NNTPRangeItem*)(range_list.First()); while (item) { unread -= (item->m_to - item->m_from + 1); item = (NNTPRangeItem*)(item->Suc()); } return max(0, unread); } OP_STATUS NNTPRange::GetNextUnreadRange(INT32& low_limit, BOOL optimize, BOOL only_one_item, OpString8& unread_string, OpString8& optimized_string, INT32* count, INT32* max_to) const { INT32 from, to; unread_string.Empty(); optimized_string.Empty(); if (count) *count = 0; if (max_to) *max_to = 0; if (low_limit>m_availablerange_to || m_availablerange_from<0 || m_availablerange_to<0) return OpStatus::OK; from = max(low_limit, m_availablerange_from); to = m_availablerange_to; NNTPRangeItem* item = (NNTPRangeItem*)(range_list.First()); while (item && item->m_to<from) //Skip items before requested range { item = (NNTPRangeItem*)(item->Suc()); } while (item && item->m_from<=to) //Search for read ranges within the unread range { if (!optimize || ((item->m_to-item->m_from)>=10) || (item->m_from<=from && item->m_to>=to)) { if (item->m_from <= from) //Cut away from the start of the range. Still need to find the end of the range { from = item->m_to+1; } else { to = max(from, item->m_from-1); //Cut away from the end of the range. We have a final range, break out break; } } else //We optimize away this range. Add it to the optimized_string { OP_STATUS ret; if (!optimized_string.IsEmpty() && ((ret=optimized_string.Append(",")) != OpStatus::OK) ) return ret; char temp_string[22]; if (item->m_from<0 || item->m_to<0) { temp_string[0] = 0; } else { if (item->m_to<=item->m_from) { sprintf(temp_string, "%d", item->m_from); } else { sprintf(temp_string, "%d-%d", item->m_from, item->m_to); } } if ((ret=optimized_string.Append(temp_string)) != OpStatus::OK) return ret; } item = (NNTPRangeItem*)(item->Suc()); } if (from > m_availablerange_to) //No range available return OpStatus::OK; if (max_to) *max_to = to; if (count) { *count = (to - from) + 1; return OpStatus::OK; } char temp_string[22]; //Generate string if (from<0 || to<0) { temp_string[0] = 0; } else { if (to<=from || only_one_item) { sprintf(temp_string, "%d", from); low_limit = ++from; } else { sprintf(temp_string, "%d-%d", from, to); low_limit = ++to; } } return unread_string.Set(temp_string); } INT32 NNTPRange::GetNextUnreadCount(INT32& max_to) const { INT32 low_limit = 0; INT32 count; OpString8 unread_string, optimized_string; if (GetNextUnreadRange(low_limit, FALSE, FALSE, unread_string, optimized_string, &count, &max_to) == OpStatus::OK) return count; else return 0; } OP_STATUS NNTPRange::AddRange(const OpStringC8& string) { OP_STATUS ret; INT32 from, to; char* range_ptr = (char*)(string.CStr()); while (range_ptr) { if ( (ParseNextRange(range_ptr, from, to) == OpStatus::OK) && ((ret=AddRange(from, to)) != OpStatus::OK) ) { return ret; } } return OpStatus::OK; } OP_STATUS NNTPRange::AddRange(INT32 from, INT32 to) { if (from<0 || to<0) //No range to add return OpStatus::OK; //#pragma PRAGMAMSG("FG: Just to track down that strange bug in .newsrc-file [20020909]") OP_ASSERT(from<500000 && to<500000); if (from > to) { INT32 tmp_to = to; to = from; from = tmp_to; } if (range_list.Empty()) //Optimize handling of empty list { NNTPRangeItem* item = OP_NEW(NNTPRangeItem, ()); if (!item) return OpStatus::ERR_NO_MEMORY; item->m_from = from; item->m_to = to; item->Into(&range_list); return OpStatus::OK; } //Skip unrelated entries (item should never become NULL) NNTPRangeItem* item = (NNTPRangeItem*)(range_list.First()); NNTPRangeItem* tmp_item; while (item && ((item->m_to+1) < from)) { tmp_item = (NNTPRangeItem*)(item->Suc()); if (!tmp_item || (tmp_item->m_to+1)>=from) break; item = tmp_item; } NNTPRangeItem* current_item; if ((item->m_to+1)==from) { current_item = item; current_item->m_to = to; } else { current_item = OP_NEW(NNTPRangeItem, ()); if (!current_item) return OpStatus::ERR_NO_MEMORY; current_item->m_from = from; current_item->m_to = to; if (item->m_to < from) { current_item->Follow(item); } else { current_item->Precede(item); } } item = (NNTPRangeItem*)(current_item->Suc()); while (item && item->m_from<=(to+1)) { if (item->m_from<from) { current_item->m_from = item->m_from; } if (item->m_to>to) { current_item->m_to = item->m_to; } tmp_item = item; item->Out(); item = (NNTPRangeItem*)(current_item->Suc()); OP_DELETE(tmp_item); } return OpStatus::OK; } OP_STATUS NNTPRange::ParseNextRange(char*& range_ptr, INT32& from, INT32& to) { from = to = -1; if (!range_ptr) return OpStatus::ERR_OUT_OF_RANGE; while (*range_ptr && (*range_ptr<'0' || *range_ptr>'9')) //Skip any garbage in front of range range_ptr++; if (!*range_ptr) { range_ptr = NULL; return OpStatus::ERR_OUT_OF_RANGE; } from = 0; while (*range_ptr>='0' && *range_ptr<='9') { from = from*10+(*range_ptr-'0'); range_ptr++; } BOOL is_range=FALSE; while (*range_ptr && (*range_ptr<'0' || *range_ptr>'9')) { if ((*range_ptr) == '-') { is_range = TRUE; } else if ((*range_ptr) == ',') { is_range = FALSE; range_ptr++; break; } range_ptr++; } if (!is_range) { to = from; } else { to = 0; while (*range_ptr>='0' && *range_ptr<='9') { to = to*10+(*range_ptr-'0'); range_ptr++; } while (*range_ptr && (*range_ptr<'0' || *range_ptr>'9')) { if ((*range_ptr) == ',') { range_ptr++; break; } range_ptr++; } } if (range_ptr && !*range_ptr) range_ptr = NULL; return OpStatus::OK; } #endif //M2_SUPPORT
#include "Air.h" #include <sstream> #include <iostream> using std::cout; using std::endl; using std::stringstream; Air::Air(){ } Air::Air(string flechas_, int pelo_){ pelo=pelo_; flechas=flechas_; } string Air::getFlechas(){ return flechas; } void Air::setFlechas(string p){ flechas=p; } int Air::getPelo(){ return pelo; } void Air::setPelo(int p){ pelo=p; } string Air::toString(){ stringstream retorno; string r; cout<<"Air: \nCantidad de flechas: "<<flechas; cout<<"\nCantidad de pelo: "<<pelo<<"\n"; r=retorno.str(); return retorno.str(); } string Air::getClass(){ return "Air"; }
#include "tablestring.h" #include "streams/streams.h" #include <sstream> using namespace NAMESPACE_BINTABLE; BinTableString::BinTableString(InputStream &stream) { read(stream); }; BinTableString::BinTableString(InputStream &stream, uint32_t size) { read(stream, size); }; BinTableString::BinTableString(const BinTableString &other) { size = other.size; buffer_size = size; data = new char[size]; std::copy(other.data, other.data + size, data); delete_data = true; }; BinTableString::BinTableString() { }; void BinTableString::read_data_array(InputStream &stream) { if (data == nullptr || delete_data == false || size > buffer_size) { if (delete_data == true) { delete[] data; } data = new char[size]; buffer_size = size; delete_data = true; } stream.read(data, size); } void BinTableString::read(InputStream &stream) { stream.read_primitive_endian_aware(size); read_data_array(stream); } void BinTableString::read(InputStream &stream, uint32_t size) { this->size = size; read_data_array(stream); } void BinTableString::write(OutputStream &stream) { stream.write_primitive_endian_aware(size); stream.write(data, size); }; void BinTableString::set(char *data, uint32_t size, bool delete_data) { if (this->delete_data) { delete[] data; } this->data = data; this->size = size; this->buffer_size = size; this->delete_data = delete_data; } char *BinTableString::get_data() { return data; } uint32_t BinTableString::get_size() { return size; } void BinTableString::read_to_stream(InputStream &input_stream, OutputStream &output_stream, uint32_t &size) { input_stream.read_primitive_endian_aware(size); output_stream.write(input_stream, size); } void BinTableString::skip(InputStream &stream, uint32_t &size) { stream.read_primitive_endian_aware(size); stream.skip(size); }; std::string BinTableString::to_string() const { std::stringstream stream; stream.write(data, size); return stream.str(); } BinTableString::~BinTableString() { if (delete_data) { delete[] data; } } bool BinTableString::operator==(const BinTableString &other) { if ((data == nullptr) || (other.data == nullptr)) { if ((data == nullptr) && (other.data == nullptr)) { return true; } else { return false; } } if (size != other.size) { return false; } for (uint32_t i = 0; i < size; i++) { if (data[i] != other.data[i]) { return false; } } return true; } bool BinTableString::operator!=(const BinTableString &other) { return !((*this) == other); } bool BinTableString::operator<(const BinTableString &other) const { if (size != other.size) { return size < other.size; } for (uint32_t i = 0; i < size; i++) { if (data[i] != other.data[i]) { return data[i] < other.data[i]; } } return false; }
#include <ostream> #ifndef _LIBROS_H_ #define _LIBROS_H_ //tamaņos maximos #define LIB_BUFFER 245 #define LIB_CAMPOS 11 #define LIB_MAX 80 //tamaņos de campos #define MAX_AUTOR 3 #define LIB_MAX_CODIGO 6 #define LIB_MAX_NOMBRE 80 #define LIB_MAX_AUTOR 30 #define LIB_MAX_EDITORIAL 20 #define LIB_MAX_CATEGORIA 20 //campos de ingreso #define LIB_CODIGO 0 #define LIB_NOMBRE 1 #define LIB_AUTOR_1 2 #define LIB_AUTOR_2 3 #define LIB_AUTOR_3 4 #define LIB_COPIA 5 #define LIB_EDICION 6 #define LIB_FECHA_PUB 7 #define LIB_EDITORIAL 8 #define LIB_CATEGORIA 9 #define LIB_DISPONIBLE 10 //estructura de datos para almacenar datos de un libro struct datos_libro { //datos de busqueda char codigo[MAX_CODIGO+1];//codigo de 5 digitos para el libro, clave de busqueda //datos de identificacion char nombre[LIB_MAX_NOMBRE];//nombre del libro char autor[MAX_AUTOR][LIB_MAX_AUTOR];//nombre del autor del libro, permite hasta tres autores //datos auxiliares unsigned short copias;//cantidad disponible de este ejemplar unsigned short edicion;//numero de edicion del libro datos_fecha fecha_pub;//fecha de publicacion char editorial[LIB_MAX_EDITORIAL];//editorial del libro //datos de clasificacion char categoria[LIB_MAX_CATEGORIA];//tipo del libro bool disponible;//si el libro esta disponible o no para el prestamo //datos de objeto bool valido;//valida el objeto para la eliminacion }; //clase para almacenar a los libros //que se almacenaran en la biblioteca //y que seran solicitados en prestamo class libro { private: datos_libro datos; public: libro(void); //ARCHIVO //leer un libro unsigned short leer(unsigned long); //ingresar un nuevo libro unsigned short escribir(void); //modificar un libro unsigned short escribir(unsigned long); //copia los datos de un estudiante void copiar(datos_libro); //obtiene una copia de los datos de un estudiante void copiar_en(datos_libro&); //ALTAS //ingresar un nuevo libro void ingresar(void); //REPORTES //imprimir los datos de un libro void imprimir(void); //BUSQUEDAS //compara los datos de un libro bool comparar(datos_libro data); //MODIFICACIONES //modifica un libro void modificar(void); //ELIMINACIONES //validar un libro void validar(bool); //SOBRECARGADAS friend ostream& operator<< (ostream&, const datos_libro&); friend bool operator== (const datos_libro&, const datos_libro&);//compara dos estructuras de datos de libros }; //funcion para el menu de seleccion de actividad void menu_libro(usuario*); //ALTAS //funcion para ingresar los libros void ingresar_libros(void);//MENU DE ALTAS //funcion para ingresar libros desde un archivo void ingresar_archivo_libros(void);//ALTAS DE ARCHIVO //funcion para obtener los campos de un archivo datos_libro obtener_libro(char*); //funcion para ingresar un libro desde teclado void ingresar_libro(void);//ALTA DE TECLADO //REPORTES //funcion para imprimir una lista de prestamos void imprimir_libros(void);//MENU DE IMPRESION //BUSQUEDAS //funcion para buscar libros en el archivo void buscar_libros(void);//MENU DE BUSQUEDAS //funcion para buscar un libro dada la clave de busqueda bool buscar_libro(datos_libro&, unsigned long&);//BUSQUEDA //MODIFICACIONES //funcion para modificar libros void modificar_libros(void);//MENU DE MODIFICACIONES //ELIMINACIONES //funcion para eliminar libros void eliminar_libros(void);//MENU DE ELIMINACIONES //UTILES //funcion para obtener el total de datos de libros unsigned long total_libros(void); //funcion que verifica datos validos unsigned long libros_no_validos(void); //ARCHIVOS //funcion para guardar los datos validos void guardar_libros(void); #endif
#include "ui_uiA.h" #include "ui_uiB.h" // AUTOUIC includes on the first two lines of a header file #include <QObject> class UicOnly : public QObject { public: UicOnly(); ~UicOnly(); private: Ui::UiA* uiA; Ui::UiB* uiB; };
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <string.h> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; const int N = 20002; int w, h; vector< pair<int, int> > a[N]; int main() { freopen("circles.in", "r", stdin); freopen("circles.out", "w", stdout); int n; cin >> w >> h >> n; while (n--) { int x, y, r; cin >> x >> y >> r; int r2 = r * r; int can = r; int dy = 0; for (int i = y; i < h; ++i) { while (can >= 0 && can * can + dy * dy > r2) --can; if (can < 0) break; a[i].push_back(make_pair(max(x - can, 0), -1)); a[i].push_back(make_pair(min(x + can + 1, w), 1)); ++dy; } can = r; dy = 1; for (int i = y - 1; i >= 0; --i) { while (can >= 0 && can * can + dy * dy > r2) --can; if (can < 0) break; a[i].push_back(make_pair(max(x - can, 0), -1)); a[i].push_back(make_pair(min(x + can + 1, w), 1)); ++dy; } } int ans = 0; for (int i = 0; i < h; ++i) { sort(a[i].begin(), a[i].end()); int p = 0, st = 0; for (int j = 0; j < w; ++j) { while (p < a[i].size() && a[i][p].first == j) { st += a[i][p].second; ++p; } if (st == 0) ++ans; } } cout << ans << endl; return 0; }
#pragma once #include <boost/noncopyable.hpp> #include <mutiplex/callbacks.h> #include <mutiplex/ServerSocket.h> #include <mutiplex/InetAddress.h> namespace muti { class EventSource; class EventLoop; class Acceptor: boost::noncopyable { public: Acceptor(EventLoop* loop, const std::string& addr_str); Acceptor(EventLoop* loop, const InetAddress& addr); ~Acceptor(); void new_connection_callback(const NewConnectionCallback& callback) { on_new_connection_ = callback; } private: EventLoop* loop_; ServerSocket server_socket_; EventSource* accept_event_; InetAddress peer_addr_; InetAddress local_addr_; NewConnectionCallback on_new_connection_; }; }
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "Spherobot.h" #include "SpherobotGameMode.h" #include "SpherobotCharacter.h" #include "SpherobotBaseLevelScriptActor.h" ASpherobotGameMode::ASpherobotGameMode() { // set default pawn class to our character DefaultPawnClass = ASpherobotCharacter::StaticClass(); static ConstructorHelpers::FObjectFinder<UClass> PlayerPawnBPClass(TEXT("Class'/Game/Spherobot/Blueprints/Character_BP/SpherobotCharacter.SpherobotCharacter_C'")); if (PlayerPawnBPClass.Object != NULL) { DefaultPawnClass = PlayerPawnBPClass.Object; } } void ASpherobotGameMode::BeginPlay() { Super::BeginPlay(); ASpherobotBaseLevelScriptActor* LevelScriptActorInstance = Cast<ASpherobotBaseLevelScriptActor>(GetWorld()->GetLevelScriptActor()); }
/* * Copyright (c) 2009 Joel de Vahl * 2009 Markus Ålind * see LICENSE file for more info */ #ifndef INC_SIMD_DEBUG_HPP #define INC_SIMD_DEBUG_HPP #include "intrinsics.hpp" #include <cstdio> #define vDebugPrint(V) vDebugPrint_helper(#V, V) #define vDebugPrint_u32(V) vDebugPrint_u32_helper(#V, V) #define vDebugPrint_u32x(V) vDebugPrint_u32x_helper(#V, V) FORCE_INLINE void vDebugPrint_helper(const char* name, v128 v) { printf("%s = (%f %f %f %f)\n", name, vExtract(v, 0), vExtract(v, 1), vExtract(v, 2), vExtract(v, 3)); } FORCE_INLINE void vDebugPrint_u32_helper(const char* name, v128 v) { printf("%s = (%u %u %u %u)\n", name, vExtract_u32(v, 0), vExtract_u32(v, 1), vExtract_u32(v, 2), vExtract_u32(v, 3)); } FORCE_INLINE void vDebugPrint_u32x_helper(const char* name, v128 v) { printf("%s = (0x%x 0x%x 0x%x 0x%x)\n", name, vExtract_u32(v, 0), vExtract_u32(v, 1), vExtract_u32(v, 2), vExtract_u32(v, 3)); } #endif
// $Id$ // // Copyright (C) 2001-2006 Greg Landrum and Rational Discovery LLC // // @@ All Rights Reserved @@ // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include <GraphMol/QueryBond.h> namespace RDKit{ QueryBond::QueryBond(BondType bT) : Bond(bT) { if( bT != Bond::UNSPECIFIED ) dp_query = makeBondOrderEqualsQuery(bT); else dp_query = makeBondNullQuery(); }; QueryBond::~QueryBond(){ delete dp_query; dp_query=NULL; }; QueryBond &QueryBond::operator=(const QueryBond &other){ // FIX: should we copy molecule ownership? I don't think so. // FIX: how to deal with atom indices? dp_mol = 0; d_bondType = other.d_bondType; dp_query = other.dp_query->copy(); delete dp_props; if(other.dp_props) dp_props = new Dict(*other.dp_props); return *this; } Bond *QueryBond::copy() const { QueryBond *res = new QueryBond(*this); return res; } void QueryBond::setBondType(BondType bT) { // NOTE: calling this blows out any existing query d_bondType = bT; delete dp_query; dp_query = NULL; dp_query = makeBondOrderEqualsQuery(bT); } void QueryBond::setBondDir(BondDir bD) { // NOTE: calling this blows out any existing query // // Ignoring bond orders (which this implicitly does by blowing out // any bond order query) is ok for organic molecules, where the // only bonds assigned directions are single. It'll fail in other // situations, whatever those may be. // d_dirTag = bD; #if 0 delete dp_query; dp_query = NULL; dp_query = makeBondDirEqualsQuery(bD); #endif } void QueryBond::expandQuery(QUERYBOND_QUERY *what, Queries::CompositeQueryType how, bool maintainOrder){ QUERYBOND_QUERY *origQ = dp_query; std::string descrip; switch(how) { case Queries::COMPOSITE_AND: dp_query = new BOND_AND_QUERY; descrip = "BondAnd"; break; case Queries::COMPOSITE_OR: dp_query = new BOND_OR_QUERY; descrip = "BondOr"; break; case Queries::COMPOSITE_XOR: dp_query = new BOND_XOR_QUERY; descrip = "BondXor"; break; default: UNDER_CONSTRUCTION("unrecognized combination query"); } dp_query->setDescription(descrip); if(maintainOrder){ dp_query->addChild(QUERYBOND_QUERY::CHILD_TYPE(origQ)); dp_query->addChild(QUERYBOND_QUERY::CHILD_TYPE(what)); } else { dp_query->addChild(QUERYBOND_QUERY::CHILD_TYPE(what)); dp_query->addChild(QUERYBOND_QUERY::CHILD_TYPE(origQ)); } } bool QueryBond::Match(const Bond::BOND_SPTR what) const { return Match(what.get()); } namespace { bool localMatch(BOND_EQUALS_QUERY const *q1,BOND_EQUALS_QUERY const *q2){ if(q1->getNegation()==q2->getNegation()){ return q1->getVal()==q2->getVal(); } else { return q1->getVal()!=q2->getVal(); } } bool queriesMatch(QueryBond::QUERYBOND_QUERY const *q1, QueryBond::QUERYBOND_QUERY const *q2){ PRECONDITION(q1,"no q1"); PRECONDITION(q2,"no q2"); static const unsigned int nQueries=6; static std::string equalityQueries[nQueries]={"BondRingSize","BondMinRingSize","BondOrder","BondDir",\ "BondInRing","BondInNRings"}; bool res=false; std::string d1=q1->getDescription(); std::string d2=q2->getDescription(); if(d1=="BondNull"||d2=="BondNull"){ res = true; } else if(d1=="BondOr"){ // FIX: handle negation on BondOr and BondAnd for(QueryBond::QUERYBOND_QUERY::CHILD_VECT_CI iter1=q1->beginChildren();iter1!=q1->endChildren();++iter1){ if(d2=="BondOr"){ for(QueryBond::QUERYBOND_QUERY::CHILD_VECT_CI iter2=q2->beginChildren();iter2!=q2->endChildren();++iter2){ if(queriesMatch(iter1->get(),iter2->get())){ res=true; break; } } } else { if(queriesMatch(iter1->get(),q2)) { res=true; } } if(res) break; } } else if(d1=="BondAnd"){ res=true; for(QueryBond::QUERYBOND_QUERY::CHILD_VECT_CI iter1=q1->beginChildren();iter1!=q1->endChildren();++iter1){ bool matched=false; if(d2=="BondAnd"){ for(QueryBond::QUERYBOND_QUERY::CHILD_VECT_CI iter2=q2->beginChildren();iter2!=q2->endChildren();++iter2){ if(queriesMatch(iter1->get(),iter2->get())){ matched=true; break; } } } else { matched = queriesMatch(iter1->get(),q2); } if(!matched){ res=false; break; } } // FIX : handle BondXOr } else if(d2=="BondOr"){ // FIX: handle negation on BondOr and BondAnd for(QueryBond::QUERYBOND_QUERY::CHILD_VECT_CI iter2=q2->beginChildren();iter2!=q2->endChildren();++iter2){ if(queriesMatch(q1,iter2->get())) { res=true; break; } } } else if(d2=="BondAnd"){ res=true; for(QueryBond::QUERYBOND_QUERY::CHILD_VECT_CI iter2=q2->beginChildren();iter2!=q2->endChildren();++iter2){ if(queriesMatch(q1,iter2->get())){ res=false; break; } } } else if(std::find(&equalityQueries[0],&equalityQueries[nQueries],d1)!= &equalityQueries[nQueries]){ res=localMatch(static_cast<BOND_EQUALS_QUERY const *>(q1), static_cast<BOND_EQUALS_QUERY const *>(q2)); } return res; } } //end of local namespace bool QueryBond::Match(Bond const *what) const { PRECONDITION(what,"bad query bond"); PRECONDITION(dp_query,"no query set"); return dp_query->Match(what); } bool QueryBond::QueryMatch(QueryBond const *what) const { PRECONDITION(what,"bad query bond"); PRECONDITION(dp_query,"no query set"); if(!what->hasQuery()){ return dp_query->Match(what); } else { return queriesMatch(dp_query,what->getQuery()); } } } // end o' namespace
#pragma once #include "color.h" #include <vector> #include <string> #include <glm/glm.hpp> class Image { std::vector<ColorRGBA> image; glm::uvec2 size = { 0, 0 }; public: void Load(glm::uvec2 Size, ColorRGBA DefaultValue = { 0, 0, 0, 255 }); void Load(const std::string& file); void Save(const std::string& file); void Reset(); ColorRGBA& operator[](glm::uvec2 pos); const ColorRGBA& operator[](glm::uvec2 pos) const; glm::uvec2 GetSize() const { return size; } const void* GetRawData() const { return &image[0]; } void* GetRawData() { return &image[0]; } };