text
stringlengths
8
6.88M
vector<int> Solution::solve(vector<int> &A, int B) { vector<int> ans; sort(A.begin(),A.end(),greater<int>()); for(int i=0;i<B;i++){ ans.push_back(A[i]); } return ans; }
#include <bits/stdc++.h> using namespace std; #define TESTC "" #define PROBLEM "673" #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 times; scanf("%d",&times); char Arithmetic; getchar(); stack <char> check; char tmp; bool ans = true; while( ~scanf("%c",&Arithmetic) ){ if( Arithmetic == '\n' ){ if( ans && check.empty() ) printf("Yes\n"); else printf("No\n"); ans = true; while( !check.empty() ) check.pop(); } else if( Arithmetic == '(' || Arithmetic == '[' ){ check.push(Arithmetic); } else if( Arithmetic == ')' ){ if( check.empty() ){ ans = false; continue; } tmp = check.top(); check.pop(); if( tmp != '(' ) ans = false; } else if( Arithmetic == ']' ){ if( check.empty() ){ ans = false; continue; } tmp = check.top(); check.pop(); if( tmp != '[' ) ans = false; } } return 0; }
#ifndef RIGIDBODY_H #define RIGIDBODY_H #include "object.h" #include "CollisionFilter.h" class RigidBody:public Object,public btRigidBody { public: ///this class inherits from btrigidbody, so you can use addforce, etc for moving objects RigidBody(btScalar mass, btMotionState* motionState,btCollisionShape* collisionShape,btVector3&localInertia, int group, int mask); ~RigidBody(); private: btMotionState* mtnState; }; #endif // RIGIDBODY_H
/* Copyright 2021 University of Manchester Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http: // www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "virtual_memory_block.hpp" using orkhestrafs::dbmstodspi::VirtualMemoryBlock; VirtualMemoryBlock::~VirtualMemoryBlock() = default; auto VirtualMemoryBlock::GetVirtualAddress() -> volatile uint32_t* { return &memory_area_.at(0); } auto VirtualMemoryBlock::GetPhysicalAddress() -> volatile uint32_t* { return &memory_area_.at(0); } auto VirtualMemoryBlock::GetSize() -> const uint32_t { return memory_area_.size() * 4; }
#include <QObject> //included at the top to fix an issue with the boost::foreach macro shadowing qt foreach (see http://stackoverflow.com/questions/15191361/boostq-foreach-has-not-been-declared) #include "SmurfItemFactory.h" #include <envire_core/items/Item.hpp> #include <QWidget> #include <QVBoxLayout> #include <QLabel> #include <envire_core/items/Item.hpp> #include <envire_smurf/Visual.hpp> #include <envire_smurf/GraphLoader.hpp> #include <smurf/Robot.hpp> #include "SmurfWidget.hpp" namespace envire { namespace viz { SmurfItemFactory::SmurfItemFactory() { envire::core::Item<envire::smurf::Visual> item; supportedTypes.emplace_back(*(item.getTypeInfo())); } QWidget* SmurfItemFactory::getConfigurationWidget(const std::type_index& type) { return new SmurfWidget(); } void SmurfItemFactory::addItem(const std::type_index& type, std::shared_ptr<envire::core::EnvireGraph> graph, const envire::core::FrameId& frame, const QWidget* configWidget) { if(type == supportedTypes[0]) { const SmurfWidget* widget = dynamic_cast<const SmurfWidget*>(configWidget); assert(widget != nullptr); widget->getPath(); envire::core::Transform robotTf; robotTf.setIdentity(); envire::smurf::GraphLoader graphLoader(graph, robotTf); ::smurf::Robot* robot = new(::smurf::Robot); robot->loadFromSmurf(widget->getPath().toStdString()); int nextGrpId = 0; graphLoader.loadStructure(graph->getVertex(frame), *robot); graphLoader.loadVisuals(*robot); } } const std::vector< std::type_index >& SmurfItemFactory::getSupportedTypes() { return supportedTypes; } }}
#include<bits/stdc++.h> using namespace std; #define MOD 1000000007 #define pb push_back #define mp make_pair typedef long long ll; #define inf 0x7fffffff long long int A[100003], B[100003]; int tree[500005]; void build_tree(int node, int a, int b) { if(a > b) return; if(a == b) { tree[node] = a; return; } build_tree(node*2, a, (a+b)/2); build_tree(node*2+1, 1+(a+b)/2, b); tree[node] = B[tree[node*2]] > B[tree[node*2+1]] ? tree[node*2] : tree[node*2 + 1]; // Init root value } int query_tree(int node, int a, int b, int i, int j) { if(a > b || a > j || b < i) return -1; if(a >= i && b <= j) return tree[node]; int q1 = query_tree(node*2, a, (a+b)/2, i, j); int q2 = query_tree(1+node*2, 1+(a+b)/2, b, i, j); if(q1 == -1) return q2; else if (q2 == -1) return q1; int res = B[q1] > B[q2] ? q1 : q2; return res; } int solve(int l, int r, int n) { if (l>r) return 0; if (l == r) { if (A[l] == B[l]) return 0; else if (A[l] < B[l]) return -1; return 1; } int max_in = query_tree(1, 0, n-1, l, r); int mid = (r-l)/2, ansl, ansr, ans; int L = max_in, R = max_in; if(A[max_in] < B[max_in]) return -1; else if (A[max_in] == B[max_in]) { ansl = solve(max_in + 1, r, n); ansr = solve(l, max_in-1, n); if (ansr == -1 || ansl == -1) return -1; ans = ansl + ansr; } else { for(int i = max_in+1; i< r; i++) { if (A[i] >= B[max_in]){ R++; A[i] = B[max_in]; } else break; } for(int i = max_in-1; i>= l; i--) { if (A[i] >= B[max_in]){ L--; A[i] = B[max_in]; } else break; } ansl = solve(max_in + 1, r, n); ansr = solve(l, max_in-1, n); if (ansr == -1 || ansl == -1) return -1; ans = ansl + ansr + 1; } return ans; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin>>t; while(t--) { int n; cin>>n; for (int i = 0; i<n; i++) cin>>A[i]; for (int i = 0; i<n; i++) cin>>B[i]; build_tree(1, 0, n-1); cout << solve(0, n-1, n) << endl; } return 0; }
#include <bits/stdc++.h> using namespace std; void solve () { int n, d; cin >> n >> d; string s; cin >> s; vector<int> a(n); for (int i=0; i<n; ++i) { a[i] = s[i] - '0'; } // for (auto it: a) cout << it << " "; // cout << endl; int l=0, prev=0; int step=0; while (l<n-1) { // cout << "start: " << (min(n-1, l+d)) << endl; for (int r=min(n-1, l+d); r>=l; --r) { if (a[r]) { l = r; ++step; break; } } // cout << "pr: " << prev << " l: " << l << " step: " << step << endl; if (prev==l) { // not found step = -1; break; } prev = l; } cout << step << endl; } int main() { ios::sync_with_stdio(0); cin.tie(0); solve(); return 0; }
#include "stdafx.h" #include "Inventory2.h" Inventory2::Inventory2() { } Inventory2::~Inventory2() { } void Inventory2::ItemSetup() { tagItemInfo item; item.itemKind = ITEM_MONSTERBALL; item.name = "몬스터볼"; item.price = 200; item.attribute = 1; item.description = "야생 포켓몬에게 던져서 잡기 위한 볼. 캡슐식으로 되어있다."; item.count = 5; m_vItem.push_back(item); } void Inventory2::AddItem(tagItemInfo item) { bool isNewItem = true; m_viItem = m_vItem.begin(); for (m_viItem; m_viItem != m_vItem.end(); ++m_viItem) { // 아이템 같은 종류인지 확인 if (m_viItem->itemKind != item.itemKind) continue; // strcmp 같음 string 안에 compare 함수 있음 // 아이템 이름 같으면 갯수만 증가 if (m_viItem->name.compare(item.name) == 0) { m_viItem->count++; isNewItem = false; break; } } if (isNewItem == true) { m_vItem.push_back(item); } } tagItemInfo Inventory2::SellItem(int num, int & gold) { tagItemInfo sellItem; m_viItem = m_vItem.begin() + num; sellItem = *m_viItem; if (m_viItem->count > 1) m_viItem->count--; else m_vItem.erase(m_viItem); int sellPrice = sellItem.price / 2; gold += sellPrice; return sellItem; }
// // Trilateration.cpp // // Created by waynewang on 17/5/14. // Copyright (c) 2014 waynewang. All rights reserved. // #pragma warning(push) #pragma warning(disable : 4267) #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/ui/text/TestRunner.h> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/CompilerOutputter.h> #pragma warning(pop) #include "Trilateration.h" // Consider an epsilon as below. const double EPSILON = 1e-6; class TrilaterationTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE( TrilaterationTest ); CPPUNIT_TEST( Test3PositionHasExactSolution ); CPPUNIT_TEST( Test3PositionHasApporxSolution ); CPPUNIT_TEST( Test4PositionHasExactSolution ); CPPUNIT_TEST( Test4PositionHasApporxSolution ); CPPUNIT_TEST_SUITE_END(); public: void setUp(); void tearDown(); void Test3PositionHasExactSolution(); void Test3PositionHasApporxSolution(); void Test4PositionHasExactSolution(); void Test4PositionHasApporxSolution(); // TODO: add more unit tests. }; // Registers the fixture into the 'registry' CPPUNIT_TEST_SUITE_REGISTRATION( TrilaterationTest ); void TrilaterationTest::setUp() { // set up } void TrilaterationTest::tearDown() { // tear down } void TrilaterationTest::Test3PositionHasExactSolution() { // workers and beacons Trilateration worker; PosAndDistance2dVec beacons; Pos2d location; beacons.push_back(PosAndDistance2d(Pos2d(0, 0), 1)); beacons.push_back(PosAndDistance2d(Pos2d(1, 1), 1)); beacons.push_back(PosAndDistance2d(Pos2d(2, 0), 1)); worker.CalculateLocation2d(beacons, location); // Expected location (1, 0) CPPUNIT_ASSERT(std::fabs(location[0] - 1) < EPSILON); CPPUNIT_ASSERT(std::fabs(location[1]) < EPSILON); } void TrilaterationTest::Test3PositionHasApporxSolution() { // workers and beacons Trilateration worker; PosAndDistance2dVec beacons; Pos2d location; beacons.push_back(PosAndDistance2d(Pos2d(0, 0), 1)); beacons.push_back(PosAndDistance2d(Pos2d(1, 1), 2)); beacons.push_back(PosAndDistance2d(Pos2d(2, 0), 1)); worker.CalculateLocation2d(beacons, location); // Expected location (1, -1.5) CPPUNIT_ASSERT(std::fabs(location[0] - 1) < EPSILON); CPPUNIT_ASSERT(std::fabs(location[1] - -1.5) < EPSILON); } void TrilaterationTest::Test4PositionHasExactSolution() { // workers and beacons Trilateration worker; PosAndDistance2dVec beacons; Pos2d location; beacons.push_back(PosAndDistance2d(Pos2d(0, 0), 1)); beacons.push_back(PosAndDistance2d(Pos2d(1, 1), 1)); beacons.push_back(PosAndDistance2d(Pos2d(2, 0), 1)); beacons.push_back(PosAndDistance2d(Pos2d(1, -1), 1)); worker.CalculateLocation2d(beacons, location); // Expected location (1, 0) CPPUNIT_ASSERT(std::fabs(location[0] - 1) < EPSILON); CPPUNIT_ASSERT(std::fabs(location[1]) < EPSILON); } void TrilaterationTest::Test4PositionHasApporxSolution() { // workers and beacons Trilateration worker; PosAndDistance2dVec beacons; Pos2d location; beacons.push_back(PosAndDistance2d(Pos2d(0, 0), 1)); beacons.push_back(PosAndDistance2d(Pos2d(1, 1), 1.5)); beacons.push_back(PosAndDistance2d(Pos2d(2, 0), 1)); beacons.push_back(PosAndDistance2d(Pos2d(1, -1), 1.5)); worker.CalculateLocation2d(beacons, location); // Expected location (1, 0) CPPUNIT_ASSERT(std::fabs(location[0] - 1) < EPSILON); CPPUNIT_ASSERT(std::fabs(location[1]) < EPSILON); } /////////////////////////////////////////////////////////////////////////////// // the main function int main(int argc, char* argv[]) { // Get the top level suite from the registry CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest(); // Adds the test to the list of test to run CppUnit::TextUi::TestRunner runner; runner.addTest( suite ); // Change the default outputter to a compiler error format outputter runner.setOutputter( new CppUnit::CompilerOutputter( &runner.result(), std::cerr ) ); // Run the tests. bool wasSucessful = runner.run(); // Wait user input to finish std::cout << "Press <ENTER> to finish" << std::endl; std::cin.get(); // Return error code 1 if the one of test failed. return wasSucessful ? 0 : 1; }
//chocolate distribution problem //minimize the diff between max and min chocolates given //m kids each get a packet //give: arr of packet where each element denotes number of chocolates in that packet //2 3 4 7 9 12 56 #include <iostream> #include <algorithm> using namespace std; int min(int a,int b){ return a<b?a:b; } int chocolate(int arr[],int n,int m){ sort(arr,arr+n); int res=arr[m-1]-arr[0]; for(int i=1;i+m-1<n;i++){ int y=arr[i+m-1]-arr[i]; std::cout << y << '\n'; res=min(res,y); } return res; } int main(int argc, char const *argv[]) { int arr[]={3,4,1,9,56,7,9,12}; int n=sizeof(arr)/sizeof(arr[0]); int m=5; int y=chocolate(arr,n,m); std::cout << "Min diff is "<<y << '\n'; return 0; }
//TMRpcm library is needed #include "SD.h" #define SD_ChipSelectPin 4 #include "TMRpcm.h" #include "SPI.h" #include "Wire.h" //MISO -> Dpin12 //MOSI -> Dpin11 //SCK -> 13 TMRpcm tmrpcm; byte address = 8; void setup() { tmrpcm.speakerPin = 9; Wire.begin(address); Wire.onReceive(receiveEvent); // register event Serial.begin(115200); if (!SD.begin(SD_ChipSelectPin)) { Serial.println("SD fail"); return; } tmrpcm.setVolume(4); //tmrpcm.play("test.wav"); //tmrpcm.loop(1); } void loop() { // put your main code here, to run repeatedly: if (Serial.available()) { switch (Serial.read()) { case 'd': tmrpcm.play("test.wav"); tmrpcm.loop(1); break; case 'P': tmrpcm.play("test2.wav"); tmrpcm.loop(0); break; case 't': tmrpcm.play("catfish"); break; case 'p': tmrpcm.pause(); break; case '?': if (tmrpcm.isPlaying()) { Serial.println("A wav file is being played"); } break; case 'S': tmrpcm.stopPlayback(); break; case '=': tmrpcm.volume(1); break; case '-': tmrpcm.volume(0); break; case '0': tmrpcm.quality(0); break; case '1': tmrpcm.quality(1); break; default: break; } } } // function that executes whenever data is received from master // this function is registered as an event, see setup() void receiveEvent(int howMany) { int x = Wire.read(); // receive byte as an integer Serial.println(x); // print the integer switch (x) { case 0: tmrpcm.pause(); break; case 1: tmrpcm.play("test.wav"); tmrpcm.loop(1); break; case 2: tmrpcm.play("test2.wav"); tmrpcm.loop(0); break; case 3: tmrpcm.pause(); break; } }
#include "iostream" #include "X.h" #include "Y.h" using namespace std; X::X(int num):m(1),m2(num){ this->n=1; cout<<"construct X n="<<this->n<<endl; }; X::~X(){ cout<<"deconstruct X"<<endl; } //X::X(const X&){ // cout<<"copy construct X"<<endl; // this->n=10; //} X& X::operator =(const X &){ cout<<"X::operator ="<<endl; n=3; return *this; } X::operator Y() const{ cout<<"自动类型转换"<<endl; return Y(); } void X::func(){ cout<<"func n="<<this->n<<endl; }
// Created on: 1993-03-04 // Created by: Jacques GOUSSARD // 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 _Contap_ContAna_HeaderFile #define _Contap_ContAna_HeaderFile #include <GeomAbs_CurveType.hxx> #include <gp_Circ.hxx> #include <gp_Dir.hxx> #include <gp_Pnt.hxx> #include <Standard.hxx> #include <Standard_Boolean.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> class gp_Sphere; class gp_Cylinder; class gp_Cone; class gp_Lin; //! This class provides the computation of the contours //! for quadric surfaces. class Contap_ContAna { public: DEFINE_STANDARD_ALLOC Standard_EXPORT Contap_ContAna(); Standard_EXPORT void Perform (const gp_Sphere& S, const gp_Dir& D); Standard_EXPORT void Perform (const gp_Sphere& S, const gp_Dir& D, const Standard_Real Ang); Standard_EXPORT void Perform (const gp_Sphere& S, const gp_Pnt& Eye); Standard_EXPORT void Perform (const gp_Cylinder& C, const gp_Dir& D); Standard_EXPORT void Perform (const gp_Cylinder& C, const gp_Dir& D, const Standard_Real Ang); Standard_EXPORT void Perform (const gp_Cylinder& C, const gp_Pnt& Eye); Standard_EXPORT void Perform (const gp_Cone& C, const gp_Dir& D); Standard_EXPORT void Perform (const gp_Cone& C, const gp_Dir& D, const Standard_Real Ang); Standard_EXPORT void Perform (const gp_Cone& C, const gp_Pnt& Eye); Standard_Boolean IsDone() const; Standard_Integer NbContours() const; //! Returns GeomAbs_Line or GeomAbs_Circle, when //! IsDone() returns True. GeomAbs_CurveType TypeContour() const; gp_Circ Circle() const; Standard_EXPORT gp_Lin Line (const Standard_Integer Index) const; protected: private: Standard_Boolean done; Standard_Integer nbSol; GeomAbs_CurveType typL; gp_Pnt pt1; gp_Pnt pt2; gp_Pnt pt3; gp_Pnt pt4; gp_Dir dir1; gp_Dir dir2; gp_Dir dir3; gp_Dir dir4; Standard_Real prm; }; #include <Contap_ContAna.lxx> #endif // _Contap_ContAna_HeaderFile
#include <bits/stdc++.h> using namespace std; # define VEC(x, y) class Solution { public: vector<vector<int>> intervalIntersection(vector<vector<int>>& firstList, vector<vector<int>>& secondList) { vector<vector<int>> result; auto first_it = firstList.begin(); auto second_it = secondList.begin(); bool first_inside = false, second_inside = false; auto first_interval = first_it, second_interval = second_it; while ( true ) { if (first_inside == false) { if (first_it == firstList.end()) return result; first_interval = first_it++; first_inside = true; } if (second_inside == false) { if (second_it == secondList.end()) return result; second_interval = second_it++; second_inside = true; } // case 1 : doesn't intersect if ((*first_interval)[0] > (*second_interval)[1]) { second_inside = false; continue; } if ((*second_interval)[0] > (*first_interval)[1]) { first_inside = false; continue; } int start = max((*first_interval)[0], (*second_interval)[0]); // case 2 : intersects. 1st ends first if ((*first_interval)[1] < (*second_interval)[1]) { result.push_back(vector<int>{start, (*first_interval)[1]}); first_inside = false; continue; } // case 3 : intersects. 2nd ends first else if ((*first_interval)[1] > (*second_interval)[1]) { result.push_back(vector<int>{start, (*second_interval)[1]}); second_inside = false; continue; } // case 4 : intersects. close at the same place else { result.push_back(vector<int>{start, (*first_interval)[1]}); first_inside = false; second_inside = false; continue; } } // end consideration: two intervals may still be opened (inside) // if (first_it == firstList.end()) { // if (first_inside == false) // return result; // } } }; int main() { Solution sol; vector<vector<int>> firstList{vector<int>{0,2},vector<int>{5,10},vector<int>{13,23},vector<int>{24,25}}; vector<vector<int>> secondList{vector<int>{1,5},vector<int>{8,12},vector<int>{15,24},vector<int>{25,26}}; auto a = sol.intervalIntersection(firstList, secondList); for (auto b : a) { for (auto c : b) cout << c << " "; cout << endl; } }
// Created on: 1994-06-06 // Created by: Jean Yves LEBEY // Copyright (c) 1994-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _TopOpeBRepDS_InterferenceIterator_HeaderFile #define _TopOpeBRepDS_InterferenceIterator_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <TopOpeBRepDS_ListIteratorOfListOfInterference.hxx> #include <Standard_Boolean.hxx> #include <TopOpeBRepDS_Kind.hxx> #include <Standard_Integer.hxx> #include <TopOpeBRepDS_ListOfInterference.hxx> class TopOpeBRepDS_Interference; //! Iterate on interferences of a list, matching //! conditions on interferences. //! Nota : //! inheritance of ListIteratorOfListOfInterference from //! TopOpeBRepDS has not been done because of the //! impossibility of naming the classical More, Next //! methods which are declared as static in //! TCollection_ListIteratorOfList ... . ListIteratorOfList //! has benn placed as a field of InterferenceIterator. class TopOpeBRepDS_InterferenceIterator { public: DEFINE_STANDARD_ALLOC Standard_EXPORT TopOpeBRepDS_InterferenceIterator(); //! Creates an iterator on the Interference of list <L>. Standard_EXPORT TopOpeBRepDS_InterferenceIterator(const TopOpeBRepDS_ListOfInterference& L); //! re-initialize interference iteration process on //! the list of interference <L>. //! Conditions are not modified. Standard_EXPORT void Init (const TopOpeBRepDS_ListOfInterference& L); //! define a condition on interference iteration process. //! Interference must match the Geometry Kind <ST> Standard_EXPORT void GeometryKind (const TopOpeBRepDS_Kind GK); //! define a condition on interference iteration process. //! Interference must match the Geometry <G> Standard_EXPORT void Geometry (const Standard_Integer G); //! define a condition on interference iteration process. //! Interference must match the Support Kind <ST> Standard_EXPORT void SupportKind (const TopOpeBRepDS_Kind ST); //! define a condition on interference iteration process. //! Interference must match the Support <S> Standard_EXPORT void Support (const Standard_Integer S); //! reach for an interference matching the conditions //! (if defined). Standard_EXPORT void Match(); //! Returns True if the Interference <I> matches the //! conditions (if defined). //! If no conditions defined, returns True. Standard_EXPORT virtual Standard_Boolean MatchInterference (const Handle(TopOpeBRepDS_Interference)& I) const; //! Returns True if there is a current Interference in //! the iteration. Standard_EXPORT Standard_Boolean More() const; //! Move to the next Interference. Standard_EXPORT void Next(); //! Returns the current Interference, matching the //! conditions (if defined). Standard_EXPORT const Handle(TopOpeBRepDS_Interference)& Value() const; Standard_EXPORT TopOpeBRepDS_ListIteratorOfListOfInterference& ChangeIterator(); protected: private: TopOpeBRepDS_ListIteratorOfListOfInterference myIterator; Standard_Boolean myGKDef; TopOpeBRepDS_Kind myGK; Standard_Boolean myGDef; Standard_Integer myG; Standard_Boolean mySKDef; TopOpeBRepDS_Kind mySK; Standard_Boolean mySDef; Standard_Integer myS; }; #endif // _TopOpeBRepDS_InterferenceIterator_HeaderFile
#pragma once #ifndef CAMERA_H #define CAMERA_H #include <GL/glew.h> #include <glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/euler_angles.hpp> #include "input.h" class Camera { public: Camera(); Camera(glm::vec3 position); //get the view matrix glm::mat4 getViewMatrix(); //get the cursor glm::vec3 getCursor(); //compute matrices void computeMatricesFromInputs(GLFWwindow* window); glm::mat4 _viewMatrix; // Initial position : on +Z glm::vec3 position; glm::vec3 cursor; float speed; }; #endif // !CAMERA_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #include "modules/layout/layout_module.h" #include "modules/layout/content_generator.h" #include "modules/layout/cssprops.h" #include "modules/layout/box/box.h" #include "modules/layout/content/content.h" #include "modules/layout/layoutprops.h" // for ATTR_HEIGHT_SUPPORT, ATTR_HEIGHT_SUPPORT, ATTR_BACKGROUND_SUPPORT #include "modules/display/styl_man.h" #include "modules/pi/OpFont.h" #include "modules/prefs/prefsmanager/collections/pc_fontcolor.h" #include "modules/util/handy.h" #include "modules/layout/cssprops.h" #define LAYOUT_PROPERTIES_POOL_SIZE 100 // Known to reach about 80 on usatoday.com and ebay.de #define HTM_LAYOUT_POOL_SIZE 20 #define CONTAINER_REFLOW_STATE_POOL_SIZE 40 // More than big enough, probably #define VERTICALBOX_REFLOW_STATE_POOL_SIZE 40 #define INLINEBOX_REFLOW_STATE_POOL_SIZE 40 #define ABSOLUTEBOX_REFLOW_STATE_POOL_SIZE 20 #define TABLECONTENT_REFLOW_STATE_POOL_SIZE 20 #define TABLEROWGROUP_REFLOW_STATE_POOL_SIZE 20 #define TABLEROW_REFLOW_STATE_POOL_SIZE 20 #define TABLECELL_REFLOW_STATE_POOL_SIZE 20 #define SPACEMANAGER_REFLOW_STATE_POOL_SIZE 40 #define FLOAT_REFLOW_CACHE_POOL_SIZE 200 #define REFLOWELEM_POOL_SIZE 200 #ifdef INTERNAL_SPELLCHECK_SUPPORT # define MISSPELLING_PAINT_INFO_POOL_SIZE 100 #endif // INTERNAL_SPELLCHECK_SUPPORT static void InitStylesL(); LayoutModule::LayoutModule() : content_generator(NULL), first_line_elm(NULL), m_img_alt_content(NULL), m_space_content(NULL), m_support_attr_array(NULL), m_blink_on(TRUE), layout_properties_pool(LAYOUT_PROPERTIES_POOL_SIZE), htm_layout_properties_pool(HTM_LAYOUT_POOL_SIZE), container_reflow_state_pool(CONTAINER_REFLOW_STATE_POOL_SIZE), verticalbox_reflow_state_pool(VERTICALBOX_REFLOW_STATE_POOL_SIZE), inlinebox_reflow_state_pool(INLINEBOX_REFLOW_STATE_POOL_SIZE), absolutebox_reflow_state_pool(ABSOLUTEBOX_REFLOW_STATE_POOL_SIZE), tablecontent_reflow_state_pool(TABLECONTENT_REFLOW_STATE_POOL_SIZE), tablerowgroup_reflow_state_pool(TABLEROWGROUP_REFLOW_STATE_POOL_SIZE), tablerow_reflow_state_pool(TABLEROW_REFLOW_STATE_POOL_SIZE), tablecell_reflow_state_pool(TABLECELL_REFLOW_STATE_POOL_SIZE), spacemanager_reflow_state_pool(SPACEMANAGER_REFLOW_STATE_POOL_SIZE), float_reflow_cache_pool(FLOAT_REFLOW_CACHE_POOL_SIZE), reflowelem_pool(REFLOWELEM_POOL_SIZE), #ifdef INTERNAL_SPELLCHECK_SUPPORT misspelling_paint_info_pool(MISSPELLING_PAINT_INFO_POOL_SIZE), #endif // INTERNAL_SPELLCHECK_SUPPORT array_decl(0), m_shared_css_manager(NULL), props_array(NULL), tmp_word_info_array(NULL) { quotes[0].value_type = 0; quotes[0].value.string = NULL; #ifdef PLATFORM_FONTSWITCHING ellipsis_str[0] = 0; ellipsis_str[1] = 0; #else ellipsis_str = NULL; #endif } void LayoutModule::InitL(const OperaInitInfo& info) { content_generator = OP_NEW_L(ContentGenerator, ()); LEAVE_IF_NULL(first_line_elm = NEW_HTML_Element()); LEAVE_IF_ERROR(first_line_elm->Construct((HLDocProfile*)NULL, NS_IDX_DEFAULT, Markup::HTE_P, (HtmlAttrEntry*) NULL, HE_INSERTED_BY_LAYOUT)); first_line_elm->SetIsFirstLinePseudoElement(); CSS_generic_value gen_val; gen_val.value_type = CSS_FUNCTION_ATTR; gen_val.value.string = (uni_char *)UNI_L("alt"); LEAVE_IF_NULL(m_img_alt_content = CSS_copy_gen_array_decl::Create(0, &gen_val, 1)); gen_val.value_type = CSS_STRING_LITERAL; gen_val.value.string = (uni_char*)UNI_L(" "); LEAVE_IF_NULL(m_space_content = CSS_copy_gen_array_decl::Create(0, &gen_val, 1)); m_support_attr_array = OP_NEWA_L(long, Markup::HTE_LAST - Markup::HTE_FIRST + 1); op_memset(m_support_attr_array, 0, sizeof(long)*(Markup::HTE_LAST - Markup::HTE_FIRST + 1)); m_support_attr_array[Markup::HTE_IMG - Markup::HTE_FIRST] = ATTR_WIDTH_SUPPORT | ATTR_HEIGHT_SUPPORT; #ifdef CANVAS_SUPPORT m_support_attr_array[Markup::HTE_CANVAS - Markup::HTE_FIRST] = ATTR_WIDTH_SUPPORT | ATTR_HEIGHT_SUPPORT; #endif // CANVAS_SUPPORT #ifdef MEDIA_HTML_SUPPORT m_support_attr_array[Markup::HTE_VIDEO - Markup::HTE_FIRST] = ATTR_WIDTH_SUPPORT | ATTR_HEIGHT_SUPPORT; #endif // MEDIA_HTML_SUPPORT m_support_attr_array[Markup::HTE_EMBED - Markup::HTE_FIRST] = ATTR_WIDTH_SUPPORT | ATTR_HEIGHT_SUPPORT; m_support_attr_array[Markup::HTE_APPLET - Markup::HTE_FIRST] = ATTR_WIDTH_SUPPORT | ATTR_HEIGHT_SUPPORT; m_support_attr_array[Markup::HTE_OBJECT - Markup::HTE_FIRST] = ATTR_WIDTH_SUPPORT | ATTR_HEIGHT_SUPPORT; m_support_attr_array[Markup::HTE_IFRAME - Markup::HTE_FIRST] = ATTR_WIDTH_SUPPORT | ATTR_HEIGHT_SUPPORT; m_support_attr_array[Markup::HTE_MARQUEE - Markup::HTE_FIRST] = ATTR_WIDTH_SUPPORT | ATTR_HEIGHT_SUPPORT; m_support_attr_array[Markup::HTE_TABLE - Markup::HTE_FIRST] = ATTR_WIDTH_SUPPORT | ATTR_HEIGHT_SUPPORT | ATTR_BACKGROUND_SUPPORT; m_support_attr_array[Markup::HTE_TD - Markup::HTE_FIRST] = ATTR_WIDTH_SUPPORT | ATTR_HEIGHT_SUPPORT | ATTR_BACKGROUND_SUPPORT; m_support_attr_array[Markup::HTE_TH - Markup::HTE_FIRST] = ATTR_WIDTH_SUPPORT | ATTR_HEIGHT_SUPPORT | ATTR_BACKGROUND_SUPPORT; m_support_attr_array[Markup::HTE_TR - Markup::HTE_FIRST] = ATTR_BACKGROUND_SUPPORT | ATTR_HEIGHT_SUPPORT; m_support_attr_array[Markup::HTE_BODY - Markup::HTE_FIRST] = ATTR_BACKGROUND_SUPPORT; m_support_attr_array[Markup::HTE_HR - Markup::HTE_FIRST] = ATTR_WIDTH_SUPPORT; m_support_attr_array[Markup::HTE_PRE - Markup::HTE_FIRST] = ATTR_WIDTH_SUPPORT; m_support_attr_array[Markup::HTE_COL - Markup::HTE_FIRST] = ATTR_WIDTH_SUPPORT; m_support_attr_array[Markup::HTE_COLGROUP - Markup::HTE_FIRST] = ATTR_WIDTH_SUPPORT; InitMemoryPoolsL(); InitStylesL(); #ifndef HAS_COMPLEX_GLOBALS extern void init_RomanStr(); init_RomanStr(); extern void init_DecimalLeadingZeroStr(); init_DecimalLeadingZeroStr(); #endif // HAS_COMPLEX_GLOBALS m_shared_css_manager = SharedCssManager::CreateL(); props_array = OP_NEWA_L(CssPropertyItem, CSSPROPS_ITEM_COUNT); tmp_word_info_array = OP_NEWA_L(WordInfo, WORD_INFO_MAX_SIZE); #ifdef PLATFORM_FONTSWITCHING ellipsis_str[0] = 0x2026; ellipsis_str[1] = 0; #else ellipsis_str = UNI_L("..."); #endif ellipsis_str_len = uni_strlen(ellipsis_str); } void LayoutModule::Destroy() { OP_DELETE(content_generator); content_generator = NULL; OP_DELETE(first_line_elm); first_line_elm = NULL; OP_DELETE(m_img_alt_content); m_img_alt_content = NULL; OP_DELETE(m_space_content); m_space_content = NULL; OP_DELETEA(m_support_attr_array); m_support_attr_array = NULL; DestroyMemoryPools(); OP_DELETE(m_shared_css_manager); m_shared_css_manager = NULL; /* Reset the decl_is_referenced bit of all our CssPropertyItems. The reference has been transfered to the props_array (which is long gone). */ if (props_array) { op_memset(props_array, 0, sizeof(CssPropertyItem) * CSSPROPS_ITEM_COUNT); OP_DELETEA(props_array); props_array = NULL; } OP_DELETEA(tmp_word_info_array); tmp_word_info_array = NULL; } void LayoutModule::InitMemoryPoolsL() { layout_properties_pool.ConstructL(); htm_layout_properties_pool.ConstructL(); container_reflow_state_pool.ConstructL(); verticalbox_reflow_state_pool.ConstructL(); inlinebox_reflow_state_pool.ConstructL(); absolutebox_reflow_state_pool.ConstructL(); tablecontent_reflow_state_pool.ConstructL(); tablerowgroup_reflow_state_pool.ConstructL(); tablerow_reflow_state_pool.ConstructL(); tablecell_reflow_state_pool.ConstructL(); spacemanager_reflow_state_pool.ConstructL(); float_reflow_cache_pool.ConstructL(); reflowelem_pool.ConstructL(); #ifdef INTERNAL_SPELLCHECK_SUPPORT misspelling_paint_info_pool.ConstructL(); #endif // INTERNAL_SPELLCHECK_SUPPORT } void LayoutModule::DestroyMemoryPools() { layout_properties_pool.Clean(); layout_properties_pool.Destroy(); htm_layout_properties_pool.Clean(); htm_layout_properties_pool.Destroy(); container_reflow_state_pool.Clean(); container_reflow_state_pool.Destroy(); verticalbox_reflow_state_pool.Clean(); verticalbox_reflow_state_pool.Destroy(); inlinebox_reflow_state_pool.Clean(); inlinebox_reflow_state_pool.Destroy(); absolutebox_reflow_state_pool.Clean(); absolutebox_reflow_state_pool.Destroy(); tablecontent_reflow_state_pool.Clean(); tablecontent_reflow_state_pool.Destroy(); tablerowgroup_reflow_state_pool.Clean(); tablerowgroup_reflow_state_pool.Destroy(); tablerow_reflow_state_pool.Clean(); tablerow_reflow_state_pool.Destroy(); tablecell_reflow_state_pool.Clean(); tablecell_reflow_state_pool.Destroy(); spacemanager_reflow_state_pool.Clean(); spacemanager_reflow_state_pool.Destroy(); float_reflow_cache_pool.Clean(); float_reflow_cache_pool.Destroy(); reflowelem_pool.Clean(); reflowelem_pool.Destroy(); #ifdef INTERNAL_SPELLCHECK_SUPPORT misspelling_paint_info_pool.Clean(); misspelling_paint_info_pool.Destroy(); #endif // INTERNAL_SPELLCHECK_SUPPORT } extern const float tsep_scale = (float) 1.0; extern const float lsep_scale = (float) 0.5; struct StyleCreateInfo { unsigned short type; signed char lho, rho, ls, ts; bool i, b; char font; char col; bool default_col, scale, inherit_fs, uline, strike; }; // Negative margin values x mean: (-x) em / 24 #define SEP_NORMAL -24 #define SEP_H1 -16 #define SEP_H2 -20 #define SEP_H3_L -24 #define SEP_H3_T -24 #define SEP_H4_L -24 #define SEP_H4_T -24 #define SEP_H5_L -40 #define SEP_H5_T -40 #define SEP_H6_L -56 #define SEP_H6_T -56 #define SEP_FORM_L 0 #define SEP_FORM_T -24 #define SEP_FS_L -16 #define SEP_FS_R -16 #define SEP_FS_T -8 #define SEP_FS_B -18 const StyleCreateInfo style_create[] = { // type lho rho ls ts i b font col def_col scal inh_fs ulin strike { Markup::HTE_DOC_ROOT, 0, 0, 0, 0, false, false, OP_SYSTEM_FONT_DOCUMENT_NORMAL, OP_SYSTEM_COLOR_DOCUMENT_NORMAL, false, false, false, false, false }, { Markup::HTE_TABLE, 0, 0, 0, 0, false, false, -1, -1, false, false, false, false, false }, { Markup::HTE_TH, 0, 0, 0, 0, false, true, -1, -1, false, false, false, false, false }, { Markup::HTE_P, 0, 0, SEP_NORMAL, SEP_NORMAL, false, false, -1, -1, false, false, false, false, false }, { Markup::HTE_DD, DEFAULT_INDENT_PIXELS, 0, 0, 0, false, false, -1, -1, false, false, false, false, false }, { Markup::HTE_OL, DEFAULT_INDENT_PIXELS, 0, SEP_NORMAL, SEP_NORMAL, false, false, -1, -1, false, false, false, false, false }, { Markup::HTE_UL, DEFAULT_INDENT_PIXELS, 0, SEP_NORMAL, SEP_NORMAL, false, false, -1, -1, false, false, false, false, false }, { Markup::HTE_DL, 0, 0, SEP_NORMAL, SEP_NORMAL, false, false, -1, -1, false, false, false, false, false }, { Markup::HTE_MENU, DEFAULT_INDENT_PIXELS, 0, SEP_NORMAL, SEP_NORMAL, false, false, -1, -1, false, false, false, false, false }, { Markup::HTE_DIR, DEFAULT_INDENT_PIXELS, 0, SEP_NORMAL, SEP_NORMAL, false, false, -1, -1, false, false, false, false, false }, { Markup::HTE_BLOCKQUOTE, DEFAULT_INDENT_PIXELS, DEFAULT_INDENT_PIXELS, SEP_NORMAL, SEP_NORMAL, false, false, -1, -1, false, false, false, false, false }, { Markup::HTE_FIGURE, DEFAULT_INDENT_PIXELS, DEFAULT_INDENT_PIXELS, SEP_NORMAL, SEP_NORMAL, false, false, -1, -1, false, false, false, false, false }, { Markup::HTE_HR, 0, 0, -12, -12, false, false, -1, -1, false, false, false, false, false }, { Markup::HTE_ISINDEX, 0, 0, 10, 10, false, false, -1, -1, false, false, false, false, false }, { Markup::HTE_LI, 0, 0, 0, 0, false, false, -1, -1, false, false, false, false, false }, { Markup::HTE_H1, 0, 0, SEP_H1, SEP_H1, false, false, OP_SYSTEM_FONT_DOCUMENT_HEADER1, OP_SYSTEM_COLOR_DOCUMENT_HEADER1, true, false, false, false, false }, { Markup::HTE_H2, 0, 0, SEP_H2, SEP_H2, false, false, OP_SYSTEM_FONT_DOCUMENT_HEADER2, OP_SYSTEM_COLOR_DOCUMENT_HEADER2, true, false, false, false, false }, { Markup::HTE_H3, 0, 0, SEP_H3_L, SEP_H3_T, false, false, OP_SYSTEM_FONT_DOCUMENT_HEADER3, OP_SYSTEM_COLOR_DOCUMENT_HEADER3, false, false, false, false, false }, { Markup::HTE_H4, 0, 0, SEP_H4_L, SEP_H4_T, false, false, OP_SYSTEM_FONT_DOCUMENT_HEADER4, OP_SYSTEM_COLOR_DOCUMENT_HEADER4, false, false, false, false, false }, { Markup::HTE_H5, 0, 0, SEP_H5_L, SEP_H5_T, false, false, OP_SYSTEM_FONT_DOCUMENT_HEADER5, OP_SYSTEM_COLOR_DOCUMENT_HEADER5, false, false, false, false, false }, { Markup::HTE_H6, 0, 0, SEP_H6_L, SEP_H6_T, false, false, OP_SYSTEM_FONT_DOCUMENT_HEADER6, OP_SYSTEM_COLOR_DOCUMENT_HEADER6, false, false, false, false, false }, { Markup::HTE_DFN, 0, 0, 0, 0, true, false, -1, -1, false, false, false, false, false }, { Markup::HTE_U, 0, 0, 0, 0, false, false, -1, -1, false, false, true, false, false }, { Markup::HTE_STRIKE, 0, 0, 0, 0, false, false, -1, -1, false, false, false, true, false }, { Markup::HTE_S, 0, 0, 0, 0, false, false, -1, -1, false, false, false, true, false }, { Markup::HTE_I, 0, 0, 0, 0, true, false, -1, -1, false, false, false, false, false }, { Markup::HTE_ADDRESS, 0, 0, 0, 0, true, false, -1, -1, false, false, false, false, false }, { Markup::HTE_B, 0, 0, 0, 0, false, true, -1, -1, false, false, false, false, false }, { Markup::HTE_EM, 0, 0, 0, 0, true, false, -1, -1, false, false, false, false, false }, { Markup::HTE_VAR, 0, 0, 0, 0, true, false, -1, -1, false, false, false, false, false }, { Markup::HTE_CITE, 0, 0, 0, 0, true, false, -1, -1, false, false, false, false, false }, { Markup::HTE_A, 0, 0, 0, 0, false, false, -1, OP_SYSTEM_COLOR_LINK, false, false, false, false, false }, { Markup::HTE_STRONG, 0, 0, 0, 0, false, true, -1, -1, false, false, false, false, false }, { Markup::HTE_INPUT, 0, 0, 0, 0, false, false, -1, -1, false, false, false, false, false }, { Markup::HTE_SELECT, 0, 0, 0, 0, false, false, -1, -1, false, false, false, false, false }, { Markup::HTE_TEXTAREA, 0, 0, 0, 0, false, false, -1, -1, false, false, false, false, false }, { Markup::HTE_FORM, 0, 0, SEP_FORM_L, SEP_FORM_T, false, false, -1, -1, false, false, false, false, false }, { Markup::HTE_FIELDSET, SEP_FS_L, SEP_FS_R, SEP_FS_T, SEP_FS_B, false, false, -1, -1, false, false, false, false, false }, { Markup::HTE_PRE, 0, 0, SEP_NORMAL, SEP_NORMAL, false, false, OP_SYSTEM_FONT_DOCUMENT_PRE, OP_SYSTEM_COLOR_DOCUMENT_PRE, false, false, false, false, false }, { Markup::HTE_LISTING, 0, 0, 0, 0, false, false, OP_SYSTEM_FONT_DOCUMENT_PRE, OP_SYSTEM_COLOR_DOCUMENT_PRE, false, false, false, false, false }, { Markup::HTE_PLAINTEXT, 0, 0, 0, 0, false, false, OP_SYSTEM_FONT_DOCUMENT_PRE, OP_SYSTEM_COLOR_DOCUMENT_PRE, false, false, false, false, false }, { Markup::HTE_XMP, 0, 0, 19, 19, false, false, OP_SYSTEM_FONT_DOCUMENT_PRE, OP_SYSTEM_COLOR_DOCUMENT_PRE, false, false, false, false, false }, { Markup::HTE_CODE, 0, 0, 0, 0, false, false, OP_SYSTEM_FONT_DOCUMENT_PRE, OP_SYSTEM_COLOR_DOCUMENT_PRE, false, false, false, false, false }, { Markup::HTE_SAMP, 0, 0, 0, 0, false, false, OP_SYSTEM_FONT_DOCUMENT_PRE, OP_SYSTEM_COLOR_DOCUMENT_PRE, false, false, false, false, false }, { Markup::HTE_TT, 0, 0, 0, 0, false, false, OP_SYSTEM_FONT_DOCUMENT_PRE, OP_SYSTEM_COLOR_DOCUMENT_PRE, false, false, false, false, false }, { Markup::HTE_KBD, 0, 0, 0, 0, false, false, OP_SYSTEM_FONT_DOCUMENT_PRE, OP_SYSTEM_COLOR_DOCUMENT_PRE, false, false, false, false, false }, }; const StyleCreateInfo form_style_create[] = { // type lho rho ls ts i b font col def_col scal inh_fs ulin strike { STYLE_EX_FORM_SELECT, 0, 0, 0, 0, false, false, OP_SYSTEM_FONT_FORM_BUTTON, OP_SYSTEM_COLOR_TEXT, false, false, false, false, false }, { STYLE_EX_FORM_BUTTON, 0, 0, 0, 0, false, false, OP_SYSTEM_FONT_FORM_BUTTON, OP_SYSTEM_COLOR_TEXT, false, false, false, false, false }, { STYLE_EX_FORM_TEXTINPUT, 0, 0, 0, 0, false, false, OP_SYSTEM_FONT_FORM_TEXT_INPUT, OP_SYSTEM_COLOR_TEXT_INPUT, false, false, false, false, false }, { STYLE_EX_FORM_TEXTAREA, 0, 0, 0, 0, false, false, OP_SYSTEM_FONT_FORM_TEXT, OP_SYSTEM_COLOR_TEXT, false, false, false, false, false }, { STYLE_MAIL_BODY, 0, 0, 0, 0, false, false, OP_SYSTEM_FONT_FORM_TEXT_INPUT, OP_SYSTEM_COLOR_TEXT_INPUT, false, false, false, false, false } }; static void InitStylesL() { FontAtt log_font; COLORREF col = USE_DEFAULT_COLOR; char last_font = -1; char last_color = -1; FontAtt* font_att = NULL; // Will be reused between iterations in the loop for (unsigned j = 0; j < 2; j++) { BOOL is_form_styles = j == 1; const StyleCreateInfo* current_table; unsigned char table_size; if (is_form_styles) { current_table = form_style_create; table_size = ARRAY_SIZE(form_style_create); } else { current_table = style_create; table_size = ARRAY_SIZE(style_create); } for (unsigned char i = 0; i < table_size; ++i) { const StyleCreateInfo* style_c_info = &current_table[i]; if (style_c_info->font == -1) font_att = NULL; else if (style_c_info->font != last_font) { g_pcfontscolors->GetFont((OP_SYSTEM_FONT)style_c_info->font, log_font); font_att = &log_font; last_font = style_c_info->font; } #ifdef HAS_FONT_FOUNDRY if (style_c_info->type == Markup::HTE_DOC_ROOT && !is_form_styles) { OpFontManager *fontman = styleManager->GetFontManager(); if (log_font.GetFaceName()) { OpString foundry; LEAVE_IF_ERROR(fontman->GetFoundry(log_font.GetFaceName(), foundry)); LEAVE_IF_ERROR(fontman->SetPreferredFoundry(foundry.CStr())); } } #endif // HAS_FONT_FOUNDRY if (style_c_info->col == -1) col = USE_DEFAULT_COLOR; else if (style_c_info->col != last_color) col = g_pcfontscolors->GetColor((OP_SYSTEM_COLOR)style_c_info->col); short lsep = style_c_info->ls; short tsep = style_c_info->ts; if (style_c_info->scale) { lsep = (short) (op_abs(int(log_font.GetHeight() * (float)0.5))); tsep = (short) (op_abs(int(log_font.GetHeight() * (float)1.0))); } BOOL uline = style_c_info->uline; BOOL strike = style_c_info->strike; if (style_c_info->type == Markup::HTE_A && !is_form_styles) { if (!g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::LinkHasColor)) col = USE_DEFAULT_COLOR; uline = g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::LinkHasUnderline); strike = g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::LinkHasStrikeThrough); } Style* style = Style::Create(style_c_info->lho, style_c_info->rho, 0, 0, lsep, tsep, style_c_info->i, style_c_info->b, font_att, col, style_c_info->inherit_fs, uline, strike); LEAVE_IF_NULL(style); if (is_form_styles) { styleManager->SetStyleEx(style_c_info->type, style); } else { LEAVE_IF_ERROR(styleManager->SetStyle((Markup::Type)style_c_info->type, style)); } } } }
#include "stdafx.h" #include "player.h" #include "CPR_Framework.h" #include "game/world.h" #include "game/bullet.h" #include "debugutils/debugrenderer.h" static const cPlayerDef sDefaultPlayerDef(0.5f, 5.0f, 0.5f * 2.0f, TO_RADIANS(0.2f), 0.8f); namespace { static bool sTestCollisionsOnLookAt = true; static bool sMoveUpAndDown = true; static bool sOverrideSpawnPos = true; static bool sUseWorldCentroid = false; } //---------------------------------------------------------------------------- cPlayer::cPlayer() : mYaw(TO_RADIANS(-90.0f)) , mPitch(0.0f) , mLookAt(cVector3::ZERO()) , mPrevMousePos(0.0f, 0.0f) , mLastShot(0.0f) , mCrosshair(nullptr) { } //---------------------------------------------------------------------------- bool cPlayer::Init(const IGameObjectDef* def, IGameObjectState*&& initial_state) { bool success = IGameObject::Init(def, std::move(initial_state)); if (success) { const cWorld* const world = cWorld::GetInstance(); CPR_assert(world != nullptr, "World has not been initialized yet!"); if (sUseWorldCentroid) { const cAABB& world_boundaries = cWorld::GetInstance()->GetWorldBoundaries(); State().mPos = world_boundaries.GetCentroid(); State().mPos.y = Def().mRadius; } } // mCrosshair = ModelRepo::GetModel(MID_BOX); mCrosshair = ModelRepo::GetModel(MID_SPHERE); return success; } //---------------------------------------------------------------------------- void cPlayer::Update(float elapsed) { // Debug::WriteLine("Player pos (%f, %f, %f)", State().mPos.x, State().mPos.y, State().mPos.z); State().mPos = cWorld::GetInstance()->StepPlayerCollision(State().mPos, ComputeLinearVelocity(), Def().mRadius, elapsed); mLookAt = ComputeLookAt(); const cVector3 eye_pos = ComputeEyePos(); if (sTestCollisionsOnLookAt && Keyboard::IsKeyPressed(Keyboard::KEY_UP)) { const cVector3 aim_dir = Normalize(mLookAt - eye_pos); cVector3 coll_pos; cVector3 coll_normal; if (cWorld::GetInstance()->CastSphereAgainstWorld(eye_pos, eye_pos + (aim_dir * 10000), Def().mRadius, false, coll_pos, coll_normal)) { Debug::cRenderer::Get().AddSphere(coll_pos + (coll_normal * Def().mRadius), Def().mRadius, TCOLOR_RED); Debug::WriteLine("Collision: (%f, %f, %f). Normal: (%f, %f, %f)", coll_pos.x, coll_pos.y, coll_pos.z, coll_normal.x, coll_normal.y, coll_normal.z); } } if (Mouse::LeftMouseButton()) { cGameObjectManager* const game_obj_mgr = cGameObjectManager::GetInstance(); const float current_time = game_obj_mgr->GetCurrTime(); if ((current_time - mLastShot) > Def().mFirePeriod) { const cVector3 eye_pos = ComputeEyePos(); const cVector3 aim_dir = Normalize(mLookAt - eye_pos); game_obj_mgr->CreateGameObject<cBullet>(gPlayerBullets, cBulletState(eye_pos, aim_dir)); mLastShot = current_time; } } const cVector3 height(0.0f, Def().mHeight, 0.0f); Camera::LookAt(State().mPos + height, mLookAt); } //---------------------------------------------------------------------------- void cPlayer::Render() { // WIP Render "crosshair" . I Have no idea why I can't get this to work... /* static float separation = 0.01f; static float distance_to_crosshair_plane = 0.4f; cVector3 crosshair_up = cVector3(0.0f, separation, distance_to_crosshair_plane); cVector3 crosshair_down = cVector3(0.0f, -separation, distance_to_crosshair_plane); cVector3 crosshair_left = cVector3(-separation, 0.0f, distance_to_crosshair_plane); cVector3 crosshair_right = cVector3(separation, 0.0f, distance_to_crosshair_plane); static float long_side = 0.01f; static float short_side = 0.005f; / * const cVector3 horizontal_boxes_scale = cVector3(long_side, short_side, short_side); const cVector3 vertical_boxes_scale = cVector3(short_side, long_side, short_side); * / const cVector3 horizontal_boxes_scale = cVector3::ONE() * long_side; const cVector3 vertical_boxes_scale = cVector3::ONE() * long_side; const cVector3 rotation(-mPitch, mYaw, 0.0f); const cVector3 eye_pos = ComputeEyePos(); cMatrix44 look_at_matrix = BuildLookAtMatrix(eye_pos, mLookAt, cVector3::YAXIS()); look_at_matrix.SetTranslation(eye_pos); const cVector3 crosshair_up_pos = look_at_matrix.RotateCoord(crosshair_up); const cVector3 crosshair_up_down = look_at_matrix.RotateCoord(crosshair_down); const cVector3 crosshair_up_left = look_at_matrix.RotateCoord(crosshair_left); const cVector3 crosshair_up_right = look_at_matrix.RotateCoord(crosshair_right); mCrosshair->Render(crosshair_up_pos, rotation, vertical_boxes_scale, TCOLOR_BLACK); mCrosshair->Render(crosshair_up_down, rotation, vertical_boxes_scale, TCOLOR_BLACK); mCrosshair->Render(crosshair_up_left, rotation, horizontal_boxes_scale, TCOLOR_BLACK); mCrosshair->Render(crosshair_up_right, rotation, horizontal_boxes_scale, TCOLOR_BLACK); */ } //---------------------------------------------------------------------------- cVector3 cPlayer::ComputeEyePos() const { return (State().mPos + cVector3(0.0f, Def().mHeight, 0.0f)); } //---------------------------------------------------------------------------- cVector3 cPlayer::ComputeLinearVelocity() const { // For now, let's have infinite acceleration to max speed, and infinite friction cVector3 linear_velocity(cVector3::ZERO()); if (Keyboard::IsKeyPressed(Keyboard::KEY_A)) { linear_velocity.x -= 1.0f; } if (Keyboard::IsKeyPressed(Keyboard::KEY_W)) { linear_velocity.z += 1.0f; } if (Keyboard::IsKeyPressed(Keyboard::KEY_S)) { linear_velocity.z -= 1.0f; } if (Keyboard::IsKeyPressed(Keyboard::KEY_D)) { linear_velocity.x += 1.0f; } if (sMoveUpAndDown) { // For debugging purposes mainly if (Keyboard::IsKeyPressed(Keyboard::KEY_SPACE)) { linear_velocity.y += 1.0f; } if (Keyboard::IsKeyPressed(Keyboard::KEY_DOWN)) { linear_velocity.y -= 1.0f; } } linear_velocity.SetNormalized(); linear_velocity *= Def().mSpeed; return linear_velocity.RotateAroundY(mYaw); } //---------------------------------------------------------------------------- cVector3 cPlayer::ComputeLookAt() { auto new_mouse_pos = Mouse::GetPosition(); auto mouse_delta = new_mouse_pos - mPrevMousePos; mPrevMousePos = new_mouse_pos; mouse_delta *= Def().mMouseSensitivity; mYaw += mouse_delta.x; mPitch -= mouse_delta.y; static const float MAX_PITCH = TO_RADIANS(85.0f); mPitch = Clamp(-MAX_PITCH, mPitch, MAX_PITCH); const float lookat_y = sin(mPitch) * Def().mRadius * 0.9f; const float lookat_z = cos(mPitch) * Def().mRadius * 0.9f; return State().mPos + cVector3(0.0f, Def().mHeight + lookat_y, lookat_z).RotateAroundY(mYaw); } //---------------------------------------------------------------------------- cVector3 cPlayer::GetForwardDir() const { return cVector3::ZAXIS().RotateAroundY(mYaw); }
//程序中用到的功能函数声明 #pragma once #include "stdafx.h" //将文本内容读入字符串str std::string & filetostr(std::string file,std::string & str); bool strtofile(std::string file,const std::string & str); //将实数a保留l位小数(四舍五入) 然后转化为字符串 std::string dtos(double a, int l=1);
#include "stdafx.h" #include "../EditTool.h" #include "../Editor.h" #include "../Resource.h" #include "../TerrainModifyDialog.h" #include "TerrainModifyTool.h" IMPLEMENT_DYNCREATE(CTerrainModifyTool, CEditTool) CTerrainModifyTool::CTerrainModifyTool() : mBrushType(E_TERRAIN_BRUSH_NULL_TYPE), mbBeginEdit(false), mBrushSize(0.02f), mHeightUpdateCountDown(0), mTimeLastFrame(0), mBrushHardness(0.001f) { m_iCurrentPageId = 0; m_pTerrainCtrl = GetEditor()->GetRollupCtrl(E_TERRAIN_CTRL); mName = "地形修改工具"; } CTerrainModifyTool::~CTerrainModifyTool() { } void CTerrainModifyTool::BeginTool() { // TODO: 在此添加控件通知处理程序代码 m_iCurrentPageId = m_pTerrainCtrl->InsertPage("修改地形", IDD_TERRAIN_MODIFY_DIALOG, RUNTIME_CLASS(CTerrainModifyDialog), 2); m_pTerrainCtrl->ExpandPage(m_iCurrentPageId); mEditDecal.Create( "DecalEdit", "DecalEdit", 16 ); //mEditDecal.SetScale( mBrushSize*TERRAIN_WORLD_SIZE * 0.5f ); // Update terrain at max 20fps mHeightUpdateRate = 50; mTimeLastFrame = Ogre::Root::getSingletonPtr()->getTimer()->getMilliseconds(); } void CTerrainModifyTool::EndTool() { // TODO: 在此添加控件通知处理程序代码 if ( m_iCurrentPageId ) { m_pTerrainCtrl->RemovePage(m_iCurrentPageId); } mEditDecal.Destroy(); } void CTerrainModifyTool::Update() { unsigned long newTime = Ogre::Root::getSingletonPtr()->getTimer()->getMilliseconds(); unsigned long timeSinceLastFrame = newTime - mTimeLastFrame; if (mHeightUpdateCountDown > 0) { mHeightUpdateCountDown -= timeSinceLastFrame; if (mHeightUpdateCountDown <= 0) { GetEditor()->GetTerrainGroup()->update(); mHeightUpdateCountDown = 0; } } mTimeLastFrame = newTime; } void CTerrainModifyTool::OnLButtonDown(UINT nFlags, CPoint point) { mbBeginEdit = true; } void CTerrainModifyTool::OnLButtonUp(UINT nFlags, CPoint point) { mbBeginEdit = false; } void CTerrainModifyTool::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { //处理键盘响应 switch(nChar) { //esc键 case VK_ESCAPE: { } break; case VK_LEFT: break; case VK_RETURN: break; } } void CTerrainModifyTool::OnMouseMove(UINT nFlags, CPoint point) { Ogre::TerrainGroup::RayResult rayResult = GetEditor()->TerrainHitTest( point ); if (rayResult.hit) { mEditDecal.setPosition(rayResult.position.x, rayResult.position.z, 2.0f); if ( mBrushType == E_TERRAIN_BRUSH_NULL_TYPE ) return; if ( mbBeginEdit ) { // figure out which terrains this affects TerrainGroup::TerrainList terrainList; Real brushSizeWorldSpace = TERRAIN_WORLD_SIZE * mBrushSize; Sphere sphere(rayResult.position, brushSizeWorldSpace); GetEditor()->GetTerrainGroup()->sphereIntersects(sphere, &terrainList); for (TerrainGroup::TerrainList::iterator it = terrainList.begin(); it != terrainList.end(); ++it) { Terrain* terrain = *it; Vector3 tsPos; terrain->getTerrainPosition(rayResult.position, &tsPos); // we need point coords Real terrainSize = (terrain->getSize() - 1); long startx = (tsPos.x - mBrushSize) * terrainSize; long starty = (tsPos.y - mBrushSize) * terrainSize; long endx = (tsPos.x + mBrushSize) * terrainSize; long endy= (tsPos.y + mBrushSize) * terrainSize; startx = std::max(startx, 0L); starty = std::max(starty, 0L); endx = std::min(endx, (long)terrainSize); endy = std::min(endy, (long)terrainSize); for (long y = starty; y <= endy; ++y) { for (long x = startx; x <= endx; ++x) { Real tsXdist = (x / terrainSize) - tsPos.x; Real tsYdist = (y / terrainSize) - tsPos.y; Real weight = std::min((Real)1.0, Math::Sqrt(tsYdist * tsYdist + tsXdist * tsXdist) / Real(0.5 * mBrushSize)); weight = 1.0 - (weight * weight); float addedHeight = weight * 250.0 * mBrushHardness; float newheight; switch( mBrushType ) { case E_TERRAIN_RISE: { newheight = terrain->getHeightAtPoint(x, y) + addedHeight; } break; case E_TERRAIN_LOWER: { newheight = terrain->getHeightAtPoint(x, y) - addedHeight; if( newheight < 0.0f ) newheight = 0.0f; } break; } terrain->setHeightAtPoint(x, y, newheight); } } } if (mHeightUpdateCountDown == 0) mHeightUpdateCountDown = mHeightUpdateRate; } } } void CTerrainModifyTool::SetBrushHardness( Real hardness ) { mBrushHardness = hardness; } void CTerrainModifyTool::SetBrushSize( Real brushSize ) { mBrushSize = brushSize; mEditDecal.SetScale( mBrushSize*TERRAIN_WORLD_SIZE * 0.5f ); } void CTerrainModifyTool::SetBrushType( E_TERRAIN_BRUSH_TYPE type ) { mBrushType = type; }
// Created on: 1997-02-06 // Created by: Laurent BOURESCHE // Copyright (c) 1997-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 _BRepBlend_RstRstConstRad_HeaderFile #define _BRepBlend_RstRstConstRad_HeaderFile #include <Adaptor3d_Surface.hxx> #include <Adaptor3d_CurveOnSurface.hxx> #include <gp_Pnt.hxx> #include <gp_Pnt2d.hxx> #include <gp_Vec.hxx> #include <gp_Vec2d.hxx> #include <BlendFunc_SectionShape.hxx> #include <Convert_ParameterisationType.hxx> #include <Blend_RstRstFunction.hxx> #include <math_Vector.hxx> #include <Blend_DecrochStatus.hxx> #include <TColStd_Array1OfReal.hxx> #include <GeomAbs_Shape.hxx> #include <TColStd_Array1OfInteger.hxx> #include <TColgp_Array1OfPnt.hxx> #include <TColgp_Array1OfVec.hxx> #include <TColgp_Array1OfPnt2d.hxx> #include <TColgp_Array1OfVec2d.hxx> class math_Matrix; class gp_Circ; class Blend_Point; //! Copy of CSConstRad with a pcurve on surface //! as support. class BRepBlend_RstRstConstRad : public Blend_RstRstFunction { public: DEFINE_STANDARD_ALLOC Standard_EXPORT BRepBlend_RstRstConstRad(const Handle(Adaptor3d_Surface)& Surf1, const Handle(Adaptor2d_Curve2d)& Rst1, const Handle(Adaptor3d_Surface)& Surf2, const Handle(Adaptor2d_Curve2d)& Rst2, const Handle(Adaptor3d_Curve)& CGuide); //! Returns 2. Standard_EXPORT Standard_Integer NbVariables() const Standard_OVERRIDE; //! Returns 2. Standard_EXPORT Standard_Integer NbEquations() const Standard_OVERRIDE; //! computes the values <F> of the Functions for the //! variable <X>. //! Returns True if the computation was done successfully, //! False otherwise. Standard_EXPORT Standard_Boolean Value (const math_Vector& X, math_Vector& F) Standard_OVERRIDE; //! returns the values <D> of the derivatives for the //! variable <X>. //! Returns True if the computation was done successfully, //! False otherwise. Standard_EXPORT Standard_Boolean Derivatives (const math_Vector& X, math_Matrix& D) Standard_OVERRIDE; //! returns the values <F> of the functions and the derivatives //! <D> for the variable <X>. //! Returns True if the computation was done successfully, //! False otherwise. Standard_EXPORT Standard_Boolean Values (const math_Vector& X, math_Vector& F, math_Matrix& D) Standard_OVERRIDE; Standard_EXPORT void Set (const Handle(Adaptor3d_Surface)& SurfRef1, const Handle(Adaptor2d_Curve2d)& RstRef1, const Handle(Adaptor3d_Surface)& SurfRef2, const Handle(Adaptor2d_Curve2d)& RstRef2); Standard_EXPORT void Set (const Standard_Real Param) Standard_OVERRIDE; //! Sets the bounds of the parametric interval on //! the guide line. //! This determines the derivatives in these values if the //! function is not Cn. Standard_EXPORT void Set (const Standard_Real First, const Standard_Real Last) Standard_OVERRIDE; Standard_EXPORT void GetTolerance (math_Vector& Tolerance, const Standard_Real Tol) const Standard_OVERRIDE; Standard_EXPORT void GetBounds (math_Vector& InfBound, math_Vector& SupBound) const Standard_OVERRIDE; Standard_EXPORT Standard_Boolean IsSolution (const math_Vector& Sol, const Standard_Real Tol) Standard_OVERRIDE; //! Returns the minimal Distance between two //! extremities of calculated sections. Standard_EXPORT virtual Standard_Real GetMinimalDistance() const Standard_OVERRIDE; Standard_EXPORT const gp_Pnt& PointOnRst1() const Standard_OVERRIDE; Standard_EXPORT const gp_Pnt& PointOnRst2() const Standard_OVERRIDE; //! Returns U,V coordinates of the point on the surface. Standard_EXPORT const gp_Pnt2d& Pnt2dOnRst1() const Standard_OVERRIDE; //! Returns U,V coordinates of the point on the curve on //! surface. Standard_EXPORT const gp_Pnt2d& Pnt2dOnRst2() const Standard_OVERRIDE; //! Returns parameter of the point on the curve. Standard_EXPORT Standard_Real ParameterOnRst1() const Standard_OVERRIDE; //! Returns parameter of the point on the curve. Standard_EXPORT Standard_Real ParameterOnRst2() const Standard_OVERRIDE; Standard_EXPORT Standard_Boolean IsTangencyPoint() const Standard_OVERRIDE; Standard_EXPORT const gp_Vec& TangentOnRst1() const Standard_OVERRIDE; Standard_EXPORT const gp_Vec2d& Tangent2dOnRst1() const Standard_OVERRIDE; Standard_EXPORT const gp_Vec& TangentOnRst2() const Standard_OVERRIDE; Standard_EXPORT const gp_Vec2d& Tangent2dOnRst2() const Standard_OVERRIDE; //! Permet d ' implementer un critere de decrochage //! specifique a la fonction. Standard_EXPORT Blend_DecrochStatus Decroch (const math_Vector& Sol, gp_Vec& NRst1, gp_Vec& TgRst1, gp_Vec& NRst2, gp_Vec& TgRst2) const Standard_OVERRIDE; Standard_EXPORT void Set (const Standard_Real Radius, const Standard_Integer Choix); //! Sets the type of section generation for the //! approximations. Standard_EXPORT void Set (const BlendFunc_SectionShape TypeSection); //! Give the center of circle define by PtRst1, PtRst2 and //! radius ray. Standard_EXPORT Standard_Boolean CenterCircleRst1Rst2 (const gp_Pnt& PtRst1, const gp_Pnt& PtRst2, const gp_Vec& np, gp_Pnt& Center, gp_Vec& VdMed) const; Standard_EXPORT void Section (const Standard_Real Param, const Standard_Real U, const Standard_Real V, Standard_Real& Pdeb, Standard_Real& Pfin, gp_Circ& C); //! Returns if the section is rationnal Standard_EXPORT Standard_Boolean IsRational() const Standard_OVERRIDE; //! Returns the length of the maximum section Standard_EXPORT Standard_Real GetSectionSize() const Standard_OVERRIDE; //! Compute the minimal value of weight for each poles //! of all sections. Standard_EXPORT void GetMinimalWeight (TColStd_Array1OfReal& Weigths) const Standard_OVERRIDE; //! Returns the number of intervals for continuity //! <S>. May be one if Continuity(me) >= <S> Standard_EXPORT Standard_Integer NbIntervals (const GeomAbs_Shape S) const Standard_OVERRIDE; //! Stores in <T> the parameters bounding the intervals //! of continuity <S>. //! The array must provide enough room to accommodate //! for the parameters. i.e. T.Length() > NbIntervals() Standard_EXPORT void Intervals (TColStd_Array1OfReal& T, const GeomAbs_Shape S) const Standard_OVERRIDE; Standard_EXPORT void GetShape (Standard_Integer& NbPoles, Standard_Integer& NbKnots, Standard_Integer& Degree, Standard_Integer& NbPoles2d) Standard_OVERRIDE; //! Returns the tolerance to reach in approximation //! to respecte //! BoundTol error at the Boundary //! AngleTol tangent error at the Boundary //! SurfTol error inside the surface. Standard_EXPORT void GetTolerance (const Standard_Real BoundTol, const Standard_Real SurfTol, const Standard_Real AngleTol, math_Vector& Tol3d, math_Vector& Tol1D) const Standard_OVERRIDE; Standard_EXPORT void Knots (TColStd_Array1OfReal& TKnots) Standard_OVERRIDE; Standard_EXPORT void Mults (TColStd_Array1OfInteger& TMults) Standard_OVERRIDE; //! Used for the first and last section Standard_EXPORT Standard_Boolean Section (const Blend_Point& P, TColgp_Array1OfPnt& Poles, TColgp_Array1OfVec& DPoles, TColgp_Array1OfPnt2d& Poles2d, TColgp_Array1OfVec2d& DPoles2d, TColStd_Array1OfReal& Weigths, TColStd_Array1OfReal& DWeigths) Standard_OVERRIDE; Standard_EXPORT void Section (const Blend_Point& P, TColgp_Array1OfPnt& Poles, TColgp_Array1OfPnt2d& Poles2d, TColStd_Array1OfReal& Weigths) Standard_OVERRIDE; //! Used for the first and last section //! The method returns Standard_True if the derivatives //! are computed, otherwise it returns Standard_False. Standard_EXPORT Standard_Boolean Section (const Blend_Point& P, TColgp_Array1OfPnt& Poles, TColgp_Array1OfVec& DPoles, TColgp_Array1OfVec& D2Poles, TColgp_Array1OfPnt2d& Poles2d, TColgp_Array1OfVec2d& DPoles2d, TColgp_Array1OfVec2d& D2Poles2d, TColStd_Array1OfReal& Weigths, TColStd_Array1OfReal& DWeigths, TColStd_Array1OfReal& D2Weigths) Standard_OVERRIDE; Standard_EXPORT void Resolution (const Standard_Integer IC2d, const Standard_Real Tol, Standard_Real& TolU, Standard_Real& TolV) const Standard_OVERRIDE; protected: private: Handle(Adaptor3d_Surface) surf1; Handle(Adaptor3d_Surface) surf2; Handle(Adaptor2d_Curve2d) rst1; Handle(Adaptor2d_Curve2d) rst2; Adaptor3d_CurveOnSurface cons1; Adaptor3d_CurveOnSurface cons2; Handle(Adaptor3d_Curve) guide; Handle(Adaptor3d_Curve) tguide; gp_Pnt ptrst1; gp_Pnt ptrst2; gp_Pnt2d pt2drst1; gp_Pnt2d pt2drst2; Standard_Real prmrst1; Standard_Real prmrst2; Standard_Boolean istangent; gp_Vec tgrst1; gp_Vec2d tg2drst1; gp_Vec tgrst2; gp_Vec2d tg2drst2; Standard_Real ray; Standard_Integer choix; gp_Pnt ptgui; gp_Vec d1gui; gp_Vec d2gui; gp_Vec nplan; Standard_Real normtg; Standard_Real theD; Handle(Adaptor3d_Surface) surfref1; Handle(Adaptor2d_Curve2d) rstref1; Handle(Adaptor3d_Surface) surfref2; Handle(Adaptor2d_Curve2d) rstref2; Standard_Real maxang; Standard_Real minang; Standard_Real distmin; BlendFunc_SectionShape mySShape; Convert_ParameterisationType myTConv; }; #endif // _BRepBlend_RstRstConstRad_HeaderFile
#include <iostream> #include<vector> using namespace std; void Out(vector<int> arr) { int Size=arr.size(); for(int i=0;i<Size;i++) { cout<<arr[i]<<" "; } } int main() { vector<int> arr; arr.push_back(1); arr.push_back(2); arr.push_back(3); arr.push_back(4); arr.push_back(5); arr.push_back(69); Out(arr); //Xoa 1 vi tri arr.erase(arr.begin()+2); cout<<"\n -----Sau khi xoa Tai 1 vi tri-------\n"; Out(arr); //Xoa doan Tu A ->(B-1) arr.erase(arr.begin()+1,arr.begin()+4); cout<<"\n**** Xoa doan Tu A->(B-1)****\n"; Out(arr); //Insert 1 so va 1 vi tri arr.insert(arr.end()-1,96); cout<<"\n****Chen 1 so vao 1 vi tri****\n"; Out(arr); //Chen so n lan vao 1 vi tri arr.insert(arr.end()-1,3,33); cout<<"\n ***Chen n Lan so vao 1 vi tri***\n"; Out(arr); return 0; }
#include "H/Memory.h" uint_8 UsableMemoryRegionCount; MemoryMapEntry* UsableMemoryRegions[10]; void memcpy(void* destination, void* source, uint_64 num){ if (num <= 8) { uint8* valPtr = (uint8*)&source; for (uint8* ptr = (uint8*)destination; ptr < (uint8*)((uint_64)destination + num); ptr++) { *ptr = *valPtr; valPtr++; } return; } uint_64 proceedingBytes = num % 8; uint_64 newnum = num - proceedingBytes; uint_64* srcptr = (uint_64*)source; for (uint64* destptr = (uint64*)destination; destptr < (uint64*)((uint_64)destination + newnum); destptr++) { *destptr = *srcptr; srcptr++; } uint8* srcptr8 = (uint8*)((uint_64)source + newnum); for (uint8* destptr8 = (uint8*)((uint64)destination + newnum); destptr8 < (uint8*)((uint64)destination + newnum); destptr8++) { *destptr8 = *srcptr8; srcptr8++; } } void printMemMap(MemoryMapEntry* memoryMap) { /*debug("Memory Base: ",memoryMap->BaseAddress); debug("Region Length: ",memoryMap->RegionLength); debug("Memory Type: ",memoryMap->RegionType); debug("Memory Attributes: ",memoryMap->ExtendedAttributes);*/ debug("Usable Memory Region count :", UsableMemoryRegionCount); debug("Memory Region count :",MemoryRegionCount); } bool MemoryRegionsGot = false; MemoryMapEntry** GetUsableMemoryRegions() { if (MemoryRegionsGot == true) return UsableMemoryRegions; uint8 UsableRegionsIndex; for(uint8 i = 0; i < MemoryRegionCount; i++) { MemoryMapEntry* memMap = (MemoryMapEntry*)0x5000; memMap += i; if (memMap->RegionType == 1) { UsableMemoryRegions[UsableRegionsIndex] = memMap; UsableRegionsIndex++; } UsableMemoryRegionCount = UsableRegionsIndex; } MemoryRegionsGot = true; return UsableMemoryRegions; } void memset(void* start, uint_64 value, uint_64 num){ if (num <= 8) { uint8* valPtr = (uint8*)&value; for (uint8* ptr = (uint8*)start; ptr < (uint8*)((uint_64)start + num); ptr++) { *ptr = *valPtr; valPtr++; } return; } uint_64 proceedingBytes = num % 8; uint_64 newnum = num - proceedingBytes; for (uint64* ptr = (uint64*)start; ptr < (uint64*)((uint_64)start + newnum); ptr++) { *ptr = value; } uint8* valPtr = (uint8*)&value; for (uint8* ptr = (uint8*)((uint64)start + newnum); ptr < (uint8*)((uint64)start + newnum); ptr++) { *ptr = *valPtr; valPtr++; } }
#include<ros/ros.h> #include <actionlib/client/simple_action_client.h> #include <mbot_visual_servoing_imagebased/GraspObjectAction.h> int main(int argc, char** argv) { ros::init(argc, argv, "action_client_vs"); mbot_visual_servoing_imagebased::GraspObjectGoal goal; actionlib::SimpleActionClient<mbot_visual_servoing_imagebased::GraspObjectAction> action_client("grasp_object", true); ROS_INFO("waiting for server: "); bool server_exists = action_client.waitForServer(); //wait forever ROS_INFO("connected to action server"); std::string class_name = "muuug"; while (ros::ok()) { goal.class_name = class_name; action_client.sendGoal(goal); bool finished_before_timeout = action_client.waitForResult(); // wait forever } }
#include "stdafx.h" #include "Alien.h" Alien::Alien() { } Alien::~Alien() { } HRESULT Alien::Init(const char * imageName, POINT position) { // 에너미에서 먼저 init Enemy::Init(imageName, position); // 추가적으로 Init this->_died = IMAGE->FindImage("alien_died"); _frameCount = 0; _currentFrameX2 = 0; return S_OK; } void Alien::Release() { Enemy::Release(); } void Alien::Update() { Animation(); } void Alien::Render() { Draw(); } void Alien::Draw() { // 살아 있는 상태면 에너미꺼만 그리기 (idle 이미지) if (_isLived) Enemy::Draw(); // 살아 있는 상태가 아니면 // 죽는 이미지 그리기 else _died->FrameRender(GetMemDC(), GetRect().left - 25, GetRect().top - 25, _currentFrameX2, 0); } void Alien::Animation() { // 살아 있는 상태면 에너미 꺼만 애니메이션 동작 (idle) if(_isLived) Enemy::Animation(); // 아니면 죽는 애니메이션 동작 else { _frameCount++; if (_frameCount % 5 == 0) { _currentFrameX2++; if (_currentFrameX2 == _died->GetMaxFrameX()) _isDied = true; } } }
#include<iostream> #include<string> #include<stack> bool correspondence ( char openedOne, char closedOne ) { if (( '[' == openedOne && ']' == closedOne) || ( '(' == openedOne && ')' == closedOne ) || ( '{' == openedOne && '}' == closedOne) || ( '"' == openedOne && '"' == closedOne) || ( '\'' == openedOne && '\'' == closedOne )) { return true; } else { return false; } } bool ckeck ( std::string input ) { int index = 0; int quantity = 0; int one; int two; std::stack < char > bracket; while ( '\0' != input [index] ) { if ( '"' == input [index] ) { if ( 0 == two % 2 ) { bracket.push ( input [index] ); } else { if ( !correspondence ( bracket.top(), input [index] )) { return false; } else { if ( !correspondence ( bracket.top(), input [index] ) ) { std::cout <<"Index : " << index << std::endl; return false; } else { bracket.pop(); } } ++ one; } if ( '{' == input [index] || '(' == input [index] || '[' == input [index] ) { bracket.push ( input [index] ) ; } if ( '}' == input [index] || ')' == input [index] || ']' == input [index] ) { if ( bracket.empty () ) { std::cout << "Index : " << index << std::endl; return false; } else { if ( false == correspondence ( bracket.top(), input [index] ) ) { std::cout << "Index : " << index << std::endl; return false; } else { bracket.pop(); } } } ++ index; } return bracket.empty(); } } int main () { std::string input; std::cout << " Input something : "; std::cin >> input; if (! ckeck ( input )) { std::cout << "Not suitable" << std::endl; } else { std::cout << "******!!!*****" << std::endl; } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2010 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef OP_SCOPE_NETWORK_LISTENER_H #define OP_SCOPE_NETWORK_LISTENER_H #ifdef SCOPE_RESOURCE_MANAGER class Window; class DocumentManager; class HeaderList; class Header_List; class Upload_EncapsulatedElement; class URL_Rep; #include "modules/pi/network/OpHostResolver.h" #include "modules/url/url_dns_man.h" /** * A 'resource' is any item used by a Window to compose a page, HTML files, * CSS files, images, and so forth. * * Use this interface to notify the client of network activity, HTTP headers, * and other events related to resources. */ class OpScopeResourceListener { public: enum LoadStatus { LS_COMPOSE_REQUEST = 1, LS_REQUEST, LS_REQUEST_FINISHED, LS_RESPONSE, LS_RESPONSE_HEADER, LS_RESPONSE_FINISHED, LS_RESPONSE_FAILED, LS_DNS_LOOKUP_START, LS_DNS_LOOKUP_END }; // LoadStatus /** * Check whether the HTTP listener is enabled. If it's not enabled, * there is no point is calling the functions (they will be ignored). * * @return TRUE if enabled, FALSE otherwise. */ static BOOL IsEnabled(); /** * Called from the URL layer when loading of a URL is started. * A URL load always happens before an OnRequest (and related callbacks). * * @param url_rep The URL this load applies to. * @param docman The originating DocumentManager (may be NULL). * @param window The originating Window (may be NULL). * @return OpStatus::OK */ static OP_STATUS OnUrlLoad(URL_Rep *url_rep, DocumentManager *docman, Window *window); /** * Called from the URL layer when loading of a URL is finished or failed. * * @param url_rep The URL that was finished. * @param result The result of the URL load, should be * URL_LOAD_FINISHED for success or * URL_LOAD_FAILED for failure or * URL_LOAD_STOPPED for manual stop * @return OpStatus::OK */ static OP_STATUS OnUrlFinished(URL_Rep *url_rep, URLLoadResult result); /** * Called from the URL layer when a URL redirection occurs. * * @param orig_url_rep The original URL that resulted in the redirect. * @param new_url_rep The URL the redirection goes to. * @return OpStatus::OK */ static OP_STATUS OnUrlRedirect(URL_Rep *orig_url_rep, URL_Rep *new_url_rep); /** * Called from the URL layer when a URL is no longer in use. * This will allow for cleaning up references to URL_Rep objects. * * @param url The URL_Rep that was destroyed. * @return OpStatus::OK */ static OP_STATUS OnUrlUnload(URL_Rep *rep); /** * Called from the URL layer when a request is about to be serialized into * data to be sent over the network. Calling this will give the debugger * a chance to add or remove headers from the request. * * @param url_rep The URL this request applies to. * @param request_id Globally unique identifier for the request. * @param upload The element from which we're about to compose a request. * @param docman The originating DocumentManager (may be NULL). * @param window The originating Window (may be NULL). * @return OpStatus::OK, or OOM. */ static OP_STATUS OnComposeRequest(URL_Rep *url_rep, int request_id, Upload_EncapsulatedElement *upload, DocumentManager *docman, Window *window); /** * Called from the URL layer when a request has been sent. * * @param url_rep The URL this request applies to. * @param request_id Globally unique identifier for the request. * @param upload The element we're about to send. * @param buf The request that was sent. * @param len The length of the request buffer. * @return OpStatus::OK */ static OP_STATUS OnRequest(URL_Rep *url_rep, int request_id, Upload_EncapsulatedElement *upload, const char* buf, size_t len); /** * Called after a POST request is made. This may be called many time for the same POST. * * @param url_rep The URL this request applies to. * @param request_id Globally unique identifier for the request. * @param upload The element that was just sent. */ static OP_STATUS OnRequestFinished(URL_Rep *url_rep, int request_id, Upload_EncapsulatedElement *upload); /** * Indicate that a request is about to be retried, due to some HTTP connection error. After this * event has been observed, we do not expect to get more events from the request tracked by * 'orig_request_id'. * * @param url_rep The URL this request applies to. * @param orig_request_id The original request ID for the request. * @param new_request_id The new request ID for the (same) request. * @return OpStatus::OK */ static OP_STATUS OnRequestRetry(URL_Rep *url_rep, int orig_request_id, int new_request_id); /** * Called at 'first contact' from the server, before headers are parsed. * * @param url The URL this response applies to. * @param request_id Globally unique identifier for the request. * @param response_code The HTTP response code for the request, e.g. 200, 304, etc. */ static OP_STATUS OnResponse(URL_Rep *url_rep, int request_id, int response_code); /** * Called from the URL layer when a header has been completely loaded * from a server response. * * @param url_rep The URL this request applies to. * @param request_id Globally unique identifier for the request. * @param headerList A list of parsed headers. * @param buf The raw response header. * @param len The length of the response buffer. */ static OP_STATUS OnResponseHeader(URL_Rep *url_rep, int request_id, const HeaderList *headerList, const char* buf, size_t len); /** * Called from the URL layer when a response has finished * * @param url_rep The URL this event applies to. * @param request_id Globally unique identifier for the request. */ static OP_STATUS OnResponseFinished(URL_Rep *url_rep, int request_id); /** * Called from the URL layer when a response has failed to load. * * @param url_rep The URL this request applies to. * @param request_id Globally unique identifier for the request. */ static OP_STATUS OnResponseFailed(URL_Rep *url_rep, int request_id); /** * Called when the URL layer needs to know whether a resource should be retrived over * the network, even if it's available in cache. * * @param url_rep The URL this request applies to. * @param docman The originating DocumentManager (may be NULL). * @param window The originating Window (may be NULL). * @return TRUE to force a full reload. FALSE does not guarantee that the resource * is *not* retrieved over the network -- it simply means "do not change load * policy". */ static BOOL ForceFullReload(URL_Rep *url_rep, DocumentManager *docman, Window *window); /** * Called when a XHR is about to be loaded, either from cache or from the network. * This is necessary because DOM_LSLoader implements its own caching rules, and * can in some cases not involve the network layer at all. * * When this function is called, and a cached load is indicated, Scope may send * events to the client indicating that a cached XHR load took place. * * @param url_rep The URL this load applies to. * @param cached TRUE if the network layer is not involved in the load, FALSE otherwise. * @param docman The originating DocumentManager (may be NULL). * @param window The originating Window (may be NULL). */ static OP_STATUS OnXHRLoad(URL_Rep *url_rep, BOOL cached, DocumentManager *docman, Window *window); /** * Return the http request-id registered in OnRequest. -1 is returned if not found. * * @param url_rep The URL we want the http request from. */ static int GetHTTPRequestID(URL_Rep *url_rep); /** * Called when DNS resolving is started. * * @param url_rep The URL resolving is connected to. */ static void OnDNSResolvingStarted(URL_Rep *url_rep); /** * Called when a DNS resolve action has completed, also called when a resolve action fails. * * @param url_rep The URL DNS resolving ended. * @param errorcode Status of the resolving. */ static void OnDNSResolvingEnded(URL_Rep *url_rep, OpHostResolver::Error errorcode); }; // OpScopeResourceListener #endif // SCOPE_RESOURCE_MANAGER #endif // OP_SCOPE_NETWORK_LISTENER_H
#pragma once #ifndef FLIGHT_H #define FLIGHT_H class City; class Flight { private: City* bcity; City* ecity; int mileage; int cost; public: Flight(City *x, City *y, int mile, int price) { bcity = x; ecity = y; mileage = mile; cost = price; }; City* getDestination() const { return ecity; }; int getMileage() { return mileage; }; }; #endif
// // 1249. Minimum Remove to Make Valid Parentheses.cpp // leetcode // // Created by xujian chen on 6/2/20. // Copyright © 2020 xujian chen. All rights reserved. // /* 1249. Minimum Remove to Make Valid Parentheses Medium 675 23 Add to List Share Given a string s of '(' , ')' and lowercase English characters. Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string. Formally, a parentheses string is valid if and only if: It is the empty string, contains only lowercase characters, or It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string. Example 1: Input: s = "lee(t(c)o)de)" Output: "lee(t(c)o)de" Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted. Example 2: Input: s = "a)b(c)d" Output: "ab(c)d" Example 3: Input: s = "))((" Output: "" Explanation: An empty string is also valid. Example 4: Input: s = "(a(b(c)d)" Output: "a(b(c)d)" Constraints: 1 <= s.length <= 10^5 s[i] is one of '(' , ')' and lowercase English letters. Accepted 56,942 Submissions 92,439 */ class Solution { public: string minRemoveToMakeValid(string s) { vector<int> index2remove; // create a vector to store index of '('. In the end, index2remove size will drop to 0 only when s is balanced. for(int i = 0; i < s.length(); ++i){ if (s[i] == '(') index2remove.push_back(i); else if (s[i] == ')'){ if (index2remove.size()>0) index2remove.pop_back(); else s[i] = 'A'; //detected ')' that can't be balanced. Mark it to 'A'. } } string result; int j = 0; for(int i = 0; i < s.length(); ++i){ // traverse s if(j < index2remove.size()){ // if(i == index2remove[j] ){ ++j; continue; } } if (s[i]== 'A') continue; result += s[i]; //cope s[i] to result only if it is not marked to 'A' or i is not in the index2remove. } return result; } };
#include <iostream> #include <vector> #include <string> #include <map> using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> pii; typedef map<int, int> mii; void solve (int n) { if (n == 2 || (n / 2) % 2 != 0) { cout << "NO\n"; return; } int sum_even = 0; int sum_odd = 0; cout << "YES\n"; for (int i = 0; i < n / 2; i++) { sum_even += 2 * (i + 1); cout << 2 * (i + 1) << " "; } for (int i = 1; i < n / 2; i++) { sum_odd += 2 * i - 1; cout << (2 * i - 1) << " "; } cout << sum_even - sum_odd << "\n"; } int main() { ios::sync_with_stdio(0); cin.tie(0); int n; cin >> n; while (n) { n--; int inp; cin >> inp; solve(inp); } return 0; }
#include "precompiled.h" #include "misc/alias.h" #include "vfs/vfs.h" using namespace misc; void AliasList::load(const string& filename) { list.clear(); vfs::File file = vfs::getFile(filename.c_str()); if (!file) return; char buf[MAX_PATH * 2]; while (file->readLine(buf, MAX_PATH * 2)) { char* bufptr = buf; char* comment = strstr(buf, "//"); if (comment) *comment = 0; strip(buf); if (!buf[0]) continue; char* key = getToken(&bufptr, " \t"); char* value = getToken(&bufptr, " \t"); if (!(key && value)) continue; list.push_back(list_t::value_type(key, value)); } } const char* AliasList::findAlias(const char* key) { for (list_t::iterator it = list.begin(); it != list.end(); it++) if (wildcmp(it->first.c_str(), key)) return it->second.c_str(); return NULL; }
// // Created by sergo on 12/6/19. // #include <iostream> #include <chrono> #include "matrix.hpp" using namespace std; template <typename F> Matrix<int>* printExecTime(F &function, Matrix<int>& A, Matrix<int>& B) { auto start = chrono::high_resolution_clock::now(); auto res = function(A, B); auto end = chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::nanoseconds> (end - start).count() / 1e9; cout << "Elapsed time: " << duration << endl; return res; } Matrix<int>* prodOneThread(Matrix<int>& A, Matrix<int>& B) { if (A.getWidth() != B.getWidth()) { throw runtime_error("Wrong matrices size"); } auto result = new Matrix<int>(A.getHeight(), B.getWidth()); auto &C = *result; for (int i = 0; i < A.getHeight(); ++i) { for (int j = 0; j < B.getWidth(); ++j) { C[i][j] = 0; for (int k = 0; k < B.getHeight(); ++k) { C[i][j] += A[i][k] * B[k][j]; } } } return result; } Matrix<int>* prodParallel(Matrix<int>& A, Matrix<int>& B) { if (A.getWidth() != B.getWidth()) { throw runtime_error("Wrong matrices size"); } auto result = new Matrix<int>(A.getHeight(), B.getWidth()); auto &C = *result; int i, j, k; #pragma parallel for, private(i) for (i = 0; i < A.getHeight(); ++i) { #pragma parallel for, private(i, j) for (j = 0; j < B.getWidth(); ++j) { // C[i][j] = 0; int sum = 0; #pragma parallel for reduction(+:sum), private(i, j, k) for (k = 0; k < B.getHeight(); ++k) { sum += A[i][k] * B[k][j]; } C[i][j] = sum; } } return result; } int main() { int size = 1000; Matrix<int> A(size), B(size); randomizeMatrix(A); randomizeMatrix(B); auto C = printExecTime(prodOneThread, A, B); auto D = printExecTime(prodParallel, A, B); if (*C == *D) { cout << "COOL" << endl; } else { cout << "NOT COOL" << endl; } return 0; }
#include <QQmlEngine> #include <QQmlComponent> #include <QProcess> #include <QDebug> #include <QDBusConnection> #include <QCoreApplication> #include "qmlloader.h" QmlLoader::QmlLoader(QObject *parent) :QObject(parent) { engine = new QQmlEngine(this); component = new QQmlComponent(engine, this); rootContext = new QQmlContext(engine, this); m_dbus_proxy = new DBusProxy(this); } QmlLoader::~QmlLoader() { delete this->m_dbus_proxy; delete this->rootContext; delete this->component; delete this->engine; } void QmlLoader::load(QUrl url) { this->component->loadUrl(url); this->rootObject = this->component->beginCreate(this->rootContext); if ( this->component->isReady() ) this->component->completeCreate(); else qWarning() << this->component->errorString(); } void QmlLoader::actionInvoked(int appId, QString actionId) { Q_EMIT m_dbus_proxy->ActionInvoked(appId, actionId); QCoreApplication::exit(0); } DBusProxy::DBusProxy(QmlLoader *parent): QDBusAbstractAdaptor(parent), m_parent(parent) { QDBusConnection::sessionBus().registerObject("/com/deepin/dialog", parent); } DBusProxy::~DBusProxy() { } int DBusProxy::ShowUninstall(QString icon, QString message, QString warning, QStringList actions) { QVariant appId; QMetaObject::invokeMethod( m_parent->rootObject, "showDialog", Q_RETURN_ARG(QVariant, appId), Q_ARG(QVariant, icon), Q_ARG(QVariant, message), Q_ARG(QVariant, warning), Q_ARG(QVariant, actions) ); return appId.toInt(); }
#include <iostream> using namespace std; int main() { int a; cin >> a; while(a--) { int n, m; cin >> n >> m; if(n % (m + 1) == 0) printf("second\n"); else printf("first\n"); } return 0; }
#include "pch.h" #include "GameUserManager.h" GameUserManager::GameUserManager() { } GameUserManager::~GameUserManager() { } BOOL GameUserManager::Begin() { m_GameUserMap.clear(); m_CurrentUserCount = 0; return TRUE; } BOOL GameUserManager::End() { m_GameUserMap.clear(); m_CurrentUserCount = 0; return TRUE; } VOID GameUserManager::AddUser(GameUser * user, DWORD UID) { m_GameUserMap.insert(pair<DWORD, GameUser*>(UID, user)); } VOID GameUserManager::RemoveUser(DWORD UID) { m_GameUserMap.erase(UID); }
/* * SDEV 340 Week 9 Problem 1 * An abstract class for representing a sequence, with two concrete subclass implementations to demonstrate * Benjamin Lovy */ #include <iostream> class AbstractSeq { public: // Return the kth value of the seq virtual int fun(int k) const = 0; // Print the sequence from k to m void printSeq(int k, int m) const; // Return the sum of the sequence from k to m int sumSeq(int k, int m) const; // Display the results of both printSeq and sumSeq void showSeq(int k, int m) const; }; // Print the sequence from k to m void AbstractSeq::printSeq(int k, int m) const { using std::cout; // Ensure k < m if (k >= m) { std::cerr << "Error: did not meet constraint k < m\n"; std::exit(1); } for (int i = k; i <= m; i++) { cout << fun(i); if (i < m) cout << ", "; } } // Return the sum of the sequence from k to m int AbstractSeq::sumSeq(int k, int m) const { // Ensure k < m if (k >= m) { std::cerr << "Error: did not meet constraint k < m\n"; std::exit(1); } int sum = 0; for (int i = k; i <= m; i++) { sum += fun(i); } return sum; } // Display the results of both printSeq and sumSeq void AbstractSeq::showSeq(int k, int m) const { using std::cout; cout << "Sequence: "; printSeq(k, m); cout << "\nSum of sequence: " << sumSeq(k, m) << ".\n"; } // Implement the odds class OddSeq : public AbstractSeq { virtual int fun(int k) const { return 2 * k + 1; } }; // Implement the cubes class CubeSeq : public AbstractSeq { virtual int fun(int k) const { return k * k * k + 1; } }; // Implement the Fibonacci seq class FibonacciSeq : public AbstractSeq { virtual int fun(int k) const { if (k == 0) return 1; else if (k == 1) return 1; else return (fun(k - 1) + fun(k - 2)); } }; int main() { using std::cout; // Init upper and lower demo bounds int k = 0; int m = 15; cout << "k: " << k << "\nm: " << m << "\n"; // init sequence objects OddSeq os; CubeSeq cs; FibonacciSeq fs; // Dislay results cout << "\nOdds:\n"; os.showSeq(k, m); cout << "\nCubes:\n"; cs.showSeq(k, m); cout << "\nFibonacci:\n"; fs.showSeq(k, m); // Exit success return 0; }
/* * Copyright 2016 Freeman Zhang <zhanggyb@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "internal/abstract-shell-view-private.hpp" #include <skland/gui/application.hpp> #include <skland/gui/mouse-event.hpp> #include <skland/gui/key-event.hpp> #include <skland/gui/surface.hpp> #include <skland/gui/shell-surface.hpp> #include <skland/gui/toplevel-shell-surface.hpp> #include <skland/gui/abstract-shell-frame.hpp> #include <skland/stock/theme.hpp> #include "internal/abstract-view-private.hpp" #include "internal/abstract-view-iterators.hpp" #include "internal/display-registry.hpp" #include "internal/abstract-event-handler-mouse-task-iterator.hpp" namespace skland { AbstractShellView::AbstractShellView(const char *title, AbstractShellView *parent, AbstractShellFrame *frame) : AbstractShellView(400, 300, title, parent, frame) { } AbstractShellView::AbstractShellView(int width, int height, const char *title, AbstractShellView *parent, AbstractShellFrame *frame) : AbstractEventHandler() { p_.reset(new Private); p_->size_.width = width; p_->size_.height = height; p_->parent_ = parent; if (title) p_->title_ = title; if (nullptr == p_->parent_) { p_->shell_surface_ = ToplevelShellSurface::Create(this, Theme::shadow_margin()); ShellSurface::Get(p_->shell_surface_)->configure().Set(this, &AbstractShellView::OnXdgSurfaceConfigure); ToplevelShellSurface *toplevel = ToplevelShellSurface::Get(p_->shell_surface_); toplevel->configure().Set(this, &AbstractShellView::OnXdgToplevelConfigure); toplevel->close().Set(this, &AbstractShellView::OnXdgToplevelClose); toplevel->SetTitle(title); } else { // TODO: create popup shell surface } int x = 0, y = 0; // The input region x += Theme::shadow_margin().left - AbstractShellFrame::kResizingMargin.left; y += Theme::shadow_margin().top - AbstractShellFrame::kResizingMargin.top; width += AbstractShellFrame::kResizingMargin.lr(); height += AbstractShellFrame::kResizingMargin.tb(); wayland::Region input_region; input_region.Setup(Display::Registry().wl_compositor()); input_region.Add(x, y, width, height); p_->shell_surface_->SetInputRegion(input_region); SetShellFrame(frame); } AbstractShellView::~AbstractShellView() { SetClientView(nullptr); if (p_->shell_frame_) { p_->shell_frame_->shell_view_ = nullptr; Theme::DestroyWindowFrame(p_->shell_frame_); } delete p_->shell_surface_; } void AbstractShellView::SetTitle(const char *title) { p_->title_ = title; if (nullptr == p_->parent_) { ToplevelShellSurface::Get(p_->shell_surface_)->SetTitle(title); } } void AbstractShellView::SetAppId(const char *app_id) { p_->app_id_ = app_id; if (nullptr == p_->parent_) { ToplevelShellSurface::Get(p_->shell_surface_)->SetAppId(app_id); } } void AbstractShellView::SetShellFrame(AbstractShellFrame *shell_frame) { if (shell_frame == p_->shell_frame_) return; if (p_->shell_frame_) { if (p_->shell_frame_->title_view_) DetachView(p_->shell_frame_->title_view_); p_->shell_frame_->shell_view_ = nullptr; delete p_->shell_frame_; p_->shell_frame_ = nullptr; } p_->shell_frame_ = shell_frame; // TODO: check if there's original window using the window frame if (p_->shell_frame_) { p_->shell_frame_->shell_view_ = this; if (p_->shell_frame_->title_view_) { AttachView(p_->shell_frame_->title_view_); } p_->shell_frame_->window_action().Connect(this, &AbstractShellView::OnWindowAction); p_->shell_frame_->OnSetup(); // shell_frame_->OnResize(size_.width, size_.height); } OnUpdate(nullptr); } void AbstractShellView::SetClientView(AbstractView *view) { if (p_->client_view_ == view) return; if (p_->client_view_) { DetachView(p_->client_view_); p_->client_view_->destroyed().DisconnectAll(this, &AbstractShellView::OnContentViewDestroyed); delete p_->client_view_; } p_->client_view_ = view; if (p_->client_view_) { AttachView(p_->client_view_); p_->client_view_->destroyed().Connect(this, &AbstractShellView::OnContentViewDestroyed); SetContentViewGeometry(); } } void AbstractShellView::Show() { if (!IsShown()) { p_->shell_surface_->Commit(); } } void AbstractShellView::Close(SLOT) { if (Surface::GetShellSurfaceCount() == 1) { Application::Exit(); } // TODO: use a close task if there's more than 1 windows in an application // windows will be deleted when application exits, uncomment this line // sometimes cause segfault when close button is clicked: // delete this; } void AbstractShellView::Maximize(SLOT) { } void AbstractShellView::Minimize(SLOT) { } const std::string &AbstractShellView::GetTitle() const { return p_->title_; } Size AbstractShellView::GetMinimalSize() const { if (IsFrameless()) return Size(100, 100); int w = 160, h = 120; // Rect client = GetClientGeometry(); // switch (window_frame_->title_bar_position()) { // case AbstractWindowFrame::kTitleBarLeft: // case AbstractWindowFrame::kTitleBarRight: { // w = window_frame_->title_bar_size() + window_frame_->border(); // w += 120; // break; // } // case AbstractWindowFrame::kTitleBarBottom: // case AbstractWindowFrame::kTitleBarTop: // default: { // h = window_frame_->title_bar_size() + window_frame_->border(); // h += 90; // break; // } // } return Size(w, h); } Size AbstractShellView::GetPreferredSize() const { return Size(640, 480); } Size AbstractShellView::GetMaximalSize() const { return Size(65536, 65536); } int AbstractShellView::GetMouseLocation(const MouseEvent *event) const { if (nullptr == p_->shell_frame_) { return kInterior; } return p_->shell_frame_->GetMouseLocation(event); } bool AbstractShellView::IsFullscreen() const { return 0 != (p_->flags_ & kFlagMaskFullscreen); } bool AbstractShellView::IsMaximized() const { return 0 != (p_->flags_ & kFlagMaskMaximized); } bool AbstractShellView::IsMinimized() const { return 0 != (p_->flags_ & kFlagMaskMinimized); } bool AbstractShellView::IsFocused() const { return 0 != (p_->flags_ & kFlagMaskFocused); } bool AbstractShellView::IsResizing() const { return 0 != (p_->flags_ & kFlagMaskResizing); } bool AbstractShellView::IsFrameless() const { return nullptr == p_->shell_frame_; } bool AbstractShellView::IsShown() const { return 0 != (p_->flags_ & kFlagMaskShown); } const Size &AbstractShellView::GetSize() const { return p_->size_; } AbstractView *AbstractShellView::GetClientView() const { return p_->client_view_; } void AbstractShellView::AttachView(AbstractView *view) { if (view->p_->shell == this) { DBG_ASSERT(nullptr == view->p_->parent); return; } if (view->p_->parent) { DBG_ASSERT(nullptr == view->p_->shell); view->p_->parent->RemoveChild(view); DBG_ASSERT(nullptr == view->p_->parent); DBG_ASSERT(nullptr == view->p_->previous); DBG_ASSERT(nullptr == view->p_->next); } else if (view->p_->shell) { DBG_ASSERT(nullptr == view->p_->parent); view->p_->shell->DetachView(view); } view->p_->shell = this; OnViewAttached(view); if (view->p_->shell == this) view->OnAttachedToShellView(); } void AbstractShellView::DetachView(AbstractView *view) { if (view->p_->shell != this) return; DBG_ASSERT(nullptr == view->p_->parent); view->p_->shell = nullptr; OnViewDetached(view); if (view->p_->shell != this) view->OnDetachedFromShellView(this); } Rect AbstractShellView::GetClientGeometry() const { if (IsFrameless()) { DBG_ASSERT(nullptr == p_->shell_frame_); return Rect::FromXYWH(0.f, 0.f, p_->size_.width, p_->size_.height); } return p_->shell_frame_->GetContentGeometry(); } void AbstractShellView::OnMouseEnter(MouseEvent *event) { if (nullptr == p_->shell_frame_) { return; } switch (p_->shell_frame_->GetMouseLocation(event)) { case kResizeTop: { event->SetCursor(Display::cursor(kCursorTop)); break; } case kResizeBottom: { event->SetCursor(Display::cursor(kCursorBottom)); break; } case kResizeLeft: { event->SetCursor(Display::cursor(kCursorLeft)); break; } case kResizeRight: { event->SetCursor(Display::cursor(kCursorRight)); break; } case kResizeTopLeft: { event->SetCursor(Display::cursor(kCursorTopLeft)); break; } case kResizeTopRight: { event->SetCursor(Display::cursor(kCursorTopRight)); break; } case kResizeBottomLeft: { event->SetCursor(Display::cursor(kCursorBottomLeft)); break; } case kResizeBottomRight: { event->SetCursor(Display::cursor(kCursorBottomRight)); break; } case kTitleBar: { AbstractView *title_bar = p_->shell_frame_->title_view_; if (nullptr == title_bar) break; MouseTaskIterator it(this); while (it.next()) ++it; // move to tail DBG_ASSERT(nullptr == it.next()); if (title_bar->Contain((int) event->window_x(), (int) event->window_y())) { title_bar->OnMouseEnter(event); if (event->IsAccepted()) { it.PushBack(title_bar); ++it; DispatchMouseEnterEvent(title_bar, event, it.mouse_task()); } } break; } case kClientArea: { if (nullptr == p_->client_view_) break; MouseTaskIterator it(this); while (it.next()) ++it; // move to tail DBG_ASSERT(nullptr == it.next()); if (p_->client_view_->Contain((int) event->window_x(), (int) event->window_y())) { p_->client_view_->OnMouseEnter(event); if (event->IsAccepted()) { it.PushBack(p_->client_view_); ++it; DispatchMouseEnterEvent(p_->client_view_, event, it.mouse_task()); } } break; } default: { event->SetCursor(Display::cursor(kCursorLeftPtr)); break; } } } void AbstractShellView::OnMouseLeave(MouseEvent *event) { MouseTaskIterator it(this); bool need_call = true; EventTask *task = nullptr; ++it; while (it) { task = it.mouse_task(); ++it; task->Unlink(); if (need_call) { static_cast<AbstractView *>(task->event_handler)->OnMouseLeave(event); if (event->IsRejected()) need_call = false; } } } void AbstractShellView::OnMouseMove(MouseEvent *event) { if (nullptr == p_->shell_frame_) { return; } switch (p_->shell_frame_->GetMouseLocation(event)) { case kResizeTop: { event->SetCursor(Display::cursor(kCursorTop)); break; } case kResizeBottom: { event->SetCursor(Display::cursor(kCursorBottom)); break; } case kResizeLeft: { event->SetCursor(Display::cursor(kCursorLeft)); break; } case kResizeRight: { event->SetCursor(Display::cursor(kCursorRight)); break; } case kResizeTopLeft: { event->SetCursor(Display::cursor(kCursorTopLeft)); break; } case kResizeTopRight: { event->SetCursor(Display::cursor(kCursorTopRight)); break; } case kResizeBottomLeft: { event->SetCursor(Display::cursor(kCursorBottomLeft)); break; } case kResizeBottomRight: { event->SetCursor(Display::cursor(kCursorBottomRight)); break; } case kTitleBar: { event->SetCursor(Display::cursor(kCursorLeftPtr)); AbstractView *title_view = p_->shell_frame_->title_view_; if (nullptr == title_view) break; MouseTaskIterator it(this); if (nullptr == it.next()) { DBG_ASSERT(it.mouse_task()->event_handler == this); DBG_ASSERT(nullptr == it.previous()); if (title_view->Contain((int) event->window_x(), (int) event->window_y())) { title_view->OnMouseEnter(event); if (event->IsAccepted()) { it.PushBack(title_view); ++it; DispatchMouseEnterEvent(title_view, event, it.mouse_task()); } else if (event->IsIgnored()) { DispatchMouseEnterEvent(title_view, event, it.mouse_task()); } } } else { while (it.next()) ++it; // move to tail AbstractView *view = nullptr; EventTask *tail = nullptr; while (it.previous()) { tail = it.mouse_task(); view = static_cast<AbstractView *>(tail->event_handler); if (view->Contain((int) event->window_x(), (int) event->window_y())) { break; } --it; tail->Unlink(); static_cast<AbstractView *>(tail->event_handler)->OnMouseLeave(event); // TODO: if need to check the response if (nullptr == it.previous()) break; } DispatchMouseEnterEvent(view, event, tail); } break; } case kClientArea: { event->SetCursor(Display::cursor(kCursorLeftPtr)); if (nullptr == p_->client_view_) break; MouseTaskIterator it(this); if (nullptr == it.next()) { DBG_ASSERT(it.mouse_task()->event_handler == this); DBG_ASSERT(nullptr == it.previous()); if (p_->client_view_->Contain((int) event->window_x(), (int) event->window_y())) { p_->client_view_->OnMouseEnter(event); if (event->IsAccepted()) { it.PushBack(p_->client_view_); ++it; DispatchMouseEnterEvent(p_->client_view_, event, it.mouse_task()); } else if (event->IsIgnored()) { DispatchMouseEnterEvent(p_->client_view_, event, it.mouse_task()); } } } else { while (it.next()) ++it; // move to tail AbstractView *view = nullptr; EventTask *tail = nullptr; while (it.previous()) { tail = it.mouse_task(); view = static_cast<AbstractView *>(tail->event_handler); if (view->Contain((int) event->window_x(), (int) event->window_y())) { break; } --it; tail->Unlink(); static_cast<AbstractView *>(tail->event_handler)->OnMouseLeave(event); // TODO: if need to check the response if (nullptr == it.previous()) break; } DispatchMouseEnterEvent(view, event, tail); } break; } default: { event->SetCursor(Display::cursor(kCursorLeftPtr)); break; } } // Now dispatch mouse move event: // task = static_cast<ViewTask *>(handler->p_->mouse_motion_task.next()); // p_->mouse_event->response_ = InputEvent::kUnknown; // while (task) { // task->view->OnMouseMove(p_->mouse_event); // if (!p_->mouse_event->IsAccepted()) break; // task = static_cast<ViewTask *>(task->next()); // } } void AbstractShellView::OnMouseButton(MouseEvent *event) { if ((event->button() == kMouseButtonLeft) && (event->state() == kMouseButtonPressed)) { if (p_->shell_frame_) { int location = p_->shell_frame_->GetMouseLocation(event); if (location == kTitleBar && (nullptr == MouseTaskIterator(this).next())) { MoveWithMouse(event); event->Ignore(); return; } if (location < kResizeMask) { ResizeWithMouse(event, (uint32_t) location); event->Ignore(); return; } } } MouseTaskIterator it(this); ++it; AbstractView *view = nullptr; while (it) { view = static_cast<AbstractView *>(it.mouse_task()->event_handler); view->OnMouseButton(event); if (event->IsRejected()) break; ++it; } } void AbstractShellView::OnKeyboardKey(KeyEvent *event) { event->Accept(); } void AbstractShellView::OnUpdate(AbstractView *view) { // override in sub class } Surface *AbstractShellView::GetSurface(const AbstractView * /* view */) const { return p_->shell_surface_; } void AbstractShellView::OnDraw(const Context *context) { if (p_->shell_frame_) p_->shell_frame_->OnDraw(context); } void AbstractShellView::OnMaximized(bool maximized) { } void AbstractShellView::OnFullscreen(bool) { } void AbstractShellView::OnFocus(bool focus) { if (p_->shell_frame_) { OnUpdate(nullptr); } } void AbstractShellView::OnViewAttached(AbstractView *view) { } void AbstractShellView::OnViewDetached(AbstractView *view) { } void AbstractShellView::MoveWithMouse(MouseEvent *event) const { ToplevelShellSurface::Get(p_->shell_surface_)->Move(event->GetSeat(), event->serial()); } void AbstractShellView::ResizeWithMouse(MouseEvent *event, uint32_t edges) const { ToplevelShellSurface::Get(p_->shell_surface_)->Resize(event->GetSeat(), event->serial(), edges); } AbstractShellFrame *AbstractShellView::shell_frame() const { return p_->shell_frame_; } Surface *AbstractShellView::shell_surface() const { return p_->shell_surface_; } void AbstractShellView::ResizeShellFrame(AbstractShellFrame *window_frame, int width, int height) { window_frame->OnResize(width, height); } void AbstractShellView::DrawShellFrame(AbstractShellFrame *window_frame, const Context *context) { window_frame->OnDraw(context); } void AbstractShellView::UpdateAll(AbstractView *view) { view->UpdateAll(); } void AbstractShellView::OnXdgSurfaceConfigure(uint32_t serial) { ShellSurface *shell_surface = ShellSurface::Get(p_->shell_surface_); shell_surface->AckConfigure(serial); if (!IsShown()) { Bit::Set<int>(p_->flags_, kFlagMaskShown); shell_surface->ResizeWindow(p_->size_.width, p_->size_.height); OnShown(); } } void AbstractShellView::OnXdgToplevelConfigure(int width, int height, int states) { using wayland::XdgToplevel; bool maximized = ((states & XdgToplevel::kStateMaskMaximized) != 0); bool fullscreen = ((states & XdgToplevel::kStateMaskFullscreen) != 0); bool resizing = ((states & XdgToplevel::kStateMaskResizing) != 0); bool focus = ((states & XdgToplevel::kStateMaskActivated) != 0); bool do_resize = true; if (width > 0 && height > 0) { Size min = this->GetMinimalSize(); Size max = this->GetMaximalSize(); DBG_ASSERT(min.width < max.width && min.height < max.height); width = clamp(width, min.width, max.width); height = clamp(height, min.height, max.height); if (width == p_->size_.width && height == p_->size_.height) do_resize = false; } else { // Initialize width = p_->size_.width; height = p_->size_.height; } if (do_resize) { ShellSurface::Get(p_->shell_surface_)->ResizeWindow(width, height); p_->size_.width = width; p_->size_.height = height; OnSizeChanged(width, height); // Resize frame first, then the content view if (p_->shell_frame_) { p_->shell_frame_->OnResize(width, height); } if (p_->client_view_) { SetContentViewGeometry(); } } if (focus != IsFocused()) { Bit::Inverse<int>(p_->flags_, kFlagMaskFocused); OnFocus(focus); } if (maximized != IsMaximized()) { Bit::Inverse<int>(p_->flags_, kFlagMaskMaximized); OnMaximized(maximized); } if (fullscreen != IsFullscreen()) { Bit::Inverse<int>(p_->flags_, kFlagMaskFullscreen); OnFullscreen(fullscreen); } if (resizing != IsResizing()) { Bit::Inverse<int>(p_->flags_, kFlagMaskResizing); } } void AbstractShellView::OnXdgToplevelClose() { Close(); } void AbstractShellView::OnWindowAction(int action, SLOT slot) { ToplevelShellSurface *toplevel = ToplevelShellSurface::Get(p_->shell_surface_); switch (action) { case kActionClose: { Close(slot); break; } case kActionMaximize: { if (IsMaximized()) { toplevel->UnsetMaximized(); } else { toplevel->SetMaximized(); } break; } case kActionMinimize: { Bit::Set<int>(p_->flags_, kFlagMaskMinimized); toplevel->SetMinimized(); DBG_ASSERT(IsMinimized()); break; } case kActionMenu: { fprintf(stderr, "menu\n"); break; } default: break; } } void AbstractShellView::OnContentViewDestroyed(AbstractView *view, SLOT slot) { DBG_ASSERT(view == p_->client_view_); p_->client_view_ = nullptr; } void AbstractShellView::SetContentViewGeometry() { Rect rect = GetClientGeometry(); p_->client_view_->MoveTo((int) rect.x(), (int) rect.y()); p_->client_view_->Resize((int) rect.width(), (int) rect.height()); } void AbstractShellView::DispatchMouseEnterEvent(AbstractView *parent, MouseEvent *event, EventTask *tail) { DBG_ASSERT(nullptr == tail->next()); AbstractView::Iterator it(parent); for (it = it.first_child(); it; ++it) { if (it.view()->Contain((int) event->window_x(), (int) event->window_y())) { it.view()->OnMouseEnter(event); if (event->IsAccepted()) { tail->PushBack(MouseTaskIterator(it.view()).mouse_task()); tail = static_cast<EventTask *>(tail->next()); DispatchMouseEnterEvent(it.view(), event, tail); } else if (event->IsIgnored()) { DispatchMouseEnterEvent(it.view(), event, tail); } break; } } } }
#include "game.h" #include "ui_game.h" #include <ctime> Game::Game(QWidget *parent,bool type,player *p1,player *p2) : QWidget(parent), ui(new Ui::Game) { ui->setupUi(this); this->setWindowFlags(Qt::FramelessWindowHint); this->setFixedSize(520,330); QBrush *brush = new QBrush; QPalette *palette = new QPalette; brush->setTextureImage(QImage(":/textures/BackgroundGame.jpg")); palette->setBrush(QPalette::Window, *brush); this->setPalette(*palette); QObject::connect(this, SIGNAL(startGamestage1()),this, SLOT(gamestage1())); QObject::connect(this, SIGNAL(startGamestage2()),this, SLOT(gamestage2())); QObject::connect(this, SIGNAL(setdeactivated1(bool)),this, SLOT(deactivate1(bool))); QObject::connect(this, SIGNAL(setdeactivated2(bool)),this, SLOT(deactivate2(bool))); QObject::connect(this, SIGNAL(result()),this, SLOT(gameresult())); QObject::connect(this, SIGNAL(isbeterror(bool)),this, SLOT(beterror(bool))); gametype=type; ui->messageDisplay->clear(); ui->score_1->setText(QString::number(SCORE1)); ui->score_2->setText(QString::number(SCORE2)); PLAYER1=p1; PLAYER1->make_dice(0,ui->dice11); PLAYER1->make_dice(1,ui->dice12); PLAYER1->make_dice(2,ui->dice13); PLAYER1->make_dice(3,ui->dice14); PLAYER1->make_dice(4,ui->dice15); ui->player1name->setText(PLAYER1->get_name()); ui->bet1->setDisabled(true); ui->bet2->setDisabled(true); ui->confirm1->setDisabled(true); ui->confirm2->setDisabled(true); ui->surrender1->setDisabled(true); ui->surrender2->setDisabled(true); ui->apply->setDisabled(true); emit setdeactivated1(true); emit setdeactivated2(true); if(gametype) { PLAYER2=p2; ui->player2name->setText(PLAYER2->get_name()); PLAYER2->make_dice(0,ui->dice21); PLAYER2->make_dice(1,ui->dice22); PLAYER2->make_dice(2,ui->dice23); PLAYER2->make_dice(3,ui->dice24); PLAYER2->make_dice(4,ui->dice25); ui->botbet->hide(); ui->botstatus->hide(); ui->sign_botbet->hide(); } else { ui->botbet->show(); ui->sign_botbet->show(); ui->bet2->hide(); ui->confirm2->hide(); ui->surrender2->hide(); ui->player2name->setText(BOT->get_name()); ui->botstatus->clear(); BOT->make_dice(0,ui->dice21); BOT->make_dice(1,ui->dice22); BOT->make_dice(2,ui->dice23); BOT->make_dice(3,ui->dice24); BOT->make_dice(4,ui->dice25); } srand(time(0)); } Game::~Game() { delete ui; } int Game::betRange() { if(gametype) { if(PLAYER1->get_gold()<PLAYER2->get_gold()) { return PLAYER1->get_gold()*20/100; } else { return PLAYER2->get_gold()*20/100; } } else { if(PLAYER1->get_gold()<BOT->get_gold()) { return PLAYER1->get_gold()*20/100; } else { return BOT->get_gold()*20/100; } } } void Game::winnerbox(bool win1) { QString result; if(win1) { PLAYER1->edit_gold(BANK); result=PLAYER1->get_name()+" won! His gold now "+QString::number(PLAYER1->get_gold()); } else { if(gametype&&!win1) { PLAYER2->edit_gold(BANK); result=PLAYER2->get_name()+" won! His gold now "+QString::number(PLAYER2->get_gold()); } else { BOT->edit_gold(BANK); result=BOT->get_name()+" won! His gold now "+QString::number(BOT->get_gold()); } } QMessageBox::information(0, "Result", result); Game::close(); } void Game::shakealldices() { for(int i=0;i<5;i++) { int rad=rand()%6+1; PLAYER1->change_dice(rad,i); } if(gametype) { for(int i=0;i<5;i++) { int rad=rand()%6+1; PLAYER2->change_dice(rad,i); } } else { for(int i=0;i<5;i++) { int rad=rand()%6+1; BOT->change_dice(rad,i); } } } void Game::controlBet(bool enable,bool player) { if(enable) { if(player) { ui->bet1->setEnabled(true); ui->confirm1->setEnabled(true); } else { ui->bet2->setEnabled(true); ui->confirm2->setEnabled(true); } } else { if(player) { ui->bet1->setDisabled(true); ui->confirm1->setDisabled(true); } else { ui->bet2->setDisabled(true); ui->confirm2->setDisabled(true); } } } void Game::message(int type) { switch(type) { case 1: ui->messageDisplay->setText("Make bet from 1 to "+QString::number(betRange())); break; case 2: ui->messageDisplay->setText("Error, make bet from 1 to "+QString::number(betRange())); break; case 3: ui->messageDisplay->setText("Lesser bet, try again"); break; } } void Game::betConfirmation(bool player,int &rate1, int &rate2) { int gold=betRange(); if(player) { rate1=(ui->bet1->text()).toInt(); } else { rate1=(ui->bet2->text()).toInt(); } controlBet(false,player); if(rate1>gold || rate1<1) { emit isbeterror(player); message(2); } else { if(rate1!=rate2) { if(rate1<rate2) { message(3); emit isbeterror(player); if(!gametype || !firsttime) { message(3); } firsttime=false; } else { if(gametype) { controlBet(true,!player); } else { rate2=rate1; ui->botbet->setText(QString::number(rate2)); switch(gamestage) { case 1: emit gamestage1(); break; case 2: emit gamestage2(); break; } } } } else { switch(gamestage) { case 1: emit gamestage1(); break; case 2: emit gamestage2(); break; } } } } void Game::beterror(bool player) { controlBet(true,player); } //-------------------------------------- void Game::on_START_clicked() { ui->START->hide(); ui->bet1->clear(); ui->surrender1->setEnabled(true); firsttime=true; if(gametype) { ui->bet2->clear(); ui->surrender2->setEnabled(true); } else { ui->botbet->clear(); BET2=rand()%betRange()+1; ui->botstatus->clear(); ui->botbet->setText(QString::number(BET2)); } controlBet(true,true); message(1); ui->dice11->setText("?"); ui->dice12->setText("?"); ui->dice13->setText("?"); ui->dice14->setText("?"); ui->dice15->setText("?"); ui->dice21->setText("?"); ui->dice22->setText("?"); ui->dice23->setText("?"); ui->dice24->setText("?"); ui->dice25->setText("?"); } void Game::on_confirm1_clicked() { betConfirmation(true,BET1,BET2); } void Game::on_confirm2_clicked() { betConfirmation(false,BET2,BET1); } void Game::on_apply_clicked() { deactivate1(true); if(gametype) { deactivate2(true); } ui->apply->setDisabled(true); gamestage++; message(1); controlBet(true,true); if(gamestage==3) { emit result(); } else { if(!gametype) { BET2=BOT->make_bet(); ui->botbet->setText(QString::number(BET2)); } } } void Game::on_surrender1_clicked() { winnerbox(false); Game::close(); } void Game::on_surrender2_clicked() { winnerbox(true); Game::close(); } void Game::gamestage1() { BANK+=BET1+BET2; ui->bankDisplay->setText(QString::number(BANK)); PLAYER1->edit_gold(-BET1); ui->bet1->clear(); ui->bet2->clear(); if(gametype) { PLAYER2->edit_gold(-BET2); } else { BOT->edit_gold(-BET2); } BET1=0; BET2=0; shakealldices(); ui->apply->setEnabled(true); } void Game::gamestage2() { BANK+=BET1+BET2; PLAYER1->edit_gold(-BET1); if(gametype) { PLAYER2->edit_gold(-BET2); } else { BOT->edit_gold(-BET2); } BET1=0; BET2=0; setdeactivated1(false); if(gametype) { setdeactivated2(false); } if(!gametype) { QString status="Rethrowed: "; BOT->get_combination(); for(int i=0;i<5;i++) { if(BOT->if_havent_pair(i)) { int rad=rand()%6+1; BOT->change_dice(rad,i); status+=QString::number(i+1)+" "; } } ui->botstatus->setText(status); } ui->apply->setEnabled(true); } void Game::gameresult() { if(gametype) { if(PLAYER1->get_combination()>PLAYER2->get_combination()) { SCORE1++; ui->score_1->setText(QString::number(SCORE1)); } else { SCORE2++; ui->score_2->setText(QString::number(SCORE2)); } } else { if(PLAYER1->get_combination()>BOT->get_combination()) { SCORE1++; ui->score_1->setText(QString::number(SCORE1)); } else { SCORE2++; ui->score_2->setText(QString::number(SCORE2)); } } if(SCORE1>1) { winnerbox(true); } else { if(SCORE2>1) { winnerbox(false); } else { QMessageBox::information(0, "Chapter","Next round!"); } } gamestage=1; emit ui->START->clicked(); } void Game::deactivate1(bool disable) { ui->dice11->setDisabled(disable); ui->dice12->setDisabled(disable); ui->dice13->setDisabled(disable); ui->dice14->setDisabled(disable); ui->dice15->setDisabled(disable); } void Game::deactivate2(bool disable) { ui->dice21->setDisabled(disable); ui->dice22->setDisabled(disable); ui->dice23->setDisabled(disable); ui->dice24->setDisabled(disable); ui->dice25->setDisabled(disable); } void Game::on_dice11_clicked() { int rad=rand()%6+1; PLAYER1->change_dice(rad,0); ui->dice11->setDisabled(true); } void Game::on_dice12_clicked() { int rad=rand()%6+1; PLAYER1->change_dice(rad,1); ui->dice12->setDisabled(true); } void Game::on_dice13_clicked() { int rad=rand()%6+1; PLAYER1->change_dice(rad,2); ui->dice13->setDisabled(true); } void Game::on_dice14_clicked() { int rad=rand()%6+1; PLAYER1->change_dice(rad,3); ui->dice14->setDisabled(true); } void Game::on_dice15_clicked() { int rad=rand()%6+1; PLAYER1->change_dice(rad,4); ui->dice15->setDisabled(true); } void Game::on_dice21_clicked() { int rad=rand()%6+1; PLAYER2->change_dice(rad,0); ui->dice21->setDisabled(true); } void Game::on_dice22_clicked() { int rad=rand()%6+1; PLAYER2->change_dice(rad,1); ui->dice22->setDisabled(true); } void Game::on_dice23_clicked() { int rad=rand()%6+1; PLAYER2->change_dice(rad,2); ui->dice23->setDisabled(true); } void Game::on_dice24_clicked() { int rad=rand()%6+1; PLAYER2->change_dice(rad,3); ui->dice24->setDisabled(true); } void Game::on_dice25_clicked() { int rad=rand()%6+1; PLAYER2->change_dice(rad,4); ui->dice25->setDisabled(true); }
#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 int inf = 1e9 + 7; int f[110][110],a[110]; int main() { int n; while (scanf("%d",&n) != EOF) { for (int i = 1;i <= n; i++) scanf("%d",&a[i]); for (int len = 0;len < n; len++) for (int i = 2;i + len < n; i++) { int j = i + len; f[i][j] = inf; for (int k = i;k <= j; k++) f[i][j] = min(f[i][j],f[i][k-1]+f[k+1][j]+a[k]*a[i-1]*a[j+1]); } printf("%d\n",f[2][n-1]); } return 0; }
#include <iostream> using namespace std; typedef long long ll; int main() { // your code goes here ll t,d,D,P,Q; cin>>t; while (t--) { cin>>D>>d>>P>>Q; ll ans=P*D; ll total=D/d; ans += Q*(total*(total-1)/2)*d; ans += Q*(total)*(D%d); cout<<ans<<"\n"; } return 0; }
#include "stdafx.h" #include "BackGround.h" #include "Common\Camera.h" BackGround::BackGround() { } BackGround::~BackGround() { } void BackGround::Init() { // 쉐이더 초기화 // 에러값 확인이 어려우므로 // 쉐이더 로딩시 에러가 나면 에러 내용을 받아올 꺼 LPD3DXBUFFER pError = NULL; // 쉐이더 옵션 지정 DWORD shaderFlag = 0; // 지정되어야만 디버깅시 쉐이더 확인이 가능함 #ifdef _DEBUG shaderFlag |= D3DXSHADER_DEBUG; #endif // _DEBUG // 쉐이더 내부에서 쓸 수 있는 게 #define, #include D3DXCreateEffectFromFile( D2D::GetDevice(), // 디바이스 //L"./Shader/BaseColor.fx", // 셰이더 파일 L"./Shader/ColorTexture.fx", NULL, // 셰이더 컴파일시 추가 #define NULL, // 셰이더 컴파일시 추가 #include // include를 쓸 수 있는거 // 외부에서 내부로 추가 할 수도 있음 // 잘쓰진 않음 shaderFlag, // 셰이더 옵션 NULL, // 셰이더 매개변수를 공유할 메모리풀 &pEffect, &pError ); if (pError != NULL) { string lastError = (char*)pError->GetBufferPointer(); MessageBox(NULL, String::StringToWString(lastError).c_str(), L"Shader Error", MB_OK); SAFE_RELEASE(pError); } vertice[0].position = Vector2(-WINSIZE_X / 2, WINSIZE_Y / 2); vertice[1].position = Vector2(-WINSIZE_X / 2, -WINSIZE_Y / 2); vertice[2].position = Vector2(WINSIZE_X / 2, -WINSIZE_Y / 2); vertice[3].position = Vector2(WINSIZE_X / 2, WINSIZE_Y / 2); vertice[0].color = 0xffffffff; vertice[1].color = 0xffffffff; vertice[2].color = 0xffffffff; vertice[3].color = 0xffffffff; vertice[0].uv = Vector2(0.0f, 1.0f); // left bottom vertice[1].uv = Vector2(0.0f, 0.0f); // left top vertice[2].uv = Vector2(1.0f, 0.0f); // right top vertice[3].uv = Vector2(1.0f, 1.0f); // right bottom stride = sizeof(Vertex); FVF = D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1; HRESULT hr = D2D::GetDevice()->CreateVertexBuffer( stride * 4, D3DUSAGE_WRITEONLY, // dynamic 쓰게 되면 FVF, D3DPOOL_MANAGED, // 이걸로 해줘야함 default 해주면 data 남아있지 않음 &vb, NULL ); assert(SUCCEEDED(hr)); Vertex * pVertex = NULL; hr = vb->Lock(0, 0, (void**)&pVertex, 0); assert(SUCCEEDED(hr)); memcpy(pVertex, vertice, stride * 4); hr = vb->Unlock(); assert(SUCCEEDED(hr)); DWORD indices[] = { 0,1,2, 0,2,3, }; hr = D2D::GetDevice()->CreateIndexBuffer( sizeof(DWORD) * 6, D3DUSAGE_WRITEONLY, D3DFMT_INDEX32, D3DPOOL_DEFAULT, &ib, NULL ); assert(SUCCEEDED(hr)); void* pIndex; hr = ib->Lock(0, 0, &pIndex, 0); assert(SUCCEEDED(hr)); memcpy(pIndex, indices, sizeof(DWORD) * 6); hr = ib->Unlock(); assert(SUCCEEDED(hr)); transform = new Transform; transform->UpdateTransform(); //hr = D3DXCreateTextureFromFile( // D2D::GetDevice(), // L"Textures/bg.png", // &pTex //); //assert(SUCCEEDED(hr)); speed = 2.5f; } void BackGround::Release() { SAFE_RELEASE(ib); SAFE_RELEASE(vb); SAFE_RELEASE(pEffect); //SAFE_RELEASE(pTex); SAFE_DELETE(transform); } void BackGround::Update() { Vertex * pVertex = NULL; HRESULT hr = vb->Lock(0, 0, (void**)&pVertex, 0); assert(SUCCEEDED(hr)); memcpy(pVertex, vertice, stride * 4); hr = vb->Unlock(); assert(SUCCEEDED(hr)); this->transform->DefaultControl2(); transform->MovePositionSelf(Vector2(-speed, 0)); if(transform->GetWorldPosition().x < -WINSIZE_X){ transform->MovePositionSelf(Vector2(WINSIZE_X * 2, 0)); } } void BackGround::Render() { //D2D::GetDevice()->SetStreamSource(0, vb, 0, stride); //D2D::GetDevice()->SetIndices(ib); //D2D::GetDevice()->SetTransform(D3DTS_WORLD, &transform->GetFinalMatrix().ToDXMatrix()); //D2D::GetDevice()->SetFVF(FVF); //D2D::GetDevice()->SetTexture(0, pTex); // //D2D::GetDevice()->DrawIndexedPrimitive( // D3DPT_TRIANGLELIST, // 0, 0, 4, 0, 2); this->pEffect->SetMatrix("matWorld", &transform->GetFinalMatrix().ToDXMatrix()); this->pEffect->SetMatrix("matView", &camera->GetViewMatrix().ToDXMatrix()); this->pEffect->SetMatrix("matProjection", &camera->GetProjection().ToDXMatrix()); this->pEffect->SetTexture("tex", pTex); this->pEffect->SetTechnique("MyShader"); // 셰이더로 렌더 UINT iPassNum = 0; this->pEffect->Begin( &iPassNum, // pEffect에 있는 패스 수를 받아온다. 0 // 플래그 ); { for (UINT i = 0; i < iPassNum; i++) { this->pEffect->BeginPass(i); { D2D::GetDevice()->SetStreamSource(0, vb, 0, stride); D2D::GetDevice()->SetIndices(ib); D2D::GetDevice()->SetFVF(FVF); // 만약에 텍스처 렌더하는 방식이면 pEffect->setTexture로 //D2D::GetDevice()->SetTexture(0, pTex); D2D::GetDevice()->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0, 4, 0, 2); } this->pEffect->EndPass(); } } this->pEffect->End(); }
#include "vehicle.h" #include <iostream> #include <iostream> #include <math.h> #include "cost.h" // mile per seconds to mile per hour const double MS_TO_MPH = 2.23694; // mile per hour to mile per second const double MPH_TO_MS = 0.44704; Vehicle::Vehicle(int lane, double target_speed){ ref_speed = target_speed; ref_lane = lane; } void Vehicle::update_data(double ax, double ay, double as, double ad, double ayaw, double aspeed, int lane, double target_speed, double delta){ //update raw data this->x = ax; this->y = ay; this->s = as; this->d = ad; this->yaw = ayaw; this->speed = aspeed; this->delta_time = delta; this->ref_speed = target_speed; this->ref_lane = lane; //clean data reset_data(); } void Vehicle::reset_data(){ //clean data //reset trajectory this->trajectory.lane_start = ref_lane; this->trajectory.lane_end = ref_lane; this->trajectory.target_speed = ref_speed; //reset update this->reference.ref_v = ref_speed; this->reference.lane = ref_lane; this->reference.target_v = 49.50; this->collider.collision = false; this->collider.distance = 10000; this->collider.closest_approach = 10000; this->collider.target_speed = 0; } void Vehicle::choose_next_state(vector<vector<double>> sensor){ State current_state = state; vector<State> possible_states; //select reachable states possible_states.push_back(KL); if (state == KL) { if(ref_lane != 0){ // check if a vehicle is ready to change lane to left. if(d<(2+4*(ref_lane)+2) && d>(2+4*(ref_lane)-2)){ possible_states.push_back(PLCL); } } // check if a vehicle is ready to change lane to left. if(ref_lane != 2){ if(d<(2+4*(ref_lane)+2) && d>(2+4*(ref_lane)-2)){ possible_states.push_back(PLCR); } } } else if(state == PLCL){ // prepare lane change left possible_states.push_back(LCL); possible_states.push_back(PLCL); } else if(state == PLCR){ // prepare lane change right possible_states.push_back(LCR); possible_states.push_back(PLCR); } // compute cost of all possible states State min_state = KL; double min_cost = 10000000; for (int i = 0; i < possible_states.size(); i++) { State possible_state = possible_states[i]; // update states to simulate the given possible state reset_data(); realize_next_state(possible_state, sensor); CostFunction cost = CostFunction(this, sensor); double value = cost.compute(); if (value < min_cost) { min_state = possible_state; min_cost = value; } } // update state with the state with the minimum cost state = min_state; reset_data(); realize_next_state(state, sensor); // update reference velocity CostFunction cost = CostFunction(this, sensor); float v = cost.compute(); std::cout << "Next state is " << state << " with cost " << min_cost << endl; // modify reference velocity if (!collider.collision && ref_speed < reference.target_v && ref_speed < 49.5) { reference.ref_v += 0.224; } else if (ref_speed > reference.target_v && ref_speed > 0) { reference.ref_v -= 0.224; } } void Vehicle::realize_next_state(State next_state, vector<vector<double>> sensor_fusion) { state = next_state; switch(state) { case KL: { trajectory.lane_start = ref_lane; trajectory.lane_end = ref_lane; reference.lane = ref_lane; break; } case PLCL: { trajectory.lane_start = ref_lane; trajectory.lane_end = ref_lane - 1; reference.lane = ref_lane; break; } case LCL: { trajectory.lane_start = ref_lane; trajectory.lane_end = ref_lane - 1; reference.lane = ref_lane - 1; break; } case PLCR: { trajectory.lane_start = ref_lane; trajectory.lane_end = ref_lane + 1; reference.lane = ref_lane; break; } case LCR: { trajectory.lane_start = ref_lane; trajectory.lane_end = ref_lane + 1; reference.lane = ref_lane + 1; break; } default: std::cout << "ERROR: invalid state" << std::endl; } double target_speed_front = 0; double target_distance_front = 10000; double target_speed_lane_front = 0; double target_distance_lane_front = 10000; double target_speed_lane_back = 0; double target_distance_lane_back = -10000; // compute collision on start and end lane for (int i = 0; i < sensor_fusion.size(); i++) { float car_d = sensor_fusion[i][6]; // safety check for speed of car which is in the same lane if((car_d < (2+4*(trajectory.lane_start)+2) && car_d > (2+4*(trajectory.lane_start)-2))){ double vx = sensor_fusion[i][3]; double vy = sensor_fusion[i][4]; double check_speed = sqrt(vx*vx + vy*vy); double check_car_s = sensor_fusion[i][5]; check_car_s += ((double) delta_time*check_speed); // check s values greater than mine and s gap double dist_to_collision = (check_car_s - s); if((check_car_s >= s) && (dist_to_collision < 30)){ if(target_distance_front > dist_to_collision){ target_speed_front = check_speed*MS_TO_MPH-2; target_distance_front = dist_to_collision; } } } // check if a target car is in the end lane. if (car_d < (2+4*(trajectory.lane_end)+2) && car_d > (2+4*(trajectory.lane_end)-2)) { double vx = sensor_fusion[i][3]; double vy = sensor_fusion[i][4]; double check_speed = sqrt(vx*vx + vy*vy); double check_car_s = sensor_fusion[i][5]; check_car_s += ((double) delta_time*check_speed); //check s values greater than mine and s gap double dist_to_collision = (check_car_s - s); if((trajectory.lane_end != trajectory.lane_start && (abs(dist_to_collision) < 30)) || ((check_car_s >= s) && (dist_to_collision < 30))){ if(collider.distance > abs(dist_to_collision)){ collider.distance = abs(dist_to_collision); collider.collision = true; collider.closest_approach = abs(dist_to_collision); collider.target_speed = check_speed*MS_TO_MPH; if(abs(dist_to_collision) > 30){ //change target speed if(check_car_s >= s){ //car in front reference.target_v = check_speed*MS_TO_MPH-2; if(target_distance_lane_front > dist_to_collision){ target_speed_lane_front = check_speed*MS_TO_MPH; target_distance_lane_front = dist_to_collision; } } else { //car in back reference.target_v = check_speed*MS_TO_MPH+2; if(target_distance_lane_back < dist_to_collision){ target_speed_lane_back = check_speed*MS_TO_MPH; target_distance_lane_back = dist_to_collision; } } } } } else if(!collider.collision && collider.closest_approach > dist_to_collision){ collider.closest_approach = dist_to_collision; collider.target_speed = check_speed*MS_TO_MPH; } } } // check if speed is safe if (state == PLCL || state == PLCR) { // When there is another car behind the car and on the next lane, // the reference velocity will be that's speed. if (target_speed_lane_back != 0 && reference.target_v < target_speed_lane_back) { reference.target_v = target_speed_lane_back; } // When there is another car in front of the car and on the next lane, // the reference velocity will be that's speed. if (target_speed_lane_front != 0 && reference.target_v > target_speed_lane_front) { reference.target_v = target_speed_lane_front; } } // When there is another car in front of the car, the car have to following the speed of one. if (target_speed_front != 0 && reference.target_v > target_speed_front) { reference.target_v = target_speed_front-2; } }
#include <LiquidCrystal.h> #include "DHT.h" #include "Wire.h" #include "Adafruit_BMP085.h" #define DHTPIN 2 #define DHTTYPE DHT11 LiquidCrystal lcd(8, 7, 6, 5, 4, 3); DHT dht(DHTPIN, DHTTYPE); Adafruit_BMP085 basincsensoru; byte santigratderece[8] = { 0b11000, 0b11000, 0b00110, 0b01001, 0b01000, 0b01000, 0b01001, 0b00110 }; void setup() { lcd.begin(16, 2); basincsensoru.begin(); dht.begin(); Serial.begin(9600); lcd.createChar(0,santigratderece); } void loop() { float h = dht.readHumidity(); float t1 = dht.readTemperature(); float t2 = basincsensoru.readTemperature(); float basinc = basincsensoru.readPressure(); float t_ort = (t1+t2)/2; float hic = dht.computeHeatIndex(t_ort, h, false); if (isnan(h) || isnan(t_ort) ) { Serial.println(F("Sensorde Hata Okundu!")); return; } int menu_kontrol=analogRead(A0); if((menu_kontrol>=0)&&(menu_kontrol<=214)){ lcd.setCursor(0,0); nem_yaz(h); } else if((menu_kontrol>=270)&&(menu_kontrol<=484)){ lcd.setCursor(0,0); sicaklik_yaz(t_ort); } else if((menu_kontrol>=538)&& (menu_kontrol<=752)){ lcd.setCursor(0,0); basinc_yaz(basinc); } else if((menu_kontrol>=807)&& (menu_kontrol<=1023)){ lcd.setCursor(0,0); hissedilen(hic); } else{ bos(); } Serial.print(h); Serial.print(" "); Serial.print(t_ort); Serial.print(" "); Serial.print(basinc/1000); Serial.print(" "); Serial.println(hic); } void nem_yaz(float a){ lcd.print(" NEM"); lcd.setCursor(5,1); lcd.print(a); lcd.print("% "); } void sicaklik_yaz(float t_ort){ lcd.print(" SICAKLIK"); lcd.setCursor(5,1); lcd.print(t_ort); lcd.write(byte(0)); } void basinc_yaz(float basinc){ lcd.print(" BASINC"); lcd.setCursor(3,1); lcd.print(basinc); lcd.print("Pa "); } void hissedilen(float hic){ lcd.print(" HISSEDILEN"); lcd.setCursor(5,1); lcd.print(hic); lcd.write(byte(0)); } void bos(){ lcd.setCursor(0,0); lcd.clear(); }
#include "transform.hpp" Matrix3d Euler2A(const double& phi, const double& theta, const double& psi) { MyAngles vehicleAngles(phi, theta, psi); // I Matrix3d result; result(0, 0) = cos(theta) * cos(psi); result(0, 1) = cos(psi) * sin(theta) * sin(phi) - cos(phi) * sin(psi); result(0, 2) = cos(phi) * cos(psi) * sin(theta) + sin(phi) * sin(psi); result(1, 0) = cos(theta) * sin(psi); result(1, 1) = cos(psi) * cos(phi) + sin(theta) * sin(phi) * sin(psi); result(1, 2) = cos(phi) * sin(theta) * sin(psi) - cos(psi) * sin(phi); result(2, 0) = -sin(theta); result(2, 1) = cos(theta) * sin(phi); result(2, 2) = cos(theta) * cos(phi); // II Matrix3d R_phi; Matrix3d R_theta; Matrix3d R_psi; R_phi << 1, 0, 0, 0, cos(phi), -sin(phi), 0, sin(phi), cos(phi); R_theta << cos(theta), 0, sin(theta), 0, 1, 0, -sin(theta), 0, cos(theta); R_psi << cos(psi), -sin(psi), 0, sin(psi), cos(psi), 0, 0, 0, 1; result = R_psi * R_theta * R_phi; // III result = AngleAxisd(psi, Vector3d::UnitZ()) * AngleAxisd(theta, Vector3d::UnitY()) * AngleAxisd(phi, Vector3d::UnitX()); return result; } bool isOrthogonal(const Matrix3d& A) { return (A.transpose() * A).isIdentity(1000) ? true : false; } bool isDetOne(const Matrix3d& A) { return (std::abs(A.determinant() - 1) <= std::abs(A.determinant() + 1) * 8 * std::numeric_limits<double>::epsilon()) ? true : false; } std::pair<RowVector3d, double> AxisAngle(const Matrix3d& A) { if(!isOrthogonal(A)) { std::cout << "Not an orthogonal matrix!" << std::endl; exit(1); } if(!isDetOne(A)) { std::cout << "Determinant of a matrix is not 1!" << std::endl; exit(1); } // finding eigenvector of matrix A for eigenvalue 1 Matrix3d Ap = A - Matrix3d::Identity(); Vector3d u = Ap.row(0); Vector3d v = Ap.row(1); Vector3d p = u.cross(v); if(p == Vector3d::Zero()) { Vector3d w = Ap.row(2); p = u.cross(w); } p.normalize(); // we are choosing arbitrary vector normal to p - in our case vector u u.normalize(); Vector3d up = A * u; up.normalize(); double phi = acos(u.dot(up)); double tripleProd = u.dot(up.cross(p)); if(tripleProd < 0) { p = -p; } return std::make_pair(p, phi); } Matrix3d Rodrigez(const Vector3d& p, const double& phi) { Matrix3d ppt = p * p.transpose(); Matrix3d mat = Matrix3d::Identity() - ppt; Matrix3d px; px << 0, -p(2), p(1), p(2), 0, -p(0), -p(1), p(0), 0; return ppt + cos(phi)*mat + sin(phi)*px; } std::tuple<double, double, double> A2Euler(const Matrix3d& A) { if(!isOrthogonal(A)) { std::cout << "Not an orthogonal matrix!" << std::endl; exit(1); } if(!isDetOne(A)) { std::cout << "Determinant of a matrix is not 1!" << std::endl; exit(1); } double psi, theta, phi; if(A(2, 0) < 1) { if(A(2,0) > -1) { psi = atan2(A(1, 0), A(0, 0)); theta = asin(-A(2, 0)); phi = atan2(A(2, 1), A(2, 2)); } else { psi = atan2(-A(0, 1), A(1, 1)); theta = M_PI_2; phi = 0; } } else { psi = atan2(-A(0, 1), A(1, 1)); theta = -M_PI_2; phi = 0; } return std::make_tuple(phi, theta, psi); } Quaterniond AxisAngle2Q(const Vector3d& p, const double& phi) { double w = cos(phi/2); Vector3d r = p.normalized(); double x = sin(phi/2)*r(0); double y = sin(phi/2)*r(1); double z = sin(phi/2)*r(2); return Quaterniond(w, x, y, z); } std::pair<RowVector3d, double> Q2AxisAngle(const Quaterniond& q) { Quaterniond r = q.normalized(); double phi = 2*acos(r.w()); double w = r.w(); Vector3d p; if(w == 1 || w == -1) { p(0) = 1; p(1) = 0; p(2) = 0; } else { p = q.vec().normalized(); } return std::make_pair(p, phi); } Quaterniond slerp(Quaterniond& q1, Quaterniond& q2, const double tm, const double t) { double dot = q1.dot(q2); if(dot < 0.0) { q1.coeffs() = -q1.coeffs(); dot = -dot; } if(dot > 0.95) { double f = 1 - t / tm; double s = t / tm; return Quaterniond(f * q1.coeffs() + s * q2.coeffs()); } double theta0 = acos(dot); double theta = theta0 * t / tm; double sinTheta0 = sin(theta0); double sinTheta = sin(theta); double f = sin(theta0 - theta) / sinTheta0; double s = sinTheta / sinTheta0; return Quaterniond(f * q1.coeffs() + s * q2.coeffs()); }
//=========================================================================== //! @file filter_manager.cpp //! @brief 描画に使用するフィルター管理 //=========================================================================== //--------------------------------------------------------------------------- //! 初期化 //--------------------------------------------------------------------------- bool FilterManager::initialize() { return true; } //--------------------------------------------------------------------------- //! 描画 //--------------------------------------------------------------------------- void FilterManager::begin() { for(auto& filter : appUsefilters_) { if(!filter.expired()) { filter.lock()->begin(); } } } //--------------------------------------------------------------------------- //! 解放 //--------------------------------------------------------------------------- void FilterManager::cleanup() { appFilterCleanup(); for(auto& filter : filters_) { filter->finalize(); filter.reset(); } filters_.clear(); } //--------------------------------------------------------------------------- //! アプリ側で使用しているフィルタ開放 //--------------------------------------------------------------------------- void FilterManager::appFilterCleanup() { for(auto& filter : appUsefilters_) { if(!filter.expired()) { filter.lock()->finalize(); } filter.reset(); } appUsefilters_.clear(); } //--------------------------------------------------------------------------- //! 使用するフィルタ設定 //--------------------------------------------------------------------------- void FilterManager::setFilter(FilterType filterType) { // 保存用フィルタに追加 addFilter(filterType); if(appUsefilters_.size() == 0) { for(auto& filter : filters_) { if(filter->getFilterType() == filterType) { // ToneMappingなら一番後ろに配置(この後に処理するかもだから、また直すかも) if(filterType == FilterType::ToneMapping) { appUsefilters_.emplace_back(filter); isHDR_ = false; } else { // フィルター追加 appUsefilters_.emplace_front(filter); } return; } } } // 同じフィルタがすでに追加されてたら終了 for(auto& appFilter : appUsefilters_) { if(appFilter.lock()->getFilterType() == filterType) { return; } } for(auto& filter : filters_) { if(filter->getFilterType() == filterType) { if(filterType == FilterType::ToneMapping) { appUsefilters_.emplace_back(filter); isHDR_ = false; break; } else { appUsefilters_.emplace_front(filter); break; } } } } //--------------------------------------------------------------------------- //! 使用するフィルタ解除 //--------------------------------------------------------------------------- void FilterManager::removeFilter(FilterType filterType) { auto itr = appUsefilters_.begin(); while(itr != appUsefilters_.end()) { if(itr->lock()->getFilterType() == filterType) { if(itr->lock()->getFilterType() == FilterType::ToneMapping) { isHDR_ = true; } itr = appUsefilters_.erase(itr); } else { ++itr; } } } //--------------------------------------------------------------------------- //! フィルタ追加 //--------------------------------------------------------------------------- void FilterManager::addFilter(FilterType filterType) { // naos for(auto& filter : filters_) { if(filter->getFilterType() == filterType) { return; } } std::unique_ptr<Filter> filter; switch(filterType) { case FilterType::GaussianBlur: filter.reset(createGaussianBlur()); break; case FilterType::ToneMapping: filter.reset(createToneMapping()); break; default: break; } if(!filter) { return; } // if(filterType == FilterType::ToneMapping) { filters_.emplace_back(filter.release()); } else { filters_.emplace_back(filter.release()); } } //--------------------------------------------------------------------------- //! ガウシアンぼかしフィルタ作成 //--------------------------------------------------------------------------- Filter* FilterManager::createGaussianBlur() { std::unique_ptr<Filter> filter(new FilterGlare()); if(!filter->initialize()) { return false; } return filter.release(); } //--------------------------------------------------------------------------- //! トーンマッピングフィルタ作成 //--------------------------------------------------------------------------- Filter* FilterManager::createToneMapping() { std::unique_ptr<Filter> filter(new ToneMapping()); if(!filter->initialize()) { return false; } return filter.release(); } //--------------------------------------------------------------------------- //! HDR中かどうか //--------------------------------------------------------------------------- bool FilterManager::isHDR() const { return isHDR_; }
#include <gtest/gtest.h> #include <solvers/sqp.hpp> using namespace sqp; namespace sqp_test { struct SimpleNLP : public NonLinearProblem<double> { using Vector = NonLinearProblem<double>::Vector; using Matrix = NonLinearProblem<double>::Matrix; const Scalar infinity = std::numeric_limits<Scalar>::infinity(); Eigen::Vector2d SOLUTION = {1, 1}; SimpleNLP() { num_var = 2; num_constr = 3; } void objective(const Vector& x, Scalar& obj) { obj = -x.sum(); } void objective_linearized(const Vector& x, Vector& grad, Scalar& obj) { grad.resize(num_var); objective(x, obj); grad << -1, -1; } void constraint(const Vector& x, Vector& c, Vector& l, Vector& u) { // 1 <= x0^2 + x1^2 <= 2 // 0 <= x0 // 0 <= x1 c << x.squaredNorm(), x; l << 1, 0, 0; u << 2, infinity, infinity; } void constraint_linearized(const Vector& x, Matrix& Jc, Vector& c, Vector& l, Vector& u) { Jc.resize(3, 2); constraint(x, c, l, u); Jc << 2 * x.transpose(), Matrix::Identity(2, 2); } }; TEST(SQPTestCase, TestSimpleNLP) { SimpleNLP problem; SQP<double> solver; Eigen::Vector2d x; // feasible initial point Eigen::Vector2d x0 = {1.2, 0.1}; Eigen::Vector3d y0 = Eigen::VectorXd::Zero(3); solver.settings().max_iter = 100; solver.settings().second_order_correction = true; solver.solve(problem, x0, y0); x = solver.primal_solution(); solver.info().print(); std::cout << "primal solution " << solver.primal_solution().transpose() << std::endl; std::cout << "dual solution " << solver.dual_solution().transpose() << std::endl; EXPECT_TRUE(x.isApprox(problem.SOLUTION, 1e-2)); EXPECT_LT(solver.info().iter, solver.settings().max_iter); } TEST(SQPTestCase, SimpleNLP_InfeasibleStart) { SimpleNLP problem; SQP<double> solver; Eigen::Vector2d x; // infeasible initial point Eigen::Vector2d x0 = {2, -1}; Eigen::Vector3d y0 = {1, 1, 1}; solver.settings().max_iter = 100; solver.settings().second_order_correction = true; solver.solve(problem, x0, y0); x = solver.primal_solution(); solver.info().print(); std::cout << "primal solution " << solver.primal_solution().transpose() << std::endl; std::cout << "dual solution " << solver.dual_solution().transpose() << std::endl; EXPECT_TRUE(x.isApprox(problem.SOLUTION, 1e-2)); EXPECT_LT(solver.info().iter, solver.settings().max_iter); } struct SimpleQP : public NonLinearProblem<double> { using Vector = NonLinearProblem<double>::Vector; using Matrix = NonLinearProblem<double>::Matrix; Eigen::Matrix2d P; Eigen::Vector2d q = {1, 1}; Eigen::Vector2d SOLUTION = {0.3, 0.7}; SimpleQP() { P << 4, 1, 1, 2; num_var = 2; num_constr = 3; } void objective(const Vector& x, Scalar& obj) final { obj = 0.5 * x.dot(P * x) + q.dot(x); } void objective_linearized(const Vector& x, Vector& grad, Scalar& obj) final { objective(x, obj); grad = P * x + q; } void constraint(const Vector& x, Vector& c, Vector& l, Vector& u) final { // x1 + x2 = 1 c << x.sum(), x; l << 1, 0, 0; u << 1, 0.7, 0.7; } void constraint_linearized(const Vector& x, Matrix& Jc, Vector& c, Vector& l, Vector& u) final { constraint(x, c, l, u); Jc << 1, 1, Matrix::Identity(2, 2); } }; TEST(SQPTestCase, TestSimpleQP) { SimpleQP problem; SQP<double> solver; Eigen::VectorXd x0 = Eigen::Vector2d(0,0); Eigen::VectorXd y0 = Eigen::Vector3d(0,0,0); solver.settings().second_order_correction = true; solver.solve(problem, x0, y0); solver.info().print(); std::cout << "primal solution " << solver.primal_solution().transpose() << std::endl; std::cout << "dual solution " << solver.dual_solution().transpose() << std::endl; EXPECT_TRUE(solver.primal_solution().isApprox(problem.SOLUTION, 1e-2)); EXPECT_LT(solver.info().iter, solver.settings().max_iter); } } // namespace sqp_test
#include "treeface/scene/SceneNodeManager.h" #include "treeface/scene/Geometry.h" #include "treeface/scene/GeometryManager.h" #include "treeface/scene/SceneGraphMaterial.h" #include "treeface/scene/SceneNode.h" #include "treeface/scene/VisualObject.h" #include "treeface/gl/VertexArray.h" #include "treeface/misc/Errors.h" #include "treeface/misc/PropertyValidator.h" #include "treeface/scene/guts/SceneNode_guts.h" #include "treeface/scene/MaterialManager.h" #include "treeface/base/PackageManager.h" #include <treecore/CriticalSection.h> #include <treecore/DynamicObject.h> #include <treecore/HashMap.h> #include <treecore/JSON.h> #include <treecore/MemoryBlock.h> #include <treecore/NamedValueSet.h> #include <treecore/RefCountSingleton.h> #include <treecore/Result.h> #include <treecore/Variant.h> using namespace treecore; namespace treeface { struct SceneNodeManager::Impl { RefCountHolder<GeometryManager> geo_mgr; RefCountHolder<MaterialManager> mat_mgr; HashMap<Identifier, RefCountHolder<SceneNode> > nodes; }; SceneNodeManager::SceneNodeManager( GeometryManager* geo_mgr, MaterialManager* mat_mgr ) : m_impl( new Impl() ) { m_impl->geo_mgr = geo_mgr; m_impl->mat_mgr = mat_mgr; } SceneNodeManager::~SceneNodeManager() { if (m_impl) delete m_impl; } SceneNode* SceneNodeManager::add_nodes( const treecore::var& data ) { SceneNode* root_node = new SceneNode(); build_node( data, root_node ); return root_node; } SceneNode* SceneNodeManager::get_node( const treecore::Identifier& name ) { if ( m_impl->nodes.contains( name ) ) return m_impl->nodes[name].get(); // build node object var data_root = PackageManager::getInstance()->get_item_json( name ); if (!data_root) throw ConfigParseError( "no package item named \"" + name.toString() + "\"" ); return add_nodes( data_root ); } #define KEY_VISUAL_MAT "material" #define KEY_VISUAL_GEO "geometry" class VisualItemPropertyValidator: public PropertyValidator, public treecore::RefCountSingleton<VisualItemPropertyValidator> { public: VisualItemPropertyValidator() { add_item( KEY_VISUAL_MAT, PropertyValidator::ITEM_SCALAR, true ); add_item( KEY_VISUAL_GEO, PropertyValidator::ITEM_SCALAR, true ); } virtual ~VisualItemPropertyValidator() {} }; VisualObject * SceneNodeManager::create_visual_object( const var &data ) { // validate node if ( !data.isObject() ) throw ConfigParseError( "visual item node is not KV" ); const NamedValueSet& data_kv = data.getDynamicObject()->getProperties(); { Result re = VisualItemPropertyValidator::getInstance()->validate( data_kv ); if (!re) throw ConfigParseError( re.getErrorMessage() ); } // get material and geometry Material* mat = m_impl->mat_mgr->get_material( data_kv[KEY_VISUAL_MAT].toString() ); if (mat == nullptr) throw ConfigParseError( "no material named \"" + data_kv[KEY_VISUAL_MAT].toString() + "\"" ); SceneGraphMaterial* scene_mat = dynamic_cast<SceneGraphMaterial*>(mat); if (!scene_mat) throw ConfigParseError( "material \"" + data_kv[KEY_VISUAL_MAT].toString() + "\" is not a scene graph material" ); Geometry* geom = m_impl->geo_mgr->get_geometry( data_kv[KEY_VISUAL_GEO].toString() ); if (geom == nullptr) throw ConfigParseError( "no geometry named \"" + data_kv[KEY_VISUAL_GEO].toString() + "\"" ); // do build return new VisualObject( geom, scene_mat ); } #define KEY_ID "id" #define KEY_TRANS "transform" #define KEY_CHILD "children" #define KEY_VISUAL "visual" class SceneNodePropertyValidator: public PropertyValidator, public RefCountSingleton<SceneNodePropertyValidator> { public: SceneNodePropertyValidator() { add_item( KEY_ID, PropertyValidator::ITEM_SCALAR, false ); add_item( KEY_TRANS, PropertyValidator::ITEM_ARRAY, false ); add_item( KEY_CHILD, PropertyValidator::ITEM_ARRAY, false ); add_item( KEY_VISUAL, PropertyValidator::ITEM_ARRAY, false ); } virtual ~SceneNodePropertyValidator() {} }; void SceneNodeManager::build_node( const treecore::var& data, SceneNode* node ) { if ( !data.isObject() ) throw ConfigParseError( "SceneNode data root is not KV" ); const NamedValueSet& data_kv = data.getDynamicObject()->getProperties(); { Result re = SceneNodePropertyValidator::getInstance()->validate( data_kv ); if (!re) throw ConfigParseError( "node data validation failed:\n" + re.getErrorMessage() ); } // // node transform // if ( data_kv.contains( KEY_TRANS ) ) { const Array<var>* trans_array = data_kv[KEY_TRANS].getArray(); if (trans_array->size() != 16) throw ConfigParseError( "transform is not an array of 16 numbers: " + String( trans_array->size() ) ); Mat4f mat( static_cast<float>( (*trans_array)[0] ), float( (*trans_array)[1] ), float( (*trans_array)[2] ), float( (*trans_array)[3] ), static_cast<float>( (*trans_array)[4] ), float( (*trans_array)[5] ), float( (*trans_array)[6] ), float( (*trans_array)[7] ), static_cast<float>( (*trans_array)[8] ), float( (*trans_array)[9] ), float( (*trans_array)[10] ), float( (*trans_array)[11] ), static_cast<float>( (*trans_array)[12] ), float( (*trans_array)[13] ), float( (*trans_array)[14] ), float( (*trans_array)[15] ) ); node->m_impl->trans = mat; node->m_impl->trans_dirty = true; } // // visual items // if ( data_kv.contains( KEY_VISUAL ) ) { const Array<var>* visual_array = data_kv[KEY_VISUAL].getArray(); for (int i = 0; i < visual_array->size(); i++) { // TODO: may be not a VisualObject VisualObject* item = create_visual_object( (*visual_array)[i] ); node->add_item( item ); } } // // child nodes // if ( data_kv.contains( KEY_CHILD ) ) { const Array<var>* child_array = data_kv[KEY_CHILD].getArray(); for (int i = 0; i < child_array->size(); i++) { SceneNode* child = new SceneNode(); build_node( (*child_array)[i], child ); child->m_impl->parent = node; child->m_impl->global_dirty = true; node->m_impl->child_nodes.add( child ); } } // // if has ID, store it // if ( data_kv.contains( KEY_ID ) ) m_impl->nodes.set( data_kv[KEY_ID].toString(), node ); } } // namespace treeface
#include "graph.h" #include <iostream> Vertex::Vertex(int n) { id = n; } bool Vertex::add_neighbor(Vertex& v, int distance) { // check if the neighbor is already in the list for (std::vector<Neighbor>::iterator neighbor_itr = adj_list.begin(); neighbor_itr != adj_list.end(); ++neighbor_itr) { if(*neighbor_itr == v) return false; } Neighbor *n = new Neighbor( v, distance); adj_list.push_back(*n); return true; } void Vertex::print_neighbors() { std::cout << "\tNeighbors: "; for (std::vector<Neighbor>::iterator neighbor_itr = adj_list.begin(); neighbor_itr != adj_list.end(); ++neighbor_itr) { std::cout << "(" << neighbor_itr->get_id() << "," << neighbor_itr->get_distance() << "), "; } std::cout << std::endl; } Neighbor::Neighbor(Vertex& v, int d) { destination = v.get_id(); distance = d; } Graph::Graph() { n_vertices = 0; n_edges = 0; } bool Graph::add_vertex(Vertex& v) { //do not allow insertion of repeated Vertices for (std::vector<Vertex>::iterator vecItr = vertices_list.begin(); vecItr != vertices_list.end(); ++vecItr) { if(*vecItr == v) return false; } vertices_list.push_back(v); n_vertices++; return true; } bool Graph::add_edge(Vertex& src, Vertex& dest, int distance) { std::vector<Vertex>::iterator vec_itr; //find the source Vertex in the list for (vec_itr = vertices_list.begin(); vec_itr != vertices_list.end(); ++vec_itr) { if(*vec_itr == src) break; } // found the source Vertex. Now add the the destination // to the list of adjacent vertices if(!(*vec_itr).add_neighbor(dest, distance)) return false; n_edges++; return true; } void Graph::print_vertices() { for (std::vector<Vertex>::iterator vec_itr = vertices_list.begin(); vec_itr != vertices_list.end(); ++vec_itr) { std::cout << "Vertex: " << vec_itr->get_id() << std::endl; vec_itr->print_neighbors(); } }
/*********************************************************\ * 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 "Direct3D9Renderer/State/SamplerState.h" #include "Direct3D9Renderer/d3d9.h" #include "Direct3D9Renderer/Mapping.h" #include "Direct3D9Renderer/Direct3D9Renderer.h" #include <Renderer/ILog.h> #include <Renderer/IAssert.h> #include <Renderer/IAllocator.h> //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace Direct3D9Renderer { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] SamplerState::SamplerState(Direct3D9Renderer& direct3D9Renderer, const Renderer::SamplerState& samplerState) : ISamplerState(direct3D9Renderer), mDirect3D9MagFilterMode(Mapping::getDirect3D9MagFilterMode(direct3D9Renderer.getContext(), samplerState.filter)), mDirect3D9MinFilterMode(Mapping::getDirect3D9MinFilterMode(direct3D9Renderer.getContext(), samplerState.filter)), mDirect3D9MipFilterMode((0.0f == samplerState.maxLOD) ? D3DTEXF_NONE : Mapping::getDirect3D9MipFilterMode(direct3D9Renderer.getContext(), samplerState.filter)), // In case "Renderer::SamplerState::maxLOD" is zero, disable mipmapping in order to ensure a correct behaviour when using Direct3D 9, float equal check is valid in here mDirect3D9AddressModeU(Mapping::getDirect3D9TextureAddressMode(samplerState.addressU)), mDirect3D9AddressModeV(Mapping::getDirect3D9TextureAddressMode(samplerState.addressV)), mDirect3D9AddressModeW(Mapping::getDirect3D9TextureAddressMode(samplerState.addressW)), mDirect3D9MipLODBias(*(reinterpret_cast<const DWORD*>(&samplerState.mipLODBias))), // Direct3D 9 type is float, but has to be handed over by using DWORD mDirect3D9MaxAnisotropy(samplerState.maxAnisotropy), mDirect3DBorderColor(0), // Set below mDirect3DMaxMipLevel((samplerState.minLOD > 0.0f) ? static_cast<unsigned long>(samplerState.minLOD) : 0) // Direct3D 9 type is unsigned long, lookout the Direct3D 9 name is twisted and implies "Renderer::SamplerState::maxLOD" but it's really "Renderer::SamplerState::minLOD" { // Sanity check RENDERER_ASSERT(direct3D9Renderer.getContext(), samplerState.maxAnisotropy <= direct3D9Renderer.getCapabilities().maximumAnisotropy, "Maximum Direct3D 9 anisotropy value violated") { // Renderer::SamplerState::borderColor[4] // For Direct3D 9, the clear color must be between [0..1] float normalizedColor[4] = { samplerState.borderColor[0], samplerState.borderColor[1], samplerState.borderColor[2], samplerState.borderColor[3] } ; for (int i = 0; i < 4; ++i) { if (normalizedColor[i] < 0.0f) { normalizedColor[i] = 0.0f; } if (normalizedColor[i] > 1.0f) { normalizedColor[i] = 1.0f; } } #ifdef RENDERER_DEBUG if (normalizedColor[0] != samplerState.borderColor[0] || normalizedColor[1] != samplerState.borderColor[1] || normalizedColor[2] != samplerState.borderColor[2] || normalizedColor[3] != samplerState.borderColor[3]) { RENDERER_LOG(direct3D9Renderer.getContext(), CRITICAL, "The given border color was clamped to [0, 1] because Direct3D 9 does not support values outside this range") } #endif mDirect3DBorderColor = D3DCOLOR_COLORVALUE(normalizedColor[0], normalizedColor[1], normalizedColor[2], normalizedColor[3]); } } SamplerState::~SamplerState() { // Nothing here } void SamplerState::setDirect3D9SamplerStates(uint32_t sampler, IDirect3DDevice9& direct3DDevice9) const { // "IDirect3DDevice9::SetSamplerState()"-documentation: "D3DSAMPLERSTATETYPE Enumerated Type" at MSDN http://msdn.microsoft.com/en-us/library/windows/desktop/bb172602%28v=vs.85%29.aspx // Renderer::SamplerState::filter direct3DDevice9.SetSamplerState(sampler, D3DSAMP_MAGFILTER, mDirect3D9MagFilterMode); direct3DDevice9.SetSamplerState(sampler, D3DSAMP_MINFILTER, mDirect3D9MinFilterMode); direct3DDevice9.SetSamplerState(sampler, D3DSAMP_MIPFILTER, mDirect3D9MipFilterMode); // Renderer::SamplerState::addressU direct3DDevice9.SetSamplerState(sampler, D3DSAMP_ADDRESSU, mDirect3D9AddressModeU); // Renderer::SamplerState::addressV direct3DDevice9.SetSamplerState(sampler, D3DSAMP_ADDRESSV, mDirect3D9AddressModeV); // Renderer::SamplerState::addressW direct3DDevice9.SetSamplerState(sampler, D3DSAMP_ADDRESSW, mDirect3D9AddressModeW); // Renderer::SamplerState::mipLODBias direct3DDevice9.SetSamplerState(sampler, D3DSAMP_MIPMAPLODBIAS, mDirect3D9MipLODBias); // Renderer::SamplerState::maxAnisotropy direct3DDevice9.SetSamplerState(sampler, D3DSAMP_MAXANISOTROPY, mDirect3D9MaxAnisotropy); // Renderer::SamplerState::comparisonFunc // -> Not available in Direct3D 9 // Renderer::SamplerState::borderColor[4] direct3DDevice9.SetSamplerState(sampler, D3DSAMP_BORDERCOLOR, mDirect3DBorderColor); // Renderer::SamplerState::minLOD direct3DDevice9.SetSamplerState(sampler, D3DSAMP_MAXMIPLEVEL, mDirect3DMaxMipLevel); // Renderer::SamplerState::maxLOD // -> Not available in Direct3D 9 } //[-------------------------------------------------------] //[ Public virtual Renderer::IResource methods ] //[-------------------------------------------------------] void SamplerState::setDebugName(const char*) { // There's no Direct3D 9 resource we could assign a debug name to } //[-------------------------------------------------------] //[ Protected virtual Renderer::RefCount methods ] //[-------------------------------------------------------] void SamplerState::selfDestruct() { RENDERER_DELETE(getRenderer().getContext(), SamplerState, this); } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // Direct3D9Renderer
#pragma once #include <vector> #include <deque> #include <set> #include <utility> #include "Cluster.h" #include "OriginPoint.h" #include "ClusterPoint.h" using std::vector; using std::set; using std::deque; using std::pair; class Chameleon { private: int k; //knn近邻子图 double **adjMat; //邻接矩阵 vector<ClusterPoint> Points; deque<Cluster> clusters; //需要随机存取,也有大量删除,故使用deque double ECofClusters(const Cluster &a,const Cluster &b); double RIofClusters(const Cluster &a,const Cluster &b); double RCofClusters(const Cluster &a,const Cluster &b); double connectionOfClusters(const Cluster &a, const Cluster &b); //void setClusterSubGraph(Cluster & cluster); pair<int, int> findClusters2Merge(); void merge2Clusters(Cluster& c1, Cluster& c2); //void clusterPartition(); void clusterAlgorithm(); double maxWeightOf2Clusters(const Cluster&c1, const Cluster&c2); void printInfo(); public: double findMaxWeight(); deque<Cluster> getClusters(); Chameleon(deque<OriginPoint>, vector<int>,int k); deque<Cluster> chameleonCluster(); void knnDfs(bool**knnMat, int PointNum,bool*visited,int idx,vector<ClusterPoint>&); void knnGenerate(int k); static set<string> clusterAnalyse(Cluster c); Chameleon(); ~Chameleon(); };
#pragma once #include <iberbar/RHI/CommandContext.h> #include <iberbar/RHI/OpenGL/Headers.h> namespace iberbar { namespace RHI { class CShaderState; namespace OpenGL { class CDevice; class CVertexBuffer; class CIndexBuffer; class CShaderState; class CShaderVariableTable; class CTexture; class __iberbarRHIOpenGLApi__ CCommandContext : public ICommandContext { public: CCommandContext( CDevice* pDevice ); virtual ~CCommandContext(); public: virtual void SetVertexBuffer( IVertexBuffer* pVertexBuffer ) override; virtual void SetIndexBuffer( IIndexBuffer* pIndexBuffer ) override; virtual void SetShaderState( IShaderState* pShaderState ) override; virtual void SetShaderVariableTable( IShaderVariableTable* pShaderVariableTable ) override; virtual void DrawElements( UPrimitiveType nPrimitiveType, UIndexFormat nIndexFormat, uint32 nCount, uint32 nOffset ) override; private: void PrepareDraw(); void PrepareShaderVariables(); void SetUniform( UShaderVariableType nVarType, GLuint nLocation, const void* pData, uint32 nElementCount ); void CleanResources(); private: CDevice* m_pDevice; CVertexBuffer* m_pVertexBuffer; CIndexBuffer* m_pIndexBuffer; CShaderState* m_pShaderState; CShaderVariableTable* m_pShaderVariableTable; CTexture* m_pTextureSlot[ 8 ]; }; } } }
#ifndef TCP_HEADER_HPP #define TCP_HEADER_HPP 1 // // 0 1 2 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | Source Port | Destination Port | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | Sequence Number | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | Acknowledgment Number | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | Data | |U|A|P|R|S|F| | // | Offset| Reserved |R|C|S|S|Y|I| Window | // | | |G|K|H|T|N|N| | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | Checksum | Urgent Pointer | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | Options | Padding | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | data | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // // TCP Header Format From the Figure 3 of RFC 793 // #include <string> #include <iostream> #include <fstream> #include <algorithm> #include <cstdint> #include <netdb.h> #include <netinet/tcp.h> // For struct tcphdr /* struct tcphdr { u_int16_t source; u_int16_t dest; u_int32_t seq; u_int32_t ack_seq; u_int16_t res1:4; u_int16_t doff:4; u_int16_t fin:1; u_int16_t syn:1; u_int16_t rst:1; u_int16_t psh:1; u_int16_t ack:1; u_int16_t urg:1; u_int16_t res2:2; u_int16_t window; u_int16_t check; u_int16_t urg_ptr; }; */ #include "protocol_header.hpp" class tcp_header : public protocol_header { public: enum { DEFAULT_WINVAL = 4096 }; typedef struct tcphdr header_type; tcp_header() : rep_{0} {} explicit tcp_header(const header_type &tcph) : rep_(tcph) {} ~tcp_header() {} uint16_t source() const { return ntohs(rep_.source); } uint16_t dest() const { return ntohs(rep_.dest); } uint32_t seq() const { return ntohl(rep_.seq); } uint32_t ack_seq() const { return ntohl(rep_.ack_seq); } uint16_t res1() const { return rep_.res1; } uint16_t doff() const { return rep_.doff; } uint16_t fin() const { return rep_.fin; } uint16_t syn() const { return rep_.syn; } uint16_t rst() const { return rep_.rst; } uint16_t psh() const { return rep_.psh; } uint16_t ack() const { return rep_.ack; } uint16_t urg() const { return rep_.urg; } uint16_t res2() const { return rep_.res2; } uint16_t window() const { return ntohs(rep_.window); } uint16_t check() const { return ntohs(rep_.check); } uint16_t urg_ptr() const { return ntohs(rep_.urg_ptr); } void source(uint16_t source) { rep_.source = htons(source); } void dest(uint16_t dest) { rep_.dest = htons(dest); } void seq(uint32_t seq) { rep_.seq = htonl(seq); } void ack_seq(uint32_t ack_seq) { rep_.ack_seq = htonl(ack_seq); } void res1(uint16_t res1) { rep_.res1 = res1; } void doff(uint16_t doff) { rep_.doff = doff; } void fin(bool fin) { rep_.fin = (fin) ? 1 : 0; } void syn(bool syn) { rep_.syn = (syn) ? 1 : 0; } void rst(bool rst) { rep_.rst = (rst) ? 1 : 0; } void psh(bool psh) { rep_.psh = (psh) ? 1 : 0; } void ack(bool ack) { rep_.ack = (ack) ? 1 : 0; } void urg(uint16_t urg) { rep_.urg = urg; } void res2(uint16_t res2) { rep_.res2 = res2; } void window(uint16_t window) { rep_.window = htons(window); } void check(uint16_t check) { rep_.check = htons(check); } void urg_ptr(uint16_t urg_ptr) { rep_.urg_ptr = htons(urg_ptr); } int length() const { return sizeof(rep_); } char* get_header() { return reinterpret_cast<char*>(&rep_); } const struct tcphdr& get() const { return rep_; } void compute_checksum(uint32_t srcaddr, uint32_t destaddr) { check(0); tcp_checksum tc = {{0}, {0}}; tc.pseudo.ip_src = htonl(srcaddr); tc.pseudo.ip_dst = htonl(destaddr); tc.pseudo.zero = 0; tc.pseudo.protocol = IPPROTO_TCP; tc.pseudo.length = htons(sizeof(tcphdr)); tc.tcphdr = rep_; rep_.check = ((checksum(reinterpret_cast<uint16_t*>(&tc), sizeof(struct tcp_checksum)))); } void compute_checksum(const std::string &srcaddr, const std::string &destaddr) { compute_checksum( boost::asio::ip::address_v4::from_string(srcaddr).to_ulong(), boost::asio::ip::address_v4::from_string(destaddr).to_ulong() ); } private: // // +--------+--------+--------+--------+ // | Source Address | // +--------+--------+--------+--------+ // | Destination Address | // +--------+--------+--------+--------+ // | zero | PTCL | TCP Length | // +--------+--------+--------+--------+ // // TCP PSEUDO HEADER FROM RFC 793 // struct tcph_pseudo { // TCP pseudo header for header checksum uint32_t ip_src; // Source IP address uint32_t ip_dst; // Destination IP address uint8_t zero; // Always 0 uint8_t protocol; // IPPROTO_TCP uint16_t length; // tcp header length + payload length (Not contained pseudo header) }; struct tcp_checksum { struct tcph_pseudo pseudo; header_type tcphdr; }; header_type rep_; }; #endif // TCP_HEADER_HPP
/******************************************************************************** This file contains functions used for generating QRcodes ********************************************************************************/ /******************************************************************************** This routine will display a large QRcode on a 240x320 TFT display ********************************************************************************/ void displayQRcode(char *const QRcodeText) { clearMainScreen(); tft.setFont(&FreeSansBold18pt7b); tft.setTextColor(ArkRed); tft.setCursor(12, 30); tft.print("Scan to Ride"); tft.setFont(&FreeSans9pt7b); tft.setTextColor(WHITE); // Allocate memory to store the QR code. // memory size depends on version number uint8_t qrcodeData[qrcode_getBufferSize(QRcode_Version)]; qrcode_initText(&qrcode, qrcodeData, QRcode_Version, QRcode_ECC, QRcodeText); // Draw white background with a few pixels of guard around the code tft.fillRoundRect(27, 77 - 30, 186, 186, 4, WHITE); // position the QRcode. uint8_t x0 = 35; uint8_t y0 = 85 - 30; // display QRcode for (uint8_t y = 0; y < qrcode.size; y++) { for (uint8_t x = 0; x < qrcode.size; x++) { if (qrcode_getModule(&qrcode, x, y) == 0) { //change to == 1 to make QR code with black background // we started by setting all background pixels to white so we don't need to clear them again. // tft.drawPixel(x0 + 3 * x, y0 + 3 * y, TFT_WHITE); // tft.drawPixel(x0 + 3 * x + 1, y0 + 3 * y, TFT_WHITE); // tft.drawPixel(x0 + 3 * x + 2, y0 + 3 * y, TFT_WHITE); // tft.drawPixel(x0 + 3 * x, y0 + 3 * y + 1, TFT_WHITE); // tft.drawPixel(x0 + 3 * x + 1, y0 + 3 * y + 1, TFT_WHITE); // tft.drawPixel(x0 + 3 * x + 2, y0 + 3 * y + 1, TFT_WHITE); // tft.drawPixel(x0 + 3 * x, y0 + 3 * y + 2, TFT_WHITE); // tft.drawPixel(x0 + 3 * x + 1, y0 + 3 * y + 2, TFT_WHITE); // tft.drawPixel(x0 + 3 * x + 2, y0 + 3 * y + 2, TFT_WHITE); } else { tft.drawPixel(x0 + 3 * x, y0 + 3 * y, QRCODE_DARK_PIXEL_COLOR); tft.drawPixel(x0 + 3 * x + 1, y0 + 3 * y, QRCODE_DARK_PIXEL_COLOR); tft.drawPixel(x0 + 3 * x + 2, y0 + 3 * y, QRCODE_DARK_PIXEL_COLOR); tft.drawPixel(x0 + 3 * x, y0 + 3 * y + 1, QRCODE_DARK_PIXEL_COLOR); tft.drawPixel(x0 + 3 * x + 1, y0 + 3 * y + 1, QRCODE_DARK_PIXEL_COLOR); tft.drawPixel(x0 + 3 * x + 2, y0 + 3 * y + 1, QRCODE_DARK_PIXEL_COLOR); tft.drawPixel(x0 + 3 * x, y0 + 3 * y + 2, QRCODE_DARK_PIXEL_COLOR); tft.drawPixel(x0 + 3 * x + 1, y0 + 3 * y + 2, QRCODE_DARK_PIXEL_COLOR); tft.drawPixel(x0 + 3 * x + 2, y0 + 3 * y + 2, QRCODE_DARK_PIXEL_COLOR); } } } }
/** * @file test_fklib.cpp * * * @author Fan Kai(fk), Peking University * */ #include "fklib.h" #include <boost/timer.hpp> using namespace std; int main() { cout <<"Test Timer ..." <<endl; fk::Timer t; cout <<t.elapsed() <<endl; sleep(1); cout <<t.elapsed() <<endl; cout <<"Test normalize_path() ..." <<endl; cout <<fk::normalize_path("/joke///") <<endl; cout <<fk::normalize_path("abc/joke///") <<endl; cout <<fk::normalize_path("abc/joke///hh") <<endl; cout <<fk::normalize_path("/joke///joke") <<endl; cout <<fk::normalize_path("////joke") <<endl; cout <<fk::normalize_path("/") <<endl; cout <<fk::normalize_path("") <<endl; cout <<fk::normalize_path("abc") <<endl; cout <<"Test parent_dir() ..." <<endl; cout <<fk::parent_dir("/abc") <<endl; cout <<fk::parent_dir("//abc/edf") <<endl; cout <<fk::parent_dir("/abc/edf/") <<endl; cout <<fk::parent_dir("abc") <<endl; cout <<fk::parent_dir("/abc///") <<endl; cout <<fk::parent_dir("/abc/def") <<endl; cout <<fk::parent_dir("/abc/def/g") <<endl; }
// ========================================================================== // $Id: g_PtrAdapter.h 3389 2012-10-19 08:23:25Z jlang $ // Wrapper code to interface g_plane // ========================================================================== // (C)opyright: // // Jochen Lang // SITE, University of Ottawa // 800 King Edward Ave. // Ottawa, On., K1N 6N5 // Canada. // http://www.site.uottawa.ca // // Creator: Jochen Lang // Email: jlang@site.uottawa.ca // ========================================================================== // $Rev: 3389 $ // $LastChangedBy: jlang $ // $LastChangedDate: 2012-10-19 04:23:25 -0400 (Fri, 19 Oct 2012) $ // ========================================================================== #ifndef WRAPPER_G_PTRADAPTER_H #define WRAPPER_G_PTRADAPTER_H // Should use a namespace #include <set> #include "g_Element.h" #include "g_PEdge.h" template <class T> class g_PtrAdapter { T& d_container; public: g_PtrAdapter(T& _container) : d_container( _container ) {} void removeDuplicates() { // Put entries in a set and get them back std::set<typename T::value_type> tSet; for ( typename T::iterator cIt=d_container.begin(); cIt != d_container.end(); ++cIt ) { tSet.insert( *cIt ); } d_container.clear(); // delete old pointers for ( typename std::set<typename T::valuetype>::iterator uniqueIt = tSet.begin(); uniqueIt != tSet.end(); ++uniqueIt ) { d_container.insert( *uniqueIt ); } return; } }; // should these work by ID and if what do we need to do if two elements are the same template <> class g_PtrAdapter<g_Element*> { g_ElementContainer& d_container; public: g_PtrAdapter(g_ElementContainer& _container) : d_container( _container ) {}; void removeDuplicates() { // Put entries in a set and get them back std::set<g_Element*> eSet; for ( g_ElementContainer::iterator eIt=d_container.begin(); eIt != d_container.end(); ++eIt ) { eSet.insert( *eIt ); } d_container.clear(); // delete old pointers for ( std::set<g_Element*>::iterator uniqueIt = eSet.begin(); uniqueIt != eSet.end(); ++uniqueIt ) { d_container.insert( *uniqueIt ); } return; } }; template <> class g_PtrAdapter<g_PEdge*> { g_PEdgeContainer& d_container; public: g_PtrAdapter(g_PEdgeContainer& _container) : d_container( _container ) {}; void removeDuplicates() { // Put entries in a set and get them back std::set<g_PEdge*> eSet; for ( g_PEdgeContainer::iterator eIt=d_container.begin(); eIt != d_container.end(); ++eIt ) { eSet.insert( *eIt ); } d_container.clear(); // delete old pointers for ( std::set<g_PEdge*>::iterator uniqueIt = eSet.begin(); uniqueIt != eSet.end(); ++uniqueIt ) { d_container.insert( *uniqueIt ); } return; } }; template <> class g_PtrAdapter<g_Node*> { g_NodeContainer& d_container; public: g_PtrAdapter(g_NodeContainer& _container) : d_container( _container ) {}; void removeDuplicates() { // Put entries in a set and get them back std::set<g_Node*> nSet; for ( g_NodeContainer::iterator nIt=d_container.begin(); nIt != d_container.end(); ++nIt ) { nSet.insert( *nIt ); } d_container.clear(); // delete old pointers for ( std::set<g_Node*>::iterator uniqueIt = nSet.begin(); uniqueIt != nSet.end(); ++uniqueIt ) { d_container.insert( *uniqueIt ); } return; } }; #endif
#include <bits/stdc++.h> using namespace std; int main() { char str[10][4]={'.',',','?','"','a','b','c','%','d','e','f','%','g','h','i','%','j','k','l','%','m','n','o','%','p','q','r','s','t','u','v','%','w','x','y','z'}; int t,a,i,arr[1005]; scanf("%d",&t); while(t--){ // printf("%c\n",str[8][1]); scanf("%d",&a); for(i=0;i<2*a;i++){ scanf("%d",&arr[i]); } for(i=0;i<a;i++){ if(arr[i]==0) printf(" "); else printf("%c",str[arr[i]-1][arr[i+a]-1]); } printf("\n"); } return 0; }
#include<iostream> using namespace std; class index1{ protected: int count; public: index1(){ count =0; } void operator ++(){ count=count+200; } void operator ++(int){ count=count+100; } void display(){ cout<<endl<<count; } }; int main(){ index1 c; c++; c.display(); ++c; c.display(); cout<<endl; return 0; }
#pragma once class CSKTracker : public Tracker { public: CSKTracker(void){ setDefaults(); }; virtual void init(const cv::Rect& bbox, const cv::Mat& image); virtual cv::Rect track(const cv::Mat& image); virtual bool empty() const { return !_isinitialized; } private: // parameters float sigma; // used when computing gauss kernel float lambda; float factor; float padding; float rate; // tracking status cv::Rect bb2; cv::Mat x0; cv::Mat alphaf0; bool _isinitialized; // core functions cv::Mat train(const cv::Mat& x); cv::Rect predict(const cv::Mat& image, const cv::Rect& bb2); void update(const cv::Mat& x, const cv::Mat& alphaf); // augment functions void setDefaults(); cv::Mat getSubwindow(const cv::Mat& image, const cv::Rect& bb); cv::Mat gaussWindow(const cv::Size& sz); cv::Mat denseGaussKernel(float sigma, const cv::Mat& x); cv::Mat denseGaussKernel(float sigma, const cv::Mat& x, const cv::Mat& y); void circleShift(cv::Mat& m); cv::Mat complexDiv(const cv::Mat& xf, const cv::Mat& yf); inline cv::Rect twiceBB(const cv::Rect& bb); inline cv::Rect halfBB(const cv::Rect& bb2); inline float getSigma(const cv::Size& sz2); };
//------------------------------------------------------------------------------ /* This file is part of Beast: https://github.com/vinniefalco/Beast Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com> Portions of this file are from JUCE. Copyright (c) 2013 - Raw Material Software Ltd. Please visit http://www.juce.com Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== void MACAddress::findAllAddresses (Array<MACAddress>& result) { ifaddrs* addrs = nullptr; if (getifaddrs (&addrs) == 0) { for (const ifaddrs* cursor = addrs; cursor != nullptr; cursor = cursor->ifa_next) { sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr; if (sto->ss_family == AF_LINK) { const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr; #ifndef IFT_ETHER #define IFT_ETHER 6 #endif if (sadd->sdl_type == IFT_ETHER) result.addIfNotAlreadyThere (MACAddress (((const uint8*) sadd->sdl_data) + sadd->sdl_nlen)); } } freeifaddrs (addrs); } } bool Process::openEmailWithAttachments (const String& /* targetEmailAddress */, const String& /* emailSubject */, const String& /* bodyText */, const StringArray& /* filesToAttach */) { bassertfalse; // xxx todo return false; }
#pragma once #include "gmock/gmock.h" #include "gtest/gtest.h" #include "Biom.hh" #include "CppCommons.hh" #include "DBFactory.hh" #include "DBManager.hh" #include "Town.hh" #include "TownTemplate.hh" namespace dbfactory_test { using namespace CCC; using namespace HotaSim; static const char* DB_PATH = "resources/HotaSim.db"; class DBFactoryMock : public DBFactory { public: DBFactoryMock() : DBFactory() {} DBManager dbmgr; }; class DBFactoryTest : public ::testing::Test { protected: void SetUp() override { testing::internal::CaptureStdout(); try { dbfactory.dbmgr.loadDB(DB_PATH); } catch( const std::exception& ) {} testing::internal::GetCapturedStdout(); prepareTemplates(); } void prepareTemplates() { correctTmpl.id = 1; correctTmpl.name = "SomeTown"; correctTmpl.biom_id = 1; correctTmpl.dbmgr = &dbfactory.dbmgr; correctTmpl2.id = 1; correctTmpl2.name = "SomeTown2"; correctTmpl2.biom_id = 1; correctTmpl2.dbmgr = &dbfactory.dbmgr; wrongTmpl.id = 1; wrongTmpl.name = "SomeTown"; wrongTmpl.biom_id = 0; wrongTmpl.dbmgr = &dbfactory.dbmgr; } DBFactoryMock dbfactory; TownTemplate correctTmpl; TownTemplate correctTmpl2; TownTemplate wrongTmpl; }; // DBFactory.create TEST_F(DBFactoryTest, shouldCreateTownFromCorrectTownTemplate) { std::shared_ptr<Town> town; ASSERT_NO_THROW(town = dbfactory.create<Town>(correctTmpl)); ASSERT_TRUE(town->getName() == "SomeTown"); ASSERT_TRUE(town->getBiom()->getName() == "Grass"); } TEST_F(DBFactoryTest, shouldThrowWhenCreateFromWrongTemplate) { ASSERT_THROW(dbfactory.create<Town>(wrongTmpl), std::exception); } TEST_F(DBFactoryTest, shouldReturnNewInstanceFromSameTemplateWhenCreate) { std::shared_ptr<Town> town; ASSERT_NO_THROW(town = dbfactory.create<Town>(correctTmpl)); std::shared_ptr<Town> town2; ASSERT_NO_THROW(town2 = dbfactory.create<Town>(correctTmpl)); ASSERT_FALSE(town == town2); } TEST_F(DBFactoryTest, shouldReturnDifferentObjectsFromDifferentsTemplatesWhenCreate) { std::shared_ptr<Town> town; ASSERT_NO_THROW(town = dbfactory.create<Town>(correctTmpl)); std::shared_ptr<Town> town2; ASSERT_NO_THROW(town2 = dbfactory.create<Town>(correctTmpl2)); ASSERT_FALSE(town == town2); } // DBFactory.share TEST_F(DBFactoryTest, shouldShareTownFromCorrectTownTemplate) { std::shared_ptr<Town> town; ASSERT_NO_THROW(town = dbfactory.share<Town>(correctTmpl)); ASSERT_TRUE(town->getName() == "SomeTown"); ASSERT_TRUE(town->getBiom()->getName() == "Grass"); } TEST_F(DBFactoryTest, shouldThrowWhenShareFromWrongTemplate) { ASSERT_THROW(dbfactory.share<Town>(wrongTmpl), std::exception); } TEST_F(DBFactoryTest, shouldReturnSameInstanceFromSameTemplateWhenShare) { std::shared_ptr<Town> town; ASSERT_NO_THROW(town = dbfactory.share<Town>(correctTmpl)); std::shared_ptr<Town> town2; ASSERT_NO_THROW(town2 = dbfactory.share<Town>(correctTmpl)); ASSERT_TRUE(town == town2); } TEST_F(DBFactoryTest, shouldReturnDifferentObjectsFromDifferentsTemplatesWhenShare) { std::shared_ptr<Town> town; ASSERT_NO_THROW(town = dbfactory.share<Town>(correctTmpl)); std::shared_ptr<Town> town2; ASSERT_NO_THROW(town = dbfactory.share<Town>(correctTmpl2)); ASSERT_FALSE(town == town2); } }
// ********************************************************************** // // Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. // // ********************************************************************** // // Ice version 3.4.2 // // <auto-generated> // // Generated from file `Assign.ice' // // Warning: do not edit this file. // // </auto-generated> // #ifndef __Assign_h__ #define __Assign_h__ #include <Ice/LocalObjectF.h> #include <Ice/ProxyF.h> #include <Ice/ObjectF.h> #include <Ice/Exception.h> #include <Ice/LocalObject.h> #include <Ice/Proxy.h> #include <Ice/Object.h> #include <Ice/Outgoing.h> #include <Ice/OutgoingAsync.h> #include <Ice/Incoming.h> #include <Ice/Direct.h> #include <IceUtil/ScopedArray.h> #include <Ice/StreamF.h> #include <Ice/UndefSysMacros.h> #ifndef ICE_IGNORE_VERSION # if ICE_INT_VERSION / 100 != 304 # error Ice version mismatch! # endif # if ICE_INT_VERSION % 100 > 50 # error Beta header file detected # endif # if ICE_INT_VERSION % 100 < 2 # error Ice patch level mismatch! # endif #endif namespace IceProxy { namespace AsyncStatefulDemo { class Assign; } } namespace AsyncStatefulDemo { class Assign; bool operator==(const Assign&, const Assign&); bool operator<(const Assign&, const Assign&); } namespace IceInternal { ::Ice::Object* upCast(::AsyncStatefulDemo::Assign*); ::IceProxy::Ice::Object* upCast(::IceProxy::AsyncStatefulDemo::Assign*); } namespace AsyncStatefulDemo { typedef ::IceInternal::Handle< ::AsyncStatefulDemo::Assign> AssignPtr; typedef ::IceInternal::ProxyHandle< ::IceProxy::AsyncStatefulDemo::Assign> AssignPrx; void __read(::IceInternal::BasicStream*, AssignPrx&); void __patch__AssignPtr(void*, ::Ice::ObjectPtr&); } namespace AsyncStatefulDemo { class Callback_Assign_asgn_Base : virtual public ::IceInternal::CallbackBase { }; typedef ::IceUtil::Handle< Callback_Assign_asgn_Base> Callback_Assign_asgnPtr; } namespace IceProxy { namespace AsyncStatefulDemo { class Assign : virtual public ::IceProxy::Ice::Object { public: bool asgn(::Ice::Int item, ::Ice::Int position) { return asgn(item, position, 0); } bool asgn(::Ice::Int item, ::Ice::Int position, const ::Ice::Context& __ctx) { return asgn(item, position, &__ctx); } ::Ice::AsyncResultPtr begin_asgn(::Ice::Int item, ::Ice::Int position) { return begin_asgn(item, position, 0, ::IceInternal::__dummyCallback, 0); } ::Ice::AsyncResultPtr begin_asgn(::Ice::Int item, ::Ice::Int position, const ::Ice::Context& __ctx) { return begin_asgn(item, position, &__ctx, ::IceInternal::__dummyCallback, 0); } ::Ice::AsyncResultPtr begin_asgn(::Ice::Int item, ::Ice::Int position, const ::Ice::CallbackPtr& __del, const ::Ice::LocalObjectPtr& __cookie = 0) { return begin_asgn(item, position, 0, __del, __cookie); } ::Ice::AsyncResultPtr begin_asgn(::Ice::Int item, ::Ice::Int position, const ::Ice::Context& __ctx, const ::Ice::CallbackPtr& __del, const ::Ice::LocalObjectPtr& __cookie = 0) { return begin_asgn(item, position, &__ctx, __del, __cookie); } ::Ice::AsyncResultPtr begin_asgn(::Ice::Int item, ::Ice::Int position, const ::AsyncStatefulDemo::Callback_Assign_asgnPtr& __del, const ::Ice::LocalObjectPtr& __cookie = 0) { return begin_asgn(item, position, 0, __del, __cookie); } ::Ice::AsyncResultPtr begin_asgn(::Ice::Int item, ::Ice::Int position, const ::Ice::Context& __ctx, const ::AsyncStatefulDemo::Callback_Assign_asgnPtr& __del, const ::Ice::LocalObjectPtr& __cookie = 0) { return begin_asgn(item, position, &__ctx, __del, __cookie); } bool end_asgn(const ::Ice::AsyncResultPtr&); private: bool asgn(::Ice::Int, ::Ice::Int, const ::Ice::Context*); ::Ice::AsyncResultPtr begin_asgn(::Ice::Int, ::Ice::Int, const ::Ice::Context*, const ::IceInternal::CallbackBasePtr&, const ::Ice::LocalObjectPtr& __cookie = 0); public: ::IceInternal::ProxyHandle<Assign> ice_context(const ::Ice::Context& __context) const { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug typedef ::IceProxy::Ice::Object _Base; return dynamic_cast<Assign*>(_Base::ice_context(__context).get()); #else return dynamic_cast<Assign*>(::IceProxy::Ice::Object::ice_context(__context).get()); #endif } ::IceInternal::ProxyHandle<Assign> ice_adapterId(const std::string& __id) const { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug typedef ::IceProxy::Ice::Object _Base; return dynamic_cast<Assign*>(_Base::ice_adapterId(__id).get()); #else return dynamic_cast<Assign*>(::IceProxy::Ice::Object::ice_adapterId(__id).get()); #endif } ::IceInternal::ProxyHandle<Assign> ice_endpoints(const ::Ice::EndpointSeq& __endpoints) const { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug typedef ::IceProxy::Ice::Object _Base; return dynamic_cast<Assign*>(_Base::ice_endpoints(__endpoints).get()); #else return dynamic_cast<Assign*>(::IceProxy::Ice::Object::ice_endpoints(__endpoints).get()); #endif } ::IceInternal::ProxyHandle<Assign> ice_locatorCacheTimeout(int __timeout) const { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug typedef ::IceProxy::Ice::Object _Base; return dynamic_cast<Assign*>(_Base::ice_locatorCacheTimeout(__timeout).get()); #else return dynamic_cast<Assign*>(::IceProxy::Ice::Object::ice_locatorCacheTimeout(__timeout).get()); #endif } ::IceInternal::ProxyHandle<Assign> ice_connectionCached(bool __cached) const { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug typedef ::IceProxy::Ice::Object _Base; return dynamic_cast<Assign*>(_Base::ice_connectionCached(__cached).get()); #else return dynamic_cast<Assign*>(::IceProxy::Ice::Object::ice_connectionCached(__cached).get()); #endif } ::IceInternal::ProxyHandle<Assign> ice_endpointSelection(::Ice::EndpointSelectionType __est) const { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug typedef ::IceProxy::Ice::Object _Base; return dynamic_cast<Assign*>(_Base::ice_endpointSelection(__est).get()); #else return dynamic_cast<Assign*>(::IceProxy::Ice::Object::ice_endpointSelection(__est).get()); #endif } ::IceInternal::ProxyHandle<Assign> ice_secure(bool __secure) const { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug typedef ::IceProxy::Ice::Object _Base; return dynamic_cast<Assign*>(_Base::ice_secure(__secure).get()); #else return dynamic_cast<Assign*>(::IceProxy::Ice::Object::ice_secure(__secure).get()); #endif } ::IceInternal::ProxyHandle<Assign> ice_preferSecure(bool __preferSecure) const { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug typedef ::IceProxy::Ice::Object _Base; return dynamic_cast<Assign*>(_Base::ice_preferSecure(__preferSecure).get()); #else return dynamic_cast<Assign*>(::IceProxy::Ice::Object::ice_preferSecure(__preferSecure).get()); #endif } ::IceInternal::ProxyHandle<Assign> ice_router(const ::Ice::RouterPrx& __router) const { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug typedef ::IceProxy::Ice::Object _Base; return dynamic_cast<Assign*>(_Base::ice_router(__router).get()); #else return dynamic_cast<Assign*>(::IceProxy::Ice::Object::ice_router(__router).get()); #endif } ::IceInternal::ProxyHandle<Assign> ice_locator(const ::Ice::LocatorPrx& __locator) const { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug typedef ::IceProxy::Ice::Object _Base; return dynamic_cast<Assign*>(_Base::ice_locator(__locator).get()); #else return dynamic_cast<Assign*>(::IceProxy::Ice::Object::ice_locator(__locator).get()); #endif } ::IceInternal::ProxyHandle<Assign> ice_collocationOptimized(bool __co) const { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug typedef ::IceProxy::Ice::Object _Base; return dynamic_cast<Assign*>(_Base::ice_collocationOptimized(__co).get()); #else return dynamic_cast<Assign*>(::IceProxy::Ice::Object::ice_collocationOptimized(__co).get()); #endif } ::IceInternal::ProxyHandle<Assign> ice_twoway() const { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug typedef ::IceProxy::Ice::Object _Base; return dynamic_cast<Assign*>(_Base::ice_twoway().get()); #else return dynamic_cast<Assign*>(::IceProxy::Ice::Object::ice_twoway().get()); #endif } ::IceInternal::ProxyHandle<Assign> ice_oneway() const { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug typedef ::IceProxy::Ice::Object _Base; return dynamic_cast<Assign*>(_Base::ice_oneway().get()); #else return dynamic_cast<Assign*>(::IceProxy::Ice::Object::ice_oneway().get()); #endif } ::IceInternal::ProxyHandle<Assign> ice_batchOneway() const { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug typedef ::IceProxy::Ice::Object _Base; return dynamic_cast<Assign*>(_Base::ice_batchOneway().get()); #else return dynamic_cast<Assign*>(::IceProxy::Ice::Object::ice_batchOneway().get()); #endif } ::IceInternal::ProxyHandle<Assign> ice_datagram() const { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug typedef ::IceProxy::Ice::Object _Base; return dynamic_cast<Assign*>(_Base::ice_datagram().get()); #else return dynamic_cast<Assign*>(::IceProxy::Ice::Object::ice_datagram().get()); #endif } ::IceInternal::ProxyHandle<Assign> ice_batchDatagram() const { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug typedef ::IceProxy::Ice::Object _Base; return dynamic_cast<Assign*>(_Base::ice_batchDatagram().get()); #else return dynamic_cast<Assign*>(::IceProxy::Ice::Object::ice_batchDatagram().get()); #endif } ::IceInternal::ProxyHandle<Assign> ice_compress(bool __compress) const { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug typedef ::IceProxy::Ice::Object _Base; return dynamic_cast<Assign*>(_Base::ice_compress(__compress).get()); #else return dynamic_cast<Assign*>(::IceProxy::Ice::Object::ice_compress(__compress).get()); #endif } ::IceInternal::ProxyHandle<Assign> ice_timeout(int __timeout) const { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug typedef ::IceProxy::Ice::Object _Base; return dynamic_cast<Assign*>(_Base::ice_timeout(__timeout).get()); #else return dynamic_cast<Assign*>(::IceProxy::Ice::Object::ice_timeout(__timeout).get()); #endif } ::IceInternal::ProxyHandle<Assign> ice_connectionId(const std::string& __id) const { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug typedef ::IceProxy::Ice::Object _Base; return dynamic_cast<Assign*>(_Base::ice_connectionId(__id).get()); #else return dynamic_cast<Assign*>(::IceProxy::Ice::Object::ice_connectionId(__id).get()); #endif } static const ::std::string& ice_staticId(); private: virtual ::IceInternal::Handle< ::IceDelegateM::Ice::Object> __createDelegateM(); virtual ::IceInternal::Handle< ::IceDelegateD::Ice::Object> __createDelegateD(); virtual ::IceProxy::Ice::Object* __newInstance() const; }; } } namespace IceDelegate { namespace AsyncStatefulDemo { class Assign : virtual public ::IceDelegate::Ice::Object { public: virtual bool asgn(::Ice::Int, ::Ice::Int, const ::Ice::Context*) = 0; }; } } namespace IceDelegateM { namespace AsyncStatefulDemo { class Assign : virtual public ::IceDelegate::AsyncStatefulDemo::Assign, virtual public ::IceDelegateM::Ice::Object { public: virtual bool asgn(::Ice::Int, ::Ice::Int, const ::Ice::Context*); }; } } namespace IceDelegateD { namespace AsyncStatefulDemo { class Assign : virtual public ::IceDelegate::AsyncStatefulDemo::Assign, virtual public ::IceDelegateD::Ice::Object { public: virtual bool asgn(::Ice::Int, ::Ice::Int, const ::Ice::Context*); }; } } namespace AsyncStatefulDemo { class Assign : virtual public ::Ice::Object { public: typedef AssignPrx ProxyType; typedef AssignPtr PointerType; virtual ::Ice::ObjectPtr ice_clone() const; virtual bool ice_isA(const ::std::string&, const ::Ice::Current& = ::Ice::Current()) const; virtual ::std::vector< ::std::string> ice_ids(const ::Ice::Current& = ::Ice::Current()) const; virtual const ::std::string& ice_id(const ::Ice::Current& = ::Ice::Current()) const; static const ::std::string& ice_staticId(); virtual bool asgn(::Ice::Int, ::Ice::Int, const ::Ice::Current& = ::Ice::Current()) = 0; ::Ice::DispatchStatus ___asgn(::IceInternal::Incoming&, const ::Ice::Current&); virtual ::Ice::DispatchStatus __dispatch(::IceInternal::Incoming&, const ::Ice::Current&); virtual void __write(::IceInternal::BasicStream*) const; virtual void __read(::IceInternal::BasicStream*, bool); // COMPILERFIX: Stream API is not supported with VC++ 6 #if !defined(_MSC_VER) || (_MSC_VER >= 1300) virtual void __write(const ::Ice::OutputStreamPtr&) const; virtual void __read(const ::Ice::InputStreamPtr&, bool); #endif }; inline bool operator==(const Assign& l, const Assign& r) { return static_cast<const ::Ice::Object&>(l) == static_cast<const ::Ice::Object&>(r); } inline bool operator<(const Assign& l, const Assign& r) { return static_cast<const ::Ice::Object&>(l) < static_cast<const ::Ice::Object&>(r); } } namespace AsyncStatefulDemo { template<class T> class CallbackNC_Assign_asgn : public Callback_Assign_asgn_Base, public ::IceInternal::TwowayCallbackNC<T> { public: typedef IceUtil::Handle<T> TPtr; typedef void (T::*Exception)(const ::Ice::Exception&); typedef void (T::*Sent)(bool); typedef void (T::*Response)(bool); CallbackNC_Assign_asgn(const TPtr& obj, Response cb, Exception excb, Sent sentcb) : ::IceInternal::TwowayCallbackNC<T>(obj, cb != 0, excb, sentcb), response(cb) { } virtual void __completed(const ::Ice::AsyncResultPtr& __result) const { ::AsyncStatefulDemo::AssignPrx __proxy = ::AsyncStatefulDemo::AssignPrx::uncheckedCast(__result->getProxy()); bool __ret; try { __ret = __proxy->end_asgn(__result); } catch(::Ice::Exception& ex) { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug __exception(__result, ex); #else ::IceInternal::CallbackNC<T>::__exception(__result, ex); #endif return; } if(response) { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug (callback.get()->*response)(__ret); #else (::IceInternal::CallbackNC<T>::callback.get()->*response)(__ret); #endif } } Response response; }; template<class T> Callback_Assign_asgnPtr newCallback_Assign_asgn(const IceUtil::Handle<T>& instance, void (T::*cb)(bool), void (T::*excb)(const ::Ice::Exception&), void (T::*sentcb)(bool) = 0) { return new CallbackNC_Assign_asgn<T>(instance, cb, excb, sentcb); } template<class T> Callback_Assign_asgnPtr newCallback_Assign_asgn(T* instance, void (T::*cb)(bool), void (T::*excb)(const ::Ice::Exception&), void (T::*sentcb)(bool) = 0) { return new CallbackNC_Assign_asgn<T>(instance, cb, excb, sentcb); } template<class T, typename CT> class Callback_Assign_asgn : public Callback_Assign_asgn_Base, public ::IceInternal::TwowayCallback<T, CT> { public: typedef IceUtil::Handle<T> TPtr; typedef void (T::*Exception)(const ::Ice::Exception& , const CT&); typedef void (T::*Sent)(bool , const CT&); typedef void (T::*Response)(bool, const CT&); Callback_Assign_asgn(const TPtr& obj, Response cb, Exception excb, Sent sentcb) : ::IceInternal::TwowayCallback<T, CT>(obj, cb != 0, excb, sentcb), response(cb) { } virtual void __completed(const ::Ice::AsyncResultPtr& __result) const { ::AsyncStatefulDemo::AssignPrx __proxy = ::AsyncStatefulDemo::AssignPrx::uncheckedCast(__result->getProxy()); bool __ret; try { __ret = __proxy->end_asgn(__result); } catch(::Ice::Exception& ex) { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug __exception(__result, ex); #else ::IceInternal::Callback<T, CT>::__exception(__result, ex); #endif return; } if(response) { #if defined(_MSC_VER) && (_MSC_VER < 1300) // VC++ 6 compiler bug (callback.get()->*response)(__ret, CT::dynamicCast(__result->getCookie())); #else (::IceInternal::Callback<T, CT>::callback.get()->*response)(__ret, CT::dynamicCast(__result->getCookie())); #endif } } Response response; }; template<class T, typename CT> Callback_Assign_asgnPtr newCallback_Assign_asgn(const IceUtil::Handle<T>& instance, void (T::*cb)(bool, const CT&), void (T::*excb)(const ::Ice::Exception&, const CT&), void (T::*sentcb)(bool, const CT&) = 0) { return new Callback_Assign_asgn<T, CT>(instance, cb, excb, sentcb); } template<class T, typename CT> Callback_Assign_asgnPtr newCallback_Assign_asgn(T* instance, void (T::*cb)(bool, const CT&), void (T::*excb)(const ::Ice::Exception&, const CT&), void (T::*sentcb)(bool, const CT&) = 0) { return new Callback_Assign_asgn<T, CT>(instance, cb, excb, sentcb); } } #endif
#include "Vulkan/VulkanBuffer.h" using namespace Rocket; void VulkanBufferStruct::Create( Ref<VulkanDevice> device, VkBufferUsageFlags usageFlags, VkMemoryPropertyFlags memoryPropertyFlags, VkDeviceSize size, bool map) { RK_GRAPHICS_TRACE("VulkanBufferStruct Create"); this->device = device->logicalDevice; this->size = size; VkDeviceSize limit = device->properties.limits.nonCoherentAtomSize; auto redundent = size % limit; if (redundent != 0) { auto free_size = limit - redundent; this->size += free_size; } device->CreateBuffer(usageFlags, memoryPropertyFlags, this->size, &buffer, &memory); descriptor = { buffer, 0, size }; if (map) { VK_CHECK(vkMapMemory(device->logicalDevice, memory, 0, this->size, 0, &mapped)); } } void VulkanBufferStruct::Finalize() { if (mapped) { Unmap(); } vkDestroyBuffer(device, buffer, nullptr); vkFreeMemory(device, memory, nullptr); buffer = VK_NULL_HANDLE; memory = VK_NULL_HANDLE; } void VulkanBufferStruct::Map() { VK_CHECK(vkMapMemory(device, memory, 0, size, 0, &mapped)); } void VulkanBufferStruct::Unmap() { if (mapped) { vkUnmapMemory(device, memory); mapped = nullptr; } } void VulkanBufferStruct::Flush(VkDeviceSize size) { VkMappedMemoryRange mappedRange{}; mappedRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; mappedRange.memory = memory; mappedRange.size = size; VK_CHECK(vkFlushMappedMemoryRanges(device, 1, &mappedRange)); }
/**************************************************************************** ** Meta object code from reading C++ file 'clavier.h' ** ** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.6) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "clavier.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'clavier.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 63 #error "This file was generated using the moc from 4.8.6. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_Clavier[] = { // content: 6, // revision 0, // classname 0, 0, // classinfo 59, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: signature, parameters, type, tag, flags 8, 23, 23, 23, 0x05, // slots: signature, parameters, type, tag, flags 24, 23, 23, 23, 0x0a, 28, 23, 23, 23, 0x0a, 32, 23, 23, 23, 0x0a, 36, 23, 23, 23, 0x0a, 40, 23, 23, 23, 0x0a, 44, 23, 23, 23, 0x0a, 48, 23, 23, 23, 0x0a, 52, 23, 23, 23, 0x0a, 56, 23, 23, 23, 0x0a, 60, 23, 23, 23, 0x0a, 64, 23, 23, 23, 0x0a, 68, 23, 23, 23, 0x0a, 72, 23, 23, 23, 0x0a, 76, 23, 23, 23, 0x0a, 80, 23, 23, 23, 0x0a, 84, 23, 23, 23, 0x0a, 88, 23, 23, 23, 0x0a, 92, 23, 23, 23, 0x0a, 96, 23, 23, 23, 0x0a, 100, 23, 23, 23, 0x0a, 104, 23, 23, 23, 0x0a, 108, 23, 23, 23, 0x0a, 112, 23, 23, 23, 0x0a, 116, 23, 23, 23, 0x0a, 120, 23, 23, 23, 0x0a, 124, 23, 23, 23, 0x0a, 128, 23, 23, 23, 0x0a, 136, 23, 23, 23, 0x0a, 143, 23, 23, 23, 0x0a, 149, 23, 23, 23, 0x0a, 158, 23, 23, 23, 0x0a, 167, 23, 23, 23, 0x0a, 174, 23, 23, 23, 0x0a, 182, 23, 23, 23, 0x0a, 187, 23, 23, 23, 0x0a, 195, 23, 23, 23, 0x0a, 203, 23, 23, 23, 0x0a, 211, 23, 23, 23, 0x0a, 219, 23, 23, 23, 0x0a, 226, 23, 23, 23, 0x0a, 234, 23, 23, 23, 0x0a, 242, 23, 23, 23, 0x0a, 251, 23, 23, 23, 0x0a, 256, 23, 23, 23, 0x0a, 261, 23, 23, 23, 0x0a, 266, 23, 23, 23, 0x0a, 271, 23, 23, 23, 0x0a, 276, 23, 23, 23, 0x0a, 281, 23, 23, 23, 0x0a, 286, 23, 23, 23, 0x0a, 291, 23, 23, 23, 0x0a, 296, 23, 23, 23, 0x0a, 301, 23, 23, 23, 0x0a, 309, 23, 23, 23, 0x0a, 316, 23, 23, 23, 0x0a, 322, 23, 23, 23, 0x0a, 328, 23, 23, 23, 0x0a, 337, 23, 23, 23, 0x0a, 0 // eod }; static const char qt_meta_stringdata_Clavier[] = { "Clavier\0Texte(QString)\0\0A()\0Z()\0E()\0" "R()\0T()\0Y()\0U()\0I()\0O()\0P()\0Q()\0S()\0" "D()\0F()\0G()\0H()\0J()\0K()\0L()\0M()\0W()\0" "X()\0C()\0V()\0B()\0N()\0Space()\0Back()\0" "Maj()\0Gauche()\0Droite()\0Virg()\0PVirg()\0" "P2()\0PExcl()\0Under()\0ChevG()\0ChevD()\0" "PInt()\0Point()\0Slash()\0ASlash()\0_9()\0" "_8()\0_7()\0_6()\0_5()\0_4()\0_3()\0_2()\0" "_1()\0_0()\0Moins()\0Plus()\0Div()\0Ast()\0" "Cancel()\0OK()\0" }; void Clavier::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Q_ASSERT(staticMetaObject.cast(_o)); Clavier *_t = static_cast<Clavier *>(_o); switch (_id) { case 0: _t->Texte((*reinterpret_cast< QString(*)>(_a[1]))); break; case 1: _t->A(); break; case 2: _t->Z(); break; case 3: _t->E(); break; case 4: _t->R(); break; case 5: _t->T(); break; case 6: _t->Y(); break; case 7: _t->U(); break; case 8: _t->I(); break; case 9: _t->O(); break; case 10: _t->P(); break; case 11: _t->Q(); break; case 12: _t->S(); break; case 13: _t->D(); break; case 14: _t->F(); break; case 15: _t->G(); break; case 16: _t->H(); break; case 17: _t->J(); break; case 18: _t->K(); break; case 19: _t->L(); break; case 20: _t->M(); break; case 21: _t->W(); break; case 22: _t->X(); break; case 23: _t->C(); break; case 24: _t->V(); break; case 25: _t->B(); break; case 26: _t->N(); break; case 27: _t->Space(); break; case 28: _t->Back(); break; case 29: _t->Maj(); break; case 30: _t->Gauche(); break; case 31: _t->Droite(); break; case 32: _t->Virg(); break; case 33: _t->PVirg(); break; case 34: _t->P2(); break; case 35: _t->PExcl(); break; case 36: _t->Under(); break; case 37: _t->ChevG(); break; case 38: _t->ChevD(); break; case 39: _t->PInt(); break; case 40: _t->Point(); break; case 41: _t->Slash(); break; case 42: _t->ASlash(); break; case 43: _t->_9(); break; case 44: _t->_8(); break; case 45: _t->_7(); break; case 46: _t->_6(); break; case 47: _t->_5(); break; case 48: _t->_4(); break; case 49: _t->_3(); break; case 50: _t->_2(); break; case 51: _t->_1(); break; case 52: _t->_0(); break; case 53: _t->Moins(); break; case 54: _t->Plus(); break; case 55: _t->Div(); break; case 56: _t->Ast(); break; case 57: _t->Cancel(); break; case 58: _t->OK(); break; default: ; } } } const QMetaObjectExtraData Clavier::staticMetaObjectExtraData = { 0, qt_static_metacall }; const QMetaObject Clavier::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_Clavier, qt_meta_data_Clavier, &staticMetaObjectExtraData } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &Clavier::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *Clavier::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *Clavier::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_Clavier)) return static_cast<void*>(const_cast< Clavier*>(this)); return QDialog::qt_metacast(_clname); } int Clavier::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 59) qt_static_metacall(this, _c, _id, _a); _id -= 59; } return _id; } // SIGNAL 0 void Clavier::Texte(QString _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } QT_END_MOC_NAMESPACE
#include <iostream> #include <vector> #include <algorithm> using namespace std; void print(std::vector<int> arr) { for(auto it = arr.cbegin(); it != arr.cend(); it++) { std::cout << *it << " "; } std::cout << "\n"; } vector<int> quickSort(vector <int> &arr, int size) { //test unit input-output // 4 5 3 7 2 // 3 4 5 7 2 // 3 4 5 7 2 // 2 3 4 5 7 // finale : // 2 3 4 5 7 int key = arr[0]; int pivot = 0; // get middle pivot/ equality for(int i=1; i < size; i++) { if( key > arr[i]) { pivot++; for (int j = i; j > 0; j--) { swap(arr[j], arr[j-1]); } } print(arr); } return arr; } int main () { std::vector<int> m_arry = {4, 5, 3, 7, 2}; vector<int> test = partition(m_arry, m_arry.size()); return 0; }
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmFileMonitor.h" #include <cassert> #include <cstddef> #include <unordered_map> #include <utility> #include <cm/memory> #include "cmsys/SystemTools.hxx" namespace { void on_directory_change(uv_fs_event_t* handle, const char* filename, int events, int status); void on_fs_close(uv_handle_t* handle); } // namespace class cmIBaseWatcher { public: virtual ~cmIBaseWatcher() = default; virtual void Trigger(const std::string& pathSegment, int events, int status) const = 0; virtual std::string Path() const = 0; virtual uv_loop_t* Loop() const = 0; virtual void StartWatching() = 0; virtual void StopWatching() = 0; virtual std::vector<std::string> WatchedFiles() const = 0; virtual std::vector<std::string> WatchedDirectories() const = 0; }; class cmVirtualDirectoryWatcher : public cmIBaseWatcher { public: ~cmVirtualDirectoryWatcher() override = default; cmIBaseWatcher* Find(const std::string& ps) { const auto i = this->Children.find(ps); return (i == this->Children.end()) ? nullptr : i->second.get(); } void Trigger(const std::string& pathSegment, int events, int status) const final { if (pathSegment.empty()) { for (auto const& child : this->Children) { child.second->Trigger(std::string(), events, status); } } else { const auto i = this->Children.find(pathSegment); if (i != this->Children.end()) { i->second->Trigger(std::string(), events, status); } } } void StartWatching() override { for (auto const& child : this->Children) { child.second->StartWatching(); } } void StopWatching() override { for (auto const& child : this->Children) { child.second->StopWatching(); } } std::vector<std::string> WatchedFiles() const final { std::vector<std::string> result; for (auto const& child : this->Children) { for (std::string const& f : child.second->WatchedFiles()) { result.push_back(f); } } return result; } std::vector<std::string> WatchedDirectories() const override { std::vector<std::string> result; for (auto const& child : this->Children) { for (std::string const& dir : child.second->WatchedDirectories()) { result.push_back(dir); } } return result; } void Reset() { this->Children.clear(); } void AddChildWatcher(const std::string& ps, cmIBaseWatcher* watcher) { assert(!ps.empty()); assert(this->Children.find(ps) == this->Children.end()); assert(watcher); this->Children.emplace(ps, std::unique_ptr<cmIBaseWatcher>(watcher)); } private: std::unordered_map<std::string, std::unique_ptr<cmIBaseWatcher>> Children; // owned! }; // Root of all the different (on windows!) root directories: class cmRootWatcher : public cmVirtualDirectoryWatcher { public: cmRootWatcher(uv_loop_t* loop) : mLoop(loop) { assert(loop); } std::string Path() const final { assert(false); return std::string(); } uv_loop_t* Loop() const final { return this->mLoop; } private: uv_loop_t* const mLoop; // no ownership! }; // Real directories: class cmRealDirectoryWatcher : public cmVirtualDirectoryWatcher { public: cmRealDirectoryWatcher(cmVirtualDirectoryWatcher* p, const std::string& ps) : Parent(p) , PathSegment(ps) { assert(p); assert(!ps.empty()); p->AddChildWatcher(ps, this); } void StartWatching() final { if (!this->Handle) { this->Handle = new uv_fs_event_t; uv_fs_event_init(this->Loop(), this->Handle); this->Handle->data = this; uv_fs_event_start(this->Handle, &on_directory_change, Path().c_str(), 0); } cmVirtualDirectoryWatcher::StartWatching(); } void StopWatching() final { if (this->Handle) { uv_fs_event_stop(this->Handle); if (!uv_is_closing(reinterpret_cast<uv_handle_t*>(this->Handle))) { uv_close(reinterpret_cast<uv_handle_t*>(this->Handle), &on_fs_close); } this->Handle = nullptr; } cmVirtualDirectoryWatcher::StopWatching(); } uv_loop_t* Loop() const final { return this->Parent->Loop(); } std::vector<std::string> WatchedDirectories() const override { std::vector<std::string> result = { Path() }; for (std::string const& dir : cmVirtualDirectoryWatcher::WatchedDirectories()) { result.push_back(dir); } return result; } protected: cmVirtualDirectoryWatcher* const Parent; const std::string PathSegment; private: uv_fs_event_t* Handle = nullptr; // owner! }; // Root directories: class cmRootDirectoryWatcher : public cmRealDirectoryWatcher { public: cmRootDirectoryWatcher(cmRootWatcher* p, const std::string& ps) : cmRealDirectoryWatcher(p, ps) { } std::string Path() const final { return this->PathSegment; } }; // Normal directories below root: class cmDirectoryWatcher : public cmRealDirectoryWatcher { public: cmDirectoryWatcher(cmRealDirectoryWatcher* p, const std::string& ps) : cmRealDirectoryWatcher(p, ps) { } std::string Path() const final { return this->Parent->Path() + this->PathSegment + "/"; } }; class cmFileWatcher : public cmIBaseWatcher { public: cmFileWatcher(cmRealDirectoryWatcher* p, const std::string& ps, cmFileMonitor::Callback cb) : Parent(p) , PathSegment(ps) , CbList({ std::move(cb) }) { assert(p); assert(!ps.empty()); p->AddChildWatcher(ps, this); } void StartWatching() final {} void StopWatching() final {} void AppendCallback(cmFileMonitor::Callback const& cb) { this->CbList.push_back(cb); } std::string Path() const final { return this->Parent->Path() + this->PathSegment; } std::vector<std::string> WatchedDirectories() const final { return {}; } std::vector<std::string> WatchedFiles() const final { return { this->Path() }; } void Trigger(const std::string& ps, int events, int status) const final { assert(ps.empty()); assert(status == 0); static_cast<void>(ps); const std::string path = this->Path(); for (cmFileMonitor::Callback const& cb : this->CbList) { cb(path, events, status); } } uv_loop_t* Loop() const final { return this->Parent->Loop(); } private: cmRealDirectoryWatcher* Parent; const std::string PathSegment; std::vector<cmFileMonitor::Callback> CbList; }; namespace { void on_directory_change(uv_fs_event_t* handle, const char* filename, int events, int status) { const cmIBaseWatcher* const watcher = static_cast<const cmIBaseWatcher*>(handle->data); const std::string pathSegment(filename ? filename : ""); watcher->Trigger(pathSegment, events, status); } void on_fs_close(uv_handle_t* handle) { delete reinterpret_cast<uv_fs_event_t*>(handle); } } // namespace cmFileMonitor::cmFileMonitor(uv_loop_t* l) : Root(cm::make_unique<cmRootWatcher>(l)) { } cmFileMonitor::~cmFileMonitor() = default; void cmFileMonitor::MonitorPaths(const std::vector<std::string>& paths, Callback const& cb) { for (std::string const& p : paths) { std::vector<std::string> pathSegments; cmsys::SystemTools::SplitPath(p, pathSegments, true); const bool pathIsFile = !cmsys::SystemTools::FileIsDirectory(p); const size_t segmentCount = pathSegments.size(); if (segmentCount < 2) { // Expect at least rootdir and filename continue; } cmVirtualDirectoryWatcher* currentWatcher = this->Root.get(); for (size_t i = 0; i < segmentCount; ++i) { assert(currentWatcher); const bool fileSegment = (i == segmentCount - 1 && pathIsFile); const bool rootSegment = (i == 0); assert( !(fileSegment && rootSegment)); // Can not be both filename and root part of the path! const std::string& currentSegment = pathSegments[i]; if (currentSegment.empty()) { continue; } cmIBaseWatcher* nextWatcher = currentWatcher->Find(currentSegment); if (!nextWatcher) { if (rootSegment) { // Root part assert(currentWatcher == this->Root.get()); nextWatcher = new cmRootDirectoryWatcher(this->Root.get(), currentSegment); assert(currentWatcher->Find(currentSegment) == nextWatcher); } else if (fileSegment) { // File part assert(currentWatcher != this->Root.get()); nextWatcher = new cmFileWatcher( dynamic_cast<cmRealDirectoryWatcher*>(currentWatcher), currentSegment, cb); assert(currentWatcher->Find(currentSegment) == nextWatcher); } else { // Any normal directory in between nextWatcher = new cmDirectoryWatcher( dynamic_cast<cmRealDirectoryWatcher*>(currentWatcher), currentSegment); assert(currentWatcher->Find(currentSegment) == nextWatcher); } } else { if (fileSegment) { auto filePtr = dynamic_cast<cmFileWatcher*>(nextWatcher); assert(filePtr); filePtr->AppendCallback(cb); continue; } } currentWatcher = dynamic_cast<cmVirtualDirectoryWatcher*>(nextWatcher); } } this->Root->StartWatching(); } void cmFileMonitor::StopMonitoring() { this->Root->StopWatching(); this->Root->Reset(); } std::vector<std::string> cmFileMonitor::WatchedFiles() const { std::vector<std::string> result; if (this->Root) { result = this->Root->WatchedFiles(); } return result; } std::vector<std::string> cmFileMonitor::WatchedDirectories() const { std::vector<std::string> result; if (this->Root) { result = this->Root->WatchedDirectories(); } return result; }
#pragma once /* * Lanq(Lan Quick) * Solodov A. N. (hotSAN) * 2016 * LqShdPtr - Pointer on shared object. * Object must have public integer field "CountPointers". */ #include "LqOs.h" #include "LqAtm.hpp" #include "LqLock.hpp" #include <type_traits> template<typename T> void SHARED_POINTERDeleteProc(T* p) { delete p; } #pragma pack(push) #pragma pack(LQSTRUCT_ALIGN_MEM) template< typename _t, /* _t - must contain CountPointers field */ void(*DeleteProc)(_t*) = SHARED_POINTERDeleteProc, /* Proc called when object have zero references */ bool IsLock = false /* true - is pointer contact with multiple threads */, bool IsNullCheck = true, /* Set false, if pointer never be setted on nullptr (For optimized) */ typename LockerType = unsigned char /* Locker type (use any integer type) */ > class LqShdPtr { template<typename _t2, void(*)(_t2*), bool, bool, typename> friend class LqShdPtr; struct _s { _t* p; inline void LockRead() const {} inline void LockWrite() const {} inline void UnlockWrite() const {} inline void UnlockRead() const {} }; struct _slk { _t* p; mutable LqLocker<LockerType> lk; inline void LockRead() const { lk.LockRead(); } inline void LockWrite() const { lk.LockWrite(); } inline void UnlockWrite() const { lk.UnlockWrite(); } inline void UnlockRead() const { lk.UnlockRead(); } }; typename std::conditional<IsLock, _slk, _s>::type fld; inline _t* Deinit() { if(IsNullCheck && (fld.p == nullptr)) return nullptr; /* thread race cond. solution */ auto Expected = fld.p->CountPointers; for(; !LqAtmCmpXchg(fld.p->CountPointers, Expected, Expected - 1); Expected = fld.p->CountPointers); return (Expected == 1) ? fld.p : nullptr; } public: static const auto IsHaveLock = IsLock; typedef LockerType LockType; typedef _t ElemType; inline LqShdPtr() { fld.p = nullptr; }; inline LqShdPtr(_t* Pointer) { if(((fld.p = Pointer) != nullptr) || !IsNullCheck) LqAtmIntrlkInc(fld.p->CountPointers); } LqShdPtr(const LqShdPtr<_t, DeleteProc, false, IsNullCheck, LockerType>& a) { if(((fld.p = a.fld.p) != nullptr) || !IsNullCheck) LqAtmIntrlkInc(fld.p->CountPointers); } LQ_NO_INLINE LqShdPtr(const LqShdPtr<_t, DeleteProc, true, IsNullCheck, LockerType>& a) { a.fld.LockRead(); if(((fld.p = a.fld.p) != nullptr) || !IsNullCheck) LqAtmIntrlkInc(fld.p->CountPointers); a.fld.UnlockRead(); } LQ_NO_INLINE ~LqShdPtr() { if(auto Del = Deinit()) DeleteProc(Del); } template<bool ArgIsHaveLock, bool ArgNullCheck, typename ArgLockerType> void Set(const LqShdPtr<_t, DeleteProc, ArgIsHaveLock, ArgNullCheck, ArgLockerType>& a) { fld.LockWrite(); a.fld.LockRead(); if((a.fld.p != nullptr) || !IsNullCheck || !ArgNullCheck) LqAtmIntrlkInc(a.fld.p->CountPointers); auto Del = Deinit(); fld.p = a.fld.p; a.fld.UnlockRead(); fld.UnlockWrite(); if(Del != nullptr) DeleteProc(Del); } void Set(_t* a) { fld.LockWrite(); if((a != nullptr) || !IsNullCheck) LqAtmIntrlkInc(a->CountPointers); auto Del = Deinit(); fld.p = a; fld.UnlockWrite(); if(Del != nullptr) DeleteProc(Del); } inline LqShdPtr& operator=(LqShdPtr&& a) { Set(a); return *this; } template<typename _TInput> inline LqShdPtr& operator=(_TInput&& a) { Set(a); return *this; } /* Set new data between NewStart() and NewFin()*/ inline _t* NewStart() { fld.LockWrite(); return fld.p; } void NewFin(_t* NewVal) { if((NewVal != nullptr) || !IsNullCheck) LqAtmIntrlkInc(NewVal->CountPointers); auto Del = Deinit(); fld.p = NewVal; fld.UnlockWrite(); if(Del != nullptr) DeleteProc(Del); } template<bool ArgIsHaveLock, bool ArgNullCheck, typename ArgLockerType> void Swap(LqShdPtr<_t, DeleteProc, ArgIsHaveLock, ArgNullCheck, ArgLockerType>& a) { fld.LockWrite(); a.fld.LockRead(); auto t = fld.p; fld.p = a.fld.p; a.fld.p = t; a.fld.UnlockRead(); fld.UnlockWrite(); } inline _t* operator->() const { return fld.p; } inline _t* Get() const { return fld.p; } inline bool operator ==(const LqShdPtr& Worker2) const { return fld.p == Worker2.fld.p; } inline bool operator !=(const LqShdPtr& Worker2) const { return fld.p != Worker2.fld.p; } inline bool operator ==(const void* Worker2) const { return fld.p == Worker2; } inline bool operator !=(const void* Worker2) const { return fld.p != Worker2; } inline bool operator ==(const _t* Worker2) const { return fld.p == Worker2; } inline bool operator !=(const _t* Worker2) const { return fld.p != Worker2; } inline bool operator ==(decltype(nullptr) n) const { return fld.p == nullptr; } inline bool operator !=(decltype(nullptr) n) const { return fld.p != nullptr; } }; /* C - defines for trivial types */ template<typename _t> inline void LqObPtrReference(_t* Ob) { LqAtmIntrlkInc(Ob->CountPointers); } template<typename _t, void(*DeleteProc)(_t*) = SHARED_POINTERDeleteProc> bool LqObPtrDereference(_t* Ob) { auto Expected = Ob->CountPointers; for(; !LqAtmCmpXchg(Ob->CountPointers, Expected, Expected - 1); Expected = Ob->CountPointers); if(Expected == 1) { DeleteProc(Ob); return true; } else { return false; } } template<typename _t, typename _LkType> void LqObPtrInit(_t*& Ob, _t* NewOb, volatile _LkType& Lk) { LqAtmLkInit(Lk); Ob = NewOb; if(Ob != nullptr) LqAtmIntrlkInc(Ob->CountPointers); } template<typename _t, typename _LkType> _t* LqObPtrGet(_t* Ob, volatile _LkType& Lk) { LqAtmLkRd(Lk); if(Ob != nullptr) LqAtmIntrlkInc(Ob->CountPointers); _t* Res = Ob; LqAtmUlkRd(Lk); return Res; } template<typename _t, void(*DeleteProc)(_t*), bool IsNullCheck, typename _LkType> LqShdPtr<_t, DeleteProc, false, IsNullCheck> LqObPtrGetEx(_t* Ob, volatile _LkType& Lk) { LqAtmLkRd(Lk); auto Res = LqShdPtr<_t, DeleteProc, false, IsNullCheck>(Ob); LqAtmUlkRd(Lk); return Res; } template<typename _t, typename _LkType> inline _t* LqObPtrNewStart(_t* Ob, volatile _LkType& Lk) { LqAtmLkWr(Lk); return Ob; } template<typename _t, void(*DeleteProc)(_t*), typename _LkType> void LqObPtrNewFin(_t*& Ob, _t* NewVal, volatile _LkType& Lk) { if(NewVal != nullptr) LqAtmIntrlkInc(NewVal->CountPointers); _t* DelVal; if(Ob != nullptr) { auto Expected = Ob->CountPointers; for(; !LqAtmCmpXchg(Ob->CountPointers, Expected, Expected - 1); Expected = Ob->CountPointers); DelVal = (Expected == 1) ? Ob : nullptr; } else { DelVal = nullptr; } Ob = NewVal; LqAtmUlkWr(Lk); if(DelVal != nullptr) DeleteProc(DelVal); } #pragma pack(pop)
 // 4.7-2.h: 4.7-2 应用程序的主头文件 // #pragma once #ifndef __AFXWIN_H__ #error "在包含此文件之前包含 'pch.h' 以生成 PCH" #endif #include "resource.h" // 主符号 // CMy472App: // 有关此类的实现,请参阅 4.7-2.cpp // class CMy472App : public CWinApp { public: CMy472App() noexcept; // 重写 public: virtual BOOL InitInstance(); virtual int ExitInstance(); // 实现 afx_msg void OnAppAbout(); DECLARE_MESSAGE_MAP() }; extern CMy472App theApp;
#include "Failure.h" #include "GameSeaquenceController.h" #include "Ready.h" #include "GameOver.h" Failure::Failure() { std::cout << "failure" << std::endl; mCount = 0; } Failure::~Failure() { } //ミス表示 Boot* Failure::Update(GameSeaquenceController* controller){ Boot* next = this; if (mCount >= 60){ if (controller->LifeNumber() <= 0){ next = new GameOver; } else{ next = new Ready; } } //描画 ++mCount; return next; }
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <functional> #include <queue> #include <string> #include <cstring> #include <numeric> #include <cstdlib> #include <cmath> using namespace std; typedef long long ll; #define INF 10e8 #define rep(i,n) for(int i=0; i<n; i++) #define rep_r(i,n,m) for(int i=m; i<n; i++) #define MAX 100 #define MOD 1000000007 #define pb push_back typedef pair<ll,ll> P; int main() { int n,m; cin >> n >> m; int a[1000], b[1000], c[1000], dist[100][100]; for (int i = 0; i < m; ++i) { cin >> a[i] >> b[i] >> c[i]; a[i]--, b[i]--; } for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i == j) dist[i][j] = 0; else dist[i][j] = INF; } } for (int i = 0; i < m; ++i) { dist[a[i]][b[i]] = c[i]; dist[b[i]][a[i]] = c[i]; } for (int k = 0; k < n; ++k) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]); } } } int ans = m; rep(i,m) { bool shortest = false; rep(j,n) if(dist[j][a[i]] + c[i] == dist[j][b[i]]) shortest = true; if (shortest) ans--; } cout << ans << endl; }
/*********************************************************\ * 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/IResource.h" //[-------------------------------------------------------] //[ Forward declarations ] //[-------------------------------------------------------] namespace Renderer { class ISamplerState; class IResourceGroup; } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace Renderer { //[-------------------------------------------------------] //[ Classes ] //[-------------------------------------------------------] /** * @brief * Abstract root signature ("pipeline layout" in Vulkan terminology) interface * * @note * - Overview of the binding models of explicit APIs: "Choosing a binding model" - https://github.com/gpuweb/gpuweb/issues/19 */ class IRootSignature : public IResource { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Destructor */ inline virtual ~IRootSignature() override; //[-------------------------------------------------------] //[ Public virtual Renderer::IRootSignature methods ] //[-------------------------------------------------------] public: /** * @brief * Create a resource group instance * * @param[in] rootParameterIndex * The root parameter index number for binding * @param[in] numberOfResources * Number of resources, having no resources is invalid * @param[in] resources * At least "numberOfResources" resource pointers, must be valid, the resource group will keep a reference to the resources * @param[in] samplerStates * If not a null pointer at least "numberOfResources" sampler state pointers, must be valid if there's at least one texture resource, the resource group will keep a reference to the sampler states * * @return * The created resource group instance, a null pointer on error. Release the returned instance if you no longer need it. */ virtual IResourceGroup* createResourceGroup(uint32_t rootParameterIndex, uint32_t numberOfResources, IResource** resources, ISamplerState** samplerStates = nullptr) = 0; //[-------------------------------------------------------] //[ Protected methods ] //[-------------------------------------------------------] protected: /** * @brief * Constructor * * @param[in] renderer * Owner renderer instance */ inline explicit IRootSignature(IRenderer& renderer); explicit IRootSignature(const IRootSignature& source) = delete; IRootSignature& operator =(const IRootSignature& source) = delete; }; //[-------------------------------------------------------] //[ Type definitions ] //[-------------------------------------------------------] typedef SmartRefCount<IRootSignature> IRootSignaturePtr; //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // Renderer //[-------------------------------------------------------] //[ Implementation ] //[-------------------------------------------------------] #include "Renderer/IRootSignature.inl"
#include <iostream> #include <fstream> #include <vector> #include <cmath> #include <cstdlib> #include "TFile.h" #include "TTree.h" #include "TH2.h" #include "TVector3.h" #include "TRandom3.h" #include "TGraphAsymmErrors.h" #include "constants.h" #include "AccMap.h" using namespace std; // Vectors which describe all of the useful info for the e'p events const int n_recoils = 1000; int main(int argc, char **argv) { if (argc != 9) { cerr << "Wrong number of arguments! Instead use\n" << "\t /path/to/ep/file /path/to/epp/file /path/to/map/file [a1] [a2] [b1] [b2] [sigPerp] \n\n"; return -1; } // Parameters const double a1=atof(argv[4]); const double a2=atof(argv[5]); const double b1=atof(argv[6]); const double b2=atof(argv[7]); const double sigPerp = atof(argv[8]); const double muPerp=0.; // Some set-up vector<TVector3> ep_pmiss_list; vector<TVector3> ep_q_list; vector<TVector3> ep_lon_list; vector<TVector3> ep_inp_list; vector<TVector3> ep_oop_list; TRandom3 myRand(0); // Read in e'p events cerr << "Loading 1p data file " << argv[1] << " ...\n"; TFile * fep = new TFile(argv[1]); TTree * tep = (TTree*)fep->Get("T"); Float_t pPVec[2][3]; // Proton momenta Float_t qVec[3]; // q Float_t pMissVec[2][3]; Float_t vertices[2][3]; // position 3 vectors of proton vertices tep->SetBranchAddress("q",qVec); tep->SetBranchAddress("Pmiss",pMissVec); tep->SetBranchAddress("Rp",vertices); tep->SetBranchAddress("Pp",pPVec); for (int i=0 ; i<tep->GetEntries() ; i++) { tep->GetEvent(i); TVector3 plead(pPVec[0][0],pPVec[0][1], pPVec[0][2]); TVector3 pmiss(pMissVec[0][0],pMissVec[0][1],pMissVec[0][2]); TVector3 q(qVec[0],qVec[1],qVec[2]); // Make Or's cuts on vertex position if(!((fabs(vertices[0][2]+22.25)<2.25) && (plead.Mag() < 2.4))) continue; ep_pmiss_list.push_back(pmiss); ep_q_list.push_back(q); // Form the rotated basis TVector3 lon = pmiss.Unit(); TVector3 oop = q.Cross(lon).Unit(); TVector3 inp = oop.Cross(lon).Unit(); ep_lon_list.push_back(lon); ep_inp_list.push_back(inp); ep_oop_list.push_back(oop); } fep->Close(); // Read in epp file cerr << "Loading 2p data file " << argv[2] << " ...\n"; TFile *fepp = new TFile(argv[2]); TTree *tepp = (TTree*)fepp->Get("T"); tepp->SetBranchAddress("q",qVec); tepp->SetBranchAddress("Pmiss",pMissVec); tepp->SetBranchAddress("Rp",vertices); tepp->SetBranchAddress("Pp",pPVec); for (int i=0 ; i<tepp->GetEntries() ; i++) { tepp->GetEvent(i); TVector3 plead(pPVec[0][0],pPVec[0][1], pPVec[0][2]); TVector3 pmiss(pMissVec[0][0],pMissVec[0][1],pMissVec[0][2]); TVector3 q(qVec[0],qVec[1],qVec[2]); // Make Or's cut on vertex position if (!((fabs(vertices[0][2]+22.25)<2.25) && (plead.Mag() < 2.4))) continue; ep_pmiss_list.push_back(pmiss); ep_q_list.push_back(q); double pmiss_mag = pmiss.Mag(); // Form the rotated basis TVector3 lon = pmiss.Unit(); TVector3 oop = q.Cross(lon).Unit(); TVector3 inp = oop.Cross(lon).Unit(); ep_lon_list.push_back(lon); ep_inp_list.push_back(inp); ep_oop_list.push_back(oop); } fepp->Close(); double n_ep_events = ep_pmiss_list.size(); cerr << "Done reading input data.\n"; cerr << "Read in " << n_ep_events << " ep events.\n"; // Load the acceptance maps AccMap myMap(argv[3]); // Histograms for storing the acceptance data TH1D * h1Gen = new TH1D("gen","Generated;pmiss [GeV];Counts",n_pmiss_bins,0.3,1.); TH1D * h1Acc = new TH1D("acc","Accepted;pmiss [GeV];Counts",n_pmiss_bins,0.3,1.); h1Gen->Sumw2(); h1Acc->Sumw2(); TGraphAsymmErrors * corr = new TGraphAsymmErrors; // Generate a pseudo data sample for each e'p event // Loop over e'p for (int j=0 ; j< n_ep_events ; j++) { // Find pmiss double pmiss = ep_pmiss_list[j].Mag(); // Get the Longitudinal Gaussian parameters given pmiss double muLong = b1 * (pmiss - 0.6) + b2; double sigLong= a1 * (pmiss - 0.6) + a2; // Generate some p recoil vectors for (int k=0 ; k<n_recoils ; k++) { // Fill generated histogram h1Gen->Fill(pmiss); // Generate random Gaussian double pcmLon = muLong + sigLong * myRand.Gaus(); double pcmInp = muPerp + sigPerp * myRand.Gaus(); double pcmOop = muPerp + sigPerp * myRand.Gaus(); TVector3 pcm = pcmLon * ep_lon_list[j] + pcmInp * ep_inp_list[j] + pcmOop * ep_oop_list[j]; TVector3 prec = pcm - ep_pmiss_list[j]; // Test acceptance, add to accepted histogram h1Acc->Fill(pmiss,myMap.recoil_accept(prec)); } } corr->BayesDivide(h1Acc,h1Gen); // Loop over bins and fill to the 2d histogram for (int i=0 ; i< corr->GetN() ; i++) { double pmiss, correction; corr->GetPoint(i,pmiss,correction); cout << pmiss << " " << correction << " " << corr->GetErrorYlow(i) << " " << corr->GetErrorYhigh(i) << "\n"; } return 0; }
#include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; void printStr(char * str, int * seqVisited, int size) { for (int i = 0; i < size; i++) { cout << str[seqVisited[i]]; } cout << endl; } void permutationUtil(char * str, int size,int i, bool * visited, int * seqVisited, int length) { if (length == size) { printStr(str,seqVisited,size); } visited[i] = true; for (int j = 0; j < size; j++) { if (!visited[j]) { length++; seqVisited[length-1] = j; permutationUtil(str, size,j,visited,seqVisited,length); seqVisited[length-1] = -1; length--; } } visited[i] = false; } void Permutation(char * str) { if (str == NULL) return; int n = strlen(str); bool * visited = (bool*)malloc(sizeof(bool) * n); for (int i = 0; i < n; i++) { visited[i] = false; } int * seqVisited =(int *)malloc(sizeof(int) * n); for (int i = 0; i < n; i++) { seqVisited[i] = -1; } for (int i = 0; i < n;i++) { int length = 1; seqVisited[0] = i; permutationUtil(str,n,i,visited,seqVisited,length); } } void main() { char * str = "ABC"; Permutation(str); }
/** Copyright (c) 2015 Eric Bruneton All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "atmosphere/measurement/measured_atmosphere.h" #include <algorithm> #include <cassert> #include <fstream> #include <iostream> #include <sstream> #include <vector> namespace { std::string ToString(double x) { std::stringstream out; out << x; if (out.str().find('.') == std::string::npos) { out << ".0"; } return out.str(); } std::string GetFileNameAndSampleLocation(const std::string& directory, const std::string& date, const std::string& hour, const std::string& minutes, int sample_index, int* x, int* y) { // Sample order used in Kider measurements, starts at North low on the // horizon, does a full turn, then a full turn in the opposite direction at a // higher elevation, and so on until the zenith is reached. static const int coords[2 * 81] = { // First turn. 8, 4, 8, 5, 8, 6, 8, 7, 8, 8, 7, 8, 6, 8, 5, 8, 4, 8, 3, 8, 2, 8, 1, 8, 0, 8, 0, 7, 0, 6, 0, 5, 0, 4, 0, 3, 0, 2, 0, 1, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0, 8, 1, 8, 2, 8, 3, // Second turn. 7, 3, 7, 2, 7, 1, 6, 1, 5, 1, 4, 1, 3, 1, 2, 1, 1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, 2, 7, 3, 7, 4, 7, 5, 7, 6, 7, 7, 7, 7, 6, 7, 5, 7, 4, // Third turn. 6, 4, 6, 5, 6, 6, 5, 6, 4, 6, 3, 6, 2, 6, 2, 5, 2, 4, 2, 3, 2, 2, 3, 2, 4, 2, 5, 2, 6, 2, 6, 3, // Fourth turn. 5, 3, 4, 3, 3, 3, 3, 4, 3, 5, 4, 5, 5, 5, 5, 4, // Zenith. 4, 4 }; *x = coords[2 * sample_index]; *y = coords[2 * sample_index + 1]; Angle view_zenith; Angle view_azimuth; HemisphericalFunction<RadianceSpectrum>::GetSampleDirection( *x, *y, &view_zenith, &view_azimuth); if (view_azimuth.to(rad) < 0.0) { view_azimuth = view_azimuth + 2.0 * pi; } std::stringstream out; out << directory << "/" << date << "___" << hour << "." << minutes << ".00/" << date << "___" << hour << "." << minutes << ".00_-_" << sample_index << "____" << ToString(view_azimuth.to(deg)) << "___" << ToString(90.0 - view_zenith.to(deg)) << ".asd.rad.txt"; return out.str(); } RadianceSpectrum LoadKiderRadianceFile(const std::string& filename) { std::vector<Wavelength> wavelengths; std::vector<SpectralRadiance> radiances; std::ifstream file(filename, std::ifstream::in); if (!file.good()) { std::cerr << "Cannot open file '" << filename << "'" << std::endl; ::exit(-1); return RadianceSpectrum(wavelengths, radiances); } std::string first_line_ignored; std::getline(file, first_line_ignored); while (file.good()) { int wavelength; double radiance; file >> wavelength >> radiance; wavelengths.push_back(wavelength * nm); radiances.push_back(radiance * watt_per_square_meter_per_sr_per_nm); } file.close(); return RadianceSpectrum(wavelengths, radiances); } } // anonymous namespace MeasuredAtmosphere::MeasuredAtmosphere(const std::string& directory, const std::string& date, const std::string& hour, const std::string& minutes, Angle sun_zenith, Angle sun_azimuth, const std::string& cache_directory, bool compute_azimuth_from_data) : directory_(directory), date_(date), hour_(hour), minutes_(minutes) { const std::string cache_file_name = cache_directory + "/" + date + hour + minutes + ".dat"; if (cache_directory.length() > 0) { std::ifstream f; f.open(cache_file_name); if (f.good()) { f.close(); measurements_.Load(cache_file_name); std::ifstream file(cache_file_name + ".params", std::ifstream::binary | std::ifstream::in); file.read(reinterpret_cast<char*>(&sun_zenith_), sizeof(sun_zenith_)); file.read(reinterpret_cast<char*>(&sun_azimuth_), sizeof(sun_azimuth_)); file.close(); return; } } std::cout << "Loading " << hour << "h" << minutes << "..." << std::endl; for (int i = 0; i < 81; ++i) { int x, y; std::string filename = GetFileNameAndSampleLocation(directory, date, hour, minutes, i, &x, &y); // Azimuth in Kider data file names is measured counterclockwise from North, // while the usual convention is to measure it clockwise from North. To use // the normal azimuth convention in GetSkyRadiance, we need to invert the // azimuth sign, which translates to inverting the y coordinate of the // samples in the unit square / unit disk (where the y axis corresponds to // East). measurements_.Set(x, 8 - y, LoadKiderRadianceFile(filename)); } // Measurement sample 0 (north) seems systematically wrong. Fix it by // interpolating the two nearest measurements at the same elevation. measurements_.Set( 8, 4, (measurements_.Get(8, 3) + measurements_.Get(8, 5)) * 0.5); sun_zenith_ = sun_zenith; if (compute_azimuth_from_data) { // The theoretical sun zenith angle from the measurement location and date // corresponds to the data, but the azimuth angle does not, and the // difference between the theoretical and the actual values is not constant // (maybe a drift in the measuring instrument?). Thus, instead of using the // theoretical azimuth, we estimate it by finding the axis of symmetry of // the interpolated measurements. std::cout << "Computing sun direction..." << std::endl; sun_azimuth_ = EstimateSunAzimuth(sun_azimuth); } else { sun_azimuth_ = sun_azimuth; } // Cache the results on disk. if (cache_directory.length() > 0) { measurements_.Save(cache_file_name); std::ofstream file(cache_file_name + ".params", std::ofstream::binary); file.write( reinterpret_cast<const char*>(&sun_zenith_), sizeof(sun_zenith_)); file.write( reinterpret_cast<const char*>(&sun_azimuth_), sizeof(sun_azimuth_)); file.close(); } } std::string MeasuredAtmosphere::GetSourceFileName(int i, int j) const { if (i == 8 && j == 4) { // Measurement sample 0 (north) seems systematically wrong. // Return a nearby sample instead. j = 5; } for (int s = 0; s < 81; ++s) { int x; int y; std::string filename = GetFileNameAndSampleLocation( directory_, date_, hour_, minutes_, s, &x, &y); if (x == i && y == 8 - j) { return filename; } } return ""; } std::string MeasuredAtmosphere::GetSourceFileName(Angle view_zenith, Angle view_azimuth) const { for (int i = 0; i < 9; ++i) { for (int j = 0; j < 9; ++j) { Angle zenith_angle; Angle azimuth; HemisphericalFunction<RadianceSpectrum>::GetSampleDirection( i, j, &zenith_angle, &azimuth); Number cos_angle = cos(view_zenith) * cos(zenith_angle) + sin(view_zenith) * sin(zenith_angle) * cos(view_azimuth - azimuth); if (acos(cos_angle).to(deg) < 0.1) { return GetSourceFileName(i, j); } } } return ""; } IrradianceSpectrum MeasuredAtmosphere::GetSunIrradiance(Length altitude, Angle sun_zenith) const { assert(altitude == 0.0 * m); assert(sun_zenith == sun_zenith_); return IrradianceSpectrum(0.0 * watt_per_square_meter_per_nm); } RadianceSpectrum MeasuredAtmosphere::GetSkyRadiance(Length altitude, Angle sun_zenith, Angle view_zenith, Angle view_sun_azimuth) const { return GetSkyRadiance(altitude, sun_zenith, sun_azimuth_, view_zenith, sun_azimuth_ + view_sun_azimuth); } RadianceSpectrum MeasuredAtmosphere::GetSkyRadiance(Length altitude, Angle sun_zenith, Angle sun_azimuth, Angle view_zenith, Angle view_azimuth) const { assert(altitude == 0.0 * m); assert(sun_zenith == sun_zenith_); assert(sun_azimuth == sun_azimuth_); return measurements_(view_zenith, view_azimuth); } RadianceSpectrum MeasuredAtmosphere::GetSkyRadianceMeasurement(Length altitude, Angle sun_zenith, Angle sun_azimuth, Angle view_zenith, Angle view_azimuth) const { assert(altitude == 0.0 * m); assert(sun_zenith == sun_zenith_); assert(sun_azimuth == sun_azimuth_); for (int i = 0; i < 9; ++i) { for (int j = 0; j < 9; ++j) { Angle zenith_angle; Angle azimuth; HemisphericalFunction<RadianceSpectrum>::GetSampleDirection( i, j, &zenith_angle, &azimuth); Number cos_angle = cos(view_zenith) * cos(zenith_angle) + sin(view_zenith) * sin(zenith_angle) * cos(view_azimuth - azimuth); if (acos(cos_angle).to(deg) < 0.1) { return measurements_.Get(i, j); } } } return RadianceSpectrum(0.0 * watt_per_square_meter_per_sr_per_nm); } Radiance MeasuredAtmosphere::GetAxiSymmetryError(Angle axis_azimuth) const { Radiance error = 0.0 * watt_per_square_meter_per_sr; for (int i = 0; i < 16; ++i) { Angle view_zenith = acos(Number((i + 0.5) / 16)); for (int j = 0; j < 64; ++j) { Angle view_azimuth = j / 64.0 * 2.0 * pi; Radiance err = Integral(measurements_(view_zenith, view_azimuth) - measurements_(view_zenith, axis_azimuth * 2.0 - view_azimuth)); error += err < 0.0 * watt_per_square_meter_per_sr ? -err : err; } } return error; } Angle MeasuredAtmosphere::EstimateSunAzimuth(Angle initial_azimuth) const { Angle min_sun_azimuth = initial_azimuth - 20.0 * deg; Angle max_sun_azimuth = initial_azimuth + 20.0 * deg; Radiance min_error = GetAxiSymmetryError(min_sun_azimuth); Angle best_sun_azimuth = min_sun_azimuth; Angle sun_azimuth = min_sun_azimuth; do { sun_azimuth = sun_azimuth + 0.2 * deg; Radiance error = GetAxiSymmetryError(sun_azimuth); if (error < min_error) { min_error = error; best_sun_azimuth = sun_azimuth; } } while (sun_azimuth < max_sun_azimuth); return best_sun_azimuth; }
#include "pch.h" GameSessionManager::GameSessionManager() { } GameSessionManager::~GameSessionManager() { } BOOL GameSessionManager::Begin(DWORD maxUserCount, SOCKET listenSocket) { CThreadSync Sync; m_ListenSocket = listenSocket; for (DWORD i = 0; i < maxUserCount; i++) { GameSession* user = new GameSession(); if (user->Begin()) m_UserSessionVector.push_back(user); else { End(); return FALSE; } } return TRUE; } BOOL GameSessionManager::End(VOID) { CThreadSync Sync; for (int i = 0; i < (int)m_UserSessionVector.size(); i++) { GameSession *user = m_UserSessionVector[i]; user->End(); delete user; } m_UserSessionVector.clear(); return TRUE; } BOOL GameSessionManager::AcceptAll(VOID) { CThreadSync Sync; for (int i = 0; i < (int)m_UserSessionVector.size(); i++) { GameSession *ConnectedUser = m_UserSessionVector[i]; if (!ConnectedUser->Accept(m_ListenSocket)) { End(); return FALSE; } //CLog::WriteDebugLog(_T("SOCKET : %d"), ConnectedUser->GetSocket()); } return TRUE; } BOOL GameSessionManager::WriteAll(DWORD protocol, BYTE * data, DWORD dataLength) { CThreadSync Sync; if (!data) return FALSE; for (int i = 0; i < (int)m_UserSessionVector.size(); i++) { GameSession *user = m_UserSessionVector[i]; if (user->GetIsConnected()) { if (!user->WritePacket(protocol, data, dataLength)) user->End(); } } return TRUE; } GameSession * GameSessionManager::GetSession(CPacketSession * pPacketSession) { CThreadSync Sync; for (DWORD i = 0; i < m_UserSessionVector.size(); i++) { if (m_UserSessionVector[i]->GetSocket() == pPacketSession->GetSocket()) { return m_UserSessionVector[i]; } } return NULL; }
// 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_Loop_HeaderFile #define _IGESSolid_Loop_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <TColStd_HArray1OfInteger.hxx> #include <IGESData_HArray1OfIGESEntity.hxx> #include <IGESData_IGESEntity.hxx> #include <Standard_Integer.hxx> class IGESBasic_HArray1OfHArray1OfInteger; class IGESBasic_HArray1OfHArray1OfIGESEntity; class IGESSolid_Loop; DEFINE_STANDARD_HANDLE(IGESSolid_Loop, IGESData_IGESEntity) //! defines Loop, Type <508> Form Number <1> //! in package IGESSolid //! A Loop entity specifies a bound of a face. It represents //! a connected collection of face boundaries, seams, and //! poles of a single face. //! //! From IGES-5.3, a Loop can be free with Form Number 0, //! else it is a bound of a face (it is the default) class IGESSolid_Loop : public IGESData_IGESEntity { public: Standard_EXPORT IGESSolid_Loop(); //! This method is used to set the fields of the class Loop //! - types : 0 = Edge; 1 = Vertex //! - edges : Pointer to the EdgeList or VertexList //! - index : Index of the edge into the EdgeList //! VertexList entity //! - orient : Orientation flag of the edge //! - nbParameterCurves : the number of parameter space curves //! for each edge //! - isoparametricFlags : the isoparametric flag of the //! parameter space curve //! - curves : the parameter space curves //! raises exception if length of types, edges, index, orient and //! nbParameterCurves do not match or the length of //! isoparametricFlags and curves do not match Standard_EXPORT void Init (const Handle(TColStd_HArray1OfInteger)& types, const Handle(IGESData_HArray1OfIGESEntity)& edges, const Handle(TColStd_HArray1OfInteger)& index, const Handle(TColStd_HArray1OfInteger)& orient, const Handle(TColStd_HArray1OfInteger)& nbParameterCurves, const Handle(IGESBasic_HArray1OfHArray1OfInteger)& isoparametricFlags, const Handle(IGESBasic_HArray1OfHArray1OfIGESEntity)& curves); //! Tells if a Loop is a Bound (FN 1) else it is free (FN 0) Standard_EXPORT Standard_Boolean IsBound() const; //! Sets or Unset the Bound Status (from Form Number) //! Default is True Standard_EXPORT void SetBound (const Standard_Boolean bound); //! returns the number of edge tuples Standard_EXPORT Standard_Integer NbEdges() const; //! returns the type of Index'th edge (0 = Edge, 1 = Vertex) //! raises exception if Index <= 0 or Index > NbEdges() Standard_EXPORT Standard_Integer EdgeType (const Standard_Integer Index) const; //! return the EdgeList or VertexList corresponding to the Index //! raises exception if Index <= 0 or Index > NbEdges() Standard_EXPORT Handle(IGESData_IGESEntity) Edge (const Standard_Integer Index) const; //! returns the orientation flag corresponding to Index'th edge //! raises exception if Index <= 0 or Index > NbEdges() Standard_EXPORT Standard_Boolean Orientation (const Standard_Integer Index) const; //! return the number of parameter space curves associated with //! Index'th Edge //! raises exception if Index <= 0 or Index > NbEdges() Standard_EXPORT Standard_Integer NbParameterCurves (const Standard_Integer Index) const; Standard_EXPORT Standard_Boolean IsIsoparametric (const Standard_Integer EdgeIndex, const Standard_Integer CurveIndex) const; //! returns the CurveIndex'th parameter space curve associated with //! EdgeIndex'th edge //! raises exception if EdgeIndex <= 0 or EdgeIndex > NbEdges() or //! if CurveIndex <= 0 or CurveIndex > NbParameterCurves(EdgeIndex) Standard_EXPORT Handle(IGESData_IGESEntity) ParametricCurve (const Standard_Integer EdgeIndex, const Standard_Integer CurveIndex) const; //! raises exception If num <= 0 or num > NbEdges() Standard_EXPORT Standard_Integer ListIndex (const Standard_Integer num) const; DEFINE_STANDARD_RTTIEXT(IGESSolid_Loop,IGESData_IGESEntity) protected: private: Handle(TColStd_HArray1OfInteger) theTypes; Handle(IGESData_HArray1OfIGESEntity) theEdges; Handle(TColStd_HArray1OfInteger) theIndex; Handle(TColStd_HArray1OfInteger) theOrientationFlags; Handle(TColStd_HArray1OfInteger) theNbParameterCurves; Handle(IGESBasic_HArray1OfHArray1OfInteger) theIsoparametricFlags; Handle(IGESBasic_HArray1OfHArray1OfIGESEntity) theCurves; }; #endif // _IGESSolid_Loop_HeaderFile
#ifndef RADWINDOW_HPP_ #define RADWINDOW_HPP_ #include "MWindowBase.hpp" #include "MRubberBand.hpp" #include "DialogRes.hpp" #include <set> #include <map> class MRadCtrl : public MWindowBase { public: BOOL m_bTopCtrl; HWND m_hwndRubberBand; BOOL m_bMoving; BOOL m_bSizing; INT m_nIndex; POINT m_pt; MRadCtrl() : m_bTopCtrl(FALSE), m_hwndRubberBand(NULL), m_bMoving(FALSE), m_bSizing(FALSE), m_nIndex(-1) { m_pt.x = m_pt.y = -1; } typedef std::set<HWND> set_type; static set_type& GetTargets() { static set_type s_set; return s_set; } static HWND& GetLastSel() { static HWND s_hwnd = NULL; return s_hwnd; } MRubberBand *GetRubberBand() { MWindowBase *base = GetUserData(m_hwndRubberBand); if (base) { MRubberBand *band = static_cast<MRubberBand *>(base); return band; } return NULL; } static MRadCtrl *GetRadCtrl(HWND hwnd) { MWindowBase *base = GetUserData(hwnd); if (base) { MRadCtrl *pCtrl; pCtrl = static_cast<MRadCtrl *>(base); return pCtrl; } return NULL; } static void DeselectSelection() { set_type::iterator it, end = GetTargets().end(); for (it = GetTargets().begin(); it != end; ++it) { MRadCtrl *pCtrl = GetRadCtrl(*it); if (pCtrl) { ::DestroyWindow(pCtrl->m_hwndRubberBand); pCtrl->m_hwndRubberBand = NULL; } } GetTargets().clear(); GetLastSel() = NULL; } static void DeleteSelection(HWND hwnd = NULL) { set_type::iterator it, end = GetTargets().end(); for (it = GetTargets().begin(); it != end; ++it) { if (hwnd == *it) continue; MRadCtrl *pCtrl = GetRadCtrl(*it); if (pCtrl) { ::DestroyWindow(pCtrl->m_hwndRubberBand); pCtrl->m_hwndRubberBand = NULL; ::DestroyWindow(*pCtrl); } } GetTargets().clear(); GetLastSel() = NULL; } void Deselect() { MRubberBand *band = GetRubberBand(); if (band) { ::DestroyWindow(*band); } GetTargets().erase(m_hwnd); m_hwndRubberBand = NULL; GetLastSel() = NULL; } static void Select(HWND hwnd) { if (hwnd == NULL) return; MRadCtrl *pCtrl = GetRadCtrl(hwnd); if (pCtrl == NULL) return; MRubberBand *band = new MRubberBand; band->CreateDx(GetParent(hwnd), hwnd, TRUE); pCtrl->m_hwndRubberBand = *band; GetTargets().insert(hwnd); GetLastSel() = hwnd; } static void MoveSelection(HWND hwnd, INT dx, INT dy) { set_type::iterator it, end = GetTargets().end(); for (it = GetTargets().begin(); it != end; ++it) { if (hwnd == *it) continue; MRadCtrl *pCtrl = GetRadCtrl(*it); if (pCtrl) { RECT rc; ::GetWindowRect(*pCtrl, &rc); ::MapWindowPoints(NULL, ::GetParent(*pCtrl), (LPPOINT)&rc, 2); OffsetRect(&rc, dx, dy); pCtrl->m_bMoving = TRUE; pCtrl->SetWindowPosDx((LPPOINT)&rc); pCtrl->m_bMoving = FALSE; } } } static void ResizeSelection(HWND hwnd, INT cx, INT cy) { set_type::iterator it, end = GetTargets().end(); for (it = GetTargets().begin(); it != end; ++it) { if (hwnd == *it) continue; MRadCtrl *pCtrl = GetRadCtrl(*it); if (pCtrl && !pCtrl->m_bSizing) { pCtrl->m_bSizing = TRUE; SIZE siz = { cx , cy }; pCtrl->SetWindowPosDx(NULL, &siz); pCtrl->m_bSizing = FALSE; MRubberBand *band = pCtrl->GetRubberBand(); if (band) { band->FitToTarget(); } } } } virtual LRESULT CALLBACK WindowProcDx(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { HANDLE_MSG(hwnd, WM_NCHITTEST, OnNCHitTest); HANDLE_MSG(hwnd, WM_KEYDOWN, OnKey); HANDLE_MSG(hwnd, WM_NCLBUTTONDOWN, OnNCLButtonDown); HANDLE_MSG(hwnd, WM_NCLBUTTONDBLCLK, OnNCLButtonDown); HANDLE_MSG(hwnd, WM_NCMOUSEMOVE, OnNCMouseMove); HANDLE_MSG(hwnd, WM_NCLBUTTONUP, OnNCLButtonUp); HANDLE_MSG(hwnd, WM_MOVE, OnMove); HANDLE_MSG(hwnd, WM_SIZE, OnSize); HANDLE_MSG(hwnd, WM_LBUTTONDBLCLK, OnLButtonDown); HANDLE_MSG(hwnd, WM_LBUTTONDOWN, OnLButtonDown); HANDLE_MSG(hwnd, WM_LBUTTONUP, OnLButtonUp); HANDLE_MSG(hwnd, WM_MOUSEMOVE, OnMouseMove); HANDLE_MSG(hwnd, WM_NCRBUTTONDOWN, OnNCRButtonDown); HANDLE_MSG(hwnd, WM_NCRBUTTONDBLCLK, OnNCRButtonDown); HANDLE_MSG(hwnd, WM_NCRBUTTONUP, OnNCRButtonUp); case WM_MOVING: case WM_SIZING: return 0; } return DefaultProcDx(hwnd, uMsg, wParam, lParam); } void OnNCRButtonDown(HWND hwnd, BOOL fDoubleClick, int x, int y, UINT codeHitTest) { if (fDoubleClick) return; SendMessage(GetParent(hwnd), WM_NCRBUTTONDOWN, (WPARAM)hwnd, MAKELPARAM(x, y)); } void OnNCRButtonUp(HWND hwnd, int x, int y, UINT codeHitTest) { } void OnLButtonDown(HWND hwnd, BOOL fDoubleClick, int x, int y, UINT keyFlags) { } void OnLButtonUp(HWND hwnd, int x, int y, UINT keyFlags) { } void OnMouseMove(HWND hwnd, int x, int y, UINT keyFlags) { } void OnMove(HWND hwnd, int x, int y) { if (!m_bTopCtrl) { DefaultProcDx(hwnd, WM_MOVE, 0, MAKELPARAM(x, y)); return; } if (!m_bMoving) { POINT pt; ::GetCursorPos(&pt); MoveSelection(hwnd, pt.x - m_pt.x, pt.y - m_pt.y); m_pt = pt; } MRubberBand *band = GetRubberBand(); if (band) { band->FitToTarget(); } RECT rc; ::GetClientRect(hwnd, &rc); ::InvalidateRect(hwnd, &rc, TRUE); } void OnSize(HWND hwnd, UINT state, int cx, int cy) { DefaultProcDx(hwnd, WM_SIZE, 0, MAKELPARAM(cx, cy)); if (!m_bTopCtrl) { return; } if (!m_bSizing) ResizeSelection(hwnd, cx, cy); } void OnKey(HWND hwnd, UINT vk, BOOL fDown, int cRepeat, UINT flags) { if (fDown) { FORWARD_WM_KEYDOWN(GetParent(hwnd), vk, cRepeat, flags, SendMessage); } } void OnNCLButtonDown(HWND hwnd, BOOL fDoubleClick, int x, int y, UINT codeHitTest) { ::GetCursorPos(&m_pt); if (fDoubleClick) return; if (codeHitTest != HTCAPTION) return; if (GetKeyState(VK_CONTROL) < 0) { if (m_hwndRubberBand) { Deselect(); return; } } else if (GetKeyState(VK_SHIFT) < 0) { if (m_hwndRubberBand) { return; } } else { if (m_hwndRubberBand) { ; } else { DeselectSelection(); } } if (m_hwndRubberBand == NULL) { Select(hwnd); } HWND hwndPrev = GetWindow(hwnd, GW_HWNDPREV); ::DefWindowProc(hwnd, WM_NCLBUTTONDOWN, HTCAPTION, MAKELPARAM(x, y)); SetWindowPosDx(NULL, NULL, hwndPrev); } void OnNCMouseMove(HWND hwnd, int x, int y, UINT codeHitTest) { ::DefWindowProc(hwnd, WM_NCMOUSEMOVE, codeHitTest, MAKELPARAM(x, y)); } void OnNCLButtonUp(HWND hwnd, int x, int y, UINT codeHitTest) { m_bMoving = FALSE; m_pt.x = -1; m_pt.y = -1; ::DefWindowProc(hwnd, WM_NCLBUTTONUP, codeHitTest, MAKELPARAM(x, y)); } UINT OnNCHitTest(HWND hwnd, int x, int y) { if (m_bTopCtrl) { return HTCAPTION; } return HTTRANSPARENT; } virtual void PostNcDestroy() { m_hwnd = NULL; delete this; } }; class MRadDialog : public MDialogBase { public: HWND GetNextCtrl(HWND hwndCtrl) const { HWND hwndNext = GetNextWindow(hwndCtrl, GW_HWNDNEXT); if (hwndNext == NULL) { hwndNext = GetNextWindow(hwndCtrl, GW_HWNDFIRST); } TCHAR szClass[64]; while (hwndNext) { ::GetClassName(hwndNext, szClass, _countof(szClass)); if (lstrcmpi(szClass, MRubberBand().GetWndClassNameDx()) != 0) break; hwndNext = GetNextWindow(hwndNext, GW_HWNDNEXT); } if (hwndNext == NULL) { hwndNext = GetNextWindow(hwndCtrl, GW_HWNDFIRST); } return hwndNext; } HWND GetPrevCtrl(HWND hwndCtrl) const { HWND hwndPrev = GetNextWindow(hwndCtrl, GW_HWNDPREV); if (hwndPrev == NULL) { hwndPrev = GetNextWindow(hwndCtrl, GW_HWNDLAST); } TCHAR szClass[64]; while (hwndPrev) { ::GetClassName(hwndPrev, szClass, _countof(szClass)); if (lstrcmpi(szClass, MRubberBand().GetWndClassNameDx()) != 0) break; hwndPrev = GetNextWindow(hwndPrev, GW_HWNDPREV); } if (hwndPrev == NULL) { hwndPrev = GetNextWindow(hwndCtrl, GW_HWNDLAST); } return hwndPrev; } virtual INT_PTR CALLBACK DialogProcDx(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { HANDLE_MSG(hwnd, WM_INITDIALOG, OnInitDialog); HANDLE_MSG(hwnd, WM_LBUTTONDOWN, OnLButtonDown); HANDLE_MSG(hwnd, WM_LBUTTONDBLCLK, OnLButtonDown); } return DefaultProcDx(hwnd, uMsg, wParam, lParam); } void OnLButtonDown(HWND hwnd, BOOL fDoubleClick, int x, int y, UINT keyFlags) { if (::GetKeyState(VK_SHIFT) < 0 || ::GetKeyState(VK_CONTROL) < 0) return; MRadCtrl::DeselectSelection(); } virtual LRESULT CALLBACK WindowProcDx(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { HANDLE_MSG(hwnd, WM_NCLBUTTONDBLCLK, OnNCLButtonDown); HANDLE_MSG(hwnd, WM_NCLBUTTONDOWN, OnNCLButtonDown); HANDLE_MSG(hwnd, WM_NCLBUTTONUP, OnNCLButtonUp); HANDLE_MSG(hwnd, WM_NCRBUTTONDBLCLK, OnNCRButtonDown); HANDLE_MSG(hwnd, WM_NCRBUTTONDOWN, OnNCRButtonDown); HANDLE_MSG(hwnd, WM_NCRBUTTONUP, OnNCRButtonUp); HANDLE_MSG(hwnd, WM_NCMOUSEMOVE, OnNCMouseMove); HANDLE_MSG(hwnd, WM_KEYDOWN, OnKey); } return CallWindowProcDx(hwnd, uMsg, wParam, lParam); } void OnNCLButtonDown(HWND hwnd, BOOL fDoubleClick, int x, int y, UINT codeHitTest) { } void OnNCLButtonUp(HWND hwnd, int x, int y, UINT codeHitTest) { } void OnNCRButtonDown(HWND hwnd, BOOL fDoubleClick, int x, int y, UINT codeHitTest) { if (fDoubleClick) return; FORWARD_WM_CONTEXTMENU(GetParent(hwnd), hwnd, x, y, SendMessage); } void OnNCRButtonUp(HWND hwnd, int x, int y, UINT codeHitTest) { } void OnNCMouseMove(HWND hwnd, int x, int y, UINT codeHitTest) { } void OnKey(HWND hwnd, UINT vk, BOOL fDown, int cRepeat, UINT flags) { if (fDown) { FORWARD_WM_KEYDOWN(GetParent(hwnd), vk, cRepeat, flags, SendMessage); } } void DoSubclass(HWND hCtrl, BOOL bTop) { MRadCtrl *pCtrl = new MRadCtrl; pCtrl->SubclassDx(hCtrl); pCtrl->m_bTopCtrl = bTop; DoSubclassChildren(hCtrl); } void DoSubclassChildren(HWND hwnd, BOOL bTop = FALSE) { HWND hCtrl = GetTopWindow(hwnd); if (bTop) { INT nIndex = 0; while (hCtrl) { DoSubclass(hCtrl, bTop); MRadCtrl *pCtrl = MRadCtrl::GetRadCtrl(hCtrl); pCtrl->m_nIndex = nIndex; hCtrl = GetWindow(hCtrl, GW_HWNDNEXT); ++nIndex; } } else { while (hCtrl) { DoSubclass(hCtrl, bTop); hCtrl = GetWindow(hCtrl, GW_HWNDNEXT); } } } BOOL OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam) { POINT pt = { 0, 0 }; SetWindowPosDx(&pt); SubclassDx(hwnd); DoSubclassChildren(hwnd, TRUE); return FALSE; } }; struct MRadWindow : MWindowBase { INT m_xDialogBaseUnit; INT m_yDialogBaseUnit; HHOOK m_mouse_hook; MRadDialog m_rad_dialog; DialogRes m_dialog_res; static MRadWindow *s_p_rad_window; MRadWindow() : m_xDialogBaseUnit(0), m_yDialogBaseUnit(0), m_mouse_hook(NULL) { } ~MRadWindow() { } static HWND GetPrimaryControl(HWND hwnd, HWND hwndDialog) { for (;;) { if (GetParent(hwnd) == NULL || GetParent(hwnd) == hwndDialog) return hwnd; hwnd = GetParent(hwnd); } } void FitToRadDialog() { RECT Rect; GetWindowRect(m_rad_dialog, &Rect); SIZE Size; Size.cx = Rect.right - Rect.left; Size.cy = Rect.bottom - Rect.top; DWORD style = GetWindowLong(m_hwnd, GWL_STYLE); DWORD exstyle = GetWindowLong(m_hwnd, GWL_EXSTYLE); SetRect(&Rect, 0, 0, Size.cx, Size.cy); AdjustWindowRectEx(&Rect, style, FALSE, exstyle); OffsetRect(&Rect, -Rect.left, -Rect.top); MoveWindow(m_hwnd, 0, 0, Rect.right, Rect.bottom, TRUE); } virtual LPCTSTR GetWndClassNameDx() const { return TEXT("katahiromz's MRadWindow Class"); } virtual void ModifyWndClassDx(WNDCLASSEX& wcx) { wcx.hIcon = NULL; wcx.hbrBackground = GetStockBrush(DKGRAY_BRUSH); wcx.hIconSm = NULL; } BOOL OnCreate(HWND hwnd, LPCREATESTRUCT lpCreateStruct) { m_dialog_res.Fixup(FALSE); std::vector<BYTE> data = m_dialog_res.data(); m_dialog_res.Fixup(TRUE); if (!m_rad_dialog.CreateDialogIndirectDx(hwnd, &data[0])) { return FALSE; } FitToRadDialog(); ShowWindow(m_rad_dialog, SW_SHOWNORMAL); UpdateWindow(m_rad_dialog); return TRUE; } void OnDestroy(HWND hwnd) { } virtual LRESULT CALLBACK WindowProcDx(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { HANDLE_MSG(hwnd, WM_CREATE, OnCreate); HANDLE_MSG(hwnd, WM_SIZE, OnSize); HANDLE_MSG(hwnd, WM_DESTROY, OnDestroy); HANDLE_MSG(hwnd, WM_CONTEXTMENU, OnContextMenu); HANDLE_MSG(hwnd, WM_KEYDOWN, OnKey); HANDLE_MSG(hwnd, WM_COMMAND, OnCommand); } return DefaultProcDx(hwnd, uMsg, wParam, lParam); } void OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify) { switch (id) { case IDM_TEST2: MsgBoxDx(TEXT("IDM_TEST2"), MB_ICONINFORMATION); break; case IDM_TEST3: MRadCtrl::DeleteSelection(); break; } } void OnKey(HWND hwnd, UINT vk, BOOL fDown, int cRepeat, UINT flags) { HWND hwndPrev, hwndNext; RECT rc; if (!fDown) return; HWND hwndTarget = MRadCtrl::GetLastSel(); if (hwndTarget == NULL && !MRadCtrl::GetTargets().empty()) { hwndTarget = *MRadCtrl::GetTargets().begin(); } MRadCtrl *pCtrl = MRadCtrl::GetRadCtrl(hwndTarget); switch (vk) { case VK_TAB: if (GetKeyState(VK_SHIFT) < 0) { if (hwndTarget == NULL) { hwndTarget = GetWindow(m_rad_dialog, GW_HWNDLAST); } else { hwndTarget = m_rad_dialog.GetPrevCtrl(hwndTarget); } MRadCtrl::DeselectSelection(); MRadCtrl::Select(hwndTarget); } else { if (hwndTarget == NULL) { hwndTarget = GetWindow(m_rad_dialog, GW_HWNDFIRST); } else { hwndTarget = m_rad_dialog.GetNextCtrl(hwndTarget); } MRadCtrl::DeselectSelection(); MRadCtrl::Select(hwndTarget); } break; case VK_UP: if (pCtrl == NULL) { return; } if (GetKeyState(VK_SHIFT) < 0) { GetWindowRect(*pCtrl, &rc); MapWindowRect(NULL, m_rad_dialog, &rc); SIZE siz = SizeFromRectDx(&rc); siz.cy -= 1; MRadCtrl::ResizeSelection(NULL, siz.cx, siz.cy); } else { MRadCtrl::MoveSelection(NULL, 0, -1); } break; case VK_DOWN: if (pCtrl == NULL) { return; } if (GetKeyState(VK_SHIFT) < 0) { GetWindowRect(*pCtrl, &rc); MapWindowRect(NULL, m_rad_dialog, &rc); SIZE siz = SizeFromRectDx(&rc); siz.cy += 1; MRadCtrl::ResizeSelection(NULL, siz.cx, siz.cy); } else { MRadCtrl::MoveSelection(NULL, 0, +1); } break; case VK_LEFT: if (pCtrl == NULL) { return; } if (GetKeyState(VK_SHIFT) < 0) { GetWindowRect(*pCtrl, &rc); MapWindowRect(NULL, m_rad_dialog, &rc); SIZE siz = SizeFromRectDx(&rc); siz.cx -= 1; MRadCtrl::ResizeSelection(NULL, siz.cx, siz.cy); } else { MRadCtrl::MoveSelection(NULL, -1, 0); } break; case VK_RIGHT: if (pCtrl == NULL) { return; } if (GetKeyState(VK_SHIFT) < 0) { GetWindowRect(*pCtrl, &rc); MapWindowRect(NULL, m_rad_dialog, &rc); SIZE siz = SizeFromRectDx(&rc); siz.cx += 1; MRadCtrl::ResizeSelection(NULL, siz.cx, siz.cy); } else { MRadCtrl::MoveSelection(NULL, +1, 0); } break; case VK_DELETE: MRadCtrl::DeleteSelection(); break; default: return; } } void OnContextMenu(HWND hwnd, HWND hwndContext, UINT xPos, UINT yPos) { HMENU hMenu = LoadMenu(GetModuleHandle(NULL), MAKEINTRESOURCE(2)); HMENU hSubMenu = GetSubMenu(hMenu, 0); ::SetForegroundWindow(hwnd); ::TrackPopupMenu(hSubMenu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, xPos, yPos, 0, hwnd, NULL); ::PostMessage(hwnd, WM_NULL, 0, 0); } BOOL GetBaseUnits(INT& xDialogBaseUnit, INT& yDialogBaseUnit) { if (m_xDialogBaseUnit == 0) { m_xDialogBaseUnit = m_dialog_res.GetBaseUnits(m_yDialogBaseUnit); if (m_xDialogBaseUnit == 0) { return FALSE; } } xDialogBaseUnit = m_xDialogBaseUnit; yDialogBaseUnit = m_yDialogBaseUnit; return TRUE; } virtual void Update(HWND hwnd) { } void OnSize(HWND hwnd, UINT state, int cx, int cy) { m_dialog_res.Update(); INT xDialogBaseUnit, yDialogBaseUnit; if (!GetBaseUnits(xDialogBaseUnit, yDialogBaseUnit)) return; RECT Rect1; GetClientRect(m_hwnd, &Rect1); INT cxPixels = Rect1.right - Rect1.left; INT cyPixels = Rect1.bottom - Rect1.top; MoveWindow(m_rad_dialog, 0, 0, cxPixels, cyPixels, TRUE); RECT Rect2; GetClientRect(m_rad_dialog, &Rect2); INT cxDialog = MulDiv((Rect2.right - Rect2.left), 4, xDialogBaseUnit); INT cyDialog = MulDiv((Rect2.bottom - Rect2.top), 8, yDialogBaseUnit); m_dialog_res.m_siz.cx = cxDialog; m_dialog_res.m_siz.cy = cyDialog; cxPixels = MulDiv(cxDialog, xDialogBaseUnit, 4); cyPixels = MulDiv(cyDialog, yDialogBaseUnit, 8); SetRect(&Rect2, 0, 0, cxPixels, cyPixels); DWORD style = GetWindowStyle(m_rad_dialog); DWORD exstyle = GetWindowExStyle(m_rad_dialog); AdjustWindowRectEx(&Rect2, style, FALSE, exstyle); OffsetRect(&Rect2, -Rect2.left, -Rect2.top); cxPixels = Rect2.right; cyPixels = Rect2.bottom; MoveWindow(m_rad_dialog, 0, 0, cxPixels, cyPixels, TRUE); Update(hwnd); } }; #endif // ndef RADWINDOW_HPP_
#pragma once namespace Jaraffe { // TODO : Àӽà ¼ÂÆÃ. class Material : public Jaraffe::Object { // **************************************************************************** // Constructor/Destructor) // ---------------------------------------------------------------------------- public: Material(); virtual ~Material(); // **************************************************************************** // Public Members) // ---------------------------------------------------------------------------- public: Jaraffe::Light::Material m_Material; Jaraffe::Texture* m_MainTexture; // **************************************************************************** // static Public Functions) // ---------------------------------------------------------------------------- public: static Material* GetDefalutMaterial(); // **************************************************************************** // static private Members) // ---------------------------------------------------------------------------- private: static Material m_pDefalutMaterial; }; }
// https://github.com/vinniefalco/LuaBridge // // Copyright 2018, Dmitry Tarakanov // SPDX-License-Identifier: MIT #pragma once #include <LuaBridge/detail/Stack.h> #include <array> namespace luabridge { template <class T, std::size_t s> struct Stack <std::array <T,s> > { static void push (lua_State* L, std::array <T,s> const& array) { lua_createtable (L, static_cast <int> (s), 0); for (std::size_t i = 0; i < s; ++i) { lua_pushinteger (L, static_cast <lua_Integer> (i + 1)); Stack <T>::push (L, array [i]); lua_settable (L, -3); } } static std::array <T, s> get (lua_State* L, int index) { if (!lua_istable (L, index)) { luaL_error (L, "#%d argments must be table", index); } if (index != s) { luaL_error (L, "array size should be %d ", s); } std::array <T, s> array; int const absindex = lua_absindex (L, index); lua_pushnil (L); int arr_index = 0; while (lua_next (L, absindex) != 0) { array[arr_index] = Stack <T>::get (L, -1); lua_pop (L, 1); arr_index++; } return array; } }; } // namespace luabridge
// // Created by 송지원 on 2020-03-13. // #include <iostream> #define UPPER(X,R) ((X)%(R)==0) ? ((X)/(R)) : (((X)/(R))+1) using namespace std; int arr[100000+5]; int main() { int N, K; int I; int L, R; scanf("%d %d", &N, &K); for (int i=0; i<N; i++) { scanf("%d", &arr[i]); if (arr[i] == 1) { I = i; } } L = I - K + 1; R = I; int sum = N; for (; L<=I; ) { int left = UPPER(L, K-1); int right = UPPER(N-1 - R, K-1); int sum_temp = left + right + 1; if (sum_temp < sum) { sum = sum_temp; } L++; R++; } printf("%d\n", sum); return 0; }
#include "Value.h" #include <iostream> void Value::Parse(std::string) { } namespace Parser { std::string FindRange(int p,std::vector<std::string>* w) { std::string d = ""; return d; } }
/* * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file tests/Audit/FakeAuditWrapper.h * @author Aleksander Zdyb <a.zdyb@samsung.com> * @version 1.0 */ #ifndef TESTS_AUDIT_FAKEAUDITWRAPPER_H #define TESTS_AUDIT_FAKEAUDITWRAPPER_H #include <gmock/gmock.h> #include <gtest/gtest.h> #include <Audit/BaseAuditWrapper.h> class FakeAuditWrapper : public Audit::BaseAuditWrapper { public: using BaseAuditWrapper::BaseAuditWrapper; MOCK_METHOD0(audit_open, int(void)); MOCK_METHOD1(audit_close, void(int fd)); MOCK_METHOD4(audit_add_rule_data, int(int fd, struct audit_rule_data *rule, int flags, int action)); MOCK_METHOD4(audit_delete_rule_data, int(int fd, struct audit_rule_data *rule, int flags, int action)); MOCK_METHOD2(audit_rule_syscallbyname_data, int(struct audit_rule_data *rule, const char *scall)); MOCK_METHOD3(audit_rule_fieldpair_data, int(struct audit_rule_data **rulep, const char *pair, int flags)); MOCK_METHOD1(audit_rule_free_data, void(struct audit_rule_data *rule)); MOCK_METHOD0(create_rule_data, struct audit_rule_data *(void)); MOCK_CONST_METHOD0(MAX_AUDIT_MESSAGE_LENGTH_CONST, int(void)); MOCK_CONST_METHOD0(AUDIT_FILTER_EXIT_CONST, int(void)); MOCK_CONST_METHOD0(AUDIT_ALWAYS_CONST, int(void)); }; #endif /* TESTS_AUDIT_FAKEAUDITWRAPPER_H */
// // Created by JACK on 11/6/2015. // #include "Vehicle.h" Vehicle::Vehicle(): Transport(),name(""),price(0) { } Vehicle::Vehicle(string trans,string name,int price): Transport(trans),name(name),price(price) { } Vehicle::Vehicle(const Vehicle& vehicle1): Transport(vehicle1),name(vehicle1.name),price(vehicle1.price) { } Vehicle& Vehicle::operator=(const Vehicle& obj) { if(this == &obj) { return *this; } Transport::operator=((const Transport&)(obj)); name = obj.name; price = obj.price; return *this; } istream& operator>>(istream& in, Vehicle& obj) { in >> (Transport&)(obj); cout << "Input name : "; in >> obj.name; cout << "Input price : "; in >> obj.price; return in; } ostream& operator<<(ostream& out, const Vehicle& obj) { out << dynamic_cast<const Transport&>(obj); out << "\nName : " << obj.name; out << "\nPrice : " << obj.price; return out; } Vehicle::~Vehicle() { name = ""; price = 0; }
// g++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` c/pyGetData.cpp -lodbc -fpermissive -o /home/bwp/miniconda3/lib/python3.7/site-packages/quantitate`python3-config --extension-suffix` #include <iostream> #include <string> #include <sqlext.h> #include <sqltypes.h> #include <sql.h> #include <stdio.h> #include <cstdlib> #include <map> #include <bits/stdc++.h> #include <iterator> #include <new> #include <vector> #include <pybind11/pybind11.h> #include <pybind11/stl.h> namespace py = pybind11; using namespace std; class DB { public: SQLHENV henv; SQLHDBC hdbc; SQLHSTMT hstmt; SQLRETURN retcode; SQLCHAR * OutConnStr = (SQLCHAR * )malloc(255); SQLSMALLINT * OutConnStrLen = (SQLSMALLINT *)malloc(255); SQLHSTMT connect(SQLCHAR* query){ retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv); // Set the ODBC version environment attribute if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) { retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); // Allocate connection handle if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) { retcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc); // Set login timeout to 5 seconds if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) { SQLSetConnectAttr(hdbc, SQL_LOGIN_TIMEOUT, (SQLPOINTER)5, 0); // Connect to data source retcode = SQLConnect(hdbc, (SQLCHAR*) "mssql", SQL_NTS, (SQLCHAR*) "QuantitateAdmin", 15, (SQLCHAR*) "SomeRandomPassword1", 19); // Allocate statement handle if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) { cout << "Success!" << endl; retcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt); // Process data if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) { if (SQL_SUCCESS != SQLExecDirect(hstmt, query, SQL_NTS)) { cout << "Error querying SQL Server" << endl; disconnect(); } else { return hstmt; } } } } } } } void disconnect(){ SQLFreeHandle(SQL_HANDLE_STMT, hstmt); SQLFreeHandle(SQL_HANDLE_ENV, henv); SQLDisconnect(hdbc); SQLFreeHandle(SQL_HANDLE_DBC, hdbc); } }; class getData { public: #define dataLen 20 SQLHSTMT hstmt; SQLRETURN retcode; map<string, SQLREAL> dataMap; map<string, float> priceMap; map<string, float> positionMap; map<string, SQLLEN> ptrMap; float roi = 1.; vector<string> items; vector<string> tickers; getData(string sQuery, vector<string> userItems, vector<string> userTickers){ tickers = userTickers; items = userItems; char* query = sQuery.c_str(); hstmt = DB().connect(query); bindColumns(); SQLFetch(hstmt); updatePrices(); } void bindColumns(){ string column; string ticker; int itemsLen = items.size(); for(int i = 0; i < tickers.size(); i++){ ticker = tickers.at(i); positionMap[ticker] = 0; for(int j = 0; j < itemsLen; j++){ column = ticker + '.' + items.at(j); SQLBindCol(hstmt, i*itemsLen+j+1, SQL_C_FLOAT, (SQLPOINTER)&dataMap[column], dataLen, ptrMap[column]); } } } void updatePrices(){ string ticker; for(int i = 0; i < tickers.size(); i++){ ticker = tickers.at(i); priceMap[ticker] = dataMap[ticker + ".open"]; } } bool next(){ retcode = SQLFetch(hstmt); roi = roi * increase(); updatePrices(); if(retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO){ return true; } else { DB().disconnect(); return false; } } float increase(){ float total = 1; float increase; float totalReturn = 1; string ticker; for(int i = 0; i < tickers.size(); i++){ ticker = tickers.at(i); increase = dataMap[ticker + ".open"]/priceMap[ticker] - 1; total += positionMap[ticker] * increase; totalReturn += positionMap[ticker] * increase; } for(int i = 0; i < tickers.size(); i++){ ticker = tickers.at(i); positionMap[ticker] = positionMap[ticker] * (dataMap[ticker + ".open"] / priceMap[ticker]) / total; } return totalReturn; } map<string, float> data(){ return dataMap; } void buy(string ticker, float position){ positionMap[ticker] = position; } float returnOnInvestment(){ return roi; } map<string, float> prices(){ return priceMap; } map<string, float> positions(){ return positionMap; } }; PYBIND11_MODULE(quantitate, m){ py::class_<getData>(m, "getData") .def(py::init<string &, vector<string>, vector<string>>()) .def("next", &getData::next) .def("data", &getData::data) .def("roi", &getData::returnOnInvestment) .def("prices", &getData::prices) .def("buy", &getData::buy) .def("positions", &getData::positions); }
#pragma once #include"common.h" //考虑线程安全,采用单例模式 class CentralCache { public: static CentralCache* GetInstance() { return &Inst; } //从中心缓存取出一定量内存给线程缓存 size_t FetchRangeObj(void*& start, void*& end, size_t n, size_t byte); //将一定数量内存释放到span跨度 void ReleaseListToSpans(void* strat, size_t byte_size); Span* GetOneSpan(SpanList* spanlist, size_t size); private: SpanList spanlist[NLIST]; // private: static CentralCache Inst; CentralCache() = default; CentralCache(const CentralCache&) = delete; CentralCache& operator= (const CentralCache&) = delete; };
#include "Game.hpp" Game::Game(){ ball = 1; }; void Game::ballDrain(){ };
// random_gens.cpp #include "BlobCrystallinOligomer/random_gens.h" namespace random_gens { RandomGens::RandomGens() { std::random_device true_random_engine {}; auto seed {true_random_engine()}; m_random_engine.seed(seed); } double RandomGens::uniform_real() { return m_uniform_real_dist(m_random_engine); } int RandomGens::uniform_int(int lower, int upper) { // Check if distribution used previously pair<int, int> key {lower, upper}; if (m_uniform_int_dists.find(key) != m_uniform_int_dists.end()) { auto dist {m_uniform_int_dists.at(key)}; return dist(m_random_engine); } // If not, make it and store it else { uniform_int_distribution<int>* dist { new uniform_int_distribution<int> {lower, upper}}; int random_int {(*dist)(m_random_engine)}; m_int_dists.emplace_back(dist); m_uniform_int_dists.insert({key, *m_int_dists.back()}); return random_int; } } }
class Solution { public: int minCut(string s) { if(s.empty()) return 0; int len = s.size(); vector<int> dp(len+1,0); dp[len] = -1; vector<vector<bool> > p(len+1,vector<bool> (len+1,false)); for(int i=len-1; i>=0; --i){ dp[i] = INT_MAX; for(int j=i; j<len; ++j){ if(s[j] == s[i] && (j-i < 2 || p[i+1][j-1])){ p[i][j] = true; dp[i] = min(dp[i],dp[j+1] + 1); } } } return dp[0]; } };
#include <iostream> using namespace std; class Reynold { public: double velocity; double viscosity; double reynold; }; double reynoldnum(int type) { float diameter; cout << "Please enter your fluid selection: "; cin >> type; cout << "Please enter the pipe diamater: "; cin >> diameter; //object of gasoline Reynold gasoline; gasoline.velocity = 0.09; gasoline.viscosity = 311 / 500000000; gasoline.reynold = (gasoline.velocity * diameter) / gasoline.viscosity; //object of fuel oil Reynold fueloil; fueloil.velocity = 0.09; fueloil.viscosity = 3523 / 1000000000; fueloil.reynold = (fueloil.velocity * diameter) / fueloil.viscosity; //object of lubricating oil Reynold lubricatingoil; lubricatingoil.velocity = 0.09; lubricatingoil.viscosity = 95966 / 1000000000; lubricatingoil.reynold = (lubricatingoil.velocity * diameter) / lubricatingoil.viscosity; //object of water Reynold water; water.velocity = 0.09; water.viscosity = 8999 / 1000000000; water.reynold = (water.velocity * diameter) / water.viscosity; //Reynold's Number = (average velocity * internal pipe diameter) / kinematic viscosity switch(type) { case '1': { return gasoline.reynold; } break; case '2': { return fueloil.reynold; } break; case '3': { return lubricatingoil.reynold; } break; case '4': { return water.reynold; } break; default : cout << "We currently don't have that fluid type"; // no break for default } } int main() { int type; cout << "\nMenu of Fluids\n"; cout << "==========\n"; cout << "1 - gasoline\n"; cout << "2 - fuel oil\n"; cout << "3 - lubricating oil\n"; cout << "4 - water\n"; double rey = reynoldnum(type); cout << "\nYour fluid's Reynold's Number is " << rey; cout << "\n"; if (rey < 2000) { cout << "You have a laminar flow"; } else if (2000 <= rey <= 3000) { cout << "You have a transition flow"; } else if (3000 < rey) { cout << "You have a turbulent flow"; } return 0; }
// Created on: 2014-03-17 // Created by: Kirill GAVRILOV // 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 OpenGl_GlCore43_HeaderFile #define OpenGl_GlCore43_HeaderFile #include <OpenGl_GlCore42.hxx> //! OpenGL 4.3 definition. struct OpenGl_GlCore43 : public OpenGl_GlCore42 { private: typedef OpenGl_GlCore42 theBaseClass_t; public: //! @name OpenGL 4.3 additives to 4.2 using theBaseClass_t::glClearBufferData; using theBaseClass_t::glClearBufferSubData; using theBaseClass_t::glDispatchCompute; using theBaseClass_t::glDispatchComputeIndirect; using theBaseClass_t::glCopyImageSubData; using theBaseClass_t::glFramebufferParameteri; using theBaseClass_t::glGetFramebufferParameteriv; using theBaseClass_t::glGetInternalformati64v; using theBaseClass_t::glInvalidateTexSubImage; using theBaseClass_t::glInvalidateTexImage; using theBaseClass_t::glInvalidateBufferSubData; using theBaseClass_t::glInvalidateBufferData; using theBaseClass_t::glInvalidateFramebuffer; using theBaseClass_t::glInvalidateSubFramebuffer; using theBaseClass_t::glMultiDrawArraysIndirect; using theBaseClass_t::glMultiDrawElementsIndirect; using theBaseClass_t::glGetProgramInterfaceiv; using theBaseClass_t::glGetProgramResourceIndex; using theBaseClass_t::glGetProgramResourceName; using theBaseClass_t::glGetProgramResourceiv; using theBaseClass_t::glGetProgramResourceLocation; using theBaseClass_t::glGetProgramResourceLocationIndex; using theBaseClass_t::glShaderStorageBlockBinding; using theBaseClass_t::glTexBufferRange; using theBaseClass_t::glTexStorage2DMultisample; using theBaseClass_t::glTexStorage3DMultisample; using theBaseClass_t::glTextureView; using theBaseClass_t::glBindVertexBuffer; using theBaseClass_t::glVertexAttribFormat; using theBaseClass_t::glVertexAttribIFormat; using theBaseClass_t::glVertexAttribLFormat; using theBaseClass_t::glVertexAttribBinding; using theBaseClass_t::glVertexBindingDivisor; using theBaseClass_t::glDebugMessageControl; using theBaseClass_t::glDebugMessageInsert; using theBaseClass_t::glDebugMessageCallback; using theBaseClass_t::glGetDebugMessageLog; using theBaseClass_t::glPushDebugGroup; using theBaseClass_t::glPopDebugGroup; using theBaseClass_t::glObjectLabel; using theBaseClass_t::glGetObjectLabel; using theBaseClass_t::glObjectPtrLabel; using theBaseClass_t::glGetObjectPtrLabel; }; #endif // _OpenGl_GlCore43_Header
// https://oj.leetcode.com/problems/decode-ways/ class Solution { public: int numDecodings(string s) { int ssize = s.size(); if (ssize == 0) { return 0; } vector<int> num(ssize + 1, 0); num[0] = 1; // always has one way from start num[1] = (s[0] == '0') ? 0 : 1; for (int i = 2; i <= ssize; i++) { if (s[i-1] != '0') { num[i] += num[i-1]; } if (s[i-2] == '1' || (s[i-2] == '2' && s[i-1] >= '0' && s[i-1] <= '6')) { num[i] += num[i-2]; } } return num[ssize]; } };
#pragma once #if defined(__GNUC__) && defined(__GXX_EXPERIMENTAL_CXX0X__) #include "type_list_cpp11.hpp" #else #include "type_list_cpp03.hpp" #endif
#include "gmock/gmock.h" #include "Person.h" class MockPerson : public Person { public: MockPerson(std::string firstName, std::string lastName, int year, int month, int date) : Person(firstName, lastName, year, month, date) {} MOCK_METHOD(std::string, getFirstName, (), (override)); MOCK_METHOD(std::string, getLastName, (), (override)); MOCK_METHOD(std::string, getAscBirth, (), (override)); MOCK_METHOD(int, getAge, (), (override)); };
// my way class Solution { public: int maxProfit(vector<int>& prices) { int lowest = INT_MAX, maxProf = 0; for(int i = 0; i < prices.size(); ++i){ if(prices[i] < lowest){ lowest = prices[i]; }else{ maxProf = max(maxProf, prices[i]-lowest); } } return maxProf; } }; //Kadane's Algorithm //https://en.wikipedia.org/wiki/Maximum_subarray_problem class Solution { public: int maxProfit(vector<int>& prices) { int maxCurr = 0, maxProf = 0; for(int i = 1; i < prices.size(); ++i){ maxCurr = max(0, maxCurr + prices[i] - prices[i-1]); maxProf = max(maxProf, maxCurr); } return maxProf; } };
/* * 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/>. */ #ifndef LSST_SG_BIGINTEGER_H_ #define LSST_SG_BIGINTEGER_H_ /// \file /// \brief This file declares a class for arbitrary precision integers. #include <stdint.h> #include <cstring> #include <stdexcept> namespace lsst { namespace sg { /// `BigInteger` is an arbitrary precision signed integer class. It is /// intended to be used in applications which need relatively small integers, /// and only supports addition, subtraction and multiplication. /// /// Internally, a BigInteger consists of a sign and an unsigned magnitude. The /// magnitude is represented by an array of 32 bit digits, stored from least /// to most significant. All non-zero integers have at least one digit, the /// most significant of which is non-zero. Zero is defined to have no digits. class BigInteger { public: /// This constructor creates a zero-valued integer with the given digit /// array. BigInteger(uint32_t * digits, unsigned capacity) : _digits(digits), _capacity(capacity), _size(0), _sign(0) {} BigInteger & operator=(BigInteger const & b) { if (this != &b) { _checkCapacity(b._size); _sign = b._sign; _size = b._size; std::memcpy(_digits, b._digits, sizeof(uint32_t) * b._size); } return *this; } /// `getSign` returns -1, 0 or 1 if this integer is negative, zero or /// positive. int getSign() const { return _sign; } /// `getSize` returns the number of digits in the value of this integer. unsigned getSize() const { return _size; } /// `getCapacity` returns the number of digits in the underlying digit /// array. unsigned getCapacity() const { return _capacity; } /// `getDigits` returns the underlying digit array. uint32_t const * getDigits() const { return _digits; } /// `setToZero` sets this integer to zero. void setToZero() { _sign = 0; _size = 0; } /// `setTo` sets this integer to the given signed 64 bit integer value. void setTo(int64_t x) { if (x < 0) { setTo(static_cast<uint64_t>(-x)); _sign = -1; } else { setTo(static_cast<uint64_t>(x)); } } /// `setTo` sets this integer to the given unsigned 64 bit integer value. void setTo(uint64_t x) { _checkCapacity(2); _digits[0] = static_cast<uint32_t>(x); _digits[1] = static_cast<uint32_t>(x >> 32); _size = (_digits[1] == 0) ? (_digits[0] != 0) : 2; _sign = (_size != 0); } /// `negate` multiplies this integer by -1. void negate() { _sign = -_sign; } /// `add` adds b to this integer. BigInteger & add(BigInteger const & b); /// `subtract` subtracts b from this integer. BigInteger & subtract(BigInteger const & b); /// `multiplyPow2` multiplies this integer by 2ⁿ. BigInteger & multiplyPow2(unsigned n); /// `multiply` multiplies this integer by b. BigInteger & multiply(BigInteger const & b); private: void _checkCapacity(unsigned n) const { if (_capacity < n) { throw std::runtime_error("BigInteger capacity is too small"); } } uint32_t * _digits; // Unowned unsigned _capacity; unsigned _size; int _sign; }; }} // namespace lsst::sg #endif // LSST_SG_BIGINTEGER_H_
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmStringReplaceHelper.h" #include <sstream> #include <utility> #include "cmMakefile.h" cmStringReplaceHelper::cmStringReplaceHelper(const std::string& regex, std::string replace_expr, cmMakefile* makefile) : RegExString(regex) , RegularExpression(regex) , ReplaceExpression(std::move(replace_expr)) , Makefile(makefile) { this->ParseReplaceExpression(); } bool cmStringReplaceHelper::Replace(const std::string& input, std::string& output) { output.clear(); // Scan through the input for all matches. std::string::size_type base = 0; while (this->RegularExpression.find(input.c_str() + base)) { if (this->Makefile != nullptr) { this->Makefile->ClearMatches(); this->Makefile->StoreMatches(this->RegularExpression); } auto l2 = this->RegularExpression.start(); auto r = this->RegularExpression.end(); // Concatenate the part of the input that was not matched. output += input.substr(base, l2); // Make sure the match had some text. if (r - l2 == 0) { std::ostringstream error; error << "regex \"" << this->RegExString << "\" matched an empty string"; this->ErrorString = error.str(); return false; } // Concatenate the replacement for the match. for (const auto& replacement : this->Replacements) { if (replacement.Number < 0) { // This is just a plain-text part of the replacement. output += replacement.Value; } else { // Replace with part of the match. auto n = replacement.Number; auto start = this->RegularExpression.start(n); auto end = this->RegularExpression.end(n); auto len = input.length() - base; if ((start != std::string::npos) && (end != std::string::npos) && (start <= len) && (end <= len)) { output += input.substr(base + start, end - start); } else { std::ostringstream error; error << "replace expression \"" << this->ReplaceExpression << "\" contains an out-of-range escape for regex \"" << this->RegExString << "\""; this->ErrorString = error.str(); return false; } } } // Move past the match. base += r; } // Concatenate the text after the last match. output += input.substr(base, input.length() - base); return true; } void cmStringReplaceHelper::ParseReplaceExpression() { std::string::size_type l = 0; while (l < this->ReplaceExpression.length()) { auto r = this->ReplaceExpression.find('\\', l); if (r == std::string::npos) { r = this->ReplaceExpression.length(); this->Replacements.emplace_back( this->ReplaceExpression.substr(l, r - l)); } else { if (r - l > 0) { this->Replacements.emplace_back( this->ReplaceExpression.substr(l, r - l)); } if (r == (this->ReplaceExpression.length() - 1)) { this->ValidReplaceExpression = false; this->ErrorString = "replace-expression ends in a backslash"; return; } if ((this->ReplaceExpression[r + 1] >= '0') && (this->ReplaceExpression[r + 1] <= '9')) { this->Replacements.emplace_back(this->ReplaceExpression[r + 1] - '0'); } else if (this->ReplaceExpression[r + 1] == 'n') { this->Replacements.emplace_back("\n"); } else if (this->ReplaceExpression[r + 1] == '\\') { this->Replacements.emplace_back("\\"); } else { this->ValidReplaceExpression = false; std::ostringstream error; error << "Unknown escape \"" << this->ReplaceExpression.substr(r, 2) << "\" in replace-expression"; this->ErrorString = error.str(); return; } r += 2; } l = r; } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Yngve Pettersen ** */ #include "core/pch.h" #if defined(_NATIVE_SSL_SUPPORT_) #include "modules/libssl/sslbase.h" #include "modules/libssl/protocol/sslstat.h" #include "modules/url/url2.h" #include "modules/url/url_sn.h" #include "modules/url/url_man.h" #include "modules/url/protocols/http1.h" #include "modules/hardcore/mem/mem_man.h" #ifdef _SECURE_INFO_SUPPORT #include "modules/util/htmlify.h" #endif SSL_SessionStateRecordList *SSL_ConnectionState::FindSessionRecord() { RemoveSession(); return (session = server_info->FindSessionRecord()); } void SSL_ConnectionState::AddSessionRecord(SSL_SessionStateRecordList *target) { server_info->AddSessionRecord(target); } void SSL_ConnectionState::RemoveSession() { if(session != NULL) { session->connections --; if (!session->is_resumable && !session->connections) server_info->RemoveSessionRecord(session); session = NULL; } } void SSL_ConnectionState::OpenNewSession() { RemoveSession(); session = OP_NEW(SSL_SessionStateRecordList, ()); if(session == NULL) { RaiseAlert(SSL_Internal, SSL_Allocation_Failure); return; } session->is_resumable = TRUE; session->session_negotiated = FALSE; session->connections = 1; session->use_correct_tls_no_cert = !server_info->TLSUseSSLv3NoCert(); session->used_cipher.Set(0,0); session->used_compression = SSL_Null_Compression; } #endif
/* * Copyright (c) 2017 Ensign Energy Incorporated * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Ensign Energy Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Ensign Energy Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Ensign Energy Incorporated. */ #ifndef __DRILLING_REQUEST_PUBLISHER_H__ #define __DRILLING_REQUEST_PUBLISHER_H__ #include "publisher.h" #include "drill.h" #include "drillSupport.h" #ifdef _WIN32 #undef pascal #endif #include "units.h" using namespace units; using namespace units::length; using namespace units::velocity; using namespace units::force; using namespace units::torque; using namespace units::pressure; class CDrillingRequestPublisher : public TPublisher< nec::process::DrillingRequest > { public: CDrillingRequestPublisher(); ~CDrillingRequestPublisher(); bool Create(int32_t domain); bool Initialize(); bool PublishSample(); // Topic getters void SetPriority(DataTypes::Priority priority); void SetTimeNeeded(DataTypes::Time timeNeeded); void SetDuration(DataTypes::Time duration); void SetRopLimit(const meters_per_second_t ropLimit); void SetWobLimit(const newton_t wobLimit); void SetDifferentialPressureLimit(const pascal_t differentialPressureLimit); void SetTorqueLimit(const newton_meter_t torqueLimit); void SetRopMode(const bool ropMode); void SetWobMode(const bool wobMode); void SetDifferentialPressureMode(const bool differentialPressureMode); void SetTorqueMode(const bool torqueMode); }; #endif // __DRILLING_REQUEST_PUBLISHER_H__
/* * Copyright (c) 2015-2017 Morwenn * SPDX-License-Identifier: MIT */ #ifndef CPPSORT_DETAIL_FRONT_INSERTER6_H_ #define CPPSORT_DETAIL_FRONT_INSERTER6_H_ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <cpp-sort/utility/as_function.h> #include "../rotate_left.h" namespace cppsort { namespace detail { template<> struct front_inserter_n<6u> { template< typename RandomAccessIterator, typename Compare, typename Projection > auto operator()(RandomAccessIterator first, Compare compare, Projection projection) const -> void { auto&& comp = utility::as_function(compare); auto&& proj = utility::as_function(projection); auto&& proj0 = proj(first[0u]); if (comp(proj(first[3u]), proj0)) { if (comp(proj(first[4u]), proj0)) { if (comp(proj(first[5u]), proj0)) { rotate_left<6u>(first); } else { rotate_left<5u>(first); } } else { rotate_left<4u>(first); } } else { if (comp(proj(first[2u]), proj0)) { rotate_left<3u>(first); } else { if (comp(proj(first[1u]), proj0)) { rotate_left<2u>(first); } } } } }; }} #endif // CPPSORT_DETAIL_FRONT_INSERTER6_H_
#pragma once #include <include/glm.h> #include <include/math.h> /* This is a simple implementation of a camera 2D. It's inspired from Laborator 5. It has only the necessary things to capture a 2D image. */ class Camera { public: Camera(const glm::vec3 &position, const glm::vec3 &center, const glm::vec3 &up); ~Camera(); void Set(const glm::vec3 &position, const glm::vec3 &center, const glm::vec3 &up); glm::mat4 GetViewMatrix(); glm::vec3 GetTargetPosition(); void SetOrthographic(float left, float right, float bottom, float top, float zNear, float zFar); glm::mat4 GetProjectionMatrix(); private: float distanceToTarget; glm::vec3 position; glm::vec3 forward; glm::vec3 right; glm::vec3 up; glm::mat4 projectionMatrix; };
#ifndef POINTSTATE_H #define POINTSTATE_H #include "Execute.h" class State; class Player; class PointState { public: PointState(); void speedX(int x); void speedY(int y); int gspeedX(); int gspeedY(); private: Player* m_players; int xSpeed =0; int ySpeed =0; }; #endif