text
stringlengths
8
6.88M
#include "Shader.h" #include "Utils.h" int CShader::Create( std::string vertexShader, std::string fragmentSa ) { char *vsSourceP = file2string( vertexShader.c_str() ); char *fsSourceP = file2string( fragmentSa.c_str() ); shaderID = glCreateProgram(); GLuint vshader_id = createShader( GL_VERTEX_SHADER, vsSourceP ); GLuint fshader_id = createShader( GL_FRAGMENT_SHADER, fsSourceP ); glAttachShader( shaderID, vshader_id ); glAttachShader( shaderID, fshader_id ); glLinkProgram( shaderID ); glDetachShader( shaderID, vshader_id ); glDetachShader( shaderID, fshader_id ); glDeleteShader( vshader_id ); glDeleteShader( fshader_id ); return shaderID; } void CShader::Bind() { glUseProgram( shaderID ); } void CShader::Unbind() { glUseProgram( 0 ); } void CShader::SetUniformMatrix( std::string name, float * data ) { auto loc = glGetUniformLocation( shaderID, name.c_str() ); glUniformMatrix4fv( loc, 1, GL_FALSE, data ); } void CShader::UseTexture( std::string name, int TextureID, int index ) { auto loc = glGetUniformLocation( shaderID, name.c_str() ); glActiveTexture( GL_TEXTURE0 + index ); glBindTexture( GL_TEXTURE_2D, TextureID ); glUniform1i( loc, index ); }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2009-2010 Benoit Jacob <jacob.benoit.1@gmail.com> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, 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 2 of // the License, or (at your option) any later version. // // Eigen 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 Lesser General Public License or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #ifndef EIGEN_JACOBISVD_H #define EIGEN_JACOBISVD_H // forward declarations (needed by ICC) // the empty bodies are required by VC template<typename MatrixType, unsigned int Options, bool IsComplex = NumTraits<typename MatrixType::Scalar>::IsComplex> struct ei_svd_precondition_2x2_block_to_be_real {}; template<typename MatrixType, unsigned int Options, bool PossiblyMoreRowsThanCols = (Options & AtLeastAsManyColsAsRows) == 0 && (MatrixType::RowsAtCompileTime==Dynamic || (MatrixType::RowsAtCompileTime>MatrixType::ColsAtCompileTime))> struct ei_svd_precondition_if_more_rows_than_cols; template<typename MatrixType, unsigned int Options, bool PossiblyMoreColsThanRows = (Options & AtLeastAsManyRowsAsCols) == 0 && (MatrixType::ColsAtCompileTime==Dynamic || (MatrixType::ColsAtCompileTime>MatrixType::RowsAtCompileTime))> struct ei_svd_precondition_if_more_cols_than_rows; /** \ingroup SVD_Module * * * \class JacobiSVD * * \brief Jacobi SVD decomposition of a square matrix * * \param MatrixType the type of the matrix of which we are computing the SVD decomposition * \param Options a bit field of flags offering the following options: \c SkipU and \c SkipV allow to skip the computation of * the unitaries \a U and \a V respectively; \c AtLeastAsManyRowsAsCols and \c AtLeastAsManyRowsAsCols allows * to hint the compiler to only generate the corresponding code paths; \c Square is equivantent to the combination of * the latter two bits and is useful when you know that the matrix is square. Note that when this information can * be automatically deduced from the matrix type (e.g. a Matrix3f is always square), Eigen does it for you. * * \sa MatrixBase::jacobiSvd() */ template<typename MatrixType, unsigned int Options> class JacobiSVD { private: typedef typename MatrixType::Scalar Scalar; typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar; typedef typename MatrixType::Index Index; enum { ComputeU = (Options & SkipU) == 0, ComputeV = (Options & SkipV) == 0, RowsAtCompileTime = MatrixType::RowsAtCompileTime, ColsAtCompileTime = MatrixType::ColsAtCompileTime, DiagSizeAtCompileTime = EIGEN_SIZE_MIN_PREFER_DYNAMIC(RowsAtCompileTime,ColsAtCompileTime), MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime, MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime, MaxDiagSizeAtCompileTime = EIGEN_SIZE_MIN_PREFER_FIXED(MaxRowsAtCompileTime,MaxColsAtCompileTime), MatrixOptions = MatrixType::Options }; typedef Matrix<Scalar, Dynamic, Dynamic, MatrixOptions> DummyMatrixType; typedef typename ei_meta_if<ComputeU, Matrix<Scalar, RowsAtCompileTime, RowsAtCompileTime, MatrixOptions, MaxRowsAtCompileTime, MaxRowsAtCompileTime>, DummyMatrixType>::ret MatrixUType; typedef typename ei_meta_if<ComputeV, Matrix<Scalar, ColsAtCompileTime, ColsAtCompileTime, MatrixOptions, MaxColsAtCompileTime, MaxColsAtCompileTime>, DummyMatrixType>::ret MatrixVType; typedef typename ei_plain_diag_type<MatrixType, RealScalar>::type SingularValuesType; typedef typename ei_plain_row_type<MatrixType>::type RowType; typedef typename ei_plain_col_type<MatrixType>::type ColType; typedef Matrix<Scalar, DiagSizeAtCompileTime, DiagSizeAtCompileTime, MatrixOptions, MaxDiagSizeAtCompileTime, MaxDiagSizeAtCompileTime> WorkMatrixType; public: /** \brief Default Constructor. * * The default constructor is useful in cases in which the user intends to * perform decompositions via JacobiSVD::compute(const MatrixType&). */ JacobiSVD() : m_isInitialized(false) {} /** \brief Default Constructor with memory preallocation * * Like the default constructor but with preallocation of the internal data * according to the specified problem \a size. * \sa JacobiSVD() */ JacobiSVD(Index rows, Index cols) : m_matrixU(rows, rows), m_matrixV(cols, cols), m_singularValues(std::min(rows, cols)), m_workMatrix(rows, cols), m_isInitialized(false) {} JacobiSVD(const MatrixType& matrix) : m_matrixU(matrix.rows(), matrix.rows()), m_matrixV(matrix.cols(), matrix.cols()), m_singularValues(), m_workMatrix(), m_isInitialized(false) { const Index minSize = std::min(matrix.rows(), matrix.cols()); m_singularValues.resize(minSize); m_workMatrix.resize(minSize, minSize); compute(matrix); } JacobiSVD& compute(const MatrixType& matrix); const MatrixUType& matrixU() const { ei_assert(m_isInitialized && "JacobiSVD is not initialized."); return m_matrixU; } const SingularValuesType& singularValues() const { ei_assert(m_isInitialized && "JacobiSVD is not initialized."); return m_singularValues; } const MatrixVType& matrixV() const { ei_assert(m_isInitialized && "JacobiSVD is not initialized."); return m_matrixV; } protected: MatrixUType m_matrixU; MatrixVType m_matrixV; SingularValuesType m_singularValues; WorkMatrixType m_workMatrix; bool m_isInitialized; template<typename _MatrixType, unsigned int _Options, bool _IsComplex> friend struct ei_svd_precondition_2x2_block_to_be_real; template<typename _MatrixType, unsigned int _Options, bool _PossiblyMoreRowsThanCols> friend struct ei_svd_precondition_if_more_rows_than_cols; template<typename _MatrixType, unsigned int _Options, bool _PossiblyMoreRowsThanCols> friend struct ei_svd_precondition_if_more_cols_than_rows; }; template<typename MatrixType, unsigned int Options> struct ei_svd_precondition_2x2_block_to_be_real<MatrixType, Options, false> { typedef JacobiSVD<MatrixType, Options> SVD; typedef typename SVD::Index Index; static void run(typename SVD::WorkMatrixType&, JacobiSVD<MatrixType, Options>&, Index, Index) {} }; template<typename MatrixType, unsigned int Options> struct ei_svd_precondition_2x2_block_to_be_real<MatrixType, Options, true> { typedef JacobiSVD<MatrixType, Options> SVD; typedef typename MatrixType::Scalar Scalar; typedef typename MatrixType::RealScalar RealScalar; typedef typename SVD::Index Index; enum { ComputeU = SVD::ComputeU, ComputeV = SVD::ComputeV }; static void run(typename SVD::WorkMatrixType& work_matrix, JacobiSVD<MatrixType, Options>& svd, Index p, Index q) { Scalar z; PlanarRotation<Scalar> rot; RealScalar n = ei_sqrt(ei_abs2(work_matrix.coeff(p,p)) + ei_abs2(work_matrix.coeff(q,p))); if(n==0) { z = ei_abs(work_matrix.coeff(p,q)) / work_matrix.coeff(p,q); work_matrix.row(p) *= z; if(ComputeU) svd.m_matrixU.col(p) *= ei_conj(z); z = ei_abs(work_matrix.coeff(q,q)) / work_matrix.coeff(q,q); work_matrix.row(q) *= z; if(ComputeU) svd.m_matrixU.col(q) *= ei_conj(z); } else { rot.c() = ei_conj(work_matrix.coeff(p,p)) / n; rot.s() = work_matrix.coeff(q,p) / n; work_matrix.applyOnTheLeft(p,q,rot); if(ComputeU) svd.m_matrixU.applyOnTheRight(p,q,rot.adjoint()); if(work_matrix.coeff(p,q) != Scalar(0)) { Scalar z = ei_abs(work_matrix.coeff(p,q)) / work_matrix.coeff(p,q); work_matrix.col(q) *= z; if(ComputeV) svd.m_matrixV.col(q) *= z; } if(work_matrix.coeff(q,q) != Scalar(0)) { z = ei_abs(work_matrix.coeff(q,q)) / work_matrix.coeff(q,q); work_matrix.row(q) *= z; if(ComputeU) svd.m_matrixU.col(q) *= ei_conj(z); } } } }; template<typename MatrixType, typename RealScalar, typename Index> void ei_real_2x2_jacobi_svd(const MatrixType& matrix, Index p, Index q, PlanarRotation<RealScalar> *j_left, PlanarRotation<RealScalar> *j_right) { Matrix<RealScalar,2,2> m; m << ei_real(matrix.coeff(p,p)), ei_real(matrix.coeff(p,q)), ei_real(matrix.coeff(q,p)), ei_real(matrix.coeff(q,q)); PlanarRotation<RealScalar> rot1; RealScalar t = m.coeff(0,0) + m.coeff(1,1); RealScalar d = m.coeff(1,0) - m.coeff(0,1); if(t == RealScalar(0)) { rot1.c() = 0; rot1.s() = d > 0 ? 1 : -1; } else { RealScalar u = d / t; rot1.c() = RealScalar(1) / ei_sqrt(1 + ei_abs2(u)); rot1.s() = rot1.c() * u; } m.applyOnTheLeft(0,1,rot1); j_right->makeJacobi(m,0,1); *j_left = rot1 * j_right->transpose(); } template<typename MatrixType, unsigned int Options, bool PossiblyMoreRowsThanCols> struct ei_svd_precondition_if_more_rows_than_cols { typedef JacobiSVD<MatrixType, Options> SVD; static bool run(const MatrixType&, typename SVD::WorkMatrixType&, JacobiSVD<MatrixType, Options>&) { return false; } }; template<typename MatrixType, unsigned int Options> struct ei_svd_precondition_if_more_rows_than_cols<MatrixType, Options, true> { typedef JacobiSVD<MatrixType, Options> SVD; typedef typename MatrixType::Scalar Scalar; typedef typename MatrixType::RealScalar RealScalar; typedef typename MatrixType::Index Index; enum { ComputeU = SVD::ComputeU, ComputeV = SVD::ComputeV }; static bool run(const MatrixType& matrix, typename SVD::WorkMatrixType& work_matrix, SVD& svd) { Index rows = matrix.rows(); Index cols = matrix.cols(); Index diagSize = cols; if(rows > cols) { FullPivHouseholderQR<MatrixType> qr(matrix); work_matrix = qr.matrixQR().block(0,0,diagSize,diagSize).template triangularView<Upper>(); if(ComputeU) svd.m_matrixU = qr.matrixQ(); if(ComputeV) svd.m_matrixV = qr.colsPermutation(); return true; } else return false; } }; template<typename MatrixType, unsigned int Options, bool PossiblyMoreColsThanRows> struct ei_svd_precondition_if_more_cols_than_rows { typedef JacobiSVD<MatrixType, Options> SVD; static bool run(const MatrixType&, typename SVD::WorkMatrixType&, JacobiSVD<MatrixType, Options>&) { return false; } }; template<typename MatrixType, unsigned int Options> struct ei_svd_precondition_if_more_cols_than_rows<MatrixType, Options, true> { typedef JacobiSVD<MatrixType, Options> SVD; typedef typename MatrixType::Scalar Scalar; typedef typename MatrixType::RealScalar RealScalar; typedef typename MatrixType::Index Index; enum { ComputeU = SVD::ComputeU, ComputeV = SVD::ComputeV, RowsAtCompileTime = SVD::RowsAtCompileTime, ColsAtCompileTime = SVD::ColsAtCompileTime, MaxRowsAtCompileTime = SVD::MaxRowsAtCompileTime, MaxColsAtCompileTime = SVD::MaxColsAtCompileTime, MatrixOptions = SVD::MatrixOptions }; static bool run(const MatrixType& matrix, typename SVD::WorkMatrixType& work_matrix, SVD& svd) { Index rows = matrix.rows(); Index cols = matrix.cols(); Index diagSize = rows; if(cols > rows) { typedef Matrix<Scalar,ColsAtCompileTime,RowsAtCompileTime, MatrixOptions,MaxColsAtCompileTime,MaxRowsAtCompileTime> TransposeTypeWithSameStorageOrder; FullPivHouseholderQR<TransposeTypeWithSameStorageOrder> qr(matrix.adjoint()); work_matrix = qr.matrixQR().block(0,0,diagSize,diagSize).template triangularView<Upper>().adjoint(); if(ComputeV) svd.m_matrixV = qr.matrixQ(); if(ComputeU) svd.m_matrixU = qr.colsPermutation(); return true; } else return false; } }; template<typename MatrixType, unsigned int Options> JacobiSVD<MatrixType, Options>& JacobiSVD<MatrixType, Options>::compute(const MatrixType& matrix) { Index rows = matrix.rows(); Index cols = matrix.cols(); Index diagSize = std::min(rows, cols); m_singularValues.resize(diagSize); const RealScalar precision = 2 * NumTraits<Scalar>::epsilon(); if(!ei_svd_precondition_if_more_rows_than_cols<MatrixType, Options>::run(matrix, m_workMatrix, *this) && !ei_svd_precondition_if_more_cols_than_rows<MatrixType, Options>::run(matrix, m_workMatrix, *this)) { m_workMatrix = matrix.block(0,0,diagSize,diagSize); if(ComputeU) m_matrixU.setIdentity(rows,rows); if(ComputeV) m_matrixV.setIdentity(cols,cols); } bool finished = false; while(!finished) { finished = true; for(Index p = 1; p < diagSize; ++p) { for(Index q = 0; q < p; ++q) { if(std::max(ei_abs(m_workMatrix.coeff(p,q)),ei_abs(m_workMatrix.coeff(q,p))) > std::max(ei_abs(m_workMatrix.coeff(p,p)),ei_abs(m_workMatrix.coeff(q,q)))*precision) { finished = false; ei_svd_precondition_2x2_block_to_be_real<MatrixType, Options>::run(m_workMatrix, *this, p, q); PlanarRotation<RealScalar> j_left, j_right; ei_real_2x2_jacobi_svd(m_workMatrix, p, q, &j_left, &j_right); m_workMatrix.applyOnTheLeft(p,q,j_left); if(ComputeU) m_matrixU.applyOnTheRight(p,q,j_left.transpose()); m_workMatrix.applyOnTheRight(p,q,j_right); if(ComputeV) m_matrixV.applyOnTheRight(p,q,j_right); } } } } for(Index i = 0; i < diagSize; ++i) { RealScalar a = ei_abs(m_workMatrix.coeff(i,i)); m_singularValues.coeffRef(i) = a; if(ComputeU && (a!=RealScalar(0))) m_matrixU.col(i) *= m_workMatrix.coeff(i,i)/a; } for(Index i = 0; i < diagSize; i++) { Index pos; m_singularValues.tail(diagSize-i).maxCoeff(&pos); if(pos) { pos += i; std::swap(m_singularValues.coeffRef(i), m_singularValues.coeffRef(pos)); if(ComputeU) m_matrixU.col(pos).swap(m_matrixU.col(i)); if(ComputeV) m_matrixV.col(pos).swap(m_matrixV.col(i)); } } m_isInitialized = true; return *this; } #endif // EIGEN_JACOBISVD_H
#include <bits/stdc++.h> using namespace std; #define REP(i,n) for(int i=0;i<(n);i++) #define for1(i,n) for(int i=1;i<=n;i++) #define FOR(i,a,b) for(int i=(a);i<=(b);i++) #define FORD(i,a,b) for(int i=(a);i>=(b);i--) const int INF = 1<<29; const int MOD=1073741824; #define pp pair<ll,ll> typedef long long int ll; bool isPowerOfTwo (ll x) { return x && (!(x&(x-1))); } void fastio() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); } long long binpow(long long a, long long b) { long long res = 1; while (b > 0) { if (b & 1) res = res * a; a = a * a; b >>= 1; } return res; } const int dx[] = {1,0,-1,0,1,1,-1,-1}; const int dy[] = {0,-1,0,1,1,-1,-1,1}; //////////////////////////////////////////////////////////////////// int main() { fastio(); int t=1; // cin>>t; while(t--) { ll a,b; cin>>a>>b; ll lc = 1LL*a*b/__gcd(a,b); ll x = lc/a,y=lc/b; if(x==y-1 || y==x-1)cout<<"Equal"; else if(x>y)cout<<"Dasha"; else cout<<"Masha"; } return 0; }
#include "base/scheduling/task_loop_for_worker.h" namespace base { void TaskLoopForWorker::Run() { while (true) { cv_.wait(mutex_, [&]() -> bool{ bool has_tasks = !queue_.empty(); bool can_skip_waiting = (has_tasks || quit_ || quit_when_idle_); return can_skip_waiting; }); // We now own the lock for |queue_|, until we explicitly release it. if (quit_ || (quit_when_idle_ && queue_.empty())) { cv_.release_lock(); break; } CHECK(queue_.size()); Callback cb = std::move(queue_.front()); queue_.pop(); cv_.release_lock(); ExecuteTask(std::move(cb)); } // We need to reset |quit_| when |Run()| actually completes, so that we can // call |Run()| again later. quit_ = false; quit_when_idle_ = false; } void TaskLoopForWorker::PostTask(Callback cb) { mutex_.lock(); queue_.push(std::move(cb)); mutex_.unlock(); cv_.notify_one(); } void TaskLoopForWorker::Quit() { mutex_.lock(); quit_ = true; mutex_.unlock(); cv_.notify_one(); } void TaskLoopForWorker::QuitWhenIdle() { mutex_.lock(); quit_when_idle_ = true; mutex_.unlock(); cv_.notify_one(); } }; // namespace base
#pragma once // CLeftToolBar 폼 보기 class CLeftToolBar : public CFormView { DECLARE_DYNCREATE(CLeftToolBar) protected: CLeftToolBar(); // 동적 만들기에 사용되는 protected 생성자입니다. virtual ~CLeftToolBar(); public: #ifdef AFX_DESIGN_TIME enum { IDD = IDD_CLeftToolBar }; #endif #ifdef _DEBUG virtual void AssertValid() const; #ifndef _WIN32_WCE virtual void Dump(CDumpContext& dc) const; #endif #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다. DECLARE_MESSAGE_MAP() public: afx_msg void OnClickedButton1(); };
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Pawn.h" #include "Pet.generated.h" UCLASS() class VIRTUALPET_API APet : public APawn { GENERATED_BODY() public: // Sets default values for this pawn's properties APet(); /* Stats */ // Basic Needs UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Stats|BasicNeeds") float MaxHunger; UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Stats|BasicNeeds") float Hunger; UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Stats|BasicNeeds") float HungerMultiplier; UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Stats|BasicNeeds") float MaxThirst; UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Stats|BasicNeeds") float Thirst; UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Stats|BasicNeeds") float ThirstMultiplier; UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Stats|BasicNeeds") float MaxHappiness; UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Stats|BasicNeeds") float Happiness; UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Stats|BasicNeeds") float HappinessMultiplier; UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Stats|BasicNeeds") float MaxSanitation; UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Stats|BasicNeeds") float Sanitation; UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Stats|BasicNeeds") float SanitationMultiplier; protected: // Called when the game starts or when spawned virtual void BeginPlay() override; FTimerHandle BasicNeedsHandle; public: // Called when the pet is born UFUNCTION(BlueprintCallable) void OnBirth(); UFUNCTION() void BasicNeedsTimer(); // Called every frame virtual void Tick(float DeltaTime) override; // Called to bind functionality to input virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; };
/* * Led.cpp * Jean Cleison Braga Guimaraes */ #include "Led.h" Led::Led(gpio_Pin pin) : mkl_GPIOPort(pin){ setPortMode(gpio_output); writeBit(0); } void Led::turnOn(){ writeBit(0); } void Led::turnOff(){ writeBit(1); }
#include<bits/stdc++.h> using namespace std; class Student{ public: int age; const int rno; //Constant variable. int &x; //reference variable for age; Student(int r,int age) : rno(r),age(age),x(this -> age){ //We must use initialization list to initialize constant variables at the time of declaration. //for Non constant variables it's optional. } void print(){ cout << age << " " << rno << " " << x << endl; } }; int main(){ Student s1(101,20); s1.print(); return 0; }
#ifndef _APPLICATION_H_ #define _APPLICATION_H_ #include "ViewLayer.h" #include "Input.h" #include"Timer.h" #include <Dbt.h> #include "GameState.h" #include "MenuState.h" #include"WinState.h" class Application { private: Application(); Timer m_timer; float m_deltaTime; float m_dtMultiplier; //DirectX Audio HDEVNOTIFY m_hNewAudio; bool m_resetAudio; std::shared_ptr<DirectX::AudioEngine> m_audioEngine; std::stack<iGameState*> m_gameStateStack; bool m_shouldQuit; volatile bool m_doneLoadingModels; void audioUpdate(); public: static Application& getInstance() { static Application instance; return instance; } ~Application(); void stateChange(); Application(Application const&) = delete; void operator=(Application const&) = delete; bool initApplication(const HINSTANCE hInstance, const LPWSTR lpCmdLine, const HWND hWnd, const int showCmd); void createWin32Window(const HINSTANCE hInstance, const wchar_t* windowTitle, HWND& _d3d11Window); bool loadGameOptions(const std::string fileName); void applicationLoop(); void pushNewState(const states state); void GameStateChecks(); void newAudioDevice() { m_resetAudio = true; OutputDebugString(L"New Audio Device!"); } Input m_input; HWND m_window; GameOptions m_gameOptions; std::unique_ptr< ViewLayer > m_viewLayerPtr; float m_framerateLimit; float m_frametimeLimit; typedef void(*OptionFn)(Application*); struct OptionKeybind { char key; char description[128]; OptionFn trigger; }; std::vector<OptionKeybind> m_options; }; #endif // !_APPLICATION_H_
/* * Copyright (c) 2020 sayandipde * Eindhoven University of Technology * Eindhoven, The Netherlands * * Name : image_signal_processing.cpp * * Authors : Sayandip De (sayandip.de@tue.nl) * Sajid Mohamed (s.mohamed@tue.nl) * * Date : March 26, 2020 * * Function : run different approximate ISP versions * * History : * 26-03-20 : Initial version. * Code is modified from https://github.com/mbuckler/ReversiblePipeline [written by Mark Buckler]. * * 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 "auto_schedule_true_rev.h" #include "auto_schedule_true_fwd_v0.h" #include "auto_schedule_true_fwd_v1.h" #include "auto_schedule_true_fwd_v2.h" #include "auto_schedule_true_fwd_v3.h" #include "auto_schedule_true_fwd_v4.h" #include "auto_schedule_true_fwd_v5.h" #include "auto_schedule_true_fwd_v6.h" // Halide #include "Halide.h" #include "halide_benchmark.h" #include "halide_image_io.h" #include "halide_image.h" #include <opencv2/opencv.hpp> #include "config.hpp" #include "LoadCamModel.h" #include "MatrixOps.h" #include <stdio.h> #include <math.h> using namespace cv; imageSignalProcessing::imageSignalProcessing(){} imageSignalProcessing::~imageSignalProcessing(){} Mat imageSignalProcessing::approximate_pipeline(Mat the_img_vrep, int the_pipe_version) { using namespace std; Mat img_rev, img_fwd; printf("Starting script. Note that processing may take several minutes for large images\n"); //Run backward pipeline printf("Running backward pipeline...\n"); img_rev = run_pipeline(false, the_img_vrep, the_pipe_version); printf("Backward pipeline complete\n"); // Run forward pipeline printf("Running forward pipeline...\n"); img_fwd = run_pipeline(true, img_rev, the_pipe_version); printf("Forward pipeline complete\n"); printf("Success!\n"); return img_fwd; } // Reversible pipeline function Mat imageSignalProcessing::run_pipeline(bool direction, Mat the_img_in, int the_pipe_version) { using namespace std; /////////////////////////////////////////////////////////////// // Input Image Parameters /////////////////////////////////////////////////////////////// // convert input Mat to Image Halide::Runtime::Buffer<uint8_t> input; input = Mat2Image(&the_img_in); /////////////////////////////////////////////////////////////////////////////////////// // Import and format model data: cpp -> halide format // Declare model parameters vector<vector<float>> Ts, Tw, TsTw; vector<vector<float>> ctrl_pts, weights, coefs; vector<vector<float>> rev_tone; // Load model parameters from file // NOTE: Ts, Tw, and TsTw read only forward data // ctrl_pts, weights, and coefs are either forward or backward // tone mapping is always backward // This is due to the the camera model format /////////////////////////////////////////////////////////////// // Camera Model Parameters /////////////////////////////////////////////////////////////// // Path to the camera model to be used char cam_model_path[] = "./camera_models/NikonD7000/"; // White balance index (select white balance from transform file) // The first white balance in the file has a wb_index of 1 // For more information on model format see the readme int wb_index = 6; // Number of control points const int num_ctrl_pts = 3702; // Colour space transform "raw2jpg_transform.txt" Ts = get_Ts (cam_model_path); // White balance transform "raw2jpg_transform.txt" Tw = get_Tw (cam_model_path, wb_index); // Combined transforms of color space and white balance for checking "raw2jpg_transform.txt" TsTw = get_TsTw (cam_model_path, wb_index); // get control points "raw2jpg_ctrlPoints.txt" and "jpg2raw_ctrlPoints.txt" ctrl_pts = get_ctrl_pts (cam_model_path, num_ctrl_pts, direction); // get weights "raw2jpg_coefs.txt"(1) and "jpg2raw_coefs.txt"(0) weights = get_weights (cam_model_path, num_ctrl_pts, direction); // get coefficients "raw2jpg_coefs.txt"(1) and "jpg2raw_coefs.txt"(0) coefs = get_coefs (cam_model_path, num_ctrl_pts, direction); // get reverse tone mapping "jpg2raw_respFcns.txt" rev_tone = get_rev_tone (cam_model_path); // Take the transpose of the color map and white balance transform for later use vector<vector<float>> TsTw_tran = transpose_mat (TsTw); // If we are performing a backward implementation of the pipeline, // take the inverse of TsTw_tran if (direction == 0) { TsTw_tran = inv_3x3mat(TsTw_tran); } using namespace Halide; using namespace Halide::Tools; // Convert control points to a Halide image int width = ctrl_pts[0].size(); int length = ctrl_pts.size(); Halide::Runtime::Buffer<float> ctrl_pts_h(width,length); for (int y=0; y<length; y++) { for (int x=0; x<width; x++) { ctrl_pts_h(x,y) = ctrl_pts[y][x]; } } // Convert weights to a Halide image width = weights[0].size(); length = weights.size(); Halide::Runtime::Buffer<float> weights_h(width,length); for (int y=0; y<length; y++) { for (int x=0; x<width; x++) { weights_h(x,y) = weights[y][x]; } } // Convert the reverse tone mapping function to a Halide image width = 3; length = 256; Halide::Runtime::Buffer<float> rev_tone_h(width,length); for (int y=0; y<length; y++) { for (int x=0; x<width; x++) { rev_tone_h(x,y) = rev_tone[y][x]; } } // Convert the TsTw_tran to a Halide image width = 3; length = 3; Halide::Runtime::Buffer<float> TsTw_tran_h(width,length); for (int y=0; y<length; y++) { for (int x=0; x<width; x++) { TsTw_tran_h(x,y) = TsTw_tran[x][y]; } } // Convert the coefs to a Halide image width = 4; length = 4; Halide::Runtime::Buffer<float> coefs_h(width,length); for (int y=0; y<length; y++) { for (int x=0; x<width; x++) { coefs_h(x,y) = coefs[x][y]; } } /////////////////////////////////////////////////////////////////////////////////////// // Import and format input image // Declare image handle variables Var x, y, c; // Halide::Runtime::Buffer<uint8_t> input; // // Load input image // if (direction == 1) { // // If using forward pipeline // input = load_and_convert_image(demosaiced_image); // } else { // // If using backward pipeline // input = load_image(jpg_image); // } //////////////////////////////////////////////////////////////////////// // run the generator Halide::Runtime::Buffer<uint8_t> output(input.width(), input.height(), input.channels()); int samples = 1; //2 int iterations = 1; //5 double auto_schedule_on = 0.0; if (direction == 1) { cout << "- cam pipe version : " << the_pipe_version << "\n"; switch(the_pipe_version){ case 0: // full rev + fwd skip 0 stages auto_schedule_on = Halide::Tools::benchmark(samples, iterations, [&]() { auto_schedule_true_fwd_v0(input, ctrl_pts_h, weights_h, rev_tone_h, TsTw_tran_h, coefs_h, output); }); printf("- fwd_transform_gamut_tonemap: %gms\n", auto_schedule_on * 1e3); break; case 1: // rev + fwd_transform_tonemap skip 1 stage auto_schedule_on = Halide::Tools::benchmark(samples, iterations, [&]() { auto_schedule_true_fwd_v1(input, ctrl_pts_h, weights_h, rev_tone_h, TsTw_tran_h, coefs_h, output); }); printf("- fwd_transform_tonemap : %gms\n", auto_schedule_on * 1e3); break; case 2: // rev + fwd_transform_gamut skip 1 stage auto_schedule_on = Halide::Tools::benchmark(samples, iterations, [&]() { auto_schedule_true_fwd_v2(input, ctrl_pts_h, weights_h, rev_tone_h, TsTw_tran_h, coefs_h, output); }); printf("- fwd_transform_gamut : %gms\n", auto_schedule_on * 1e3); break; case 3: // rev + fwd_gamut_tonemap skip 1 stage auto_schedule_on = Halide::Tools::benchmark(samples, iterations, [&]() { auto_schedule_true_fwd_v3(input, ctrl_pts_h, weights_h, rev_tone_h, TsTw_tran_h, coefs_h, output); }); printf("- fwd_gamut_tonemap : %gms\n", auto_schedule_on * 1e3); break; case 4: // rev + fwd_transform skip 2 stages auto_schedule_on = Halide::Tools::benchmark(samples, iterations, [&]() { auto_schedule_true_fwd_v4(input, ctrl_pts_h, weights_h, rev_tone_h, TsTw_tran_h, coefs_h, output); }); printf("- fwd_transform : %gms\n", auto_schedule_on * 1e3); break; case 5: // rev + fwd_gamut skip 2 stages auto_schedule_on = Halide::Tools::benchmark(samples, iterations, [&]() { auto_schedule_true_fwd_v5(input, ctrl_pts_h, weights_h, rev_tone_h, TsTw_tran_h, coefs_h, output); }); printf("- fwd_gamut : %gms\n", auto_schedule_on * 1e3); break; case 6: // rev + fwd_tonemap skip 2 stages auto_schedule_on = Halide::Tools::benchmark(samples, iterations, [&]() { auto_schedule_true_fwd_v6(input, ctrl_pts_h, weights_h, rev_tone_h, TsTw_tran_h, coefs_h, output); }); printf("- fwd_tonemap : %gms\n", auto_schedule_on * 1e3); break; case 7: // rev only skip 3 stages break; default: // should not happen cout << "Default pipe branch taken, pls check\n"; break; }// switch } else { double auto_schedule_on = Halide::Tools::benchmark(2, 5, [&]() { auto_schedule_true_rev(input, ctrl_pts_h, weights_h, rev_tone_h, TsTw_tran_h, coefs_h, output); }); printf("- Auto schedule rev: %gms\n", auto_schedule_on * 1e3); } //////////////////////////////////////////////////////////////////////// // Save the output if (direction == 1) { save_image(output, "imgs/output_fwd_test.png"); //cout << "- output(c,x,y) fwd: "<< output.channels() << " " << output.width() << " " << output.height() << endl; } else { save_image(output, "imgs/output_rev_test.png"); //cout << "- output(c,x,y) rev: "<< output.channels() << " " << output.width() << " " << output.height() << endl; } // convert Image to Mat and return Mat img_out; img_out = Image2Mat(&output); return img_out; } Mat imageSignalProcessing::Image2Mat( Halide::Runtime::Buffer<uint8_t> *InImage ) { int height = (*InImage).height(); int width = (*InImage).width(); Mat OutMat(height,width,CV_8UC3); vector<Mat> three_channels; split(OutMat, three_channels); // Convert from planar RGB memory storage to interleaved BGR memory storage for (int y=0; y<height; y++) { for (int x=0; x<width; x++) { // Blue channel three_channels[0].at<uint8_t>(y,x) = (*InImage)(x,y,2); // Green channel three_channels[1].at<uint8_t>(y,x) = (*InImage)(x,y,1); // Red channel three_channels[2].at<uint8_t>(y,x) = (*InImage)(x,y,0); } } merge(three_channels, OutMat); return OutMat; } Halide::Runtime::Buffer<uint8_t> imageSignalProcessing::Mat2Image( Mat *InMat ) { int height = (*InMat).rows; int width = (*InMat).cols; Halide::Runtime::Buffer<uint8_t> OutImage(width,height,3); vector<Mat> three_channels; split((*InMat), three_channels); // Convert from interleaved BGR memory storage to planar RGB memory storage for (int y=0; y<height; y++) { for (int x=0; x<width; x++) { // Blue channel OutImage(x,y,2) = three_channels[0].at<uint8_t>(y,x); // Green channel OutImage(x,y,1) = three_channels[1].at<uint8_t>(y,x); // Red channel OutImage(x,y,0) = three_channels[2].at<uint8_t>(y,x); } } return OutImage; }
#pragma once #include <QThread> #include <list> #include <mutex> #include "XDecodeThread.h" struct AVCodecParameters; class XResample; class XAudioPlayer; class XAudioThread : public XDecodeThread { public: XAudioThread(); virtual ~XAudioThread(); //打开,不管成功与否都清理 virtual bool Open(AVCodecParameters *para, int sampleRate, int channels); //停止线程.清理资源 virtual void Close(); virtual void Clear(); virtual void run(); void SetPause(bool isPause); long long GetPts() { return pts; } private: std::mutex amux; bool bIsPause = false; XAudioPlayer *ap = NULL; XResample *res = NULL; //当前音频播放的pts long long pts = 0; };
#pragma once #include "stdafx.h" #include "DataTypes\vec.h" #include <map> #include "..\KEGIES\bonePacking.h" #include "DataTypes\mat.h" #define matEYEi Mat3x3i(Vec3i(1,0,0), Vec3i(0,1,0), Vec3i(0,0,1)) #define rotXi Mat3x3i(Vec3i(1,0,0), Vec3i(0,0,1), Vec3i(0,1,0)) #define rotYi Mat3x3i(Vec3i(0,0,1), Vec3i(0,1,0), Vec3i(1,0,0)) #define rotZi Mat3x3i(Vec3i(0,1,0), Vec3i(1,0,0), Vec3i(0,0,1)) class rotationMap { };
#include "StringCards.hpp" #include <iostream> // cout const string StringCards::cards = "🂠🃁🃂🃃🃄🃅🃆🃇🃈🃉🃊🃋🃌🃍🃎🂱🂲🂳🂴🂵🂶🂷🂸🂹🂺🂻🂼🂽🂾🂡🂢🂣🂤🂥🂦🂧🂨🂩🂪🂫🂬🂭🂮🃑🃒🃓🃔🃕🃖🃗🃘🃙🃚🃛🃜🃝🃞🃟" ; string StringCards::french_card(unsigned int i){ if (i<0 || i>57){ throw std::invalid_argument("StringCards::french_card() --> "+std::to_string(i)) ; } return cards.substr((i)*4,4); } string StringCards::color(unsigned int i){ if (i==0) return "♦"; if (i==1) return "♥"; if (i==2) return "♠"; if (i==3) return "♣"; else return "Indéfini"; }
// Created on: 1991-12-02 // Created by: Laurent PAINNOT // Copyright (c) 1991-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 _AppDef_MultiLine_HeaderFile #define _AppDef_MultiLine_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <AppDef_HArray1OfMultiPointConstraint.hxx> #include <Standard_Integer.hxx> #include <AppDef_Array1OfMultiPointConstraint.hxx> #include <TColgp_Array1OfPnt.hxx> #include <TColgp_Array1OfPnt2d.hxx> #include <Standard_OStream.hxx> class AppDef_MultiPointConstraint; //! This class describes the organized set of points used in the //! approximations. A MultiLine is composed of n //! MultiPointConstraints. //! The approximation of the MultiLine will be done in the order //! of the given n MultiPointConstraints. //! //! Example of a MultiLine composed of MultiPointConstraints: //! //! P1______P2_____P3______P4________........_____PNbMult //! //! Q1______Q2_____Q3______Q4________........_____QNbMult //! . . //! . . //! . . //! R1______R2_____R3______R4________........_____RNbMult //! //! Pi, Qi, ..., Ri are points of dimension 2 or 3. //! //! (P1, Q1, ...R1), ...(Pn, Qn, ...Rn) n= 1,...NbMult are //! MultiPointConstraints. //! There are NbPoints points in each MultiPointConstraint. class AppDef_MultiLine { public: DEFINE_STANDARD_ALLOC //! creates an undefined MultiLine. Standard_EXPORT AppDef_MultiLine(); //! given the number NbMult of MultiPointConstraints of this //! MultiLine , it initializes all the fields.SetValue must be //! called in order for the values of the multipoint //! constraint to be taken into account. //! An exception is raised if NbMult < 0. Standard_EXPORT AppDef_MultiLine(const Standard_Integer NbMult); //! Constructs a MultiLine with an array of MultiPointConstraints. Standard_EXPORT AppDef_MultiLine(const AppDef_Array1OfMultiPointConstraint& tabMultiP); //! The MultiLine constructed will have one line of //! 3d points without their tangencies. Standard_EXPORT AppDef_MultiLine(const TColgp_Array1OfPnt& tabP3d); //! The MultiLine constructed will have one line of //! 2d points without their tangencies. Standard_EXPORT AppDef_MultiLine(const TColgp_Array1OfPnt2d& tabP2d); //! returns the number of MultiPointConstraints of the //! MultiLine. Standard_EXPORT Standard_Integer NbMultiPoints() const; //! returns the number of Points from MultiPoints composing //! the MultiLine. Standard_EXPORT Standard_Integer NbPoints() const; //! Sets the value of the parameter for the //! MultiPointConstraint at position Index. //! Exceptions //! - Standard_OutOfRange if Index is less //! than 0 or Index is greater than the number //! of Multipoint constraints in the MultiLine. Standard_EXPORT void SetParameter (const Standard_Integer Index, const Standard_Real U); //! It sets the MultiPointConstraint of range Index to the //! value MPoint. //! An exception is raised if Index < 0 or Index> MPoint. //! An exception is raised if the dimensions of the //! MultiPoints are different. Standard_EXPORT void SetValue (const Standard_Integer Index, const AppDef_MultiPointConstraint& MPoint); //! returns the MultiPointConstraint of range Index //! An exception is raised if Index<0 or Index>MPoint. Standard_EXPORT AppDef_MultiPointConstraint Value (const Standard_Integer Index) const; //! Prints on the stream o information on the current //! state of the object. //! Is used to redefine the operator <<. Standard_EXPORT void Dump (Standard_OStream& o) const; protected: Handle(AppDef_HArray1OfMultiPointConstraint) tabMult; private: }; #endif // _AppDef_MultiLine_HeaderFile
/************************************************************************ * @project : $rootnamespace$ * @class : $safeitemrootname$ * @version : v1.0.0 * @description : * @author : $username$ * @creat : $time$ * @revise : $time$ ************************************************************************ * Copyright @ OscarShen 2017. All rights reserved. ************************************************************************/ #pragma once #ifndef SLOTH_WORD_HPP #define SLOTH_WORD_HPP #include <sloth.h> #include "character.hpp" namespace sloth { class Word { private: std::shared_ptr<std::vector<std::shared_ptr<Character>>> m_Characters; double m_Width = 0.0; double m_FontSize; public: /*********************************************************************** * @description : 存储一个单词 fontSize : 字体大小 * @author : Oscar Shen * @creat : 2017年2月22日20:05:48 ***********************************************************************/ Word(double fontSize) :m_FontSize(fontSize), m_Characters(new std::vector<std::shared_ptr<Character>>) {} /*********************************************************************** * @description : 在单词尾部增加一个字符 * @author : Oscar Shen * @creat : 2017年2月22日20:06:06 ***********************************************************************/ void addCharacter(std::shared_ptr<Character> character) { m_Characters->push_back(character); m_Width += character->getXAdvance() * m_FontSize; } inline std::shared_ptr<std::vector<std::shared_ptr<Character>>> getCharacters() const { return m_Characters; } inline double getWordWidth() const { return m_Width; } }; } #endif // !SLOTH_WORD_HPP
#include <bits/stdc++.h> using namespace std; #define TESTC "" #define PROBLEM "103" #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) struct Box{ int id,len,pre; vector<int> edge; Box(){ pre = -1; len = 1; }; void S(){ sort(edge.begin(), edge.end()); } bool operator<( const Box &rhs )const{ for(int i = 0 ; i < edge.size() ; i++ ) if( !( edge[i] < rhs.edge[i] ) ) return false; return true; } }; bool cmp(Box &lhs, Box &rhs){ int n = 0; while( lhs.edge[n] == rhs.edge[n] && n < lhs.edge.size() ) n++; if( n == lhs.edge.size() ) return lhs.id < rhs.id; return lhs.edge[n] < rhs.edge[n]; } int main(int argc, char const *argv[]) { #ifdef DBG freopen("uva" PROBLEM TESTC ".in", "r", stdin); freopen("uva" PROBLEM ".out", "w", stdout); #endif vector <Box> table; Box tmp; int box,dimension; int num,cur; stack <int> ans; while( ~scanf("%d %d",&box,&dimension) ){ table.clear(); for(int i = 1 ; i <= box ; i++ ){ tmp.edge.clear(); tmp.id = i; for(int i = 0 ; i < dimension ; i++ ){ scanf("%d",&num); tmp.edge.push_back(num); } tmp.S(); table.push_back(tmp); } sort(table.begin(), table.end(),cmp); int MAX = 0; for(int i = 0 ; i < table.size() ; i++ ){ for(int j = i+1 ; j < table.size() ; j++ ){ if( table[i] < table[j] ){ if( table[i].len+1 > table[j].len ){ table[j].len = table[i].len+1; table[j].pre = i; } } } if( table[i].len > MAX ){ MAX = table[i].len; cur = i; } } printf("%d\n",MAX ); do{ ans.push(table[cur].id); cur = table[cur].pre; }while( cur != -1 ); while( !ans.empty() ){ printf("%d%c", ans.top(), ans.size()==1 ? '\n':' ' ); ans.pop(); } } return 0; }
#include <iostream> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Codec { private: static string intToString(int num){ string res = ""; do{ res += num % 10 + '0'; num /= 10; }while(num); reverse(res.begin(), res.end()); return res; } static int stringToInt(string num){ int res = 0; for(int i=0;i<num.size();i++) res = 10 * res + num[i] - '0'; return res; } static string subdata(string data, int beginIndex){ char c = data[beginIndex]; string subData(1, c); int paranthesis = 1; int i = beginIndex + 1; while(paranthesis > 0){ subData += data[i]; if(data[i] == '{') paranthesis ++; else if(data[i] == '}') paranthesis --; i++; } return subData; } public: // Encodes a tree to a single string. string serialize(TreeNode* root) { if(!root) return "{}"; string serialized = "{"; serialized += intToString(root -> val); serialized += ","; serialized += serialize(root -> left); serialized += ","; serialized += serialize(root -> right); serialized += "}"; return serialized; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { if(data[1] == '}') return NULL; int commaIndex = data.find(','); string val = data.substr(1, commaIndex - 1); TreeNode* root = new TreeNode(stringToInt(val)); string leftData = subdata(data, commaIndex + 1); root -> left = deserialize(leftData); string rightData = subdata(data, commaIndex + 1 + leftData.size() + 1); root -> right = deserialize(rightData); return root; } }; int main(){ TreeNode *root = new TreeNode(1); root -> left = new TreeNode(2); root -> right = new TreeNode(3); root -> right -> left = new TreeNode(4); root -> right -> right = new TreeNode(5); root -> right -> right -> right = new TreeNode(6); Codec codec; cout << codec.serialize(root) << endl; codec.deserialize(codec.serialize(root)); }
#include <string> #include <exception> #include <iostream> #include "execution/engine_simpledb.hh" #include "execution/response.hh" #include "protobufs/gg.pb.h" #include "protobufs/netformats.pb.h" #include "protobufs/util.hh" #include "thunk/ggutils.hh" #include "thunk/thunk_writer.hh" #include "util/iterator.hh" #include "util/crc16.hh" using namespace std; using namespace gg; using namespace gg::thunk; using namespace simpledb::proto; class ProgramFinished : public exception {}; void SimpleDBExecutionEngine::init(ExecutionLoop& loop) { for (size_t idx = 0; idx < address_.size(); idx++) { shared_ptr<TCPConnection> connection = loop.make_connection<TCPConnection>( address_[idx], [this, idx](shared_ptr<TCPConnection>, string && data) -> bool { this->workers_[idx].parser.parse(data); while (not this->workers_[idx].parser.empty()) { auto response = this->workers_[idx].parser.front(); this->workers_[idx].parser.pop(); auto &thunk = this->workers_[idx].executing_thunks[response.id()].get(); if (response.return_code() != 0) { failure_callback_(thunk.hash(), JobStatus::ExecutionFailure); return true; } gg::protobuf::ExecutionResponse exec_resp; protoutil::from_string(response.val(), exec_resp); std::cerr << exec_resp.stdout() << endl; if (JobStatus::Success != static_cast<JobStatus>(exec_resp.return_code())) { failure_callback_(thunk.hash(), static_cast<JobStatus>(exec_resp.return_code())); return true; } for (const auto& executed_thunk: exec_resp.executed_thunks()) { for ( const auto & output : executed_thunk.outputs()) { gg::cache::insert(gg::hash::for_output(executed_thunk.thunk_hash(), output.tag()), output.hash()); if (output.data().length() > 0) { roost::atomic_create(output.data(), gg::paths::blob(output.hash())); } } gg::cache::insert(executed_thunk.thunk_hash(), executed_thunk.outputs(0).hash()); vector<ThunkOutput> thunk_outputs; for (auto & output : executed_thunk.outputs()) { if (crc16(output.hash()) % this->workers_.size() != idx) this->workers_[idx].objects.insert(output.hash()); thunk_outputs.emplace_back(move(output.hash()), move(output.tag())); } success_callback_(executed_thunk.thunk_hash(), move(thunk_outputs), 0); } workers_.at(idx).scheduled_jobs_--; running_jobs_--; } workers_.at(idx).state = State::Idle; free_workers_.insert(idx); return true; }, [] () { throw ProgramFinished(); }, [] () { throw ProgramFinished(); } ); workers_.emplace_back(idx, max(1ul, max_jobs_/address_.size()), move(connection)); free_workers_.insert(idx); } } size_t SimpleDBExecutionEngine::job_count() const { return running_jobs_; } bool SimpleDBExecutionEngine::can_execute( const Thunk & thunk ) const { (void) thunk; return true; } size_t SimpleDBExecutionEngine::prepare_worker( const Thunk& thunk, KVRequest& request, const SelectionStrategy s) { // static const bool timelog = ( getenv( "GG_TIMELOG" ) != nullptr ); static string exec_func_ = "gg-execute-simpledb-static"; request.set_id(finished_jobs_++); auto exec_request = request.mutable_exec_request(); exec_request->set_func(exec_func_); // exec_request->add_immediate_args("--cleanup"); // if (timelog) // exec_request->add_immediate_args("--timelog"); exec_request->add_immediate_args(thunk.hash()); exec_request->add_immediate_args(ThunkWriter::serialize(thunk)); for (const auto & item : join_containers(thunk.values(), thunk.executables())) { exec_request->add_file_args(item.first); } if (free_workers_.size() == 0) throw runtime_error("No free workers to pick from."); size_t selected_worker = numeric_limits<size_t>::max(); switch (s) { case SelectionStrategy::First: selected_worker = *free_workers_.begin(); break; case SelectionStrategy::MostObjectsWeight: { size_t max_common_size = 0; unordered_set<string> thunk_objects; for ( const auto & item : join_containers(thunk.values(), thunk.executables())) { thunk_objects.insert( item.first ); } for (const auto & free_lambda : free_workers_) { const auto &worker = workers_.at( free_lambda ); size_t common_size = 0; for ( const string & obj : thunk_objects ) { if (crc16(obj) % workers_.size() == free_lambda) { common_size += gg::hash::size(obj); } else if (worker.objects.count( obj ) ) { common_size += gg::hash::size(obj); } } if ( common_size > max_common_size ) { selected_worker = free_lambda; max_common_size = common_size; } } if (selected_worker == numeric_limits<size_t>::max()) { selected_worker = *free_workers_.begin(); } break; } case SelectionStrategy::MostObjects: { size_t max_common_size = 0; unordered_set<string> thunk_objects; for ( const auto & item : join_containers(thunk.values(), thunk.executables())) { thunk_objects.insert( item.first ); } for (const auto & free_lambda : free_workers_) { const auto &worker = workers_.at( free_lambda ); size_t common_size = 0; for ( const string & obj : thunk_objects ) { if (crc16(obj) % workers_.size() == free_lambda) { common_size += 1; } else if (worker.objects.count( obj ) ) { common_size += 1; } } if ( common_size > max_common_size ) { selected_worker = free_lambda; max_common_size = common_size; } } if (selected_worker == numeric_limits<size_t>::max()) { selected_worker = *free_workers_.begin(); } break; } case SelectionStrategy::Random: { // Not yet implemented! selected_worker = *free_workers_.begin(); break; } case SelectionStrategy::LargestObject: { /* what's the largest object in this thunk? */ string largest_hash; uint32_t largest_size = 0; for ( const auto & item : join_containers( thunk.values(), thunk.executables() ) ) { if ( gg::hash::size( item.first ) > largest_size ) { largest_size = gg::hash::size( item.first ); largest_hash = item.first; } } if ( largest_hash.length() ) { for ( const auto & free_worker : free_workers_ ) { if ( workers_.at( free_worker ).objects.count( largest_hash ) ) { selected_worker = free_worker; break; } } } if (selected_worker == numeric_limits<size_t>::max()) { selected_worker = *free_workers_.begin(); } break; } default: throw runtime_error( "invalid selection strategy" ); } for (const auto & item : join_containers(thunk.values(), thunk.executables())) { workers_[selected_worker].objects.insert(item.first); } return selected_worker; } void SimpleDBExecutionEngine::force_thunk(const Thunk& thunk, ExecutionLoop & loop) { (void) loop; KVRequest request; const size_t worker_idx = prepare_worker(thunk, request); const size_t slot = workers_[worker_idx].idx; workers_[worker_idx].idx++; if (workers_[worker_idx].idx >= workers_[worker_idx].num_pipeline) workers_[worker_idx].idx = 0; workers_[worker_idx].scheduled_jobs_++; workers_[worker_idx].executing_thunks[slot].reset(thunk); running_jobs_++; if (workers_[worker_idx].scheduled_jobs_ == workers_[worker_idx].num_pipeline) { workers_[worker_idx].state = State::Busy; free_workers_.erase(worker_idx); } request.set_id(slot); string s_request_(sizeof(size_t), 0); *((size_t*) &s_request_[0]) = request.ByteSize(); s_request_.append(request.SerializeAsString()); workers_[worker_idx].connection->enqueue_write(s_request_); }
#ifndef _ZORK_TRIGGER_ #define _ZORK_TRIGGER_ #include "Zork_Def.hpp" #include <list> #include <iostream> #include <string> using namespace std; class Trigger { public: Trigger(const string& com, const string& prt,bool permenant):command(com),print(prt),type(permenant){} void addAction(Action act){action.push_front(act);} void addCondition(Condition cd){cond.push_front(cd);} const string& getCMD() const {return command;} const bool isPerm() const {return type;} const string& getprint() const {return print;} bool run(const string& input) { list<Condition>::iterator i; // check if conditions meets if(command.find(input) == string::npos) return false; for(i=cond.begin();i!=cond.end();++i){ if(!(*i)()){ return false; } } // run logic cout<<print<<endl; list<Action>::iterator t; for(t=action.begin();t!=action.end();++t){ (*t)(input); } return true; } private: bool type; string command; string print; list<Action> action; list<Condition> cond; }; #endif
#include "Switzerland.hpp" /***************************************************************** * default constructor * The default constructor initializes the name to the country and the * checkpoint variables to false. ******************************************************************/ Switzerland::Switzerland() { name = "Switzerland"; moveOn = false; optionA = false; optionB = false; watchFound = false; } Switzerland::~Switzerland() { } /*************************************************************** * explore() * This is a virtual function from Country. It takes the player * through the city and send him to the next country. ***************************************************************/ void Switzerland::explore(Player *p) { char c = menu1(); while (moveOn == false) { if (c == 'a') { cout << "\nThe exchange rate hurts. That'll be $25." << endl; p->withdraw(25); cout << "\nWell, at least the old town is nice..." << endl; if (p->searchItem("Swiss watch") == false) { cout << "\nHey, what's that behind the Fraumünster Cathedral?" << endl; cout << "\nA watch?! No way! I've heard these are very valuable. " << endl; cout << "\na. Take it." << endl; cout << "b. Leave it. " << endl; InputValidation i; char z = i.getChar2ab(); if (z == 'a' || z == 'A') { p->checkSize("Swiss watch"); watchFound = true; } if (z == 'b' || z == 'B') { cout << endl << "Inventory: "; p->printInventory(); } } optionA = true; } if (c == 'b') { cout << "\nThe exchange rate hurts. That'll be $25." << endl; p->withdraw(25); hostel(p); optionB = true; } if (optionA == true && optionB == true) { moveOn = true; } if (p->getMoney() <= 0) { return; } if (moveOn == false) { c = menu1(); } } moveOn = false; c = menu2(); if (c == 'a' || c == 'A') { p->setCountry(this->north->getName()); cout << "To " << p->getCountry() << "?" << endl; cout << "That'll be $20. " << endl; p->withdraw(20); } if (c == 'b' || c == 'B') { p->setCountry(this->east->getName()); cout << "To " << p->getCountry() << "?" << endl; cout << "That'll be $20. " << endl; p->withdraw(25); } } /*************************************************************** * hostel() * This is a virtual function from Country. It simulates * a conversation with a hostel employee. ***************************************************************/ void Switzerland::hostel(Player *p) { cout << "\nHi, how can I help you?" << endl; cout << "\na. I think I lost my laptop, can you check for me?" << endl; InputValidation i; char c = i.getChar1(); cout << "\nSure, what's your first name?" << endl; string name; cin >> name; cout << "\nSorry " << name << ". No laptop. But I did find the Swiss army knife under your name. " << endl; cout << "\na. Thanks, I was looking for that! " << endl; cout << "b. Oh, that's not mine. " << endl; c = i.getChar2ab(); if (c == 'a') { cout << "\nSure thing. " << endl; p->checkSize("Swiss army knife"); } if (c == 'b') { cout << "\nOh, ok. Thanks for your honesty!" << endl; } } /*************************************************************** * menu1() * The first menu is for things to do in the city. ***************************************************************/ char Switzerland::menu1() { cout << "\nBack to Switzerland. I can't stay long here, it's too expensive! " << endl; cout << "Let me think, where was I in Zurich?..." << endl; cout << "\na. Go to the old town. " << endl; cout << "\nb. Go to the hostel. " << endl; InputValidation i; char c = i.getChar2ab(); return c; } /*************************************************************** * menu2() * The second menu is for selecting the next country. ***************************************************************/ char Switzerland::menu2() { cout << "\nThe laptop isn't in Zurich, but I'm not giving up. " << endl; cout << "a. Go to Germany. " << endl; cout << "b. Go to Austria. " << endl; InputValidation i; char c = i.getChar2ab(); return c; }
#ifndef _DtBarcoPesquero_ #define _DtBarcoPesquero_ #include "DtBarco.h" class DtBarcoPesquero: public DtBarco{ private: int capacidad; int carga; public: //Constructores DtBarcoPesquero(string nombre,string id, int capacidad, int carga); //Getters int get_capacidad(); int get_carga(); //Destructor ~DtBarcoPesquero(); friend const ostream& operator<< (ostream& os, DtBarcoPesquero obj); }; #endif
/** * Project: ows-qt-console * File name: domains_manager.cpp * Description: this class describes the connections management dialog window * * @author Mathieu Grzybek on 2012-04-30 * @copyright 2012 Mathieu Grzybek. All rights reserved. * @version $Id: code-gpl-license.txt,v 1.2 2004/05/04 13:19:30 garry Exp $ * * @see The GNU Public License (GPL) version 3 or higher * * * ows-qt-console 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 GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "domains_manager.h" #include "ui_domains_manager.h" Domains_Manager::Domains_Manager(QStandardItemModel* model, QDialog* parent) : QDialog(parent), ui(new Ui::Domains_Manager) { servers_model = model; ui->setupUi(this); ui->Saved_Servers_List->setModel(model); ui->Saved_Servers_List->show(); } Domains_Manager::~Domains_Manager() { delete ui; servers_model = NULL; } void Domains_Manager::add_blank_server() { QStandardItem new_item; new_item.appendRow(new QStandardItem("")); new_item.appendRow(new QStandardItem("")); new_item.appendRow(new QStandardItem("")); new_item.appendRow(new QStandardItem("")); servers_model->appendRow(&new_item); } void Domains_Manager::on_New_Server_Button_clicked() { add_blank_server(); } void Domains_Manager::on_Delete_Server_Button_clicked() { QModelIndexList selected_items = ui->Saved_Servers_List->selectionModel()->selectedIndexes(); Q_FOREACH(QModelIndex index, selected_items) { servers_model->removeRow(index.row()); } }
// // Created by kumaran on 9/6/20. // #include <bits/stdc++.h> using namespace std; #define debug(x) cout << '>' << #x << ':' << x << endl; #define all(v) v.begin(), v.end() #define pii pair<int, int> #define mxN 1e7 #define newl cout << "\n" #define vi vector<int> typedef pair<int, pair<int, int>> threepair; class Solution { public: int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) { int n = matrix.size(); if(n == 0) return 0; int m = matrix[0].size(), ans = 0; vector<vector<int>> dp(n, vector<int>(m, 0)); for(int i = 0; i < m; i++) { dp[0][i] = matrix[0][i]; } for(int i = 1; i < n; i++) { for(int j = 0; j < m; j++ ) { dp[i][j] += dp[i-1][j] + matrix[i][j]; cout<<dp[i][j]<<" "; } newl; } newl; vector<int> arr(m, 0); for(int i = 0; i < n; i++) { debug(i); for(int j = 0; j <= i; j++ ) { debug(j); fill(all(arr), 0); for(int k = 0; k < m; k++) { if(j-1 >= 0) { arr[k] -= dp[j][k]; } arr[k] += dp[i][k]; } for(auto x:arr) cout<<x<<" "; newl; //find prefix sum hash to int sum = 0; unordered_map<int, int> hm; hm[0] = 1; for(int k = 0; k < m; k++) { sum += arr[k]; if(hm.find(sum - target) != hm.end()) ans += hm[sum-target]; hm[sum]++; } } } return ans; } }; int main() { auto sol = Solution(); vector<vector<int>> arr = {{0,1,0}, {1,1,1}, {0,1,0}}; vector<int> vec = {2, 3, 4}; int n = arr.size(); auto res = sol.numSubmatrixSumTarget(arr, 0); debug(res); vector<int> v; }
/* * 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_UTILS_H_ #define LSST_SG_UTILS_H_ /// \file /// \brief This file declares miscellaneous utility methods. #include "Angle.h" namespace lsst { namespace sg { // Forward declarations class Vector3d; class UnitVector3d; /// Let p be the unit vector closest to v that lies on the plane with /// normal n in the direction of the cross product of a and b. If p is in the /// interior of the great circle segment from a to b, then this function /// returns the squared chord length between p and v. Otherwise it returns 4 - /// the maximum squared chord length between any pair of points on the unit /// sphere. double getMinSquaredChordLength(Vector3d const & v, Vector3d const & a, Vector3d const & b, Vector3d const & n); /// Let p be the unit vector furthest from v that lies on the plane with /// normal n in the direction of the cross product of a and b. If p is in the /// interior of the great circle segment from a to b, then this helper function /// returns the squared chord length between p and v. Otherwise it returns 0 - /// the minimum squared chord length between any pair of points on the sphere. double getMaxSquaredChordLength(Vector3d const & v, Vector3d const & a, Vector3d const & b, Vector3d const & n); /// `getMinAngleToCircle` returns the minimum angular separation between a /// point at latitude x and the points on the circle of constant latitude c. inline Angle getMinAngleToCircle(Angle x, Angle c) { return abs(x - c); } /// `getMaxAngleToCircle` returns the maximum angular separation between a /// point at latitude x and the points on the circle of constant latitude c. inline Angle getMaxAngleToCircle(Angle x, Angle c) { Angle a = getMinAngleToCircle(x, c); if (abs(x) <= abs(c)) { return a + Angle(PI) - 2.0 * abs(c); } if (a < abs(x)) { return Angle(PI) - 2.0 * abs(c) - a; } return Angle(PI) + 2.0 * abs(c) - a; } /// `getWeightedCentroid` returns the center of mass of the given spherical /// triangle (assuming a uniform mass distribution over the triangle surface), /// weighted by the triangle area. Vector3d getWeightedCentroid(UnitVector3d const & v0, UnitVector3d const & v1, UnitVector3d const & v2); }} // namespace lsst::sg #endif // LSST_SG_UTILS_H_
#ifndef STAGE_H #define STAGE_H #include "enemy.h" #include <vector> using std::vector; class Room { private: static int nbRoom; vector<Enemy*> listEnemy; public: Room(int a=0); ~Room(); vector<Enemy*> getListEnemy(){return listEnemy;} //Vérifie si une salle tous les monstres de la salle sont morts (pour savoir si on peut passer ou pas à la salle suivante) bool isClear(); }; #endif // STAGE_H
/*! @file LogVol_Collimator_ToSample.hh @brief Defines mandatory user class LogVol_Collimator_ToSample. @date August, 2012 @author Flechas (D. C. Flechas dcflechasg@unal.edu.co) @version 1.9 In this header file, the 'physical' setup is defined: materials, geometries and positions. This class defines the experimental hall used in the toolkit. */ /* no-geant4 classes*/ #include "LogVol_Collimator_ToSample.hh" /* units and constants */ #include "G4UnitsTable.hh" #include "G4SystemOfUnits.hh" #include "G4PhysicalConstants.hh" /* geometric objects */ #include "G4Box.hh" #include "G4Polycone.hh" /* logic and physical volume */ #include "G4LogicalVolume.hh" /* geant4 materials */ #include "G4NistManager.hh" /* visualization */ #include "G4VisAttributes.hh" LogVol_Collimator_ToSample:: LogVol_Collimator_ToSample(G4String fname,G4double frad,G4double fheight,G4double fang, G4double fsrad, G4double fsourceh, G4Material* fmaterial): G4LogicalVolume(new G4Box(fname+"_Sol",10*mm, 10*mm, 10*mm),fmaterial,fname,0,0,0) { /* set variables */ SetName(fname); // Dimensions // SetRadius(frad); if(fheight>fsourceh) SetHeight(fheight); else { SetHeight(3.0*mm); G4cout<<"\n"<<"\n"<<"*********** WARNING MESSAGE ***********"<<"\n"<<G4endl; G4cout<<"WARNING:: Height of the collimator is smaller than source"<<G4endl; G4cout<<"Height of collimator ro sample will be 3 mm"<<"\n"<<G4endl; } SetAngOpening(fang); SetSourceRadius(fsrad); SetSourceHeight(fsourceh); // Construct solid volume // ConstructSolidVol_Collimator_ToSample(); //*** Visualization ***// G4VisAttributes* black_vis = new G4VisAttributes(true,G4Colour(0.4,0.4,0.4)); black_vis->SetForceWireframe(false); black_vis->SetForceSolid(false); this->SetVisAttributes(black_vis); } LogVol_Collimator_ToSample::~LogVol_Collimator_ToSample() {} void LogVol_Collimator_ToSample::ConstructSolidVol_Collimator_ToSample(void) { G4double h1=2.0*mm; G4double rinner1=1.3/2.0*mm; G4double rinner2=rinner1+h1*std::tan(AngOp/rad); if(Height<4.0*mm) h1=Height-SourceH; const G4int numZPlanesCollimator_ToSample=5; const G4double zPlaneCollimator_ToSample[]={0.0, -SourceH,-SourceH, -SourceH-h1, -Height}; const G4double rInnerCollimator_ToSample[]={SourceRad,SourceRad,rinner1,rinner2,MaxRadius}; const G4double rOuterCollimator_ToSample[]={MaxRadius,MaxRadius,MaxRadius,MaxRadius,MaxRadius}; Collimator_ToSample_solid = new G4Polycone(Name+"_Sol",0.*rad,2*M_PI*rad, numZPlanesCollimator_ToSample, zPlaneCollimator_ToSample, rInnerCollimator_ToSample, rOuterCollimator_ToSample); /*** Main trick here: Set the new solid volume ***/ SetSolidVol_Collimator_ToSample(); } void LogVol_Collimator_ToSample::SetSolidVol_Collimator_ToSample(void) { /*** Main trick here: Set the new solid volume ***/ if(Collimator_ToSample_solid) this->SetSolid(Collimator_ToSample_solid); }
/* -*- mode: c++; c-file-style: "gnu" -*- */ group "XMLUtils.XMLFragment.xpath"; require init; require XMLUTILS_XMLFRAGMENT_XPATH_SUPPORT; include "modules/xmlutils/xmlfragment.h"; test("XMLFragment xpath #1") { XMLFragment fragment; verify(OpStatus::IsSuccess(fragment.Parse(UNI_L("<root><element1/>text1<element2/>text2<element3/>text3</root>")))); double result = 0; verify(OpStatus::IsSuccess(fragment.EvaluateXPathToNumber(result, UNI_L("count(root/*)")))); verify(result == 3); } test("XMLFragment xpath #2") { XMLFragment fragment; verify(OpStatus::IsSuccess(fragment.Parse(UNI_L("<root><element1/>text1<element2/>text2<element3/>text3</root>")))); BOOL result = FALSE; verify(OpStatus::IsSuccess(fragment.EvaluateXPathToBoolean(result, UNI_L("count(root/*)=3")))); verify(result == TRUE); } test("XMLFragment xpath #3") { XMLFragment fragment; verify(OpStatus::IsSuccess(fragment.Parse(UNI_L("<root><element1/>text1<element2/>text2<element3/>text3</root>")))); OpString result; verify(OpStatus::IsSuccess(fragment.EvaluateXPathToString(result, UNI_L("root/text()[2]")))); verify(result.Compare(UNI_L("text2")) == 0); }
//Read a cover file void cover_read(string file, CoverList & l, int n) { //Create the ifstream object ifstream input; //Open the cover file input.open(file.c_str()); //Check for error opening the cover file if(input.is_open() == false) { //Display the error cerr << "Error opening " << file << endl; //Exit exit(EXIT_FAILURE); } //Auxuliar strings string str, arr[_MAX_BAMS], chrnow = "null"; //Auxiliar pointers for the chromosomes CoverList aux, end; //Initialize the list l = NULL; //Read the input file while(!input.eof()) { //Get the first line getline(input, str); //Check if is empty string if(str == "") { continue; } //Converts string to array str_split(str, arr, _MAX_BAMS, "\t"); //Create the new cover value aux = new Cover; //Save the chromosome aux->chromosome = arr[0]; //Save the position aux->position = stoi(arr[1]); //Initialize the coverage values aux->values = new float[n]; //Read all the cover values for(int i = 0; i < n; i++) { //Save the cover value aux->values[i] = stof(arr[i + 2]); } //Next element aux->next = NULL; //Check for empty list if(l == NULL) { //Initialize the list l = aux; //Initialize the last element pointer end = l; } else { //Save this element end->next = aux; //Point to the next element end = aux; } } //Finish the list end->next = NULL; //Close the file input.close(); }
#include "Tank-turret.hpp" Turret::Turret(SDL_Renderer* rend, SDL_Texture* ast, SDL_Rect mov): Unit(rend, ast), mover(mov) { turret_src = {603, 0, 507, 152}; } void Turret::draw() { Unit::draw(turret_src,turret_mover); }
#pragma once #include "CoreMinimal.h" #include "Engine/DataTable.h" #include "Animation/AnimInstance.h" #include "EnemyData.generated.h" // 적 캐릭터 정보를 나타내는 구조체 USTRUCT(BlueprintType) struct ARPG_API FEnemyData : public FTableRowBase { GENERATED_USTRUCT_BODY() public: // 적 코드 UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "기본") FName EnemyCode; // 적 이름 UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "기본") FText EnemyName; // 적 Capsule 크기 UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "기본") float CapsuleHalfHeight; // 적 Capsule 반지름 UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "기본") float CapsuleRadius; // 적 SkeletalMesh 경로 UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "기본") FSoftObjectPath SkeletalMeshPath; // 적 애님 블루프린트 클래스 UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "기본") TSubclassOf<UAnimInstance> AnimClass; // 최대 이동 속력 UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "이동") float MaxMoveSpeed; // 사용되는 BehaviorTree 애셋 경로 UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "AI") FSoftObjectPath UseBehaviorTreeAssetPath; public : FEnemyData(); };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #if defined(VEGA_SUPPORT) && (defined(VEGA_3DDEVICE) || defined(CANVAS3D_SUPPORT)) #include "modules/libvega/vega3ddevice.h" // The component copy templates need some info akin to std::numeric_limits<T> so we just implement what we need here. template<typename T> inline T maxval() { return CHAR_MAX; }; template<> inline unsigned char maxval() { return UCHAR_MAX; } template<> inline short maxval() { return SHRT_MAX; } template<> inline unsigned short maxval() { return USHRT_MAX; } template<typename T> inline bool issigned() { return true; } template<> inline bool issigned<unsigned char>() { return false; } template<> inline bool issigned<unsigned short>() { return false; } // Step any pointer in byte increments. template <typename T> inline void IncPointerBytes(T *&ptr, unsigned int bytes) { ptr = (T*)(((char *)ptr) + bytes); } // Copy a component over as is without modifying it except for zero-striding it in the destination. void CopyVertexComponent(void *inBuffer, unsigned int inStride, void *outBuffer, unsigned int outSize, unsigned int maxVertices) { if (inStride == outSize) op_memcpy(outBuffer, inBuffer, outSize * maxVertices); else { unsigned char *in = (unsigned char*)inBuffer; unsigned char *out = (unsigned char *)outBuffer; for (unsigned int i = 0; i < maxVertices; ++i) { for (unsigned int b = 0; b < outSize; ++b) *out++ = in[b]; in += inStride; } } } // Copy a component over, statically casting it to the right type and widen it to match the target // number of components by filling it with zeroes except element four which will be set to one. template <typename IN_TYPE, unsigned int IN_COMP, typename OUT_TYPE, unsigned int OUT_COMP, bool NORM> void ConvertVertexComponentCast(void *inBuffer, unsigned int inStride, void *outBuffer, unsigned int maxVertices) { const IN_TYPE *in = (const IN_TYPE*)inBuffer; OUT_TYPE *out = (OUT_TYPE *)outBuffer; const OUT_TYPE one = NORM ? maxval<OUT_TYPE>() : OUT_TYPE(1); for (unsigned int i = 0; i < maxVertices; ++i) { for (unsigned int c = 0; c < IN_COMP; ++c) *out++ = static_cast<OUT_TYPE>(in[c]); for (unsigned int c = IN_COMP; c < OUT_COMP; ++c) *out++ = c == 3 ? one : OUT_TYPE(0); IncPointerBytes(in, inStride); } } // Copy a component over but normalize it to a float. No need to widen. template <typename IN_TYPE, unsigned int IN_COMP> void ConvertVertexComponentNormFloat(void *inBuffer, unsigned int inStride, void *outBuffer, unsigned int maxVertices) { const IN_TYPE *in = (const IN_TYPE*)inBuffer; float *out = (float *)outBuffer; const IN_TYPE one = maxval<IN_TYPE>(); const float div = 1.0f/(2*static_cast<float>(maxval<IN_TYPE>())+1); for (unsigned int i = 0; i < maxVertices; ++i) { for (unsigned int c = 0; c < IN_COMP; ++c) { float f = static_cast<float>(in[c]); if (issigned<IN_TYPE>()) *out++ = (2 * f + 1) * div; else *out++ = f / one; } IncPointerBytes(in, inStride); } } void CopyVertexComponent(void *inPtr, unsigned int inStride, VEGA3dVertexLayout::VertexType inType, void *outPtr, unsigned int outStride, VEGA3dVertexLayout::VertexType outType, unsigned int maxVertices, bool normalize) { // Identity, copy across as is. if (inType == outType) CopyVertexComponent(inPtr, inStride, outPtr, outStride, maxVertices); // Non-normalized USHORT1-4 --> FLOAT1-4 // Normalized USHORT1 --> USHORT2 // Normalized USHORT3 --> USHORT4 else if (inType == VEGA3dVertexLayout::USHORT1 && outType == VEGA3dVertexLayout::FLOAT1 && !normalize) ConvertVertexComponentCast<unsigned short, 1, float, 1, false>(inPtr, inStride, outPtr, maxVertices); else if (inType == VEGA3dVertexLayout::USHORT2 && outType == VEGA3dVertexLayout::FLOAT2 && !normalize) ConvertVertexComponentCast<unsigned short, 2, float, 2, false>(inPtr, inStride, outPtr, maxVertices); else if (inType == VEGA3dVertexLayout::USHORT3 && outType == VEGA3dVertexLayout::FLOAT3 && !normalize) ConvertVertexComponentCast<unsigned short, 3, float, 3, false>(inPtr, inStride, outPtr, maxVertices); else if (inType == VEGA3dVertexLayout::USHORT4 && outType == VEGA3dVertexLayout::FLOAT4 && !normalize) ConvertVertexComponentCast<unsigned short, 4, float, 4, false>(inPtr, inStride, outPtr, maxVertices); else if (inType == VEGA3dVertexLayout::USHORT1 && outType == VEGA3dVertexLayout::USHORT2 && normalize) ConvertVertexComponentCast<unsigned short, 1, unsigned short, 2, true>(inPtr, inStride, outPtr, maxVertices); else if (inType == VEGA3dVertexLayout::USHORT3 && outType == VEGA3dVertexLayout::USHORT4 && normalize) ConvertVertexComponentCast<unsigned short, 3, unsigned short, 4, true>(inPtr, inStride, outPtr,maxVertices); // Non-normalized SHORT1-4 --> FLOAT1-4 // Normalized SHORT1 --> SHORT2 // Normalized SHORT3 --> SHORT4 else if (inType == VEGA3dVertexLayout::SHORT1 && outType == VEGA3dVertexLayout::FLOAT1 && !normalize) ConvertVertexComponentCast<short, 1, float, 1, false>(inPtr, inStride, outPtr, maxVertices); else if (inType == VEGA3dVertexLayout::SHORT3 && outType == VEGA3dVertexLayout::FLOAT2 && !normalize) ConvertVertexComponentCast<short, 2, float, 2, false>(inPtr, inStride, outPtr, maxVertices); else if (inType == VEGA3dVertexLayout::SHORT3 && outType == VEGA3dVertexLayout::FLOAT3 && !normalize) ConvertVertexComponentCast<short, 3, float, 3, false>(inPtr, inStride, outPtr, maxVertices); else if (inType == VEGA3dVertexLayout::SHORT4 && outType == VEGA3dVertexLayout::FLOAT4 && !normalize) ConvertVertexComponentCast<short, 4, float, 4, false>(inPtr, inStride, outPtr, maxVertices); else if (inType == VEGA3dVertexLayout::SHORT1 && outType == VEGA3dVertexLayout::SHORT2 && normalize) ConvertVertexComponentCast<short, 1, short, 2, true>(inPtr, inStride, outPtr, maxVertices); else if (inType == VEGA3dVertexLayout::SHORT3 && outType == VEGA3dVertexLayout::SHORT4 && normalize) ConvertVertexComponentCast<short, 3, short, 4, true>(inPtr, inStride, outPtr, maxVertices); // Non-normalized UBYTE1-4 --> FLOAT1-4 // Normalized UBYTE1-3 --> UBYTE4 else if (inType == VEGA3dVertexLayout::UBYTE1 && outType == VEGA3dVertexLayout::FLOAT1 && !normalize) ConvertVertexComponentCast<unsigned char, 1, float, 1, false>(inPtr, inStride, outPtr, maxVertices); else if (inType == VEGA3dVertexLayout::UBYTE2 && outType == VEGA3dVertexLayout::FLOAT2 && !normalize) ConvertVertexComponentCast<unsigned char, 2, float, 2, false>(inPtr, inStride, outPtr, maxVertices); else if (inType == VEGA3dVertexLayout::UBYTE3 && outType == VEGA3dVertexLayout::FLOAT3 && !normalize) ConvertVertexComponentCast<unsigned char, 3, float, 3, false>(inPtr, inStride, outPtr, maxVertices); else if (inType == VEGA3dVertexLayout::UBYTE4 && outType == VEGA3dVertexLayout::FLOAT4 && !normalize) ConvertVertexComponentCast<unsigned char, 4, float, 4, false>(inPtr, inStride, outPtr, maxVertices); else if (inType == VEGA3dVertexLayout::UBYTE1 && outType == VEGA3dVertexLayout::UBYTE4 && normalize) ConvertVertexComponentCast<unsigned char, 1, unsigned char, 4, true>(inPtr, inStride, outPtr, maxVertices); else if (inType == VEGA3dVertexLayout::UBYTE2 && outType == VEGA3dVertexLayout::UBYTE4 && normalize) ConvertVertexComponentCast<unsigned char, 2, unsigned char, 4, true>(inPtr, inStride, outPtr, maxVertices); else if (inType == VEGA3dVertexLayout::UBYTE3 && outType == VEGA3dVertexLayout::UBYTE4 && normalize) ConvertVertexComponentCast<unsigned char, 3, unsigned char, 4, true>(inPtr, inStride, outPtr, maxVertices); // Non-normalized BYTE1-4 --> FLOAT1-4 // Normalized BYTE1-4 --> BYTE4 else if (inType == VEGA3dVertexLayout::BYTE1 && outType == VEGA3dVertexLayout::FLOAT1 && !normalize) ConvertVertexComponentCast<char, 1, float, 1, false>(inPtr, inStride, outPtr, maxVertices); else if (inType == VEGA3dVertexLayout::BYTE2 && outType == VEGA3dVertexLayout::FLOAT2 && !normalize) ConvertVertexComponentCast<char, 2, float, 2, false>(inPtr, inStride, outPtr, maxVertices); else if (inType == VEGA3dVertexLayout::BYTE3 && outType == VEGA3dVertexLayout::FLOAT3 && !normalize) ConvertVertexComponentCast<char, 3, float, 3, false>(inPtr, inStride, outPtr, maxVertices); else if (inType == VEGA3dVertexLayout::BYTE4 && outType == VEGA3dVertexLayout::FLOAT4 && !normalize) ConvertVertexComponentCast<char, 4, float, 4, false>(inPtr, inStride, outPtr, maxVertices); else if (inType == VEGA3dVertexLayout::BYTE1 && outType == VEGA3dVertexLayout::BYTE4 && normalize) ConvertVertexComponentCast<char, 1, char, 4, true>(inPtr, inStride, outPtr, maxVertices); else if (inType == VEGA3dVertexLayout::BYTE2 && outType == VEGA3dVertexLayout::BYTE4 && normalize) ConvertVertexComponentCast<char, 2, char, 4, true>(inPtr, inStride, outPtr, maxVertices); else if (inType == VEGA3dVertexLayout::BYTE3 && outType == VEGA3dVertexLayout::BYTE4 && normalize) ConvertVertexComponentCast<char, 3, char, 4, true>(inPtr, inStride, outPtr, maxVertices); else { OP_ASSERT(false); // Conversion not implemented! } } #endif
/*! * \file mpredialog.cpp * \author Simon Coakley * \date 2012 * \copyright Copyright (c) 2012 University of Sheffield * \brief Implementation of mpre dialog */ #include <QtGui> #include <QHBoxLayout> #include <QVBoxLayout> #include "./mpredialog.h" MpreDialog::MpreDialog(Machine * a, QString * mt, QWidget *parent) : QDialog(parent) { setupUi(this); agent = a; QStringList operators; operators << "==" << "!=" << "<" << ">" << "<=" << ">=" << "IN"; comboBox_valueOp->addItems(operators); operators.clear(); operators << "AND" << "OR"; comboBox_nestedOp->addItems(operators); QStringList agentMemoryNames = agent->getAgentMemoryNames(agent->name); comboBox_lhsAgentVariable->addItems(agentMemoryNames); comboBox_rhsAgentVariable->addItems(agentMemoryNames); comboBox_period->addItems(agent->getTimeUnits()); comboBox_phaseVariable->addItems(agentMemoryNames); if (mt == 0) { // if agent then disable message variables checkBox_lhsMessageVariable->setEnabled(false); comboBox_lhsMessageVariable->setEnabled(false); checkBox_rhsMessageVariable->setEnabled(false); comboBox_rhsMessageVariable->setEnabled(false); } else { // if message then populate message variable combo boxes QStringList messageMemoryNames = agent->getMessageMemoryNames(*mt); comboBox_lhsMessageVariable->addItems(messageMemoryNames); comboBox_rhsMessageVariable->addItems(messageMemoryNames); } connect(checkBox_enabled, SIGNAL(clicked(bool)), this, SLOT(enableCondition(bool))); connect(checkBox_lhsAgentVariable, SIGNAL(clicked(bool)), this, SLOT(checkedLhsAgentVariable(bool))); connect(checkBox_lhsMessageVariable, SIGNAL(clicked(bool)), this, SLOT(checkedLhsMessageVariable(bool))); connect(checkBox_lhsValue, SIGNAL(clicked(bool)), this, SLOT(checkedLhsValue(bool))); connect(checkBox_rhsAgentVariable, SIGNAL(clicked(bool)), this, SLOT(checkedRhsAgentVariable(bool))); connect(checkBox_rhsMessageVariable, SIGNAL(clicked(bool)), this, SLOT(checkedRhsMessageVariable(bool))); connect(checkBox_rhsValue, SIGNAL(clicked(bool)), this, SLOT(checkedRhsValue(bool))); connect(radioButton_value, SIGNAL(clicked()), this, SLOT(valueClicked())); connect(radioButton_time, SIGNAL(clicked()), this, SLOT(timeClicked())); connect(radioButton_nested, SIGNAL(clicked()), this, SLOT(nestedClicked())); connect(pushButton_editLhs, SIGNAL(clicked()), this, SLOT(editLhsClicked())); connect(pushButton_editRhs, SIGNAL(clicked()), this, SLOT(editRhsClicked())); connect(checkBox_phaseVariable, SIGNAL(clicked(bool)), this, SLOT(disableTimePhaseValue(bool))); connect(checkBox_phaseValue, SIGNAL(clicked(bool)), this, SLOT(disableTimePhaseVariable(bool))); connect(pushButton_levelUp, SIGNAL(clicked()), this, SLOT(levelUpClicked())); } void MpreDialog::setCurrentCondition(Condition *cond) { c = cond; if (c->enabled) lineEdit_condition->setText(c->toString()); else lineEdit_condition->setText(""); /* If not root condition */ if (c->parentCondition) { checkBox_enabled->setChecked(true); checkBox_enabled->setEnabled(false); pushButton_levelUp->setEnabled(true); } else { checkBox_enabled->setEnabled(true); pushButton_levelUp->setEnabled(false); } checkBox_enabled->setChecked(c->enabled); enableCondition(c->enabled); if (c->isValues) { if (c->enabled) { groupBox_value->setEnabled(true); groupBox_time->setEnabled(false); groupBox_nested->setEnabled(false); } radioButton_value->setChecked(true); checkBox_notValue->setChecked(c->isNot); checkBox_lhsAgentVariable->setChecked(c->lhsIsAgentVariable); checkBox_lhsMessageVariable->setChecked(c->lhsIsMessageVariable); checkBox_lhsValue->setChecked(c->lhsIsValue); comboBox_lhsAgentVariable->setEnabled(c->lhsIsAgentVariable); comboBox_lhsMessageVariable->setEnabled(c->lhsIsMessageVariable); doubleSpinBox_lhsValue->setEnabled(c->lhsIsValue); doubleSpinBox_lhsValue->setValue(c->lhsDouble); comboBox_lhsAgentVariable->setCurrentIndex(0); if (c->lhsIsAgentVariable) { for (int i = 0; i < comboBox_lhsAgentVariable->count(); i++) { if (QString::compare(comboBox_lhsAgentVariable->itemText(i), c->lhs) == 0) comboBox_lhsAgentVariable->setCurrentIndex(i); } } comboBox_lhsMessageVariable->setCurrentIndex(0); if (c->lhsIsMessageVariable) { for (int i = 0; i < comboBox_lhsMessageVariable->count(); i++) { if (QString::compare(comboBox_lhsMessageVariable->itemText(i), c->lhs) == 0) comboBox_lhsMessageVariable->setCurrentIndex(i); } } checkBox_rhsAgentVariable->setChecked(c->rhsIsAgentVariable); checkBox_rhsMessageVariable->setChecked(c->rhsIsMessageVariable); checkBox_rhsValue->setChecked(c->rhsIsValue); comboBox_rhsAgentVariable->setEnabled(c->rhsIsAgentVariable); comboBox_rhsMessageVariable->setEnabled(c->rhsIsMessageVariable); doubleSpinBox_rhsValue->setEnabled(c->rhsIsValue); doubleSpinBox_rhsValue->setValue(c->rhsDouble); comboBox_rhsAgentVariable->setCurrentIndex(0); if (c->rhsIsAgentVariable) { for (int i = 0; i < comboBox_rhsAgentVariable->count(); i++) { if (QString::compare(comboBox_rhsAgentVariable->itemText(i), c->rhs) == 0) comboBox_rhsAgentVariable->setCurrentIndex(i); } } comboBox_rhsMessageVariable->setCurrentIndex(0); if (c->rhsIsMessageVariable) { for (int i = 0; i < comboBox_rhsMessageVariable->count(); i++) { if (QString::compare(comboBox_rhsMessageVariable->itemText(i), c->rhs) == 0) comboBox_rhsMessageVariable->setCurrentIndex(i); } } for (int i = 0; i < comboBox_valueOp->count(); i++) { if (QString::compare(comboBox_valueOp->itemText(i), c->op) == 0) comboBox_valueOp->setCurrentIndex(i); } } else { checkBox_notValue->setChecked(false); checkBox_lhsAgentVariable->setChecked(false); checkBox_lhsValue->setChecked(true); comboBox_lhsAgentVariable->setEnabled(false); doubleSpinBox_lhsValue->setEnabled(true); doubleSpinBox_lhsValue->setValue(0.0); comboBox_lhsAgentVariable->setCurrentIndex(0); checkBox_rhsAgentVariable->setChecked(false); checkBox_rhsValue->setChecked(true); comboBox_rhsAgentVariable->setEnabled(false); doubleSpinBox_rhsValue->setEnabled(true); doubleSpinBox_rhsValue->setValue(0.0); comboBox_rhsAgentVariable->setCurrentIndex(0); comboBox_valueOp->setCurrentIndex(0); } if (c->isTime) { if (c->enabled) { groupBox_value->setEnabled(false); groupBox_time->setEnabled(true); groupBox_nested->setEnabled(false); } radioButton_time->setChecked(true); checkBox_notTime->setChecked(c->isNot); if (c->timePeriod == "") { comboBox_period->setCurrentIndex(0); } else { for (int i = 0; i < comboBox_period->count(); i++) { if (QString::compare(comboBox_period->itemText(i), c->timePeriod) == 0) comboBox_period->setCurrentIndex(i); } } checkBox_phaseVariable->setChecked(c->timePhaseIsVariable); checkBox_phaseValue->setChecked(!c->timePhaseIsVariable); comboBox_phaseVariable->setEnabled(c->timePhaseIsVariable); spinBox_phaseValue->setEnabled(!c->timePhaseIsVariable); if (c->timePhaseIsVariable) { if (c->timePhaseVariable == "") { comboBox_phaseVariable->setCurrentIndex(0); } else { for (int i = 0; i < comboBox_phaseVariable->count(); i++) { if (QString::compare(comboBox_phaseVariable->itemText(i), c->timePhaseVariable) == 0) comboBox_phaseVariable->setCurrentIndex(i); } } } else { spinBox_phaseValue->setValue(c->timePhaseValue); } spinBox_duration->setValue(c->timeDuration); } else { checkBox_notTime->setChecked(false); comboBox_period->setCurrentIndex(0); checkBox_phaseVariable->setChecked(false); checkBox_phaseValue->setChecked(true); comboBox_phaseVariable->setEnabled(false); spinBox_phaseValue->setEnabled(0); comboBox_phaseVariable->setCurrentIndex(0); spinBox_duration->setValue(0); } if (c->isConditions) { if (c->enabled) { groupBox_value->setEnabled(false); groupBox_time->setEnabled(false); groupBox_nested->setEnabled(true); } radioButton_nested->setChecked(true); checkBox_notNested->setChecked(c->isNot); lineEdit_lhsCondition->setText(c->lhsCondition->toString()); for (int i = 0; i < comboBox_nestedOp->count(); i++) { if (QString::compare(comboBox_nestedOp->itemText(i), c->op) == 0) comboBox_nestedOp->setCurrentIndex(i); } lineEdit_rhsCondition->setText(c->rhsCondition->toString()); } else { checkBox_notNested->setChecked(false); lineEdit_lhsCondition->setText(""); comboBox_nestedOp->setCurrentIndex(0); lineEdit_rhsCondition->setText(""); } } void MpreDialog::setCondition(Condition c) { condition = c; setCurrentCondition(&condition); } void MpreDialog::getCurrentCondition() { c->enabled = checkBox_enabled->isChecked(); c->isValues = radioButton_value->isChecked(); c->isTime = radioButton_time->isChecked(); c->isConditions = radioButton_nested->isChecked(); if (c->isValues) { c->isNot = checkBox_notValue->isChecked(); c->op = comboBox_valueOp->currentText(); } if (c->isTime) c->isNot = checkBox_notTime->isChecked(); if (c->isConditions) { c->isNot = checkBox_notNested->isChecked(); c->op = comboBox_nestedOp->currentText(); } c->lhsIsAgentVariable = checkBox_lhsAgentVariable->isChecked(); c->lhsIsMessageVariable = checkBox_lhsMessageVariable->isChecked(); c->lhsIsValue = checkBox_lhsValue->isChecked(); if (c->lhsIsAgentVariable) c->lhs = comboBox_lhsAgentVariable->currentText(); if (c->lhsIsMessageVariable) c->lhs = comboBox_lhsMessageVariable->currentText(); c->lhsDouble = doubleSpinBox_lhsValue->value(); c->rhsIsAgentVariable = checkBox_rhsAgentVariable->isChecked(); c->rhsIsMessageVariable = checkBox_rhsMessageVariable->isChecked(); c->rhsIsValue = checkBox_rhsValue->isChecked(); if (c->rhsIsAgentVariable) c->rhs = comboBox_rhsAgentVariable->currentText(); if (c->rhsIsMessageVariable) c->rhs = comboBox_rhsMessageVariable->currentText(); c->rhsDouble = doubleSpinBox_rhsValue->value(); c->timePeriod = comboBox_period->currentText(); c->timePhaseIsVariable = checkBox_phaseVariable->isChecked(); c->timePhaseVariable = comboBox_phaseVariable->currentText(); c->timePhaseValue = spinBox_phaseValue->value(); c->timeDuration = spinBox_duration->value(); } Condition MpreDialog::getCondition() { getCurrentCondition(); return condition; } void MpreDialog::enableCondition(bool e) { radioButton_value->setEnabled(e); radioButton_time->setEnabled(e); radioButton_nested->setEnabled(e); groupBox_value->setEnabled(e); groupBox_time->setEnabled(e); groupBox_nested->setEnabled(e); if (e) { if (c->isValues) { groupBox_time->setEnabled(false); groupBox_nested->setEnabled(false); } if (c->isTime) { groupBox_value->setEnabled(false); groupBox_nested->setEnabled(false); } if (c->isConditions) { groupBox_value->setEnabled(false); groupBox_time->setEnabled(false); } } } void MpreDialog::valueClicked() { groupBox_value->setEnabled(true); groupBox_time->setEnabled(false); groupBox_nested->setEnabled(false); } void MpreDialog::timeClicked() { groupBox_value->setEnabled(false); groupBox_time->setEnabled(true); groupBox_nested->setEnabled(false); } void MpreDialog::nestedClicked() { groupBox_value->setEnabled(false); groupBox_time->setEnabled(false); groupBox_nested->setEnabled(true); } void MpreDialog::checkedLhsAgentVariable(bool b) { if (checkBox_lhsMessageVariable->isEnabled()) checkBox_lhsMessageVariable->setChecked(!b); checkBox_lhsValue->setChecked(!b); comboBox_lhsAgentVariable->setEnabled(b); comboBox_lhsMessageVariable->setEnabled(!b); doubleSpinBox_lhsValue->setEnabled(!b); } void MpreDialog::checkedLhsMessageVariable(bool b) { checkBox_lhsAgentVariable->setChecked(!b); checkBox_lhsValue->setChecked(!b); comboBox_lhsAgentVariable->setEnabled(!b); comboBox_lhsMessageVariable->setEnabled(b); doubleSpinBox_lhsValue->setEnabled(!b); } void MpreDialog::checkedLhsValue(bool b) { checkBox_lhsAgentVariable->setChecked(!b); if (checkBox_lhsMessageVariable->isEnabled()) checkBox_lhsMessageVariable->setChecked(!b); comboBox_lhsAgentVariable->setEnabled(!b); comboBox_lhsMessageVariable->setEnabled(!b); doubleSpinBox_lhsValue->setEnabled(b); } void MpreDialog::checkedRhsAgentVariable(bool b) { if (checkBox_rhsMessageVariable->isEnabled()) checkBox_rhsMessageVariable->setChecked(!b); checkBox_rhsValue->setChecked(!b); comboBox_rhsAgentVariable->setEnabled(b); comboBox_rhsMessageVariable->setEnabled(!b); doubleSpinBox_rhsValue->setEnabled(!b); } void MpreDialog::checkedRhsMessageVariable(bool b) { checkBox_rhsAgentVariable->setChecked(!b); checkBox_rhsValue->setChecked(!b); comboBox_rhsAgentVariable->setEnabled(!b); comboBox_rhsMessageVariable->setEnabled(b); doubleSpinBox_rhsValue->setEnabled(!b); } void MpreDialog::checkedRhsValue(bool b) { checkBox_rhsAgentVariable->setChecked(!b); if (checkBox_rhsMessageVariable->isEnabled()) checkBox_rhsMessageVariable->setChecked(!b); comboBox_rhsAgentVariable->setEnabled(!b); comboBox_rhsMessageVariable->setEnabled(!b); doubleSpinBox_rhsValue->setEnabled(b); } void MpreDialog::disableTimePhaseVariable(bool b) { checkBox_phaseVariable->setChecked(!b); comboBox_phaseVariable->setEnabled(!b); spinBox_phaseValue->setEnabled(b); } void MpreDialog::disableTimePhaseValue(bool b) { checkBox_phaseValue->setEnabled(!b); comboBox_phaseVariable->setEnabled(b); spinBox_phaseValue->setEnabled(!b); } void MpreDialog::editLhsClicked() { getCurrentCondition(); if (c->lhsCondition == 0) { c->lhsCondition = new Condition(); c->lhsCondition->enabled = true; c->lhsCondition->isValues = true; } c->lhsCondition->parentCondition = c; setCurrentCondition(c->lhsCondition); } void MpreDialog::editRhsClicked() { getCurrentCondition(); if (c->rhsCondition == 0) { c->rhsCondition = new Condition(); c->lhsCondition->enabled = true; c->lhsCondition->isValues = true; } c->rhsCondition->parentCondition = c; setCurrentCondition(c->rhsCondition); } void MpreDialog::levelUpClicked() { getCurrentCondition(); setCurrentCondition(c->parentCondition); }
#ifndef FINE_FITTING_TRACKING_LOCAL #define FINE_FITTING_TRACKING_LOCAL #include "util_wrapper.h" #include "MeshSimplification.h" #include "LinearFemDeformation.h" #include <vector> #include <cmath> using namespace std; #define MAX_NUM_ITER 1000 #define ENERGY_TOLERANCE 0.0001 #define MAX_ANGLE 60 #define MAX_DIST 5.0 #define PI 3.14159265 #define MD_THRESHOLD_DIVIDE 10.0 /* This class is used to deform a template mesh given using the class TriangleMesh (an extension of g_Part) to a frame (points + normals). Note that the classes TriangleMesh, g_Part, g_Node, and g_Element can maybe be replaced using the open source trimesh library. The class MeshSimplification performs edge collapses to get a multi-resolution hierarchy and can probably be replaced by some open source library. NOTE: THIS CLASS USES QUATERNIONS TO EXPRESS THE TRANSFORMATIONS */ class FineFittingTrackingLocalFrame { public: FineFittingTrackingLocalFrame(); ~FineFittingTrackingLocalFrame(); void setTemplate(TriangleMesh * mesh); void resetTemplateCoo(g_NodeContainer nodes, char * filename = NULL); void setFrame(TriangleMesh * mesh, g_Vector probePos=g_Vector(), g_Vector probeOrient=g_Vector(), double depth = 0.0, double radius=-1); // set the position and orientation for the probe in the first frame // implies that the probe does not slip and remains attached to the location on the mesh bool setProbeConstraint( const g_Vector& probePos, const g_Vector& probeOrient ); TriangleMesh * computeDeformedTemplate(char * filename = NULL, bool rigidAligment = false, bool * selfIntersectReturn = NULL, bool onlyUseMarkers = false); double * getTransformationParameters(){return transformationParameters;} //Use this method to adjust the geometry of the mesh to the shape predicted by the FEM simulation: //changes the nodes to the transformed coordinate //ONLY CALL THIS AFTER computeDeformedTemplate was called void adjustTransformations(g_Part * targetMesh, vector<int> indicesModifiedWithFEM, bool * selfIntersectReturn = NULL); //Export the transformations: only call this AFTER adjustTransformations void exportTransformationParameters(char * filename); //This method can be used to define a set of manually clicked markers to achieve a better alignment to the first frame void setMarkers(char * markersToFirstFrame, int numMarkers, double scaleFactor); void unsetMarkers(); vector<int> getNearestNeighbors(bool excludeBoundary); //Size of neighborhood used for access energy double SIZE_NBHD; private: void postProcess(g_Part * currentMesh); void smoothTransformations(int index, char * filename = NULL); void alignRigidlyToFrame(bool onlyUseMarkers); void computeTranslationMat(double tx, double ty, double tz, double *& mat); void computeRotationMat(double tx, double ty, double tz, double angle, double *& mat); void computeScalingMat(double s, double *& mat); void computeTranslationGrad(double tx, double ty, double tz, double *& mat, int index); void computeRotationGrad(double tx, double ty, double tz, double angle, double *& mat, int index); void computeScalingGrad(double s, double *& mat); void fitToData(g_Part * mesh, vector<g_Vector> normalVectors, vector< vector<int> > clusterIds, vector<int> * isFeature = NULL, bool onlyUseMarkers = false); double solveOptimization(g_Part * mesh, vector<g_Vector> normalVectors, vector< vector<int> > clusterIds, vector<int> * isFeature = NULL, bool onlyUseMarkers = false); void computeHierarchy(int numberLevels); void computeNearestNeighbors(g_Part * mesh, vector<g_Vector> normalVectors, vector<int> * isFeature = NULL, bool onlyUseMarkers = false, bool excludeBoundary = false); double nearestNeighborEnergy(g_Part * mesh, bool useFeatures = false); void nearestNeighborGradient(g_Part * mesh, double *& g); void computeAccessNeighbors(g_Part * mesh, vector<int> * indices = NULL); double accessEnergy(g_Part * mesh); void accessGradient(g_Part * mesh, double *& g); void computeMdNeighbors(g_Part * mesh, vector<int> * indices = NULL); double mdEnergy(g_Part * mesh); void mdGradient(g_Part * mesh, double *& g); void computeMdNeighborsFixedBarycenters(g_Part * mesh, vector<int> * indices = NULL); double mdEnergyFixedBarycenters(g_Part * mesh); void mdGradientFixedBarycenters(g_Part * mesh, double *& g); double distanceResolutionEnergy(g_Part * mesh, g_Part * reconstructedMesh, vector<int> indices); void distanceResolutionGradient(g_Part * mesh, g_Part * reconstructedMesh, vector<int> indices, double *& g); g_Vector computeTransformedPoint(double * X, g_Vector point, int index = -1); //Member Variables: g_PEdgeContainer allEdges; int smallestMeshNum; double * transformationParameters; double nnWeight, accessWeight, mdWeight; double largestDist; TriangleMesh * templateMesh, * frameMesh, * resultMesh; g_Part * smallestMesh; vector<MeshSimplification *> hierarchy; //Store the normal vectors of the hierarchy vector< vector<g_Vector> > meshNormals; vector<int> nearestNeighbors; vector<g_Vector> approxNearestPointPlaneNeighbors; vector< vector<int> > isFeatureInHierarchy; vector< vector<int> > indicesForIntersection; vector< vector<int> > indicesForSimpleRegularization; vector< vector<int> > indicesForMd; vector<int> numUsedNeighbors; vector<int> triangleIdsForMd; vector<double> barycentersForMd; //kd-tree for frameMesh: bool kdInitialized; ANNpointArray dataPts; ANNkd_tree* kdTree; // Points for probe locations are stored after this index in frameMesh int probeNodeBegin; // use of constraints for probe location bool useProbeConstraint; std::vector< vector<bool> > constraintNodesHierarchy; // Internal classes used in the minimization process // Needed to be declared here because of the "friending" class RigidAlignmentCostFunction : public vnl_cost_function { public: RigidAlignmentCostFunction(FineFittingTrackingLocalFrame * tracker) : vnl_cost_function(8) {this->tracker=tracker;}; virtual void compute (vnl_vector< double > const &x, double *f, vnl_vector< double > *g); bool recomputeNeighbors; bool featuresOnly; private: FineFittingTrackingLocalFrame * tracker; vector<int> fixedNN; }; friend void RigidAlignmentCostFunction::compute(vnl_vector< double > const &x, double *f, vnl_vector< double > *g); class SolveOptimizationCostFunction : public vnl_cost_function { public: SolveOptimizationCostFunction(FineFittingTrackingLocalFrame * tracker, g_Part * mesh, vector<g_Vector> normalVectors, vector< vector<int> > clusterIds, vector<int> * isFeature, int dimension) : vnl_cost_function(dimension) { this->tracker = tracker; this->mesh = mesh; this->normalVectors = normalVectors; this->clusterIds = clusterIds; this->isFeature = isFeature; } virtual void compute (vnl_vector< double > const &x, double *f, vnl_vector< double > *g); private: FineFittingTrackingLocalFrame * tracker; g_Part * mesh; vector<g_Vector> normalVectors; vector< vector<int> > clusterIds; vector<int> * isFeature; }; friend void SolveOptimizationCostFunction::compute(vnl_vector< double > const &x, double *f, vnl_vector< double > *g); class AdjustTransformationCostFunction : public vnl_cost_function { public: AdjustTransformationCostFunction(FineFittingTrackingLocalFrame * tracker, g_Part * mesh, g_Part * targetMesh, vector<int> indices, vector<int> indicesLowRes, int dimension) : vnl_cost_function(dimension) { this->tracker=tracker; this->mesh = mesh; this->targetMesh = targetMesh; this->indices = indices; this->indicesLowRes = indicesLowRes; } virtual void compute (vnl_vector< double > const &x, double *f, vnl_vector< double > *g); private: FineFittingTrackingLocalFrame * tracker; g_Part * mesh, * targetMesh; vector<int> indices, indicesLowRes; }; friend void AdjustTransformationCostFunction::compute(vnl_vector< double > const &x, double *f, vnl_vector< double > *g); class SmoothTransformationCostFunction : public vnl_cost_function { public: SmoothTransformationCostFunction(FineFittingTrackingLocalFrame * tracker, g_Part * mesh, g_Part * reconstructedMesh, vector<int> newIndices, int dimension) : vnl_cost_function(dimension) { this->tracker=tracker; this->mesh = mesh; this->reconstructedMesh = reconstructedMesh; this->newIndices = newIndices; } virtual void compute (vnl_vector< double > const &x, double *f, vnl_vector< double > *g); private: FineFittingTrackingLocalFrame * tracker; g_Part * mesh, * reconstructedMesh; vector<int> newIndices; }; friend void SmoothTransformationCostFunction::compute(vnl_vector< double > const &x, double *f, vnl_vector< double > *g); }; #endif
////////////////////////////////////////////////////////////////////// ///Copyright (C) 2011-2012 Benjamin Quach // //This file is part of the "Lost Horizons" video game demo // //"Lost Horizons" 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 GNU General Public License //along with this program. If not, see <http://www.gnu.org/licenses/>. // /////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ship.h" #include "GFramework.h" //main ship code //player object does not inheriet from ship code CShip::CShip(irr::IrrlichtDevice *graphics,irrklang::ISoundEngine *sound, const core::vector3df& ship_position, const core::vector3df& ship_rotation,ship_base *s_class,ship_faction faction, const wchar_t *name, ShaderCallBack *callback) : CObject(name), graphics(graphics), sound(sound), callback(callback) { //initialize variables for ship alive=true; this->s_class = s_class; this->isStation = s_class->station; this->hullPoints =s_class->hullPoints; this->shieldPoints = s_class->shieldPoints; this->armorPoints = s_class->armorPoints; this->maxTurn = s_class->maxTurn; this->maxShieldPoints = s_class->shieldPoints; this->maxVelocity = s_class->maxVelocity; this->numFighters = s_class->maxFighters; this->maxFighters = s_class->maxFighters; this->faction = faction; this->type = type; this->energy = s_class->energy; //variable initialization last_time = graphics->getTimer()->getTime(); cannon.primary = graphics->getTimer()->getTime(); cannon.secondary = graphics->getTimer()->getTime(); cannon.light = graphics->getTimer()->getTime(); //economy initializiation buy_modifier = 1.1; sell_modifier = 0.8; indemand_modifier = 1.5; buy_amount_modifier = 1; s32 bump = video::EMT_SOLID; bump = graphics->getVideoDriver()->getGPUProgrammingServices()->addHighLevelShaderMaterialFromFiles("shaders/bumpmap.vsh","vertexMain",video::EVST_VS_3_0,"shaders/bumpmap.psh","pixelMain",video::EPST_PS_3_0,callback); ship=graphics->getSceneManager()->addAnimatedMeshSceneNode(graphics->getSceneManager()->getMesh(s_class->ship)); if(ship) { /* scene::ITriangleSelector* selector = 0; selector = graphics->getSceneManager()->createTriangleSelector(ship); ship->setTriangleSelector(selector); scene::ISceneNodeAnimator* anim = graphics->getSceneManager()->createCollisionResponseAnimator( selector, graphics->getSceneManager()->getActiveCamera(), core::vector3df(30,30,30),vector3df(0,0,0)); graphics->getSceneManager()->getActiveCamera()->addAnimator(anim); selector->drop(); anim->drop(); */ if(callback->shader_enabled==true) { video::ITexture *normal_map = graphics->getVideoDriver()->getTexture(s_class->normal_map); graphics->getVideoDriver()->makeNormalMapTexture(normal_map,20.f); ship->setMaterialTexture(2,normal_map); ship->setMaterialType((video::E_MATERIAL_TYPE)bump); } ship->setPosition(ship_position); ship->setRotation(ship_rotation); ship->setScale(s_class->scale); ship->setMaterialFlag(video::EMF_LIGHTING,true); ship->getMaterial(0).NormalizeNormals=true; ship->getMesh()->setBoundingBox(core::aabbox3df(-400,-300,-400,400,300,400)); } //setup the initial turn variables turn.X = ship->getRotation().X; turn.Y = ship->getRotation().Y; turn.Z = ship->getRotation().Z; fireRot.X = ship->getRotation().X; fireRot.Y = ship->getRotation().Y; fireRot.Z = ship->getRotation().Z; subsystem.engine = 100; subsystem.light_weapons =100; subsystem.primary_weapons=100; subsystem.secondary_weapons =100; subsystem.warpdrive =100; velocity = 0; station_ship_creation_time=0; fighter_creation_time=0; home_planet=0; target=0; warp=false; state = STATE_SEARCH; //temporary until I implement faction warfare //so I guess its actually permanent if(faction==FACTION_PROVIAN_CONSORTIUM) hostile = true; if(faction==FACTION_NEUTRAL) hostile = false; if(faction==FACTION_TERRAN_FEDERATION) hostile = false; //initialize ship roles int r = rand()%3; if(r==1) setRole(ROLE_ATTACKING); if(r==2) setRole(ROLE_DEFENDING); if(r==3) setRole(ROLE_TRADING); if(s_class->contrails!=false) { exhaust_01 = ship->getJointNode("exhaust1"); exhaust_02 = ship->getJointNode("exhaust2"); exhaust_03 = ship->getJointNode("exhaust3"); //setup particle effects scene::IParticleSystemSceneNode *exhaust_ps1=graphics->getSceneManager()->addParticleSystemSceneNode(false,exhaust_01); scene::IParticleSystemSceneNode *exhaust_ps2=graphics->getSceneManager()->addParticleSystemSceneNode(false,exhaust_02); scene::IParticleSystemSceneNode *exhaust_ps3=graphics->getSceneManager()->addParticleSystemSceneNode(false,exhaust_03); scene::IParticleEmitter *em = exhaust_ps1->createBoxEmitter(core::aabbox3d<f32>(-15,-50,-15,15,50,15), // emitter size core::vector3df(0.0f,0.0f,0.0f), // initial direction 400,800, // emit rate video::SColor(0,255,255,255), // darkest color video::SColor(0,255,255,255), // brightest color 300,500,0, // min and max age, angle core::dimension2df(10.f,10.f), // min size core::dimension2df(25.f,25.f)); // max size exhaust_ps1->setEmitter(em); exhaust_ps2->setEmitter(em); exhaust_ps3->setEmitter(em); em->drop(); exhaust_ps1->setMaterialTexture(0,graphics->getVideoDriver()->getTexture("res/textures/engine_trails.pcx")); exhaust_ps1->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR); exhaust_ps1->setMaterialFlag(video::EMF_LIGHTING,false); exhaust_ps2->setMaterialTexture(0,graphics->getVideoDriver()->getTexture("res/textures/engine_trails.pcx")); exhaust_ps2->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR); exhaust_ps2->setMaterialFlag(video::EMF_LIGHTING,false); exhaust_ps3->setMaterialTexture(0,graphics->getVideoDriver()->getTexture("res/textures/engine_trails.pcx")); exhaust_ps3->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR); exhaust_ps3->setMaterialFlag(video::EMF_LIGHTING,false); } //Create 2d picture over ship //to indicate that it is a target array_pos = graphics->getSceneManager()->getSceneCollisionManager()->getScreenCoordinatesFrom3DPosition(getPos(),graphics->getSceneManager()->getActiveCamera()); if(hostile==true) target_array = graphics->getGUIEnvironment()->addImage(graphics->getVideoDriver()->getTexture("res/menu/target_array_enemy.png"),array_pos); else target_array = graphics->getGUIEnvironment()->addImage(graphics->getVideoDriver()->getTexture("res/menu/target_array.png"),array_pos); //engine_sound = sound->play3D("res/sounds/engine.ogg",getPos(),true,false,true); //setup primary turrets for(int i = 0; i < s_class->num_turrets; i ++) { //string conversion n shit int temp = i + 1; stringc str("turret_0"); str+=temp; //lets string read each turret bone from the model, must be named turret_01, turret_02, etc. char *char_str = new char[9]; //char 9 because the string "turret_0" is 8 characters, and you want the number to fit. so double digit turret numbers will probably crash the game strcpy(char_str,str.c_str()); scene::IBoneSceneNode *bone = ship->getJointNode(char_str); turret *t = new turret (graphics,temp,bone, core::vector3df(0,0,0), items().PRI_RAIL ,ship); turret_manager.push_back(t); } //secondary for(int i = 0; i<s_class->num_secondary_turrets; i++) { int temp = i+1; stringc str("secondary_turret_0"); str+=temp; char *char_str = new char[19]; strcpy(char_str,str.c_str()); scene::IBoneSceneNode *bone = ship->getJointNode(char_str); turret *t = new turret (graphics,temp,bone,core::vector3df(0,0,0), items().SEC_ANTIMATTER,ship); secondary_turret_manager.push_back(t); } //setup light //mostly the same as above loop for(int i = 0; i<s_class->num_light_turrets; i++) { int temp = i+1; stringc str("light_turret_0"); str+=temp; char *char_str = new char[15]; strcpy(char_str,str.c_str()); scene::IBoneSceneNode *bone = ship->getJointNode(char_str); turret *t = new turret (graphics,temp,bone,core::vector3df(0,0,0), items().LIGHT_GATLING,ship); light_turret_manager.push_back(t); } } CShip::~CShip() { ship->setVisible(false); //engine_sound->drop(); velocity=0; target_array->remove(); for(int i=0; i<turret_manager.size();i++) { turret_manager[i]->drop(); turret_manager.erase(turret_manager.begin()+i); } turret_manager.clear(); for(int i=0; i<secondary_turret_manager.size();i++) { secondary_turret_manager[i]->drop(); secondary_turret_manager.erase(secondary_turret_manager.begin()+i); } secondary_turret_manager.clear(); } //This is the primary run function for AI ships void CShip::AIRun(f32 frameDeltaTime) { if(hullPoints>0) { //update 2d picture position //engine_sound->setPosition(getPos()); //ensure ships stop being retarded if(turn.X > 50) turn.X = 50; if(turn.X < -50) turn.X = -50; array_pos = graphics->getSceneManager()->getSceneCollisionManager()->getScreenCoordinatesFrom3DPosition(getPos(),graphics->getSceneManager()->getActiveCamera()); target_array->setRelativePosition(vector2d<s32>(array_pos.X-32,array_pos.Y-32)); movement(frameDeltaTime); //Shields regenerate 1 point every 0.1 seconds if(shieldPoints<maxShieldPoints) { if(last_time<graphics->getTimer()->getTime()) { shieldPoints+=1; last_time = graphics->getTimer()->getTime()+100; //milliseconds } } //manage the ship turrets //remember that shots are generated in the gameManager loop for(u32 i = 0; i<turret_manager.size();i++) { turret_manager[i]->setPos(turret_manager[i]->getBonePos()); } for(u32 i = 0; i<secondary_turret_manager.size();i++) { secondary_turret_manager[i]->setPos(secondary_turret_manager[i]->getBonePos()); } for(u32 i = 0; i<light_turret_manager.size();i++) { light_turret_manager[i]->setPos(light_turret_manager[i]->getBonePos()); } } } //Movement function //All movement code gets processed here void CShip::movement(f32 frameDeltaTime) { if(ship->getRotation().Y<turn.Y) //ship wants to rotate right { sRot = ship->getRotation(); rotSlow.Y=0.5*(abs(ship->getRotation().Y-turn.Y)); //simulate inertia if(rotSlow.Z>4) rotSlow.Z=4; if(rotSlow.Y>maxTurn) rotSlow.Y=maxTurn; sRot.Y+=rotSlow.Y*frameDeltaTime; sRot.Z=-rotSlow.Z; ship->setRotation(sRot); } if(ship->getRotation().Y>turn.Y) //ship wants to rotate left { sRot = ship->getRotation(); rotSlow.Y=0.5*(abs(ship->getRotation().Y-turn.Y)); //simulate inertia if(rotSlow.Z>4) rotSlow.Z=4; if(rotSlow.Y>maxTurn) rotSlow.Y=maxTurn; sRot.Y-=rotSlow.Y*frameDeltaTime; sRot.Z=rotSlow.Z; ship->setRotation(sRot); } if(ship->getRotation().X<turn.X) //ship wants to rotate up { sRot = ship->getRotation(); rotSlow.X=0.5*(abs(ship->getRotation().X-turn.X)); //simulate inertia if(rotSlow.X>maxTurn) rotSlow.X=maxTurn; sRot.X+=rotSlow.X*frameDeltaTime; ship->setRotation(sRot); } if(ship->getRotation().X>turn.X) //ship wants to rotate down { sRot = ship->getRotation(); rotSlow.X=0.5*(abs(ship->getRotation().X-turn.X)); //simulate inertia if(rotSlow.X>maxTurn) rotSlow.X=maxTurn; sRot.X-=rotSlow.X*frameDeltaTime; ship->setRotation(sRot); } //only move ship if ship has velocity if(subsystem.engine >0) { if(velocity!=0) { sPos=getPos(); float i = ship->getRotation().Y; float z = -(ship->getRotation().X); //if i dont do this the ship doesnt rotate right sPos.Y=frameDeltaTime*velocity*(sin(z * 3.14/180)); sPos.Y+=getPos().Y; sPos.X=frameDeltaTime*velocity*(sin(i * 3.14/180)); sPos.X+=getPos().X; sPos.Z=frameDeltaTime*velocity*(cos(i * 3.14/180)); sPos.Z+=getPos().Z; ship->setPosition(sPos); } } if(getVelocity()<-10) { //automatically force the player to speed up //if velocity is less than -1 velocity+=(2+velocity/2)*frameDeltaTime; } } //used in ship collisions //used to push the ship in a specific spot without ruining the rotation or velocity void CShip::applyForce(vector3df &rotation, int amount, f32 frameDeltaTime) { vector3df pos = getPos(); float i = rotation.Y; float z = -rotation.X; pos.Y=frameDeltaTime*amount*(sin(z * 3.14/180)); pos.Y+=getPos().Y; pos.X=frameDeltaTime*amount*(sin(i * 3.14/180)); pos.X+=getPos().X; pos.Z=frameDeltaTime*amount*(cos(i * 3.14/180)); pos.Z+=getPos().Z; setPos(pos); } void CShip::damageShip(int damage) { //Damage shields first, then armor (which has resistance) then hull. if(shieldPoints>0) { shieldPoints-=damage; } else { if(armorPoints>0) { armorPoints-=damage/1.15; } else { if(hullPoints>0) { hullPoints-=damage; } } } } //rotates the ship to point void CShip::rotateToPoint(core::vector3df& point) { float x,y,z, angleY,angleX,tmp; x = (point.X - getPos().X); y = (point.Y - getPos().Y); z = (point.Z - getPos().Z); angleY = std::atan2(x,z)*180/3.1415296; tmp = sqrt(x*x + z*z); angleX = std::atan2(tmp,y)*180/3.1415296; angleX -=90; turn.Y = angleY; turn.X = angleX; } //rotate away from the taret void CShip::rotateAwayFromPoint(core::vector3df& point) { const float x = (point.X - getPos().X); const float y = (point.Y - getPos().Y); const float z = (point.Z - getPos().Z); float angleY = std::atan2(x,z)*180/3.1451296; float tmp = sqrt(x*x + z*z); float angleX = std::atan2(tmp,y)*180/3.1451296; angleX -= 270; turn.Y = -angleY; turn.Y+=rand()%20-10; //turn.X = -angleX; //turn.X += rand()%50-25; } //patrol a 30km long area around the point void CShip::patrolArea(core::vector3df& point) { if(getPos().getDistanceFrom(point)>30000) { rotateToPoint(point); } else { if(last_move<graphics->getTimer()->getTime()) { turn.Y += rand()%720 - 360; turn.X += rand()%20-10; last_move = graphics->getTimer()->getTime() + rand()%10000; } } } //aim turrets at point void CShip::shootAtPoint(core::vector3df& point, f32 frameDeltaTime) { for(u32 i = 0; i< turret_manager.size();i++) { const float x = (point.X - turret_manager[i]->getPos().X); const float y = (point.Y - turret_manager[i]->getPos().Y); const float z = (point.Z - turret_manager[i]->getPos().Z); float angleY = std::atan2(x,z)*180/3.145296; float tmp = sqrt(x*x+z*z); float angleX = std::atan2(tmp,y)*180/3.14159265; angleX-=90; //make them less pinpoint accurate angleX+=rand()%2-1; angleY+=rand()%2-1; turret_manager[i]->aimTurret(vector3df(angleX,angleY,0),frameDeltaTime); } for(u32 i = 0; i< secondary_turret_manager.size();i++) { const float x = (point.X - secondary_turret_manager[i]->getPos().X); const float y = (point.Y - secondary_turret_manager[i]->getPos().Y); const float z = (point.Z - secondary_turret_manager[i]->getPos().Z); float angleY = std::atan2(x,z)*180/3.145296; float tmp = sqrt(x*x+z*z); float angleX = std::atan2(tmp,y)*180/3.14159265; angleX-=90; //make them less pinpoint accurate angleX+=rand()%2-1; angleY+=rand()%2-1; secondary_turret_manager[i]->aimTurret(vector3df(angleX,angleY,0),frameDeltaTime); } } void CShip::PDatPoint(vector3df& point, f32 frameDeltaTime) { for(u32 i = 0; i< light_turret_manager.size();i++) { const float x = (point.X - light_turret_manager[i]->getPos().X); const float y = (point.Y - light_turret_manager[i]->getPos().Y); const float z = (point.Z - light_turret_manager[i]->getPos().Z); float angleY = std::atan2(x,z)*180/3.145296; float tmp = sqrt(x*x+z*z); float angleX = std::atan2(tmp,y)*180/3.14159265; angleX-=90; //make them less pinpoint accurate angleX+=rand()%2-1; angleY+=rand()%2-1; light_turret_manager[i]->aimTurret(vector3df(angleX,angleY,0),frameDeltaTime); } } //Creates a shot //then the gameManager picks up the shot to add to the projectile_manager projectile *CShip::addShot(core::vector3df& pos) { irrklang::ISound *shot = sound->play3D("res/sounds/photon.wav",getPos(),false,false,false); projectile *p = new photonCannonShot(graphics, pos, core::vector3df(fireRot.X,fireRot.Y,fireRot.Z),ship); return p; } //The gameManager uses this to see if the ship wants to shoot //if the ship wants to shoot, it returns true //which then the gameManager creates a bullet void CShip::ableToShoot() { if(subsystem.primary_weapons>0) { if(cannon.primary<graphics->getTimer()->getTime()) { //BUG : WHEN THE TURRET_MANAGER[0] IS USED, SHIPS THAT DONT HAVE A PRIMARY TURRT //AKA STATIONS MAKE THE GAME CRASH //fixed if(s_class->num_turrets>0) { cannon.primary = graphics->getTimer()->getTime()+turret_manager[0]->getReloadTime(); cannon.primary_shoot=true; } } else { //cannon.primary_shoot=false; } } else cannon.primary=false; if(subsystem.secondary_weapons>0) { if(cannon.secondary<graphics->getTimer()->getTime()) { if(s_class->num_secondary_turrets>0) { cannon.secondary = graphics->getTimer()->getTime()+secondary_turret_manager[0]->getReloadTime(); cannon.secondary_shoot=true; } } else { //cannon.secondary_shoot=false; } } else cannon.secondary=false; } void CShip::pdShoot() { if(subsystem.light_weapons>0) { if(cannon.light<graphics->getTimer()->getTime()) { if(s_class->num_light_turrets>0) { cannon.light = graphics->getTimer()->getTime()+light_turret_manager[0]->getReloadTime(); cannon.light_shoot=true; } } else { //cannon.light_shoot=false; } } } //set cannons to false void CShip::resetCannons() { cannon.primary_shoot=false; cannon.secondary_shoot=false; } void CShip::resetPD() { cannon.light_shoot = false; } //player engagement code //although, it can be easily used to engage other ships void CShip::engagePlayer(core::vector3df& playerpos, f32 frameDeltaTime) { shootAtPoint(playerpos,frameDeltaTime); ableToShoot(); dodgeFire(); if(getDistToPoint(playerpos)>5000) //outside effective range.... { rotateToPoint(playerpos); } else { if(getDistToPoint(playerpos)<3000) //too close... { rotateAwayFromPoint(playerpos); } } } //engages current target void CShip::engageCurrentTarget(f32 frameDeltaTime) { if(target!=0 && target->getHullPoints()>0) { float Y = target->getRot().Y; float X = -target->getRot().X; core::vector3df pPos; //pPos.Y = target->getVelocity() * sin(Y * 3.1415/ 180); pPos.Y = target->getPos().Y; pPos.X = target->getVelocity() * cos(Y *3.1415/180); pPos.X += target->getPos().X; pPos.Z = target->getVelocity() * cos( X *3.1415 / 180 ); pPos.Z += target->getPos().Z; shootAtPoint(pPos,frameDeltaTime); if(getDistToPoint(target->getPos())<5000) ableToShoot(); else resetCannons(); dodgeFire(); if(getDistToPoint(target->getPos())>5000) //outside effective range.... { rotateToPoint(target->getPos()); } else { if(getDistToPoint(target->getPos())<3000) //too close... { rotateAwayFromPoint(target->getPos()); } } } } //returns distance to point, no biggie float CShip::getDistToPoint(core::vector3df& point) { float x = getPos().X - point.X; float y = getPos().Y - point.Y; float z = getPos().Z - point.Z; float dist = sqrt(x*x+y*y+z*z); return dist; } //Makes ships slightly less retarded and less predictable void CShip::dodgeFire() { velocity=maxVelocity; if(last_move<graphics->getTimer()->getTime()) { turn.Y += rand()%720 - 360; turn.X += rand()%40-20; last_move = graphics->getTimer()->getTime() + rand()%10000; } } void CShip::warpToPlanet(planet* target_planet) { //safety if(subsystem.warpdrive > 0) { if(target_planet != 0) { if(getWarping()!=true) { //basic rotation to point code rotateToPoint(target_planet->getPos()); setWarping(true); } else { //if warping is true if(getRot().Y+3>turn.Y && getRot().Y-3<turn.Y && getRot().X+3>turn.X && getRot().X-3 < turn.X) { if(getPos().getDistanceFrom(target_planet->getPos())>SHIP_WARP_DISTANCE+rand()%1000-500) { setVelocity(SHIP_WARP_SPEED); } else { setVelocity(0); setWarping(false); } } } } } } void CShip::setState(AI_STATE state) { this->state = state; } AI_STATE CShip::getState() { return state; } int CShip::getStarshipCreationTime() { return this->station_ship_creation_time; } void CShip::setStarshipCreationTime(int time) { station_ship_creation_time = time; } int CShip::getFighterCreationTime() { return fighter_creation_time; } void CShip::setFighterCreationTime(int time) { fighter_creation_time = time; } bool CShip::getWarping() { return warp; } void CShip::setWarping(bool warp) { this->warp = warp; } void CShip::setTargetArrayVisible(bool visible) { target_array->setVisible(visible); } void CShip::setHomePlanet(planet *homeplanet) { home_planet = homeplanet; } planet *CShip::getHomePlanet() { if(home_planet!=0) return home_planet; return 0; } //Various return funcs bool CShip::getWithinRadarRange() { return target_array->isVisible(); } bool CShip::getIsStation() { return this->isStation; } void CShip::setVisible(bool visible) { ship->setVisible(visible); } void CShip::setVelocity(float newvelocity) { velocity = newvelocity; } int CShip::getHullPoints() const { return this->hullPoints; } int CShip::getArmorPoints() const { return this->armorPoints; } int CShip::getShieldPoints() const { return this->shieldPoints; } bool CShip::getHostileToPlayer() const { return this->hostile; } int CShip::getNumFighters() { return numFighters; } void CShip::setNumFighters(int fighters) { numFighters = fighters; } void CShip::modNumFighters(int fighters) { numFighters +=fighters; } void CShip::drop() { alive=false; delete this; } core::vector3df CShip::getPos() const { return ship->getPosition(); } void CShip::setPos(vector3df newpos) { this->ship->setPosition(newpos); } core::vector3df CShip::getRot() const { return ship->getRotation(); } void CShip::setRot(vector3df newrot) { this->ship->setRotation(newrot); } void CShip::setHullPoints(int hullpoints) { this->hullPoints = hullpoints; } void CShip::setShieldPoints(int shieldpoints) { this->shieldPoints = shieldpoints; } void CShip::setArmorPoints(int armorpoints) { this->armorPoints = armorpoints; } ship_base *CShip::getShipClass() { return s_class; } ship_faction CShip::getShipFaction() { return faction; } float CShip::getVelocity() { return velocity; } float CShip::getMaxVelocity() { return this->maxVelocity; } int CShip::getEnergy() const { return energy; } void CShip::setTarget(CShip *target) { this->target = target; } CShip *CShip::getTarget() { //return 0 if there is no target if(target!=0) { return target; } return 0; } vector2d<int> CShip::getArrayPos() { return this->array_pos; } std::vector<turret*> CShip::getTurretManager() { return this->turret_manager; } std::vector<turret*> CShip::getSecondaryTurretManager() { return this->secondary_turret_manager; } std::vector<turret*> CShip::getLightTurretManager() { return this->light_turret_manager; } std::vector<item*> CShip::getInventory() { return this->inventory; } void CShip::setInventory(std::vector<item*> in) { this->inventory = in; } //add item to inventory array void CShip::addItemToInventory(item* add) { inventory.push_back(add); } //check if item is in the inventory of the ship bool CShip::itemInInventory(item *check) { for(unsigned int i=0; i<inventory.size();i++) { //same item index means same item //ish if(check->getItemIndex()==inventory[i]->getItemIndex()) { return true; } } return false; } float CShip::getModifierBuy() { return buy_modifier; } float CShip::getModifierSell() { return sell_modifier; } float CShip::getModifierInDemand() { return indemand_modifier; } float CShip::getModifierBuyAmount() { return buy_amount_modifier; } void CShip::setRole(SHIP_ROLE role) { this->role = role; } SHIP_ROLE CShip::getRole() { return role; }
#ifndef _TimeOutProcess_H_ #define _TimeOutProcess_H_ #include "BaseProcess.h" class TimeOutProcess :public BaseProcess { public: TimeOutProcess(); virtual ~TimeOutProcess(); virtual int doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt) ; virtual int doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt ) ; }; #endif
#include "stdafx.h" #include "Camera.h" Camera::Camera() { /*if (isMainCamera) { renderer->SetMainCamera(shared_ptr<Camera>(this)); }*/ projectionMatrix = XMMatrixPerspectiveFovRH(55.0f * (XM_PI / 180.0f), ((float) Win32App::Width) / Win32App::Height, 0.01f, 1000.0f); orthographicMatrix = XMMatrixOrthographicRH(Win32App::Width, Win32App::Height, 0.01f, 1000.0f); } XMMATRIX Camera::GetViewMatrix() { lookAtParams.eye = transform.position; lookAtParams.focus = lookAtParams.eye + XMVector3Transform(XMVectorSet(0.0f, 0.0f, -1.0f, 0.0f), XMMatrixRotationRollPitchYawFromVector(transform.rotation * (XM_PI / 180.0f))); lookAtParams.up = XMVectorSet(0.0f, 1.0f, 0.0f, 1.0f); return XMMatrixLookAtRH(lookAtParams.eye, lookAtParams.focus, lookAtParams.up); }
#ifndef COLLISION_MANAGER_H #define COLLISION_MANAGER_H #include <sgfx/primitives.hpp> #include <list> class collider; class collision_manager { public: class handle { public: handle(const handle&) = delete; handle& operator=(const handle&) = delete; handle(handle&& other) : parent_{other.parent_}, it_{other.it_} { other.parent_ = nullptr; }; handle& operator=(handle&& other) { if (this != &other) { if (parent_) parent_->colliders_.erase(it_); parent_ = other.parent_; it_ = other.it_; other.parent_ = nullptr; } return *this; } handle() = default; ~handle() { if (parent_) parent_->colliders_.erase(it_); } private: collision_manager* parent_ = nullptr; std::list<collider*>::iterator it_; handle(collision_manager* parent, std::list<collider*>::iterator it) : parent_{parent}, it_{it} {} friend class collision_manager; }; collision_manager() = default; collision_manager(const collision_manager&) = delete; collision_manager& operator=(const collision_manager&) = delete; handle register_collider(collider& new_collider); void handle_collisions(); private: std::list<collider*> colliders_; }; class collider { public: virtual sgfx::rectangle bounds() const = 0; virtual void hit() = 0; protected: ~collider() = default; }; #endif
#include <iostream> int fnx[20][200001]; int main() { std::cin.sync_with_stdio(false); std::cin.tie(NULL); int m; std::cin >> m; for(int i = 1; i <= m; i++) { std::cin >> fnx[0][i]; } for(int n = 1; n < 20; n++) { for(int x = 1; x <= m; x++) { fnx[n][x] = fnx[n - 1][fnx[n - 1][x]]; } } int Q; std::cin >> Q; while(Q--) { int n, x; std::cin >> n >> x; for(int i = 0; n > 0; i++) { if(n % 2) { x = fnx[i][x]; } n /= 2; } std::cout << x << '\n'; } return 0; }
#include <iostream> #define REP(i, a, n) for(int i = ((int) a); i < ((int) n); i++) using namespace std; template<typename FI> void parted_rotate(FI first1, FI last1, FI first2, FI last2) { if(first1 == last1 || first2 == last2) return; FI next = first2; while(first1 != next) { std::iter_swap(first1++, next++); if(first1 == last1) first1 = first2; if(next == last2) next = first2; else if(first1 == first2) first2 = next; } } template<typename BI> bool next_combination_imp(BI first1, BI last1, BI first2, BI last2) { if(first1 == last1 || first2 == last2) return false; BI target = last1; --target; BI last_elem = last2; --last_elem; while(target != first1 && !(*target < *last_elem)) --target; if(target == first1 && !(*target < *last_elem)) { parted_rotate(first1, last1, first2, last2); return false; } BI next = first2; while(!(*target < *next)) ++next; std::iter_swap(target++, next++); parted_rotate(target, last1, next, last2); return true; } template<typename BI> inline bool next_combination(BI first, BI mid, BI last) { return next_combination_imp(first, mid, mid, last); } int main(void) { int a[5]; REP(i, 0, 5) a[i] = i; do { REP(i, 0, 3) cout << a[i] << " "; cout << endl; } while(next_combination(a, a + 3, a + 5)); return 0; }
#pragma once #include <vector> #include <omp.h> #include "linalg.h" std::vector<Point> momentums_with_energy_in_direction(double theta, double energy_value); void set_probabilities(); double get_probability(double energy);
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Adam Minchinton, Michal Zajaczkowski */ #include "core/pch.h" #ifdef AUTO_UPDATE_SUPPORT #include "adjunct/autoupdate/autoupdater.h" #include "adjunct/autoupdate/updatablefile.h" #include "adjunct/autoupdate/updatablesetting.h" #ifdef AUTOUPDATE_PACKAGE_INSTALLATION # include "adjunct/autoupdate/updater/pi/aufileutils.h" # include "adjunct/autoupdate/updater/audatafile_reader.h" #endif #include "adjunct/desktop_pi/DesktopOpSystemInfo.h" #include "modules/locale/oplanguagemanager.h" #include "modules/prefs/prefsmanager/prefsmanager.h" #include "modules/prefs/prefsmanager/collections/pc_network.h" #include "modules/prefs/prefsmanager/collections/pc_ui.h" #include "modules/util/opfile/opfile.h" #ifdef AUTOUPDATE_ENABLE_AUTOUPDATE_INI #include "modules/prefsfile/prefsfile.h" #endif // AUTOUPDATE_ENABLE_AUTOUPDATE_INI #include "modules/libssl/updaters.h" #include "adjunct/quick/managers/LaunchManager.h" #ifndef _MACINTOSH_ #include "adjunct/autoupdate/autoupdate_checker/adaptation_layer/ipc.h" #endif // _MACINTOSH_ #include "adjunct/desktop_util/resources/pi/opdesktopresources.h" #include "adjunct/desktop_util/resources/pi/opdesktopproduct.h" #include "adjunct/desktop_util/resources/ResourceDefines.h" #ifndef _MACINTOSH_ #include "adjunct/autoupdate/autoupdate_checker/adaptation_layer/global_storage.h" #endif // _MACINTOSH_ #include "modules/util/path.h" const uni_char* autoupdate_error_strings[] = { UNI_L("No error"), UNI_L("Internal error"), UNI_L("In progress error"), UNI_L("Connection error"), UNI_L("Save error"), UNI_L("Validation error"), UNI_L("Update error") }; OperaVersion AutoUpdater::m_opera_version; /** * See autoupdater.h for description of the values below. */ const int AutoUpdater::MAX_UPDATE_CHECK_INTERVAL_SEC = (7*24*60*60); const int AutoUpdater::MIN_UPDATE_CHECK_INTERVAL_SEC = (5*60); const int AutoUpdater::MIN_UPDATE_CHECK_INTERVAL_RUNNING_SEC = (24*60*60); const int AutoUpdater::UPDATE_CHECK_INTERVAL_DELTA_SEC = (24*60*60); const int AutoUpdater::AUTOUPDATE_RECHECK_TIMEOUT_SEC = (24*60*60); const int AutoUpdater::AUTOUPDATE_SSL_UPDATERS_BUSY_RECHECK_TIMEOUT_SEC = 10; const int AutoUpdater::AUTOUPDATE_RESOURCE_CHECK_BASE_TIMEOUT_SEC = 60; #ifndef _MACINTOSH_ using namespace opera_update_checker::ipc; using namespace opera_update_checker::global_storage; using namespace opera_update_checker::status; #endif // _MACINTOSH_ AutoUpdater::AutoUpdater(): m_xml_downloader(NULL), m_autoupdate_xml(NULL), m_autoupdate_server_url(NULL), m_update_state(AUSUpToDate), m_silent_update(TRUE), m_last_error(AUNoError), m_update_check_timer(NULL), m_download_timer(NULL), m_download_countdown(0), m_download_retries(0), m_activated(FALSE), m_resources_check_only(FALSE), m_check_increased_update_check_interval(TRUE), m_time_of_last_update_check(0), m_update_check_interval(86400), m_update_check_delay(0), m_user_initiated(FALSE) #ifndef _MACINTOSH_ ,m_channel_to_checker(NULL) ,m_channel_id(0) ,m_checker_launch_retry_timer(NULL) ,m_checker_launch_retry_count(0) ,m_checker_state(CheckerOk) #endif //_MACINTOSH_ { } AutoUpdater::~AutoUpdater() { g_pcui->UnregisterListener(this); OP_DELETE(m_xml_downloader); OP_DELETE(m_autoupdate_xml); OP_DELETE(m_autoupdate_server_url); OP_DELETE(m_update_check_timer); OP_DELETE(m_download_timer); #ifndef _MACINTOSH_ OP_DELETE(m_checker_launch_retry_timer); if (m_channel_to_checker) m_channel_to_checker->Disconnect(); Channel::Destroy(m_channel_to_checker); #endif // _MACINTOSH_ } OP_STATUS AutoUpdater::Init(BOOL check_increased_update_check_interval) { OpDesktopResources* resources; RETURN_IF_ERROR(OpDesktopResources::Create(&resources)); OpAutoPtr<OpDesktopResources> auto_resources(resources); RETURN_IF_ERROR(g_pcui->RegisterListener(this)); #ifndef _MACINTOSH_ RETURN_IF_ERROR(resources->GetUpdateCheckerPath(m_checker_path)); m_channel_id = opera_update_checker::ipc::GetCurrentProcessId(); op_srand(m_channel_id); m_channel_to_checker = Channel::Create(true, m_channel_id, Channel::CHANNEL_MODE_READ_WRITE, Channel::BIDIRECTIONAL); RETURN_OOM_IF_NULL(m_channel_to_checker); #endif // _MACINTOSH_ m_check_increased_update_check_interval = check_increased_update_check_interval; m_level_of_automation = static_cast<LevelOfAutomation>(g_pcui->GetIntegerPref(PrefsCollectionUI::LevelOfUpdateAutomation)); int saved_state = g_pcui->GetIntegerPref(PrefsCollectionUI::AutoUpdateState); m_update_state = static_cast<AutoUpdateState>(saved_state & 0xFFFF); // The lower word is the update state. #ifndef _MACINTOSH_ m_checker_state = static_cast<CheckerState>(saved_state >> 16); // The higher word is the checker state. // If couldn't launch the checker last time schedule the new attempt. if (m_checker_state == CheckerCouldntLaunch) { m_checker_launch_retry_timer = OP_NEW(OpTimer, ()); if (m_checker_launch_retry_timer) { m_checker_launch_retry_timer->SetTimerListener(this); m_checker_launch_retry_timer->Start(CHECKER_LAUNCH_RETRY_TIME_MS); } } #endif // _MACINTOSH_ m_time_of_last_update_check = static_cast<time_t>(g_pcui->GetIntegerPref(PrefsCollectionUI::TimeOfLastUpdateCheck)); const int DELTA_PERIOD_MINUTES = 4 * 60; const int DELTA_RESOLUTION_MINUTES = 10; /* Random delta needed by the user counting system to detect collisions. It's required to be wihin +- 4h with 10min. resolution. Since rand operates on ranges starting from 0 only in order to achieve [-4h; 4h] range rand from [0h; 7h50min] range is done and 4h is substracted from the result (+1 below is needed due to how % operator works and -10 min is so that after rounding the result is still within the expected range). To achieve 10 minutes resolution the result delta is rounded to the nearest number being a multiplication of 10. */ m_update_check_random_delta = (op_rand() % (2 * DELTA_PERIOD_MINUTES - DELTA_RESOLUTION_MINUTES + 1)) - DELTA_PERIOD_MINUTES; // In minutes. // Rounding. m_update_check_random_delta += m_update_check_random_delta > 0 ? (DELTA_RESOLUTION_MINUTES - 1) : -(DELTA_RESOLUTION_MINUTES - 1); m_update_check_random_delta = m_update_check_random_delta / DELTA_RESOLUTION_MINUTES * DELTA_RESOLUTION_MINUTES; m_update_check_random_delta = m_update_check_random_delta == 0 ? DELTA_RESOLUTION_MINUTES : m_update_check_random_delta; m_update_check_random_delta *= 60; // In seconds. m_update_check_interval = g_pcui->GetIntegerPref(PrefsCollectionUI::UpdateCheckInterval); m_update_check_delay = g_pcui->GetIntegerPref(PrefsCollectionUI::DelayedUpdateCheckInterval); // Allow the version object to read the faked version from the autoupdate.ini file, should there be one. // This helps testing the autoupdate. m_opera_version.AllowAutoupdateIniOverride(); if ( (m_update_state < AUSUpToDate) || (m_update_state > AUSError) ) { // Force up to date state RETURN_IF_ERROR(SetUpdateState(AUSUpToDate)); } OpAutoPtr<AutoUpdateXML> autoupdate_xml_guard(OP_NEW(AutoUpdateXML, ())); RETURN_OOM_IF_NULL(autoupdate_xml_guard.get()); RETURN_IF_ERROR(autoupdate_xml_guard->Init()); OpAutoPtr<AutoUpdateServerURL> autoupdate_server_url_guard(OP_NEW(AutoUpdateServerURL, ())); RETURN_OOM_IF_NULL(autoupdate_server_url_guard.get()); RETURN_IF_ERROR(autoupdate_server_url_guard->Init()); OpAutoPtr<StatusXMLDownloader> xml_downloader_guard(OP_NEW(StatusXMLDownloader, ())); RETURN_OOM_IF_NULL(xml_downloader_guard.get()); RETURN_IF_ERROR(xml_downloader_guard->Init(StatusXMLDownloader::CheckTypeUpdate, this)); m_autoupdate_xml = autoupdate_xml_guard.release(); m_autoupdate_server_url = autoupdate_server_url_guard.release(); m_xml_downloader = xml_downloader_guard.release(); return OpStatus::OK; } OP_STATUS AutoUpdater::WritePref(PrefsCollectionUI::integerpref which, int val) { TRAPD(st, g_pcui->WriteIntegerL(which, val)); RETURN_IF_ERROR(st); TRAP(st, g_prefsManager->CommitL()); return st; } OP_STATUS AutoUpdater::Activate() { OP_ASSERT(m_xml_downloader); if(m_activated) { Console::WriteError(UNI_L("AutoUpdate already activated.")); return OpStatus::ERR_NOT_SUPPORTED; } m_activated = TRUE; if (m_level_of_automation < NoChecking || m_level_of_automation > AutoInstallUpdates) return OpStatus::OK; // If the user is interested in updates or update notifications, get on with that. switch(m_update_state) { case AUSChecking: { // Opera probably exited or crashed while checking // Set initial state, and schedule new update check. break; } case AUSDownloading: { // Opera probably exited or crashed while downloading. If the last check was done less than 1 day ago, // try parsing the autoupdate xml we already downloaded, if not, schedule another check if(g_timecache->CurrentTime() - m_time_of_last_update_check < AUTOUPDATE_RECHECK_TIMEOUT_SEC) { // This method is to only be run once after the object has been created, expect the XML downloader // to not exist yet. SetUpdateState(AUSChecking); StatusXMLDownloader::DownloadStatus status = m_xml_downloader->ParseDownloadedXML(); if(status == StatusXMLDownloader::SUCCESS) { StatusXMLDownloaded(m_xml_downloader); return OpStatus::OK; } } break; } case AUSReadyToInstall: { // Illegal state when activated // Set initial state, and schedule new check break; } case AUSError: case AUSUpToDate: case AUSUpdating: case AUSUnpacking: case AUSReadyToUpdate: case AUSUpdateAvailable: case AUSErrorDownloading: break; default: OP_ASSERT(!"What about this state?"); break; } SetUpdateState(AUSUpToDate); OP_STATUS ret = OpStatus::OK; if (m_autoupdate_xml->NeedsResourceCheck()) { // DSK-336588 // If any of the resource timestamps are set to 0, we need to trigger a resource check NOW. // The browserjs timestamp will be set 0 to browser upgrade. ret = ScheduleResourceCheck(); } else { // Schedule the next update check according to the schedule. ret = ScheduleUpdateCheck(ScheduleStartup); } if (OpStatus::IsSuccess(ret)) Console::WriteMessage(UNI_L("The autoupdate mechanism activated.")); else Console::WriteError(UNI_L("Failed to activate the autoupdate mechanism.")); return ret; } OP_STATUS AutoUpdater::CheckAndUpdateState() { switch(m_update_state) { case AUSUpToDate: { BroadcastOnUpToDate(IsSilent()); Console::WriteMessage(UNI_L("Up to date.")); Reset(); return ScheduleUpdateCheck(ScheduleRunning); } case AUSChecking: { BroadcastOnChecking(IsSilent()); Console::WriteMessage(UNI_L("Checking for updates...")); break; } case AUSDownloading: { UpdatableResource::UpdatableResourceType update_type = GetAvailableUpdateType(); OpFileLength total_size = GetTotalUpdateSize(); BroadcastOnDownloading(update_type, total_size, 0, 0.0, 0, IsSilent()); Console::WriteMessage(UNI_L("Downloading updates...")); break; } case AUSReadyToUpdate: { BroadcastOnReadyToUpdate(); Console::WriteMessage(UNI_L("Ready to update.")); if(m_level_of_automation > NoChecking || !IsSilent()) { /** Update all resources */ #ifdef AUTOUPDATE_PACKAGE_INSTALLATION StartUpdate(TRUE); #else StartUpdate(FALSE); #endif } else if(m_level_of_automation == NoChecking) { /** Only update spoof and browerjs file when in NoChecking mode. */ StartUpdate(FALSE); } break; } case AUSUpdating: { BroadcastOnUpdating(); Console::WriteMessage(UNI_L("Updating...")); break; } case AUSUnpacking: { BroadcastOnUnpacking(); Console::WriteMessage(UNI_L("Extracting from downloaded package...")); break; } case AUSReadyToInstall: { Console::WriteMessage(UNI_L("Ready to install new version.")); // Call listener OpString version; GetAvailablePackageInfo(&version, NULL, NULL); BroadcastOnReadyToInstallNewVersion(version, IsSilent()); break; } case AUSError: { // Call listener BroadcastOnError(m_last_error, IsSilent()); if(m_last_error < (int)ARRAY_SIZE(autoupdate_error_strings)) { Console::WriteError(autoupdate_error_strings[m_last_error]); } // Set initial state SetUpdateState(AUSUpToDate); Reset(); // Schedule new update check return ScheduleUpdateCheck(ScheduleRunning); } case AUSErrorDownloading: { // Call listener BroadcastOnDownloadingFailed(IsSilent()); Console::WriteError(UNI_L("Downloading update failed.")); // Increase the time to next update check IncreaseDelayedUpdateCheckInterval(); // Schedule new download if(IsSilent()) { // Go back to up to date state SetUpdateState(AUSUpToDate); CheckAndUpdateState(); } else { m_silent_update = TRUE; SetUpdateState(AUSUpdateAvailable); //CheckAndUpdateState(); } break; } case AUSUpdateAvailable: { Console::WriteMessage(UNI_L("An update is available.")); // Call listener OpString info_url; OpFileLength size = 0; GetAvailablePackageInfo(NULL, &info_url, &size); UpdatableResource::UpdatableResourceType update_type = GetAvailableUpdateType(); BroadcastOnUpdateAvailable(update_type, size, info_url.CStr(), IsSilent()); BOOL has_package = update_type & UpdatableResource::RTPackage; if(!has_package) { // Update is silent if we dont have a package m_silent_update = TRUE; } if(IsSilent()) { switch(m_level_of_automation) { case NoChecking: { /** Only download spoof and browerjs file when in NoChecking mode. */ DownloadUpdate(FALSE); break; } case CheckForUpdates: { /** If there is no package, continue updating other resources */ DownloadUpdate(FALSE); break; } case AutoInstallUpdates: { /** Get on with downloading the update */ DownloadUpdate(TRUE); break; } } } break; } default: { OP_ASSERT(!"Should never reach this."); } } return OpStatus::OK; } OP_STATUS AutoUpdater::CheckForUpdate() { if (m_update_state == AUSUpToDate || m_update_state == AUSUpdateAvailable) { m_silent_update = FALSE; return DownloadStatusXML(); } else { BroadcastOnError(AUInProgressError, IsSilent()); return OpStatus::OK; } } UpdatableResource::UpdatableResourceType AutoUpdater::GetAvailableUpdateType() const { OP_ASSERT(m_xml_downloader); int res_type = 0; UpdatableResource* dl_elm = m_xml_downloader->GetFirstResource(); while (dl_elm) { int cur_type = dl_elm->GetType(); res_type |= cur_type; dl_elm = m_xml_downloader->GetNextResource(); } return static_cast<UpdatableResource::UpdatableResourceType>(res_type); } BOOL AutoUpdater::GetAvailablePackageInfo(OpString* version, OpString* info_url, OpFileLength* size) const { OP_ASSERT(m_xml_downloader); UpdatableResource* dl_elm = m_xml_downloader->GetFirstResource(); while (dl_elm) { if(dl_elm->GetType() == UpdatableResource::RTPackage) { UpdatablePackage* up = static_cast<UpdatablePackage*>(dl_elm); if(version) RETURN_VALUE_IF_ERROR(up->GetAttrValue(URA_VERSION, *version), FALSE); if(info_url) RETURN_VALUE_IF_ERROR(up->GetAttrValue(URA_INFOURL, *info_url), FALSE); if(size) { int size_int; RETURN_VALUE_IF_ERROR(up->GetAttrValue(URA_SIZE, size_int), FALSE); *size = size_int; } return TRUE; } dl_elm = m_xml_downloader->GetNextResource(); } return FALSE; } OpFileLength AutoUpdater::GetTotalUpdateSize() const { OP_ASSERT(m_xml_downloader); OpFileLength size = 0; UpdatableResource* resource = m_xml_downloader->GetFirstResource(); while (resource) { int size_int; if (OpStatus::IsSuccess(resource->GetAttrValue(URA_SIZE, size_int))) size += size_int; resource = m_xml_downloader->GetNextResource(); } return size; } void AutoUpdater::StatusXMLDownloaded(StatusXMLDownloader* downloader) { OP_ASSERT(m_autoupdate_xml); OP_ASSERT(downloader); OP_ASSERT(downloader == m_xml_downloader); OP_ASSERT(m_update_state == AUSChecking); // Better safe than sorry if (NULL == downloader) return; #ifdef AUTOUPDATE_PACKAGE_INSTALLATION DeleteUpgradeFolderIfNeeded(); #endif // Success for a response from the Autoupdate server so set the flag to say we have // spoken to this server at least once. Used for stats to detect first runs and upgrades TRAPD(err, g_pcui->WriteIntegerL(PrefsCollectionUI::AutoUpdateResponded, 1)); // On a successful check, set delayed update check interval back to default m_update_check_delay = 0; TRAP(err, g_pcui->WriteIntegerL(PrefsCollectionUI::DelayedUpdateCheckInterval, 0)); TRAP(err, g_prefsManager->CommitL()); // Not much we can do about it now anyway OpStatus::Ignore(err); // Check if the server is increasing the update check interval. // In that case, dont download any packages, to avoid overloading the server BOOL increased_update_check_interval = FALSE; UpdatableResource* current_resource = m_xml_downloader->GetFirstResource(); UpdatablePackage* package = NULL; while (current_resource) { UpdatableResource::UpdatableResourceType type = current_resource->GetType(); switch(type) { case UpdatableResource::RTSetting: { UpdatableSetting* setting = static_cast<UpdatableSetting*>(current_resource); if (setting->IsUpdateCheckInterval()) { int new_interval = 0; if (OpStatus::IsSuccess(setting->GetAttrValue(URA_DATA, new_interval))) { if (new_interval > m_update_check_interval) if(m_check_increased_update_check_interval) increased_update_check_interval = TRUE; // we could just wait for PrefsChanged, but it won't be called if operaprefs.ini // is read-only m_update_check_interval = new_interval; // PrefsCollectionUI::UpdateCheckInterval will be updated by UpdateResource } } if (!(setting->CheckResource() && OpStatus::IsSuccess(setting->UpdateResource()))) OP_ASSERT(!"Could not update setting resource!"); m_xml_downloader->RemoveResource(current_resource); OP_DELETE(current_resource); current_resource = NULL; } break; case UpdatableResource::RTPackage: { if (package) OP_ASSERT(!"Got more than one package from the server!"); package = static_cast<UpdatablePackage*>(current_resource); if(AutoInstallUpdates == m_level_of_automation && package->GetShowNotification()) m_silent_update = FALSE; } break; case UpdatableResource::RTPatch: // Do we know what to do with a patch? Carry on anyway. OP_ASSERT(!"A patch...?!"); case UpdatableResource::RTSpoofFile: case UpdatableResource::RTBrowserJSFile: case UpdatableResource::RTDictionary: case UpdatableResource::RTHardwareBlocklist: case UpdatableResource::RTHandlersIgnore: // A dictionary may be updated with a regular autoupdate check. // Carry on break; case UpdatableResource::RTPlugin: // We don't expect any plugins with an update check. OP_ASSERT(!"Didn't expect a plugin with autoupdate check!"); m_xml_downloader->RemoveResource(current_resource); OP_DELETE(current_resource); current_resource = NULL; break; default: OP_ASSERT(!"Uknown resource type"); break; } current_resource = m_xml_downloader->GetNextResource(); } if (package) { if ((NoChecking == m_level_of_automation && IsSilent()) || increased_update_check_interval) { if(!increased_update_check_interval) Console::WriteError(UNI_L("Did not expect package from server with current autoupdate level.")); else Console::WriteMessage(UNI_L("Increased update check interval.")); m_xml_downloader->RemoveResource(package); OP_DELETE(package); package = NULL; } } if (m_xml_downloader->GetResourceCount() > 0) { // Server returned some resources UpdatableResource::UpdatableResourceType update_type = GetAvailableUpdateType(); if (CheckForUpdates == m_level_of_automation && (update_type & UpdatableResource::RTPackage)) m_silent_update = FALSE; SetUpdateState(AUSUpdateAvailable); } else SetUpdateState(AUSUpToDate); CheckAndUpdateState(); } void AutoUpdater::StatusXMLDownloadFailed(StatusXMLDownloader* downloader, StatusXMLDownloader::DownloadStatus status) { OP_ASSERT(m_autoupdate_xml); OP_ASSERT(downloader); OP_ASSERT(downloader == m_xml_downloader); OP_ASSERT(m_update_state == AUSChecking); AutoUpdateError error = AUInternalError; switch(status) { case StatusXMLDownloader::NO_TRANSFERITEM: case StatusXMLDownloader::NO_URL: case StatusXMLDownloader::LOAD_FAILED: case StatusXMLDownloader::DOWNLOAD_FAILED: case StatusXMLDownloader::DOWNLOAD_ABORTED: { error = AUConnectionError; break; } case StatusXMLDownloader::PARSE_ERROR: case StatusXMLDownloader::WRONG_XML: { error = AUValidationError; break; } } // Increase delayed update check interval when the request fails. if(error == AUConnectionError) { // Go through the server list OP_ASSERT(m_autoupdate_server_url); if (OpStatus::IsSuccess(m_autoupdate_server_url->IncrementURLNo(AutoUpdateServerURL::NoWrap))) { // There is more servers to check so increment to the next server and check right away RETURN_VOID_IF_ERROR(SetUpdateState(AUSUpToDate)); RETURN_VOID_IF_ERROR(DownloadStatusXML()); } else { // Last server in the list so reset back to the start and set a delayed called RETURN_VOID_IF_ERROR(m_autoupdate_server_url->ResetURLNo()); IncreaseDelayedUpdateCheckInterval(); } } SetLastError(error); SetUpdateState(AUSError); CheckAndUpdateState(); } void AutoUpdater::PrefChanged(OpPrefsCollection::Collections id, int pref, int newvalue) { if (id == OpPrefsCollection::UI) { switch (pref) { case PrefsCollectionUI::TimeOfLastUpdateCheck: m_time_of_last_update_check = static_cast<time_t>(newvalue); break; case PrefsCollectionUI::UpdateCheckInterval: m_update_check_interval = newvalue; break; case PrefsCollectionUI::DelayedUpdateCheckInterval: m_update_check_delay = newvalue; break; default: break; } } } void AutoUpdater::OnFileDownloadDone(FileDownloader* file_downloader, OpFileLength total_size) { OP_ASSERT(m_update_state == AUSDownloading); UpdatableFile* file = static_cast<UpdatableFile*>(file_downloader); if (file) { UpdatableResource::UpdatableResourceType type = file->GetType(); OpString target_filename; file->GetTargetFilename(target_filename); BroadcastOnDownloadingDone(type, target_filename, total_size, IsSilent()); } OP_STATUS ret = StartNextDownload(file_downloader); if (OpStatus::IsSuccess(ret)) return; // Last file if (ret == OpStatus::ERR_NO_SUCH_RESOURCE) { // All files are downloaded, check all SetUpdateState(AUSReadyToUpdate); CheckAndUpdateState(); } else { // One or more file downloads failed SetLastError(AUConnectionError); SetUpdateState(AUSErrorDownloading); CheckAndUpdateState(); } } void AutoUpdater::OnFileDownloadFailed(FileDownloader* file_downloader) { OP_ASSERT(m_update_state == AUSDownloading); // Set error downloading state SetLastError(AUConnectionError); SetUpdateState(AUSErrorDownloading); CheckAndUpdateState(); } void AutoUpdater::OnFileDownloadAborted(FileDownloader* file_downloader) { } void AutoUpdater::OnFileDownloadProgress(FileDownloader* file_downloader, OpFileLength total_size, OpFileLength downloaded_size, double kbps, unsigned long time_estimate) { OP_ASSERT(m_update_state == AUSDownloading); UpdatableFile* file = static_cast<UpdatableFile*>(file_downloader); UpdatableResource::UpdatableResourceType type = UpdatableResource::RTEmpty; if(file) { type = file->GetType(); } BroadcastOnDownloading(type, total_size, downloaded_size, kbps, time_estimate, IsSilent()); } void AutoUpdater::DeferUpdate() { // Destroy the retry download timer if we have one. if(m_download_timer) { OP_DELETE(m_download_timer); m_download_timer = NULL; } switch(m_update_state) { case AUSUpdateAvailable: { break; } case AUSDownloading: { StopDownloads(); SetUpdateState(AUSUpdateAvailable); //CheckAndUpdateState(); break; } default: { m_silent_update = TRUE; SetUpdateState(AUSUpToDate); CheckAndUpdateState(); } } TRAPD(err, g_pcui->WriteIntegerL(PrefsCollectionUI::BrowserJSTime, 0)); OpStatus::Ignore(ScheduleResourceCheck()); } OP_STATUS AutoUpdater::DownloadUpdate() { #ifdef AUTOUPDATE_PACKAGE_INSTALLATION m_silent_update = FALSE; m_download_retries++; return DownloadUpdate(TRUE); #else m_silent_update = TRUE; m_download_retries++; return DownloadUpdate(FALSE); #endif } OP_STATUS AutoUpdater::GetDownloadPageURL(OpString& url) { OP_ASSERT(m_xml_downloader); return m_xml_downloader->GetDownloadURL(url); } OP_STATUS AutoUpdater::DownloadUpdate(BOOL include_resources_requiring_restart) { OP_ASSERT(m_xml_downloader); if(m_update_state != AUSUpdateAvailable && m_update_state != AUSErrorDownloading) { BroadcastOnError(AUInternalError, IsSilent()); return OpStatus::ERR; } m_include_resources_requiring_restart = include_resources_requiring_restart; // Destroy the retry download timer if we have one. if(m_download_timer) { OP_DELETE(m_download_timer); m_download_timer = NULL; } OP_STATUS ret = StartNextDownload(NULL); if(OpStatus::IsSuccess(ret)) { SetUpdateState(AUSDownloading); CheckAndUpdateState(); } else { if(ret == OpStatus::ERR_NO_SUCH_RESOURCE) { // No files to download, but continue updating other resources SetUpdateState(AUSReadyToUpdate); CheckAndUpdateState(); } else { StopDownloads(); SetLastError(AUConnectionError); SetUpdateState(AUSErrorDownloading); CheckAndUpdateState(); } } return OpStatus::OK; } OP_STATUS AutoUpdater::StartNextDownload(FileDownloader* previous_download) { OP_ASSERT(m_xml_downloader); UpdatableResource* resource = m_xml_downloader->GetFirstResource(); BOOL found_previous_download = previous_download == NULL ? TRUE : FALSE; for(; resource; resource = m_xml_downloader->GetNextResource()) { if ( resource->GetResourceClass() == UpdatableResource::File && (m_include_resources_requiring_restart || !resource->UpdateRequiresRestart())) { UpdatableFile* file = static_cast<UpdatableFile*>(resource); // Start with the first download after previous_download if(!found_previous_download) { if(file == previous_download) { found_previous_download = TRUE; } } else { return file->StartDownloading(this); } } } return OpStatus::ERR_NO_SUCH_RESOURCE; } OP_STATUS AutoUpdater::StopDownloads() { OP_ASSERT(m_xml_downloader); UpdatableResource* resource = m_xml_downloader->GetFirstResource(); while(resource) { if(resource->GetResourceClass() == UpdatableResource::File) { UpdatableFile* file = static_cast<UpdatableFile*>(resource); file->StopDownload(); } resource = m_xml_downloader->GetNextResource(); } return OpStatus::OK; } OP_STATUS AutoUpdater::StartUpdate(BOOL include_resources_requiring_restart) { OP_ASSERT(m_xml_downloader); OP_ASSERT(m_update_state == AUSReadyToUpdate); if(m_update_state != AUSReadyToUpdate) { BroadcastOnError(AUInternalError, IsSilent()); return OpStatus::ERR; } SetUpdateState(AUSUpdating); CheckAndUpdateState(); // broadcast updating state BOOL call_ready_to_install = FALSE; BOOL waiting_for_unpacking = FALSE; BOOL update_error = FALSE; UpdatableResource* dl_elm = m_xml_downloader->GetFirstResource(); for (; dl_elm; dl_elm = m_xml_downloader->GetNextResource()) { if ( include_resources_requiring_restart || !dl_elm->UpdateRequiresRestart()) { if(dl_elm->CheckResource()) { if(OpStatus::IsSuccess(dl_elm->UpdateResource())) { if(dl_elm->UpdateRequiresUnpacking()) { waiting_for_unpacking = TRUE; g_main_message_handler->SetCallBack(this, MSG_AUTOUPDATE_UNPACKING_COMPLETE, 0); } if(dl_elm->UpdateRequiresRestart()) { call_ready_to_install = TRUE; } OpString message; message.AppendFormat(UNI_L("Updated %s resource."), dl_elm->GetResourceName()); Console::WriteMessage(message.CStr()); } else { OpString error; error.AppendFormat(UNI_L("Failed to update %s resource."), dl_elm->GetResourceName()); Console::WriteError(error.CStr()); SetLastError(AUUpdateError); if(dl_elm->UpdateRequiresRestart()) { update_error = TRUE; } } } else { OpString error; error.AppendFormat(UNI_L("Resource check failed for %s resource."), dl_elm->GetResourceName()); Console::WriteError(error.CStr()); SetLastError(AUValidationError); if(dl_elm->UpdateRequiresRestart()) { update_error = TRUE; } } } } // Clean up resources OpStatus::Ignore(CleanupAllResources()); if (waiting_for_unpacking) { SetUpdateState(AUSUnpacking); if(call_ready_to_install) m_state_after_unpacking = AUSReadyToInstall; else if(update_error) m_state_after_unpacking = AUSUpdateAvailable; else m_state_after_unpacking = AUSUpToDate; } else if(call_ready_to_install) { SetUpdateState(AUSReadyToInstall); } else if(update_error) { BroadcastOnError(m_last_error, IsSilent()); SetUpdateState(AUSUpdateAvailable); return OpStatus::ERR; } else { BroadcastOnFinishedUpdating(); SetUpdateState(AUSUpToDate); } CheckAndUpdateState(); return OpStatus::OK; } void AutoUpdater::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { if (msg == MSG_AUTOUPDATE_UNPACKING_COMPLETE) { g_main_message_handler->UnsetCallBack(this, MSG_AUTOUPDATE_UNPACKING_COMPLETE); if (m_state_after_unpacking == AUSUpdateAvailable) { BroadcastOnError(m_last_error, IsSilent()); } else if (m_state_after_unpacking == AUSUpToDate) { BroadcastOnFinishedUpdating(); } SetUpdateState(m_state_after_unpacking); CheckAndUpdateState(); } } OP_STATUS AutoUpdater::CleanupAllResources() { OP_ASSERT(m_xml_downloader); OP_STATUS ret = OpStatus::OK; UpdatableResource* resource = m_xml_downloader->GetFirstResource(); while (resource) { ret |= resource->Cleanup(); resource = m_xml_downloader->GetNextResource(); } return ret; } void AutoUpdater::OnTimeOut(OpTimer *timer) { if (timer == m_download_timer) { m_download_countdown--; if(m_download_countdown > 0) { m_download_timer->Start(1000); BroadcastOnRestartingDownload(m_download_countdown, m_last_error, IsSilent()); } else { OP_DELETE(m_download_timer); m_download_timer = NULL; m_download_retries++; DownloadUpdate(TRUE); } return; } if (timer == m_update_check_timer) { if(!g_ssl_auto_updaters->Active()) { OP_DELETE(m_update_check_timer); m_update_check_timer = NULL; m_silent_update = TRUE; RETURN_VOID_IF_ERROR(DownloadStatusXML()); } else { // If the SSL auto update is active, schedule auto update check later m_update_check_timer->Start(AUTOUPDATE_SSL_UPDATERS_BUSY_RECHECK_TIMEOUT_SEC * 1000); } return; } #ifndef _MACINTOSH_ if (timer == m_checker_launch_retry_timer) { TryRunningChecker(); return; } #endif // _MACINTOSH_ OP_ASSERT("Unknown timer!"); } void AutoUpdater::GetDownloadStatus(INT32* total_file_count, INT32* downloaded_file_count, INT32* failed_download_count) { OP_ASSERT(m_xml_downloader); if(total_file_count) *total_file_count = 0; if(downloaded_file_count) *downloaded_file_count = 0; if(failed_download_count) *failed_download_count = 0; UpdatableResource* resource = m_xml_downloader->GetFirstResource(); while (resource) { if(resource->GetResourceClass() == UpdatableResource::File) { UpdatableFile* file = static_cast<UpdatableFile*>(resource); if(file->DownloadStarted()) { if(downloaded_file_count && file->Downloaded()) { (*downloaded_file_count)++; } if(failed_download_count && file->DownloadFailed()) { (*failed_download_count)++; } if(total_file_count) { (*total_file_count)++; } } } resource = m_xml_downloader->GetNextResource(); } } BOOL AutoUpdater::CheckAllResources() { OP_ASSERT(m_xml_downloader); UpdatableResource* resource = m_xml_downloader->GetFirstResource(); int resource_checked_count = 0; while (resource) { if(!resource->CheckResource()) { OpString error; error.AppendFormat(UNI_L("Resource check failed for %s resource."), resource->GetResourceName()); Console::WriteError(error.CStr()); return FALSE; } resource_checked_count++; resource = m_xml_downloader->GetNextResource(); } return (resource_checked_count > 0) ? TRUE : FALSE; } #ifndef _MACINTOSH_ namespace { BOOL LaunchTheChecker(const uni_char* path, int channel_id) { const int argc = 18; char* argv[argc]; OperaVersion version; version.AllowAutoupdateIniOverride(); OpString8 tmp_str; tmp_str.Empty(); tmp_str.AppendFormat("%d.%02d.%04d", version.GetMajor(), version.GetMinor(), version.GetBuild()); argv[0] = op_strdup("-version"); argv[1] = op_strdup(tmp_str.CStr()); argv[2] = op_strdup("-host"); tmp_str.SetUTF8FromUTF16(g_pcui->GetStringPref(PrefsCollectionUI::AutoUpdateGeoServer)); argv[3] = op_strdup(tmp_str.CStr()); argv[4] = op_strdup("-firstrunver"); tmp_str.SetUTF8FromUTF16(g_pcui->GetStringPref(PrefsCollectionUI::FirstVersionRun)); argv[5] = op_strdup(tmp_str.CStr()); argv[6] = op_strdup("-firstrunts"); tmp_str.Empty(); tmp_str.AppendFormat("%d", g_pcui->GetIntegerPref(PrefsCollectionUI::FirstRunTimestamp)); argv[7] = op_strdup(tmp_str.CStr()); argv[8] = op_strdup("-loc"); tmp_str.Empty(); OpStringC user = g_pcui->GetStringPref(PrefsCollectionUI::CountryCode); OpStringC detected = g_pcui->GetStringPref(PrefsCollectionUI::DetectedCountryCode); OpString tmp_loc; tmp_loc.AppendFormat("%s;%s;%s;%s", user.HasContent() ? user.CStr() : UNI_L("empty"), detected.HasContent() ? detected.CStr() : UNI_L("empty"), g_region_info->m_country.HasContent() ? g_region_info->m_country.CStr() : UNI_L("empty"), g_region_info->m_region.HasContent() ? g_region_info->m_region.CStr() : UNI_L("empty")); tmp_str.SetUTF8FromUTF16(tmp_loc.CStr()); argv[9] = op_strdup(tmp_str.CStr()); argv[10] = op_strdup("-lang"); tmp_str.SetUTF8FromUTF16(g_languageManager->GetLanguage().CStr()); argv[11] = op_strdup(tmp_str.CStr()); argv[12] = op_strdup("-pipeid"); tmp_str.Empty(); tmp_str.AppendFormat("%d", channel_id); argv[13] = op_strdup(tmp_str.CStr()); argv[14] = op_strdup("-producttype"); #ifdef _DEBUG argv[15] = op_strdup("Debug"); #else switch (g_desktop_product->GetProductType()) { case PRODUCT_TYPE_OPERA: argv[15] = op_strdup(""); break; case PRODUCT_TYPE_OPERA_NEXT: argv[15] = op_strdup("Next"); break; case PRODUCT_TYPE_OPERA_LABS: argv[15] = op_strdup("Labs");break; default: argv[15] = op_strdup(""); break; } #endif // _DEBUG /* Send path to SSL certificate file. This is irrelevant on platforms that * use OpenSSL and supply the certificate file from memory. The standalone * checkers on these platforms will ignore this argument. The checkers that * rely only on CURL and need to supply the certificate in a file will * expect a -certfile argument with the path. It should be: * OPFILE_RESOURCES_FOLDER/cert.pem */ OpString cert_dir; OP_STATUS status = g_folder_manager->GetFolderPath(OPFILE_RESOURCES_FOLDER, cert_dir); OpString8 cert_file8; if (OpStatus::IsSuccess(status)) { OpString cert_file; status += OpPathDirFileCombine(cert_file, cert_dir, OpStringC(UNI_L("cert.pem"))); status += cert_file8.SetUTF8FromUTF16(cert_file); } if (OpStatus::IsSuccess(status)) { argv[16] = op_strdup("-certfile"); argv[17] = op_strdup(cert_file8.CStr()); } else { argv[16] = NULL; // Likely an OOM in GetFolderPath or string operations argv[17] = NULL; // This will fail the launch } BOOL valid = TRUE; for (int i = 0; i < argc; ++i) { if (!argv[i]) { valid = FALSE; break; } } if (valid) valid = g_launch_manager->Launch(path, argc, argv); for (int i = 0; i < argc; ++i) op_free(argv[i]); return valid; } } OP_STATUS AutoUpdater::TryRunningChecker() { OP_STATUS status = OpStatus::OK; OP_DELETE(m_checker_launch_retry_timer); m_checker_launch_retry_timer = NULL; m_checker_state = CheckerOk; BOOL ok = LaunchTheChecker(m_checker_path.CStr(), m_channel_id); if (!ok) { m_checker_state = CheckerCouldntLaunch; if (++m_checker_launch_retry_count <= MAX_CHECKER_LAUNCH_RETRIES) { m_checker_launch_retry_timer = OP_NEW(OpTimer, ()); if (m_checker_launch_retry_timer) { m_checker_launch_retry_timer->SetTimerListener(this); m_checker_launch_retry_timer->Start(CHECKER_LAUNCH_RETRY_TIME_MS); } else { m_checker_launch_retry_count = 0; status = OpStatus::ERR_NO_MEMORY; } } else // give up. m_checker_launch_retry_count = 0; } else { m_checker_launch_retry_count = 0; if (m_channel_to_checker) m_channel_to_checker->Connect(25); // This is only so the updater is connected and it does not retry. We won't be using its results here. } SetUpdateState(m_update_state); // Force asving the state. return status; } #endif // _MACINTOSH_ OP_STATUS AutoUpdater::DownloadStatusXML() { OP_ASSERT(m_xml_downloader); OP_ASSERT(m_autoupdate_xml); OP_ASSERT(m_update_state == AUSUpToDate || m_update_state == AUSUpdateAvailable); #ifndef _MACINTOSH_ OP_ASSERT(m_checker_path.Length() > 0); #endif // _MACINTOSH_ if (m_update_state != AUSUpToDate && m_update_state != AUSUpdateAvailable) { BroadcastOnError(AUInternalError, IsSilent()); return OpStatus::ERR_NOT_SUPPORTED; } if (m_resources_check_only) Console::WriteMessage(UNI_L("Starting a resource check.")); else Console::WriteMessage(UNI_L("Starting an update check.")); // Stop the update check timer, if we have one OP_DELETE(m_update_check_timer); m_update_check_timer = NULL; SetUpdateState(AUSChecking); CheckAndUpdateState(); AutoUpdateXML::AutoUpdateLevel autoupdate_level = AutoUpdateXML::UpdateLevelResourceCheck; if (!m_resources_check_only) { if (m_level_of_automation > NoChecking || !IsSilent()) { #ifdef AUTOUPDATE_PACKAGE_INSTALLATION if (!HasDownloadedNewerVersion()) #endif // AUTOUPDATE_PACKAGE_INSTALLATION { autoupdate_level = AutoUpdateXML::UpdateLevelDefaultCheck; } } } // In case of an error below, a new update check will be scheduled in CheckAndUpdateState(). // Scheduling an update sets m_resource_check_only to FALSE, so we don't have any retry // mechanism for the initial resource check, but we schedule a full update check that // will happen when the time comes. A new resource check will be attempted if needed on the // next browser start. // In case of no error here, we will schedule a new update check after the resource check is // over, and that will also set m_resources_check_only to FALSE. // However, because we prefer to be rather safe than sorry, we set it explicitly here, so that // we don't get stuck in the resource-check-only state somehow. m_resources_check_only = FALSE; OpString url_string; OpString8 xml; OP_ASSERT(m_autoupdate_server_url); if (OpStatus::IsError(m_autoupdate_server_url->GetCurrentURL(url_string))) { SetLastError(AUInternalError); SetUpdateState(AUSError); CheckAndUpdateState(); return OpStatus::ERR; } // No addition items are sent with an update request m_autoupdate_xml->ClearRequestItems(); AutoUpdateXML::AutoUpdateLevel used_level; if (OpStatus::IsError(m_autoupdate_xml->GetRequestXML(xml, autoupdate_level, AutoUpdateXML::RT_Main, &used_level))) { SetLastError(AUInternalError); SetUpdateState(AUSError); CheckAndUpdateState(); return OpStatus::ERR; } #ifndef _MACINTOSH_ // The checker needs to be run when launching Opera for the first time and every time the main update is asked for. // It also has to be launched if there is no uuid stored yet. BOOL run_checker = (used_level == AutoUpdateXML::UpdateLevelDefaultCheck || used_level == AutoUpdateXML::UpdateLevelUpgradeCheck || g_run_type->m_type == StartupType::RUNTYPE_FIRST || g_run_type->m_type == StartupType::RUNTYPE_FIRSTCLEAN || g_run_type->m_type == StartupType::RUNTYPE_FIRST_NEW_BUILD_NUMBER) && !m_user_initiated; if (run_checker) if (OpStatus::IsMemoryError(TryRunningChecker())) { SetLastError(AUInternalError); SetUpdateState(AUSError); CheckAndUpdateState(); return OpStatus::ERR_NO_MEMORY; } #endif // _MACINTOSH_ // Set time of last check m_time_of_last_update_check = g_timecache->CurrentTime(); OP_STATUS st = WritePref(PrefsCollectionUI::TimeOfLastUpdateCheck, static_cast<int>(m_time_of_last_update_check)); if (OpStatus::IsError(st)) { SetLastError(AUInternalError); SetUpdateState(AUSError); CheckAndUpdateState(); return OpStatus::ERR; } if (OpStatus::IsError(m_xml_downloader->StartXMLRequest(url_string, xml))) { m_xml_downloader->StopRequest(); SetLastError(AUConnectionError); SetUpdateState(AUSError); CheckAndUpdateState(); return OpStatus::ERR; } return OpStatus::OK; } OP_STATUS AutoUpdater::ScheduleResourceCheck() { if (AUSChecking == m_update_state) { // A check is already in progress. // We hope to get the new resources along with the check. // Ignore this request. Console::WriteMessage(UNI_L("Ignoring resource check request.")); return OpStatus::ERR_NO_ACCESS; } if (m_update_check_timer) { // An update check is already scheduled. // Forget that, schedule an immediate resource check, the update check // will be scheduled after we have finished. OP_DELETE(m_update_check_timer); m_update_check_timer = NULL; Console::WriteMessage(UNI_L("Suspending the update check schedule in order to make a resource check.")); } m_update_check_timer = OP_NEW(OpTimer, ()); if (!m_update_check_timer) { Console::WriteError(UNI_L("Could not schedule a resource check.")); return OpStatus::ERR_NO_MEMORY; } // Schedule the resource check as required. Note, that this timeout should not be set "too high", since it is // responsible for downloading the new browserjs after upgrading Opera and having the old browserjs may cause // quite serious problems. It should not also be set "too low" since we might hit the browser startup phase // and slow it down. int seconds_to_resource_check = CalculateTimeOfResourceCheck(); m_resources_check_only = TRUE; m_update_check_timer->SetTimerListener(this); m_update_check_timer->Start(seconds_to_resource_check * 1000); Console::WriteMessage(UNI_L("Scheduled an immediate resource check.")); return OpStatus::OK; } OP_STATUS AutoUpdater::ScheduleUpdateCheck(ScheduleCheckType schedule_type) { OP_ASSERT(m_update_state == AUSUpToDate); OP_ASSERT(!m_update_check_timer); if (m_update_state == AUSUpToDate && !m_update_check_timer) { m_update_check_timer = OP_NEW(OpTimer, ()); if (m_update_check_timer) { int seconds_to_next_check = CalculateTimeOfNextUpdateCheck(schedule_type); m_update_check_timer->SetTimerListener(this); m_update_check_timer->Start(seconds_to_next_check * 1000); m_resources_check_only = FALSE; OpString message; message.AppendFormat(UNI_L("Scheduled new update check in %d seconds."), seconds_to_next_check); Console::WriteMessage(message.CStr()); return OpStatus::OK; } } Console::WriteError(UNI_L("Failed to schedule new update check.")); return OpStatus::ERR; } int AutoUpdater::CalculateTimeOfResourceCheck() { OP_ASSERT(AUTOUPDATE_RESOURCE_CHECK_BASE_TIMEOUT_SEC > 0); OP_ASSERT(m_update_check_delay >= 0); int timeout = AUTOUPDATE_RESOURCE_CHECK_BASE_TIMEOUT_SEC + m_update_check_delay; return timeout; } int AutoUpdater::CalculateTimeOfNextUpdateCheck(ScheduleCheckType schedule_type) { // Set the time the code below will normalize it if needed. int time_between_checks_sec = m_update_check_interval + m_update_check_delay + m_update_check_random_delta; int seconds_to_next_check = 0; // Make sure the time between checks is in range [MIN_UPDATE_CHECK_TIMEOUT, UPDATE_CHECK_INTERVAL_MAX] OP_ASSERT(MIN_UPDATE_CHECK_INTERVAL_SEC < MAX_UPDATE_CHECK_INTERVAL_SEC); OP_ASSERT(MIN_UPDATE_CHECK_INTERVAL_RUNNING_SEC < MAX_UPDATE_CHECK_INTERVAL_SEC); if (ScheduleRunning == schedule_type) time_between_checks_sec = MAX(time_between_checks_sec, MIN_UPDATE_CHECK_INTERVAL_RUNNING_SEC + m_update_check_random_delta); else if (ScheduleStartup == schedule_type) time_between_checks_sec = MAX(time_between_checks_sec, MIN_UPDATE_CHECK_INTERVAL_SEC); else { OP_ASSERT("Unknown ScheduleCheckType!"); } time_between_checks_sec = MIN(time_between_checks_sec, MAX_UPDATE_CHECK_INTERVAL_SEC); time_t time_now_sec = g_timecache->CurrentTime(); time_t time_of_next_scheduled_check = m_time_of_last_update_check + time_between_checks_sec; if(time_of_next_scheduled_check < time_now_sec) seconds_to_next_check = 0; else seconds_to_next_check = time_of_next_scheduled_check - time_now_sec; // To ensure that we dont check too often. #ifdef _DEBUG seconds_to_next_check = MAX(seconds_to_next_check, 1); #else seconds_to_next_check = MAX(seconds_to_next_check, 5); #endif return seconds_to_next_check; } OP_STATUS AutoUpdater::ScheduleDownload() { OP_ASSERT(m_update_state == AUSErrorDownloading); OP_ASSERT(!m_download_timer); if(m_update_state != AUSErrorDownloading) return OpStatus::ERR; if(m_download_timer) return OpStatus::ERR; m_download_timer = OP_NEW(OpTimer, ()); if(!m_download_timer) return OpStatus::ERR_NO_MEMORY; m_download_timer->SetTimerListener(this); m_download_timer->Start(1000); m_download_countdown = 60; return OpStatus::OK; } void AutoUpdater::BroadcastOnUpToDate(BOOL silent) { for (OpListenersIterator iterator(m_listeners); m_listeners.HasNext(iterator);) { m_listeners.GetNext(iterator)->OnUpToDate(silent); } } void AutoUpdater::BroadcastOnChecking(BOOL silent) { for (OpListenersIterator iterator(m_listeners); m_listeners.HasNext(iterator);) { m_listeners.GetNext(iterator)->OnChecking(silent); } } void AutoUpdater::BroadcastOnUpdateAvailable(UpdatableResource::UpdatableResourceType type, OpFileLength update_size, const uni_char* update_info_url, BOOL silent) { for (OpListenersIterator iterator(m_listeners); m_listeners.HasNext(iterator);) { m_listeners.GetNext(iterator)->OnUpdateAvailable(type, update_size, update_info_url, silent); } } void AutoUpdater::BroadcastOnDownloading(UpdatableResource::UpdatableResourceType type, OpFileLength total_size, OpFileLength downloaded_size, double kbps, unsigned long time_estimate, BOOL silent) { for (OpListenersIterator iterator(m_listeners); m_listeners.HasNext(iterator);) { m_listeners.GetNext(iterator)->OnDownloading(type, total_size, downloaded_size, kbps, time_estimate, silent); } } void AutoUpdater::BroadcastOnDownloadingDone(UpdatableResource::UpdatableResourceType type, const OpString& filename, OpFileLength total_size, BOOL silent) { for (OpListenersIterator iterator(m_listeners); m_listeners.HasNext(iterator);) { m_listeners.GetNext(iterator)->OnDownloadingDone(type, filename, total_size, silent); } } void AutoUpdater::BroadcastOnDownloadingFailed(BOOL silent) { for (OpListenersIterator iterator(m_listeners); m_listeners.HasNext(iterator);) { m_listeners.GetNext(iterator)->OnDownloadingFailed(silent); } } void AutoUpdater::BroadcastOnRestartingDownload(INT32 seconds_until_restart, AutoUpdateError last_error, BOOL silent) { for (OpListenersIterator iterator(m_listeners); m_listeners.HasNext(iterator);) { m_listeners.GetNext(iterator)->OnRestartingDownload(seconds_until_restart, last_error, silent); } } void AutoUpdater::BroadcastOnReadyToUpdate() { for (OpListenersIterator iterator(m_listeners); m_listeners.HasNext(iterator);) { m_listeners.GetNext(iterator)->OnReadyToUpdate(); } } void AutoUpdater::BroadcastOnUpdating() { for (OpListenersIterator iterator(m_listeners); m_listeners.HasNext(iterator);) { m_listeners.GetNext(iterator)->OnUpdating(); } } void AutoUpdater::BroadcastOnFinishedUpdating() { for (OpListenersIterator iterator(m_listeners); m_listeners.HasNext(iterator);) { m_listeners.GetNext(iterator)->OnFinishedUpdating(); } } void AutoUpdater::BroadcastOnUnpacking() { for (OpListenersIterator iterator(m_listeners); m_listeners.HasNext(iterator);) { m_listeners.GetNext(iterator)->OnUnpacking(); } } void AutoUpdater::BroadcastOnReadyToInstallNewVersion(const OpString& version, BOOL silent) { for (OpListenersIterator iterator(m_listeners); m_listeners.HasNext(iterator);) { m_listeners.GetNext(iterator)->OnReadyToInstallNewVersion(version, silent); } } void AutoUpdater::BroadcastOnError(AutoUpdateError error, BOOL silent) { for (OpListenersIterator iterator(m_listeners); m_listeners.HasNext(iterator);) { m_listeners.GetNext(iterator)->OnError(error, silent); } } OP_STATUS AutoUpdater::SetUpdateState(AutoUpdateState update_state) { #ifndef _MACINTOSH_ int state = m_checker_state << 16 | update_state; #else int state = update_state; #endif // _MACINTOSH_ RETURN_IF_LEAVE(g_pcui->WriteIntegerL(PrefsCollectionUI::AutoUpdateState, state)); TRAPD(err, g_prefsManager->CommitL()); m_update_state = update_state; return OpStatus::OK; } void AutoUpdater::Reset() { m_download_retries = 0; OP_DELETE(m_update_check_timer); m_update_check_timer = NULL; OP_DELETE(m_download_timer); m_download_timer = NULL; } #ifdef AUTOUPDATE_PACKAGE_INSTALLATION BOOL AutoUpdater::HasDownloadedNewerVersion() { AUDataFileReader reader; if(OpStatus::IsSuccess(reader.Init()) && OpStatus::IsSuccess(reader.LoadFromOpera())) { OperaVersion downloaded_version; uni_char* version = reader.GetVersion(); uni_char* buildnum = reader.GetBuildNum(); OpString version_string; if(OpStatus::IsSuccess(version_string.Set(version)) && OpStatus::IsSuccess(version_string.Append(".")) && OpStatus::IsSuccess(version_string.Append(buildnum)) && OpStatus::IsSuccess(downloaded_version.Set(version_string))) { if(m_opera_version < downloaded_version) { // Only resource check if we have downloaded a higher version return TRUE; } } OP_DELETEA(version); OP_DELETEA(buildnum); } return FALSE; } #endif // AUTOUPDATE_PACKAGE_INSTALLATION #ifdef AUTOUPDATE_PACKAGE_INSTALLATION void AutoUpdater::DeleteUpgradeFolderIfNeeded() { // Create the aufile utils object AUFileUtils* file_utils = AUFileUtils::Create(); if (!file_utils) return; // If the last installation succedded then clean up the remains of the // special upgrade folder OpString autoupdate_textfile_path; uni_char* temp_folder = NULL; if (file_utils->GetUpgradeFolder(&temp_folder) == AUFileUtils::OK) { // Build the path to the text file RETURN_VOID_IF_ERROR(autoupdate_textfile_path.Set(temp_folder)); RETURN_VOID_IF_ERROR(autoupdate_textfile_path.Append(PATHSEP)); RETURN_VOID_IF_ERROR(autoupdate_textfile_path.Append(AUTOUPDATE_UPDATE_TEXT_FILENAME)); // Check if the upgrade folder even exists OpFile upgrade_path; BOOL exists = FALSE; // Build the OpFile RETURN_VOID_IF_ERROR(upgrade_path.Construct(temp_folder)); // If the file doesn't exist kill the folder if (OpStatus::IsSuccess(upgrade_path.Exists(exists)) && exists) { // If the text file exists then don't clean up we can assume they want to do this next time // Otherwise kill the folder OpFile autoupdate_textfile; // reset exists exists = FALSE; RETURN_VOID_IF_ERROR(autoupdate_textfile.Construct(autoupdate_textfile_path)); // If the file doesn't exist kill the folder if (OpStatus::IsSuccess(autoupdate_textfile.Exists(exists)) && !exists) { // Delete this entire folder RETURN_VOID_IF_ERROR(upgrade_path.Delete(TRUE)); } } } OP_DELETEA(temp_folder); OP_DELETE(file_utils); } #endif // AUTOUPDATE_PACKAGE_INSTALLATION void AutoUpdater::IncreaseDelayedUpdateCheckInterval() { m_update_check_delay = MIN(m_update_check_delay + UPDATE_CHECK_INTERVAL_DELTA_SEC, MAX_UPDATE_CHECK_INTERVAL_SEC); // Don't let increasing the upgrade check time to break any further operation OpStatus::Ignore(WritePref(PrefsCollectionUI::DelayedUpdateCheckInterval, m_update_check_delay)); } void Console::WriteMessage(const uni_char* message) { #ifdef OPERA_CONSOLE OpConsoleEngine::Message cmessage(OpConsoleEngine::AutoUpdate, OpConsoleEngine::Verbose); cmessage.message.Set(message); TRAPD(err, g_console->PostMessageL(&cmessage)); #endif } void Console::WriteError(const uni_char* error) { #ifdef OPERA_CONSOLE OpConsoleEngine::Message cmessage(OpConsoleEngine::AutoUpdate, OpConsoleEngine::Error); cmessage.message.Set(error); TRAPD(err, g_console->PostMessageL(&cmessage)); #endif } #endif // AUTO_UPDATE_SUPPORT
/* * OLED.h * * Created on: Jan 13, 2019 * Author: Marek */ #ifndef CLASSES_OLED_H_ #define CLASSES_OLED_H_ #define OLED_BUFFER_SIZE 8192 #include "Allshit.h" #include "alphabet.h" class OLED { private: uint8_t buffer [OLED_BUFFER_SIZE]; void send_REG(uint8_t cmd); void send_DATA(uint8_t data); void OLED_Init_Registers(); void OLED_reset(); void reset_buffer(); void update_all_screen(); public: void Init(); void setImage(unsigned int imageId); void process(); OLED(); virtual ~OLED(); }; extern OLED oled; extern int counter; #endif /* CLASSES_OLED_H_ */
class Solution { public: int rob(vector<int>& nums) { int n=nums.size(); if(n==0) { return 0; } int dpR[n]; int dpN[n]; dpR[0]=nums[0]; dpN[0]=0; for(int i=1;i<n;i++) { dpR[i]=max(nums[i]+dpN[i-1],dpR[i-1]); dpN[i]=dpR[i-1]; } return max(dpR[n-1],dpN[n-1]); } };
//Copyright 2011-2016 Tyler Gilbert; All Rights Reserved #include "sgfx.hpp" #include "ui/Element.hpp" #include "draw.hpp" using namespace ui; Element::Element(){} void Element::draw_scroll(const DrawingScaledAttr & attr, int selected, int total, int visible){ sg_point_t p = attr.p(); Dim d = attr.d(); int bar_size; sg_dim_t bar; bar_size = d.h() / total; attr.b().set(p, d); p.y = p.y + selected*bar_size; bar.w = d.w(); bar.h = bar_size; attr.b().clear(p, bar); } Element * Element::handle_event(const Event & event, const DrawingAttr & attr){ return this; } void Element::set_animation_type(u8 v){} u8 Element::animation_type() const{ return AnimationAttr::PUSH_LEFT; } void Element::set_animation_path(u8 path){} void Element::set_animation(u8 type, u8 path){ set_animation_type(type); set_animation_path(path); } u8 Element::animation_path() const { return AnimationAttr::SQUARED; }
// Created on: 1998-11-26 // Created by: Xuan PHAM PHU // Copyright (c) 1998-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 _TopOpeBRepTool_TOOL_HeaderFile #define _TopOpeBRepTool_TOOL_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Integer.hxx> #include <TopTools_Array1OfShape.hxx> #include <TopAbs_State.hxx> #include <TopTools_ListOfShape.hxx> #include <TopTools_DataMapOfShapeListOfShape.hxx> class TopoDS_Shape; class TopoDS_Edge; class TopoDS_Vertex; class TopoDS_Face; class gp_Pnt2d; class TopOpeBRepTool_C2DF; class gp_Vec; class gp_Dir2d; class BRepAdaptor_Curve; class gp_Vec2d; class gp_Dir; class Geom2d_Curve; class gp_Pnt; class TopOpeBRepTool_TOOL { public: DEFINE_STANDARD_ALLOC Standard_EXPORT static Standard_Integer OriinSor (const TopoDS_Shape& sub, const TopoDS_Shape& S, const Standard_Boolean checkclo = Standard_False); Standard_EXPORT static Standard_Integer OriinSorclosed (const TopoDS_Shape& sub, const TopoDS_Shape& S); Standard_EXPORT static Standard_Boolean ClosedE (const TopoDS_Edge& E, TopoDS_Vertex& vclo); Standard_EXPORT static Standard_Boolean ClosedS (const TopoDS_Face& F); Standard_EXPORT static Standard_Boolean IsClosingE (const TopoDS_Edge& E, const TopoDS_Face& F); Standard_EXPORT static Standard_Boolean IsClosingE (const TopoDS_Edge& E, const TopoDS_Shape& W, const TopoDS_Face& F); Standard_EXPORT static void Vertices (const TopoDS_Edge& E, TopTools_Array1OfShape& Vces); Standard_EXPORT static TopoDS_Vertex Vertex (const Standard_Integer Iv, const TopoDS_Edge& E); Standard_EXPORT static Standard_Real ParE (const Standard_Integer Iv, const TopoDS_Edge& E); Standard_EXPORT static Standard_Integer OnBoundary (const Standard_Real par, const TopoDS_Edge& E); Standard_EXPORT static gp_Pnt2d UVF (const Standard_Real par, const TopOpeBRepTool_C2DF& C2DF); Standard_EXPORT static Standard_Boolean ParISO (const gp_Pnt2d& p2d, const TopoDS_Edge& e, const TopoDS_Face& f, Standard_Real& pare); Standard_EXPORT static Standard_Boolean ParE2d (const gp_Pnt2d& p2d, const TopoDS_Edge& e, const TopoDS_Face& f, Standard_Real& par, Standard_Real& dist); Standard_EXPORT static Standard_Boolean Getduv (const TopoDS_Face& f, const gp_Pnt2d& uv, const gp_Vec& dir, const Standard_Real factor, gp_Dir2d& duv); Standard_EXPORT static Standard_Boolean uvApp (const TopoDS_Face& f, const TopoDS_Edge& e, const Standard_Real par, const Standard_Real eps, gp_Pnt2d& uvapp); Standard_EXPORT static Standard_Real TolUV (const TopoDS_Face& F, const Standard_Real tol3d); Standard_EXPORT static Standard_Real TolP (const TopoDS_Edge& E, const TopoDS_Face& F); Standard_EXPORT static Standard_Real minDUV (const TopoDS_Face& F); Standard_EXPORT static Standard_Boolean outUVbounds (const gp_Pnt2d& uv, const TopoDS_Face& F); Standard_EXPORT static void stuvF (const gp_Pnt2d& uv, const TopoDS_Face& F, Standard_Integer& onU, Standard_Integer& onV); Standard_EXPORT static Standard_Boolean TggeomE (const Standard_Real par, const BRepAdaptor_Curve& BC, gp_Vec& Tg); Standard_EXPORT static Standard_Boolean TggeomE (const Standard_Real par, const TopoDS_Edge& E, gp_Vec& Tg); Standard_EXPORT static Standard_Boolean TgINSIDE (const TopoDS_Vertex& v, const TopoDS_Edge& E, gp_Vec& Tg, Standard_Integer& OvinE); Standard_EXPORT static gp_Vec2d Tg2d (const Standard_Integer iv, const TopoDS_Edge& E, const TopOpeBRepTool_C2DF& C2DF); Standard_EXPORT static gp_Vec2d Tg2dApp (const Standard_Integer iv, const TopoDS_Edge& E, const TopOpeBRepTool_C2DF& C2DF, const Standard_Real factor); Standard_EXPORT static gp_Vec2d tryTg2dApp (const Standard_Integer iv, const TopoDS_Edge& E, const TopOpeBRepTool_C2DF& C2DF, const Standard_Real factor); Standard_EXPORT static Standard_Boolean XX (const gp_Pnt2d& uv, const TopoDS_Face& f, const Standard_Real par, const TopoDS_Edge& e, gp_Dir& xx); Standard_EXPORT static Standard_Boolean Nt (const gp_Pnt2d& uv, const TopoDS_Face& f, gp_Dir& normt); Standard_EXPORT static Standard_Boolean NggeomF (const gp_Pnt2d& uv, const TopoDS_Face& F, gp_Vec& ng); Standard_EXPORT static Standard_Boolean NgApp (const Standard_Real par, const TopoDS_Edge& E, const TopoDS_Face& F, const Standard_Real tola, gp_Dir& ngApp); Standard_EXPORT static Standard_Boolean tryNgApp (const Standard_Real par, const TopoDS_Edge& E, const TopoDS_Face& F, const Standard_Real tola, gp_Dir& ng); Standard_EXPORT static Standard_Integer tryOriEinF (const Standard_Real par, const TopoDS_Edge& E, const TopoDS_Face& F); Standard_EXPORT static Standard_Boolean IsQuad (const TopoDS_Edge& E); Standard_EXPORT static Standard_Boolean IsQuad (const TopoDS_Face& F); Standard_EXPORT static Standard_Boolean CurvE (const TopoDS_Edge& E, const Standard_Real par, const gp_Dir& tg0, Standard_Real& Curv); Standard_EXPORT static Standard_Boolean CurvF (const TopoDS_Face& F, const gp_Pnt2d& uv, const gp_Dir& tg0, Standard_Real& Curv, Standard_Boolean& direct); Standard_EXPORT static Standard_Boolean UVISO (const Handle(Geom2d_Curve)& PC, Standard_Boolean& isou, Standard_Boolean& isov, gp_Dir2d& d2d, gp_Pnt2d& o2d); Standard_EXPORT static Standard_Boolean UVISO (const TopOpeBRepTool_C2DF& C2DF, Standard_Boolean& isou, Standard_Boolean& isov, gp_Dir2d& d2d, gp_Pnt2d& o2d); Standard_EXPORT static Standard_Boolean UVISO (const TopoDS_Edge& E, const TopoDS_Face& F, Standard_Boolean& isou, Standard_Boolean& isov, gp_Dir2d& d2d, gp_Pnt2d& o2d); Standard_EXPORT static Standard_Boolean IsonCLO (const Handle(Geom2d_Curve)& PC, const Standard_Boolean onU, const Standard_Real xfirst, const Standard_Real xperiod, const Standard_Real xtol); Standard_EXPORT static Standard_Boolean IsonCLO (const TopOpeBRepTool_C2DF& C2DF, const Standard_Boolean onU, const Standard_Real xfirst, const Standard_Real xperiod, const Standard_Real xtol); Standard_EXPORT static void TrslUV (const gp_Vec2d& t2d, TopOpeBRepTool_C2DF& C2DF); Standard_EXPORT static Standard_Boolean TrslUVModifE (const gp_Vec2d& t2d, const TopoDS_Face& F, TopoDS_Edge& E); Standard_EXPORT static Standard_Real Matter (const gp_Vec& d1, const gp_Vec& d2, const gp_Vec& ref); Standard_EXPORT static Standard_Real Matter (const gp_Vec2d& d1, const gp_Vec2d& d2); Standard_EXPORT static Standard_Boolean Matter (const gp_Dir& xx1, const gp_Dir& nt1, const gp_Dir& xx2, const gp_Dir& nt2, const Standard_Real tola, Standard_Real& Ang); Standard_EXPORT static Standard_Boolean Matter (const TopoDS_Face& f1, const TopoDS_Face& f2, const TopoDS_Edge& e, const Standard_Real pare, const Standard_Real tola, Standard_Real& Ang); Standard_EXPORT static Standard_Boolean MatterKPtg (const TopoDS_Face& f1, const TopoDS_Face& f2, const TopoDS_Edge& e, Standard_Real& Ang); Standard_EXPORT static Standard_Boolean Getstp3dF (const gp_Pnt& p, const TopoDS_Face& f, gp_Pnt2d& uv, TopAbs_State& st); Standard_EXPORT static Standard_Boolean SplitE (const TopoDS_Edge& Eanc, TopTools_ListOfShape& Splits); Standard_EXPORT static void MkShell (const TopTools_ListOfShape& lF, TopoDS_Shape& She); Standard_EXPORT static Standard_Boolean Remove (TopTools_ListOfShape& loS, const TopoDS_Shape& toremove); Standard_EXPORT static Standard_Boolean WireToFace (const TopoDS_Face& Fref, const TopTools_DataMapOfShapeListOfShape& mapWlow, TopTools_ListOfShape& lFs); Standard_EXPORT static Standard_Boolean EdgeONFace (const Standard_Real par, const TopoDS_Edge& ed, const gp_Pnt2d& uv, const TopoDS_Face& fa, Standard_Boolean& isonfa); protected: private: }; #endif // _TopOpeBRepTool_TOOL_HeaderFile
/* leetcode 485 * * * */ class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums) { if (nums.empty()) { return 0; } int sum = 0; int maxSum = sum; for (int i = 0; i < nums.size(); i++) { if (nums.at(i) == 1) { sum++; } else { if (maxSum < sum) { maxSum = sum; } sum = 0; } } if (maxSum < sum) { maxSum = sum; } return maxSum; } }; /************************** run solution **************************/ int _solution_run(vector<int>& nums) { Solution leetcode_485; return leetcode_485.findMaxConsecutiveOnes(nums); } #ifdef USE_SOLUTION_CUSTOM vector<vector<int>> _solution_custom(TestCases &tc) { return {}; } #endif /************************** get testcase **************************/ #ifdef USE_GET_TEST_CASES_IN_CPP vector<string> _get_test_cases_string() { return {}; } #endif
#include <CASE/random.hpp> #include <CASE/neighbors.hpp> #include <CASE/quad.hpp> #include <CASE/grid.hpp> #include <CASE/static_sim.hpp> #include <CASE/random.hpp> #define COLUMNS 300 #define ROWS 300 #define CELL_SIZE 2 int RULESET = 0; class Wolfram { int x, y; public: bool live = false; bool scanline = false; int index = 0; Wolfram(int _x = 0, int _y = 0) : x(CELL_SIZE * _x), y(CELL_SIZE * _y) { } void update(Wolfram & next) const { auto neighbors = CASE::CAdjacent<Wolfram>{this, COLUMNS, ROWS}; int pattern = 0b000; if (neighbors(-1, -1).live) pattern = pattern | 0b100; if (neighbors(0, -1).live) pattern = pattern | 0b010; if (neighbors(1, -1).live) pattern = pattern | 0b001; static const int rules[8][8] = { { 0, 0, 0, 1, 1, 1, 1, 0 }, { 0, 1, 1, 1, 1, 0, 0, 0 }, { 0, 1, 0, 1, 1, 0, 1, 0 }, { 1, 0, 0, 1, 0, 1, 1, 0 }, { 0, 1, 0, 1, 0, 1, 1, 0 }, { 0, 1, 1, 1, 0, 1, 1, 0 }, { 0, 1, 1, 1, 1, 1, 1, 0 }, { 0, 1, 1, 0, 1, 0, 0, 1 } }; if (scanline) { next.scanline = false; next.live = rules[RULESET][pattern]; } else if (neighbors(0, -1).scanline) next.scanline = true; } void draw(sf::Vertex * vs) const { if (live) CASE::quad(x, y, CELL_SIZE, CELL_SIZE, 0, 0, 0, vs); else if (scanline) CASE::quad(x, y, CELL_SIZE, CELL_SIZE, 255, 255, 100, vs); else CASE::quad(x, y, CELL_SIZE, CELL_SIZE, 255, 255, 255, vs); } }; struct Wolframs_Rules { using Agent = Wolfram; const int columns = COLUMNS; const int cell_size = CELL_SIZE; const int rows = ROWS; double framerate = 100.0; const int subset = columns * rows; const char* title = "Wolfram rules"; const sf::Color bgcolor = sf::Color{220, 220, 220}; void init(Wolfram * agents) { int index = 0; for (auto y = 0; y < ROWS; y++) { for (auto x = 0; x < COLUMNS; x++) { auto & agent = agents[CASE::index(x, y, COLUMNS)]; agent = Wolfram{x, y}; agent.index = index++; } } for (auto x = 0; x < COLUMNS; x++) { auto & agent = agents[CASE::index(x, 1, COLUMNS)]; agent.scanline = true; } const auto x = COLUMNS / 2; const auto y = 0; auto & agent = agents[CASE::index(x, y, COLUMNS)]; agent.live = true; /* static CASE::Uniform<0, 10> rand; int index = 0; for (auto y = 0; y < ROWS; y++) { for (auto x = 0; x < COLUMNS; x++) { auto & agent = agents[CASE::index(x, y, COLUMNS)]; agent = Wolfram{x, y}; agent.index = index++; } } for (auto x = 0; x < COLUMNS; x++) { auto & agent = agents[CASE::index(x, 1, COLUMNS)]; agent.scanline = true; } for (auto x = 0; x < COLUMNS; x++) { auto & agent = agents[CASE::index(x, 0, COLUMNS)]; if (rand() < 3) agent.live = true; } */ }; void postprocessing(Wolfram * agents) { static bool pressed = false; if(sf::Keyboard::isKeyPressed(sf::Keyboard::PageDown)) { if (!pressed) { RULESET = (RULESET + 1) % 7; std::cout << RULESET << std::endl; pressed = true; } } else pressed = false; } }; int main() { CASE::Static<Wolframs_Rules>(); }
#include "String.h" #include "Object.h" #include "Map.h" #include "CFunc.h" #include "GC.h" #include "StringBuilder.h" #include <stdio.h> #include <string.h> #include <assert.h> Value String::value(GC *gc, unsigned len) { return len <= 5 ? VAL_TAG(T_STR0 + len) : VAL_OBJ(String::alloc(gc, len)); } Value String::value(GC *gc, const char *s) { return value(gc, s, strlen(s)); } Value String::value(GC *gc, const char *s, unsigned len) { Value v = value(gc, len); char *p = GET_CSTR(v); memcpy(p, s, len); p[len] = 0; return v; } String::~String() { } String *String::alloc(GC *gc, unsigned size) { String *s = (String *) gc->alloc(sizeof(String) + size + 1, false); s->setSize(size); return s; } String *String::alloc(GC *gc, const char *p, unsigned size) { String *s = alloc(gc, size); memcpy(s->s, p, size); s->s[size] = 0; return s; } Value String::indexGet(Value s, Value p) { assert(IS_STRING(s)); // ERR(!IS_NUM(p), E_INDEX_NOT_NUMBER); if (!IS_NUM(p)) { return VNIL; } s64 pos = (s64) GET_NUM(p); unsigned size = len(s); if (pos < 0) { pos += size; } if (pos >= size || pos < 0) { return VNIL; } return VALUE_(T_STR1, (unsigned char) *(GET_CSTR(s) + (unsigned)pos)); } Value String::getSlice(GC *gc, Value s, Value p1, Value p2) { assert(IS_STRING(s)); ERR(!IS_NUM(p1) || !IS_NUM(p2), E_INDEX_NOT_NUMBER); s64 pos1 = (s64) GET_NUM(p1); s64 pos2 = (s64) GET_NUM(p2); unsigned size = len(s); if (pos1 < 0) { pos1 += size; } if (pos2 < 0) { pos2 += size; } if (pos1 < 0) { pos1 = 0; } if (pos2 > size) { pos2 = size; } // if (pos1 < 0 || pos2 >= size) { return VNIL; } return value(gc, GET_CSTR(s) + pos1, (pos1 < pos2) ? (unsigned)(pos2-pos1) : 0); } unsigned String::hashCode(char *buf, int size) { unsigned char *p = (unsigned char *) buf; unsigned h = 0; unsigned char *end = p + size; while (p < end) { h = (h ^ *p++) * FNV; } return h; } unsigned String::hashCode() { return hashCode(s, size()); } bool String::equals(String *other) { return _size == other->_size && !memcmp(s, other->s, size()); // && *(int*)s==*(int*)other->s } static Value stringConcat(GC *gc, Value a, char *pb, unsigned sb) { assert(IS_STRING(a)); unsigned sa = len(a); Value v = String::value(gc, sa + sb); char *pv = GET_CSTR(v); char *pa = GET_CSTR(a); memcpy(pv, pa, sa); memcpy(pv + sa, pb, sb); pv[sa + sb] = 0; return v; } Value String::concat(GC *gc, Value a, Value b) { StringBuilder sb; sb.append(b, true); return stringConcat(gc, a, sb.cstr(), sb.size); } Value String::findField(VM *vm, int op, void *data, Value *stack, int nCallArg) { if (op != CFunc::CFUNC_CALL) { return VNIL; } assert(nCallArg > 0); Value *p = stack, *end = p + nCallArg; Value v1 = *p++; if (IS_NIL(v1)) { if (p >= end) { return VNIL; } v1 = *p++; } if (p >= end) { return VNIL; } Value v2 = *p++; if (!IS_STRING(v1) || !IS_STRING(v2)) { return VNIL; } char *str1 = GET_CSTR(v1); char *str2 = GET_CSTR(v2); // unsigned len1 = len(v1); // unsigned len2 = len(v2); char *pos = strstr(str1, str2); return VAL_NUM(pos ? pos - str1 : -1); }
#ifndef MYENGINE_H #define MYENGINE_H #include "Engine.h" class MyEngine : Engine { public: //MyEngine(); ~MyEngine(); virtual void started(); private: }; #endif
#include <iostream> #include <fstream> #include <stdint.h> #include "fann.h" #include "DEdvs/config.h" void createLUT(const char* path_to_fann_net, uint16_t depth_lut[dedvs::kXtionDepthResolutionX] [dedvs::kXtionDepthResolutionY] [dedvs::kDepthLUTEntries]); int main(int argc, char *argv[]) { std::cout << "FANN/EDVS Lookup Table Creator" << std::endl; //// Command line arguments if(argc != 3) { std::cout << "Wrong Usage" << std::endl; std::cout << "nncalib_lookup_creator <path_to/calib.net> <path_to/dest_lut.bin>" << std::endl; return 0; } static uint16_t depth_lut[dedvs::kXtionDepthResolutionX] [dedvs::kXtionDepthResolutionY] [dedvs::kDepthLUTEntries]; createLUT(argv[1],depth_lut); std::cout << std::endl << "Writing file..."; std::fstream file(argv[2], std::ios::out | std::ios::binary); file.write((char*) &depth_lut[0][0][0], dedvs::kXtionDepthResolutionX * dedvs::kXtionDepthResolutionY * dedvs::kDepthLUTEntries * sizeof(uint16_t)); file.close(); std::cout << " Done!" << std::endl;; return 0; } void createLUT(const char* path_to_fann_net, uint16_t depth_lut[dedvs::kXtionDepthResolutionX] [dedvs::kXtionDepthResolutionY] [dedvs::kDepthLUTEntries]) { struct fann *ann = fann_create_from_file(path_to_fann_net); // FANN requires special types to work on fann_type *xyd_input = (fann_type *) malloc(3 * sizeof(fann_type)); fann_type *uv_output = (fann_type *) malloc(2 * sizeof(fann_type)); int u_idx, v_idx, d_idx; for(int x = 0; x < dedvs::kXtionDepthResolutionX; ++x) { for(int y = 0; y < dedvs::kXtionDepthResolutionY; ++y) { for(int d = dedvs::kMinDepth; d < dedvs::kMaxDepth; d += dedvs::kDepthLUTResolution) { //Setting up the input data xyd_input[0] = static_cast<float>(x) / static_cast<float>(dedvs::kXtionDepthResolutionX); xyd_input[1] = static_cast<float>(y) / static_cast<float>(dedvs::kXtionDepthResolutionY); xyd_input[2] = static_cast<float>(d) / static_cast<float>(dedvs::kMaxDepth); //Reading out the output data uv_output = fann_run(ann,xyd_input); u_idx = static_cast<int>(lround(uv_output[0])); v_idx = static_cast<int>(lround(uv_output[1])); // v_idx = static_cast<int>(lround(uv_output[0])); //TO USE OLD ANNs // u_idx = static_cast<int>(lround(uv_output[1])); //Values should be between [0,127] if(u_idx < 0) u_idx = 0; if(u_idx >= dedvs::kEdvsResolution_U) u_idx = dedvs::kEdvsResolution_U - 1; if(v_idx < 0) v_idx = 0; if(v_idx >= dedvs::kEdvsResolution_V) v_idx = dedvs::kEdvsResolution_V - 1; d_idx = lround((d-dedvs::kMinDepth)/static_cast<float>(dedvs::kDepthLUTResolution)); depth_lut[x][y][d_idx] = u_idx + dedvs::kEdvsResolution_U * v_idx; } } std::cout << 100.0 * x/static_cast<float>(dedvs::kXtionDepthResolutionX) << "%" << std::endl; } fann_destroy(ann); }
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*- * * Copyright (C) 1995-2002 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #ifdef XSLT_SUPPORT #include "modules/xslt/src/xslt_unsupported.h" #include "modules/xslt/src/xslt_compiler.h" /* virtual */ void XSLT_Unsupported::AddAttributeL (XSLT_StylesheetParserImpl *parser, XSLT_AttributeType type, const XMLCompleteNameN &name, const uni_char *value, unsigned value_length) { switch (type) { case XSLTA_EXTENSION_ELEMENT_PREFIXES: if (GetType () == XSLTE_UNSUPPORTED) { parser->SetStringL (extension_elements, name, value, value_length); break; } case XSLTA_NO_MORE_ATTRIBUTES: case XSLTA_OTHER: break; default: XSLT_Element::AddAttributeL (parser, type, name, value, value_length); } } /* virtual */ void XSLT_Unsupported::CompileL (XSLT_Compiler *compiler) { for (unsigned index = 0; index < children_count; ++index) if (children[index]->GetType () == XSLTE_FALLBACK) children[index]->CompileL(compiler); } #endif // XSLT_SUPPORT
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofSetBackgroundColor(50); jelly1.init(ofPoint(0,0,0), ofPoint(1,1,1)); gui.setup(); gui.add(rad1.setup("rad", PI, 0, 2*PI)); gui.add(rad2.setup("rad", 1.5*PI, 0, 2*PI)); } //-------------------------------------------------------------- void ofApp::update(){ jelly1.update(rad1, rad2); } //-------------------------------------------------------------- void ofApp::draw(){ cam.begin(); jelly1.draw(); cam.end(); gui.draw(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
/*! @file LogVol_CCHardCovering_Lid.hh @brief Defines mandatory user class LogVol_CCHardCovering_Lid. @date August, 2012 @author Flechas (D. C. Flechas dcflechasg@unal.edu.co) @version 1.9 In this header file, the 'physical' setup is defined: materials, geometries and positions. This class defines the experimental hall used in the toolkit. */ /* no-geant4 classes*/ #include "LogVol_CCHardCovering_Lid.hh" /* units and constants */ #include "G4UnitsTable.hh" #include "G4SystemOfUnits.hh" #include "G4PhysicalConstants.hh" /* geometric objects */ #include "G4Box.hh" #include "G4Tubs.hh" #include "G4Polycone.hh" #include "G4UnionSolid.hh" #include "G4SubtractionSolid.hh" /* logic and physical volume */ #include "G4LogicalVolume.hh" #include "G4PVPlacement.hh" /* geant4 materials */ #include "G4NistManager.hh" #include "G4Material.hh" /* visualization */ #include "G4VisAttributes.hh" LogVol_CCHardCovering_Lid:: LogVol_CCHardCovering_Lid(G4String fname): G4LogicalVolume(new G4Box(fname+"_Sol",65*cm/2.0,65*cm/2.0,50*cm/2.0),(G4NistManager::Instance())->FindOrBuildMaterial("G4_Al"),fname,0,0,0) { /* set variables */ SetName(fname); //material=(G4NistManager::Instance())->FindOrBuildMaterial("G4_Al"); Cyl_height = 19.0*cm; Cyl_radius = 22.5/2.0*cm; Box_height = 9.7*cm; Box_length = 27.25*cm; Box_width = 22.5*cm; Lid_thickness = 0.3*cm; /* Construct solid volume */ ConstructSolidVol_CCHardCovering_Lid(); /* Visualization */ G4VisAttributes* gray_vis = new G4VisAttributes(true,G4Colour(0.5,0.5,0.5)); gray_vis->SetForceWireframe(false); gray_vis->SetForceSolid(false); this->SetVisAttributes(gray_vis); } LogVol_CCHardCovering_Lid::~LogVol_CCHardCovering_Lid() {} void LogVol_CCHardCovering_Lid::ConstructSolidVol_CCHardCovering_Lid(void) { /// Outer part /// const G4int numZPlanes_Cyl = 2; G4double zPlane_Cyl[numZPlanes_Cyl] = {0.0*cm,Cyl_height}; G4double rInner_Cyl[numZPlanes_Cyl] = {0.0*cm,0.0*cm}; G4double rOuter_Cyl[numZPlanes_Cyl] = {Cyl_radius,Cyl_radius}; G4Polycone* Cyl_Outer = new G4Polycone(Name+"_CylOut_Sol",0.*rad,2*M_PI*rad,numZPlanes_Cyl, zPlane_Cyl,rInner_Cyl,rOuter_Cyl); G4Box* Box_Outer = new G4Box(Name+"_BoxOut_Sol",Box_width/2.0,Box_length/2.0,Box_height/2.0); G4UnionSolid* Lid_Outer = new G4UnionSolid(Name+"_LidOut_Sol", Cyl_Outer, Box_Outer,0, G4ThreeVector(0.,Box_length/2.0,Box_height/2.0)); /// Inner space //// const G4int numZPlanes_Cyl_In = 2; G4double zPlane_Cyl_In[numZPlanes_Cyl_In] = {0.0*cm,Cyl_height}; G4double rInner_Cyl_In[numZPlanes_Cyl_In] = {0.0*cm,0.0*cm}; G4double rOuter_Cyl_In[numZPlanes_Cyl_In] = {Cyl_radius-Lid_thickness, Cyl_radius-Lid_thickness}; G4Polycone* Cyl_Inner = new G4Polycone(Name+"_CylOut_Sol",0.*rad,2*M_PI*rad,numZPlanes_Cyl_In, zPlane_Cyl_In,rInner_Cyl_In,rOuter_Cyl_In); G4Box* Box_Inner = new G4Box(Name+"_BoxOut_Sol",(Box_width-2.0*Lid_thickness)/2.0, (Box_length-Lid_thickness)/2.0, (Box_height)/2.0); G4UnionSolid* Lid_Inner = new G4UnionSolid(Name+"_LidInn_Sol", Cyl_Inner, Box_Inner,0, G4ThreeVector(0., (Box_length-Lid_thickness)/2.0, Box_height/2.0)); CCHardCovering_Lid_solid = new G4SubtractionSolid(Name+"_Sol", Lid_Outer,Lid_Inner, 0,G4ThreeVector(0.,0.,-Lid_thickness)); /*** Main trick here: Set the new solid volume ***/ SetSolidVol_CCHardCovering_Lid(); } void LogVol_CCHardCovering_Lid::SetSolidVol_CCHardCovering_Lid(void) { /*** Main trick here: Set the new solid volume ***/ if(CCHardCovering_Lid_solid) this->SetSolid(CCHardCovering_Lid_solid); }
//////////////////////////////////////////////////////////////////////////////// // // (C) Andy Thomason 2012-2014 // // Modular Framework for OpenGLES2 rendering on multiple platforms. // namespace octet { /// Scene containing a box with octet. class example_shader : public app { // scene for drawing box ref<visual_scene> app_scene; ref<material> custom_mat; ref<param_uniform> num_spots; public: /// this is called when we construct the class before everything is initialised. example_shader(int argc, char **argv) : app(argc, argv) { } /// this is called once OpenGL is initialized void app_init() { app_scene = new visual_scene(); app_scene->create_default_camera_and_lights(); param_shader *shader = new param_shader("shaders/default.vs", "shaders/spots.fs"); custom_mat = new material(vec4(1, 1, 1, 1), shader); atom_t atom_num_spots = app_utils::get_atom("num_spots"); float val = 4; num_spots = custom_mat->add_uniform(&val, atom_num_spots, GL_FLOAT, 1, param::stage_fragment); mesh_box *box = new mesh_box(vec3(4)); scene_node *node = new scene_node(); app_scene->add_child(node); app_scene->add_mesh_instance(new mesh_instance(node, box, custom_mat)); } /// this is called to draw the world void draw_world(int x, int y, int w, int h) { int vx = 0, vy = 0; get_viewport_size(vx, vy); app_scene->begin_render(vx, vy); // change the number of spots dynamically float nf = (float)(get_frame_number()/33)+8; custom_mat->set_uniform(num_spots, &nf, sizeof(nf)); // update matrices. assume 30 fps. app_scene->update(1.0f/30); // draw the scene app_scene->render((float)vx / vy); // tumble the box (there is only one mesh instance) scene_node *node = app_scene->get_mesh_instance(0)->get_node(); node->rotate(1, vec3(1, 0, 0)); node->rotate(1, vec3(0, 1, 0)); } }; }
#include "ClientSocketEx.h" #include <stdlib.h> #include <memory.h> #include <iostream> #include <fcntl.h> //#include <stdio.h> #include <unistd.h> #include "Logger.h" #ifndef MSG_NOSIGNAL #define MSG_NOSIGNAL 0 #endif //每次读数据的最大长度, 注意:这里不是限制包的总长度,纯粹是为了分段读数据 #define MaxOnceRecv 1024 #define MaxOnceSend 1024 CClientSocketEx::CClientSocketEx() : CClientSocket() { } CClientSocketEx::CClientSocketEx(const std::string& host,const int port, const unsigned int nTimeOutMicroSend, const unsigned int nTimeOutMicroRecv) : CClientSocket(host,port,nTimeOutMicroSend,nTimeOutMicroRecv) { } CClientSocketEx::~CClientSocketEx() { } int CClientSocketEx::SendEx( OutputPacket* outPack, bool isEncrypt/*=true*/, bool bReConnect /*= true*/ ) { if(!IsValid()) ReConnect(); if(isEncrypt) outPack->EncryptBuffer(); int nSend = Send((char*)outPack->packet_buf(),outPack->packet_size()); if (nSend != outPack->packet_size() && bReConnect) { //重连,然后再发送一次 if(!ReConnect()) return -1; nSend = Send(outPack->packet_buf(),outPack->packet_size()); } return nSend; } int CClientSocketEx::RecvEx( InputPacket& pPackRecv, bool bReConnect /*= true*/ ) { if(!IsValid()) { if(bReConnect) ReConnect(); return -1; //重连后直接退出,因为服务器不会向新的scoket发消息的 } char* szBuffRet = NULL; int nRead = Recv(szBuffRet); if (NULL == szBuffRet) { if(bReConnect) ReConnect(); return -1; //重连后直接退出,因为服务器不会向新的scoket发消息的 } pPackRecv.Copy(szBuffRet,nRead); if (szBuffRet) delete[] szBuffRet; return nRead; }
//============================================================================ // Name : UnorderedMap.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include<unordered_map> using namespace std; int main() { // unordered_map<string,int> umap; // umap.insert(pair<string,int>("k1",12)); // umap.insert(pair<string,int>("k1",12)); // umap.insert(pair<string,int>("k3",12)); // umap.insert(pair<string,int>("k3",12)); // umap.insert(pair<string,int>("k1",12)); // umap.insert(pair<string,int>("k11",12)); // umap.insert(pair<string,int>("k12",12)); // umap.insert(pair<string,int>("k1",12)); // // for(pair<string,int> e:umap){ // // cout<<e.first<<" "<<e.second<<endl; // } //frequencies of words // unordered_map<string, int> umap; // string str; // int num; // // cin>>num; // // while (num>0) { // cin >> str; // std::unordered_map<string, int>::iterator it = umap.find(str); // if (it == umap.end()) { // umap.insert(pair<string, int>(str, 1)); // } else { // // umap[it->first] = it->second + 1; // } // num--; // } // // for (pair<string, int> e : umap) { // // cout << e.first << " " << e.second << endl; // } // return 0; }
//知识点:并查集 /* By:Luckyblock 题目要求: 给定一张图, 判断 这张图每个点是否都联通 并且图中不存在环 (即:为一棵树) 分析题意: 要求 图中不存在环 ,容易联想到Kruscal求生成树的过程 且 要求每个点均联通 , 容易想到 使用并查集来进行维护 算法实现: 使用并查集 每次读入时, 都判断两个点是否在同一个联通块中. 如果在同一联通块 , 那么将这两个点连接后, 图中就会出现一个环 , 则此图不合法 读入时记录图中点的编号 读图完毕后 ,枚举每一个点的祖先,判断它们是否在一个联通块中 以此来判断 所有的点是否联通 */ #include<cstdio> #include<vector> #include<ctype.h> const int MARX = 1e5+20; //============================================================= int pre[MARX],use[MARX]; //============================================================= inline int read() { int s=1, w=0; char ch=getchar(); for(; !isdigit(ch);ch=getchar()) if(ch=='-') s =-1; for(; isdigit(ch);ch=getchar()) w = w*10+ch-'0'; return s*w; } //并查集 路径压缩 int find(int fir) {return (pre[fir]==fir?fir:pre[fir]=find(pre[fir]));} void unico(int fir,int sec) { int r1=find(fir), r2=find(sec); if(r1 != r2) pre[r1] = pre[r2]; } //============================================================= signed main() { for(bool flag=0,flag1=0; ; flag1=0) { for(int i=1; i<MARX-10; i++) pre[i] = i,use[i]=0;//初始化 std::vector <int> node;//存 图中的点 for(int x,y; ;) { x = read(),y = read(); if(x == -1 && y == -1) {flag=1;break;}//文件读入完毕 if(x == 0 && y == 0) break; if(flag1) continue; if(find(x) != find(y)) unico(x,y);//连接后不会出现环 else flag1 = 1; if(!use[x]) node.push_back(x);//记录各点编号 if(!use[y]) node.push_back(y); use[x] = use[y] = 1; } if(flag) return 0; //枚举祖先, 判断是否在同一联通块中 for(int i=0,size=node.size(); i<size-1; i++) if(find(node[i])!=find(node[i+1])) {flag1=1;break;} //按需输出 if(flag1) putchar('0'),putchar('\n'); else putchar('1'),putchar('\n'); } }
#include "boundaryConditions.h" #include <math.h> double leftVal(double y) { return 0.0; } double rightVal(double y) { return 0.0; } double topVal(double x) { return 0.0; } double bottomDer(double x) { return 0.0; }
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifndef ATOMICTWEEN_H_ #define ATOMICTWEEN_H_ #include <cstddef> #include <memory> #include <iostream> #include "ease/IEquation.h" #include "accessor/IAccessor.h" #include "AbstractTween.h" #include "TweeningProperty.h" #include "ITargetable.h" namespace Tween { class IMultiTween; /** * Tween dla pojedynczej wartości (na przykład współrzędnej X w punkcie). */ class AtomicTween : public AbstractTween, public ITargetable { public: enum Type { TO, FROM }; AtomicTween (); virtual ~AtomicTween () {} void *getTarget () { return object; } void const *getTarget () const { return object; } void setTarget (void *o) { object = o; } IMultiTween *getParent () { return parent; } void setParent (IMultiTween *p) { parent = p; } AtomicTween *abs (unsigned int property, double value); AtomicTween *abs (std::string const &property, double value); AtomicTween *rel (unsigned int property, double value); AtomicTween *rel (std::string const &property, double value); Overwrite getOverwrite () const { return overwrite; } void setOverwrite (Overwrite o) { overwrite = o; } void addProperty (TweeningProperty *p) { properties.push_back (p); } void removeProperty (IAccessor *a); int getDurationMs () const { return durationMs; } void setDurationMs (int ms) { durationMs = ms; } void remove (void const *target, bool onlyActive); void remove (void const *target, TweeningProperty *property, bool onlyActive = false); protected: AtomicTween *property (IAccessor const *accessor, double value, bool abs); // Uruchamia się jeden raz na poczatku działania tweena (lub po repeat). void initEntry (bool reverse); void initExit (bool reverse); void delayEntry (bool reverse); void delayExit (bool reverse); void runEntry (bool reverse); void runExit (bool reverse); void finishedEntry (bool reverse); void finishedExit (bool reverse); void updateRun (int deltaMs, bool direction); bool checkEnd (bool direction); private: IEquation const *equation; int durationMs; void *object; TweeningPropertyList properties; Type type; Overwrite overwrite; IMultiTween *parent; friend AtomicTween *to (void *targetObject, unsigned int durationMs, Ease ease, ITargetable::Overwrite o = ITargetable::NONE); friend AtomicTween *from (void *targetObject, unsigned int durationMs, Ease ease, ITargetable::Overwrite o = ITargetable::NONE); friend class ParserImpl; }; /** * * @param targetObject * @param durationMs * @param ease * @return */ extern AtomicTween *to (void *targetObject, unsigned int durationMs, Ease ease = LINEAR_INOUT); extern AtomicTween *from (void *targetObject, unsigned int durationMs, Ease ease = LINEAR_INOUT); } # endif /* ATOMICTWEEN_H_ */
#include <iostream> #include <fstream> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <ncurses.h> #include <string> using namespace std; int n, sum, s[100][100]; void input() { scanf("%d", &n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { scanf("%d", &s[i][j]); } } } void solve() { for (int j = 0; j < n; j++) { sum = 0; for (int i = 0; i < n; i++) { sum += s[i][j]; } printf("%d\n", sum); } } int main() { freopen("trunghoc1b.inp", "r", stdin); input(); solve(); getchar(); return 0; }
/* * mysql_test.cpp * Copyright: 2018 Shanghai Yikun Electrical Engineering Co,Ltd */ //#include "yikun_common/mysql/db_helper.h" int main(int argc,char* argv[]) { // yikun_client_common::DbHelper slavedb("127.0.0.1","ir_master"); // if(slavedb.dbconnect()) // { // bool ret = slavedb.selectHostsFromRobotsList("sunjiayuan1"); // std::cout<<ret<<std::endl;; // slavedb.dbdisconnect(); // } return 0; }
#include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <unistd.h> #include <string> #include <sstream> #include <map> #include <iostream> #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/core/core.hpp" #include "hough.h" #define MAX_SLOPE 10 #define MIN_SLOPE 0.5 #define LEFT_BORDER 20 #define RIGHT_BORDER 20 #define TOP_BORDER 10 #define BOTTOM_BORDER 10 #define MIN_BAR_HEIGHT 10 #define MIN_BAR_WIDTH 30 // padding on top of each bar for other notes #define TOP_BAR_PADDING 10 #define SEGMENTS 4 #define CROPPED_BARS_PATH "./cropped_bars/bar" #define CROPPED_NOTES_PATH "./cropped_notes/note" extern FILE *stdin; extern FILE *stdout; extern FILE *stderr; std::stringstream out; std::string img_path; int threshold = 0; const char* CW_IMG_CROP = "crop"; const char* CW_IMG_ORIGINAL = "Result"; const char* CW_IMG_EDGE = "Canny Edge Detection"; const char* CW_ACCUMULATOR = "Accumulator"; // define types typedef std::pair<int, int> point; typedef std::pair<point, point> line; typedef std::pair<line, line> row; typedef bool(*pairCompare)(line, line); // Declerations void doTransform(std::string, int threshold); float findSlope(point first, point second); bool horizCompare(line firstLine, line secondLine); bool vertCompare(line firstLine, line secondLine); void findRows( std::vector<line> horizontal, std::vector<row>& rows, int imageSize ); void findColumns( std::vector<line> vertical, std::vector<row>& columns, int imageSize ); void findSpaces( std::vector<row>& ans, std::vector<line>& lines, bool vertical ); void findRowSpaces( std::vector<row>& ans, std::vector<line>& lines, bool vertical ); void removeBorders( std::vector<line>& ans, std::vector<line>& lines, bool vertical, int imageSize ); void drawLine( cv::Mat img_res, line currLine, cv::Scalar color=cv::Scalar(0, 0, 255) ); void printRows(std::vector<row>& rows); // Usage explanation void usage(char * s) { fprintf( stderr, "\n"); fprintf( stderr, "%s -s <source file> [-t <threshold>] - hough transform. build: %s-%s \n", s, __DATE__, __TIME__); fprintf( stderr, " s: path image file\n"); fprintf( stderr, " t: hough threshold\n"); fprintf( stderr, "\nexample: ./hough -s ./img/russell-crowe-robin-hood-arrow.jpg -t 195\n"); fprintf( stderr, "\n"); } int main(int argc, char** argv) { int c; while ( ((c = getopt( argc, argv, "s:t:?" ) ) ) != -1 ) { switch (c) { case 's': img_path = optarg; break; case 't': threshold = atoi(optarg); break; case '?': default: usage(argv[0]); return -1; } } if(img_path.empty()) { usage(argv[0]); return -1; } cv::namedWindow(CW_IMG_CROP, cv::WINDOW_AUTOSIZE); cv::namedWindow(CW_IMG_ORIGINAL, cv::WINDOW_AUTOSIZE); cv::namedWindow(CW_IMG_EDGE, cv::WINDOW_AUTOSIZE); cv::namedWindow(CW_ACCUMULATOR, cv::WINDOW_AUTOSIZE); cvMoveWindow(CW_IMG_CROP, 100, 100); cvMoveWindow(CW_IMG_ORIGINAL, 10, 10); cvMoveWindow(CW_IMG_EDGE, 680, 10); cvMoveWindow(CW_ACCUMULATOR, 1350, 10); doTransform(img_path, threshold); return 0; } void doTransform(std::string file_path, int threshold) { cv::Mat img_edge; cv::Mat img_blur; cv::Mat img_crop; cv::Mat img_ori = cv::imread( file_path, 1 ); cv::blur( img_ori, img_blur, cv::Size(5,5) ); cv::Canny(img_blur, img_edge, 100, 150, 3); int w = img_edge.cols; int h = img_edge.rows; //Transform Hough hough; hough.Transform(img_edge.data, w, h); if(threshold == 0) threshold = w>h?w/4:h/4; while(1) { cv::Mat img_res = img_ori.clone(); // Region of interest cv::Rect roi; float rectTopLeftX, rectTopLeftY, rectBottomLeftX, rectBottomLeftY; // line vectors std::vector<line> horizontal; std::vector<line> vertical; std::vector<row> rows; std::vector<row> columns; // Iterators std::vector<line>::iterator lineIt; std::vector<row>::iterator rowIt; std::vector<row>::iterator rowIt2; //Search the accumulator std::vector<line> lines = hough.GetLines(threshold); //Draw the results for(lineIt=lines.begin();lineIt!=lines.end();lineIt++) { // check if the line is horizontal or vertical // if not, dismiss it float lineSlope = findSlope(lineIt->first, lineIt->second); // add to our vector of horizontal lines if (lineSlope > MAX_SLOPE) { horizontal.push_back(std::make_pair(lineIt->first, lineIt->second)); } else if (lineSlope < MIN_SLOPE) { vertical.push_back(std::make_pair(lineIt->first, lineIt->second)); } } // now we have all of the horizontal lines. // find the ones clustered together and declare them as a row findRows(horizontal, rows, img_res.rows); findColumns(vertical, columns, img_res.cols); // now crop based on each row int noteIndex = 0; for(rowIt=rows.begin();rowIt!=rows.end();rowIt++) { for(rowIt2=columns.begin();rowIt2!=columns.end();rowIt2++) { // each iteration gives us a bar! rectTopLeftX = rowIt2->first.first.first; rectTopLeftY = rowIt->first.first.second; rectBottomLeftX = rowIt2->second.first.first; rectBottomLeftY = rowIt->second.first.second; int addedSegment = (rowIt2 == columns.begin()) ? 1 : 0; roi.x = rectTopLeftX; roi.y = rectTopLeftY - TOP_BAR_PADDING; roi.width = (rectBottomLeftX - rectTopLeftX) / (SEGMENTS + addedSegment); roi.height = rectBottomLeftY - rectTopLeftY + 2*TOP_BAR_PADDING; // normalizations roi.y = (roi.y < 0) ? 0 : roi.y; roi.height = (roi.y + roi.height > img_res.rows) ? img_res.rows - roi.y : roi.height; /* Crop the original image to the defined ROI */ // save image if(roi.area() > 0) { // write all notes for(int i = 0; i < (addedSegment + SEGMENTS); i++) { if(!(i==0 && addedSegment)) { img_crop = img_res(roi); cv::resize(img_crop, img_crop, cv::Size(30, 50), 0, 0, cv::INTER_CUBIC); out << noteIndex; std::string path = CROPPED_NOTES_PATH + out.str() + ".jpg"; cv::imwrite(path, img_crop); out.str(std::string()); noteIndex++; } // move on to the next note roi.x += roi.width; } } } } //Draw the results: // Visualize all lines for(lineIt=lines.begin();lineIt!=lines.end();lineIt++) { // check if the line is horizontal or vertical // if not, dismiss it float lineSlope = findSlope(lineIt->first, lineIt->second); if (lineSlope > MAX_SLOPE || lineSlope < MIN_SLOPE) { // Visualize cv::line( img_res, cv::Point(lineIt->first.first, lineIt->first.second), cv::Point(lineIt->second.first, lineIt->second.second), cv::Scalar( 0, 0, 255), 1, 8 ); } } // Visualize rows cv::Scalar currColor; cv::Scalar color1 = cv::Scalar(0,0,255); cv::Scalar color2 = cv::Scalar(0,255,0); bool parity = false; for(rowIt=rows.begin();rowIt!=rows.end();rowIt++) { currColor = color2; if (parity) currColor = color1; parity = !parity; //draw this row drawLine(img_res, rowIt->first, currColor); drawLine(img_res, rowIt->second, currColor); } // Visualize columns for(rowIt=columns.begin();rowIt!=columns.end();rowIt++) { drawLine(img_res, rowIt->first); drawLine(img_res, rowIt->second); } //Visualize all int aw, ah, maxa; aw = ah = maxa = 0; const unsigned int* accu = hough.GetAccu(&aw, &ah); for(int p=0;p<(ah*aw);p++) { if((int)accu[p] > maxa) maxa = accu[p]; } double contrast = 1.0; double coef = 255.0 / (double)maxa * contrast; cv::Mat img_accu(ah, aw, CV_8UC3); for(int p=0;p<(ah*aw);p++) { unsigned char c = (double)accu[p] * coef < 255.0 ? (double)accu[p] * coef : 255.0; img_accu.data[(p*3)+0] = 255; img_accu.data[(p*3)+1] = 255-c; img_accu.data[(p*3)+2] = 255-c; } cv::imshow(CW_IMG_ORIGINAL, img_res); cv::imshow(CW_IMG_EDGE, img_edge); cv::imshow(CW_ACCUMULATOR, img_accu); char c = cv::waitKey(360000); if(c == '+') threshold += 5; if(c == '-') threshold -= 5; if(c == 27) break; } } void drawLine(cv::Mat img_res, line currLine, cv::Scalar color1) { cv::line( img_res, cv::Point(currLine.first.first, currLine.first.second), cv::Point(currLine.second.first, currLine.second.second), color1, 5, 8 ); } // Utility functions void findSpaces( std::vector<row>& ans, std::vector<line>& lines, bool vertical ) { // find all the spaces (don't add small ones) std::vector<line>::iterator lineIt; int currDist; int minLength = (vertical) ? MIN_BAR_WIDTH : MIN_BAR_HEIGHT; if (!lines.size()){ return; } for(lineIt=lines.begin();lineIt < lines.end()-1;lineIt++) { // start of row if (vertical) { currDist = (lineIt+1)->first.first - lineIt->first.first; } else { currDist = (lineIt+1)->first.second - lineIt->first.second; } if (currDist > minLength) { ans.push_back(make_pair(*lineIt, *(lineIt + 1))); } } } // function in beta, slightly different approach from above void findRowSpaces( std::vector<row>& ans, std::vector<line>& lines, bool vertical ) { // find all the spaces (don't add small ones) std::vector<line>::iterator lineIt; line firstLine; int currDist; if (!lines.size()) { return; } firstLine = *lines.begin(); for(lineIt=lines.begin();lineIt < lines.end()-2;lineIt++) { currDist = (lineIt+1)->first.second - lineIt->first.second; if (currDist > ((vertical) ? MIN_BAR_WIDTH : MIN_BAR_HEIGHT)) { ans.push_back(make_pair(firstLine, *(lineIt+1))); firstLine = *(lineIt + 2); lineIt += 1; } } } void removeBorders( std::vector<line>& ans, std::vector<line>& lines, bool vertical, int imageSize ) { // remove all of the bordering lines std::vector<line>::iterator lineIt; for(lineIt=lines.begin();lineIt!=lines.end();lineIt++) { // start of row if (vertical) { if ( lineIt->first.first > LEFT_BORDER && lineIt->first.first < (imageSize - RIGHT_BORDER) ){ // push 2 points into the new vector ans.push_back(*lineIt); } } else { if ( lineIt->first.second > TOP_BORDER && lineIt->first.second < (imageSize - BOTTOM_BORDER) ){ // push 2 points into the new vector ans.push_back(*lineIt); } } } } void findRows( std::vector<line> horizontal, std::vector<row>& rows, int imageSize ) { // spaces vector std::vector<row> spaces; std::vector<line> nonBorders; row currRow; // iterator std::vector<row>::iterator rowIt; std::sort(horizontal.begin(), horizontal.end(), horizCompare); removeBorders( nonBorders, horizontal, false, imageSize ); findRowSpaces( spaces, nonBorders, false ); if(!spaces.size()) { return; } rows = spaces; } void findColumns( std::vector<line> vertical, std::vector<row>& columns, int imageSize ) { // spaces vector std::vector<row> spaces; std::vector<line> nonBorders; row currRow; // iterator std::vector<line>::iterator lineIt; std::vector<row>::iterator rowIt; std::sort(vertical.begin(), vertical.end(), vertCompare); removeBorders( nonBorders, vertical, true, imageSize ); findSpaces( spaces, nonBorders, true ); // no shifting, the ones we want are spaced out. // however remove whitespace from beginning and end columns = spaces; } void printRows(std::vector<row>& rows) { std::vector<row>::iterator rowIt; int firstLineX, secondLineX; // print out distances for(rowIt=rows.begin();rowIt!=rows.end();rowIt++) { firstLineX = rowIt->first.first.second; secondLineX = rowIt->second.first.second; std::cout << "|" << firstLineX << "\t" << secondLineX << "|" << std::endl; } } // finds the slope of a line float findSlope(point first, point second) { return abs( (float)(first.first - second.first) / (float)(first.second - second.second) ); } // Compares 2 horizontal lines bool horizCompare(line firstLine, line secondLine) { return firstLine.first.second < secondLine.first.second; } // Compares 2 vertical lines bool vertCompare(line firstLine, line secondLine) { return firstLine.first.first < secondLine.first.first; }
#include <stdio.h> #include <time.h> #include <opencv2/opencv.hpp> #include <iostream> #include "opencv2/highgui/highgui.hpp" #include "opencv2/core/core.hpp" #include "opencv2/opencv.hpp" #include <opencv2\imgproc\types_c.h> #include "bits.h" #include <string> #include <fstream> using namespace std; bool decode(string filename,string& raw_data,int& code_count); void ConvertIntoPoint(int img[64][64][2], int height, int width); void ConvertBatToText();
/** * @file CannyDetector_Demo.cpp * @brief Sample code showing how to detect edges using the Canny Detector * @author OpenCV team */ #include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" using namespace cv; //![variables] Mat src, src_gray; Mat dst, detected_edges; int edgeThresh = 1; int lowThreshold; int const max_lowThreshold = 100; int ratio = 3; int kernel_size = 3; const char* window_name = "Edge Map"; //![variables] /** * @function CannyThreshold * @brief Trackbar callback - Canny thresholds input with a ratio 1:3 */ static void CannyThreshold(int, void*) { //![reduce_noise] /// Reduce noise with a kernel 3x3 blur( src_gray, detected_edges, Size(3,3) ); //![reduce_noise] //![canny] /// Canny detector Canny( detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size ); //![canny] /// Using Canny's output as a mask, we display our result //![fill] dst = Scalar::all(0); //![fill] //![copyto] src.copyTo( dst, detected_edges); //![copyto] //![display] imshow( window_name, dst ); //![display] } /** * @function main */ int main( int, char** argv ) { //![load] src = imread( argv[1], IMREAD_COLOR ); // Load an image if( src.empty() ) { return -1; } //![load] //![create_mat] /// Create a matrix of the same type and size as src (for dst) dst.create( src.size(), src.type() ); //![create_mat] //![convert_to_gray] cvtColor( src, src_gray, COLOR_BGR2GRAY ); //![convert_to_gray] //![create_window] namedWindow( window_name, WINDOW_AUTOSIZE ); //![create_window] //![create_trackbar] /// Create a Trackbar for user to enter threshold createTrackbar( "Min Threshold:", window_name, &lowThreshold, max_lowThreshold, CannyThreshold ); //![create_trackbar] /// Show the image CannyThreshold(0, 0); /// Wait until user exit program by pressing a key waitKey(0); return 0; }
// // CRequestFactory.h // server // // Created by Sergey Proforov on 17.05.16. // Copyright (c) 2016 Proforov Inc. All rights reserved. // #ifndef __server__CRequestFactory__ #define __server__CRequestFactory__ #include "Poco/Net/HTTPRequestHandlerFactory.h" #include "Poco/Net/HTTPRequestHandler.h" #include "Poco/Net/HTTPServerRequest.h" #include "Poco/Net/HTTPServerResponse.h" #include "Poco/URI.h" using namespace Poco::Net; //класс обработки входящих запросов class CRequestHandlerFactory : public HTTPRequestHandlerFactory{ public: virtual HTTPRequestHandler* createRequestHandler(const HTTPServerRequest &); }; //класс обработки запроса на разложение на множители class CExpandRequestHandler : public HTTPRequestHandler{ virtual void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response); }; //обработка неизвестного запроса class CNotFoundRequestHandler : public HTTPRequestHandler{ virtual void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response); }; #endif
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Pawn.h" #include "ShooterController.generated.h" // Hit and shot missed delegate declarations DECLARE_DELEGATE_OneParam(FOnTargetHit, class ATarget*); DECLARE_DELEGATE(FOnShotMissed); UCLASS() class SHOOTINGGALLERY_API AShooterController : public APawn { GENERATED_BODY() public: // Sets default values for this pawn's properties AShooterController(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; // Called to bind functionality to input virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; // Hit and shot missed delegates FOnTargetHit OnTargetHit; FOnShotMissed OnShotMissed; private: // Root scene component class USceneComponent* SceneRootComponent; // Spring arm component to operate camera UPROPERTY(EditDefaultsOnly, Category=Camera, meta = (AllowPrivateAccess = "true")) class USpringArmComponent* SpringArm; // The main game camera UPROPERTY(EditDefaultsOnly, Category=Camera, meta = (AllowPrivateAccess = "true")) class UCameraComponent* Camera; // Shot hit sound cue UPROPERTY(EditDefaultsOnly, Category="Sounds", meta = (AllowPrivateAccess = "true")) class USoundCue* ShotHitSoundCue; // Shot missed sound cue UPROPERTY(EditDefaultsOnly, Category="Sounds", meta = (AllowPrivateAccess = "true")) class USoundCue* ShotMissedSoundCue; // Particles to spawn on line trace blocking hit UPROPERTY(EditDefaultsOnly, Category="Particles", meta = (AllowPrivateAccess = "true")) class UParticleSystem* ImpactParticles; // Target controller reference class ATargetController* TargetController; private: // Input bound function to look up and down void LookUp(float value); // Input bound function to look right and left void LookRight(float value); // Input bound function to fire bb gun void Fire(); };
#include <iostream> using namespace std; int main (int argc, char *argv []) { cout << "hallo"; cout << "world"; cout << "\n"; cout << "cs 101\n"; cout << "batch of 2010\n"; // this is a comment. // observe the formatting in the output and trace it in this source file }
#pragma once #include "Module.h" #include "p2List.h" #include "ModulePhysics.h" struct Flipper{ b2Body* Placement; b2Body* ForceShape; b2RevoluteJoint* Flipper_joint; }; class Colliders : public Module { public: Colliders(Application* app, bool start_enabled=true); ~Colliders(); bool Start(); void OnCollision(PhysBody* bodyA, PhysBody* bodyB); update_status Update(); public: uint Flipper_FX; PhysBody* Spring; b2RevoluteJoint* flipper_joint; void CreateFlipper(Flipper &flipers, int x, int y, int width, int height, int radius, int angle,int low_Angle, int max_Angle); bool Right_flippers_Active; bool Left_flippers_Active; Flipper Left_Flipper; Flipper Right_Flipper; Flipper MidLeft_Flipper; Flipper MidRight_Flipper; Flipper TopLeft_Flipper; Flipper TopRight_Flipper; float flipper_speed = 3.0f * b2_pi; //2PI radians/s float flipper_Speed_Right = -3.0f * b2_pi; //2PI radians/s float flipper_speed_back = -5.0f; float flipper_speed_back_right = 5.0f; PhysBody* orange; PhysBody* blue; PhysBody* green; PhysBody* yellow; PhysBody* pink; PhysBody* red; PhysBody* boy; PhysBody* girl; PhysBody* green_square_mid; PhysBody* green_square_top; PhysBody* multiball; PhysBody* left; PhysBody* right; p2List<PhysBody*> circles; PhysBody* last_collidedA; PhysBody* last_collidedB; PhysBody* ground; bool spawn_multiball; //Debug purposes mouse position int x; int y; };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Manuela Hutter (manuelah) */ #ifndef ST_WEBSERVER_MANAGER_H #define ST_WEBSERVER_MANAGER_H #include "adjunct/quick/managers/WebServerManager.h" #include "adjunct/quick/managers/OperaAccountManager.h" #include "adjunct/quick/managers/DesktopGadgetManager.h" #include "adjunct/quick/hotlist/HotlistManager.h" #include "modules/opera_auth/opera_auth_myopera.h" #include "adjunct/quick/hotlist/HotlistGenericModel.h" /*********************************************************************************** ** @class FakeFeatureControllerListener ** @brief ************************************************************************************/ class FakeFeatureControllerListener : public FeatureControllerListener, public OpTimerListener { public: enum PassingCriteria { None, FeatureEnabled, FeatureSettingsChanged }; FakeFeatureControllerListener() : m_passing_criteria(None) { m_timer.SetTimerListener(this); } virtual void OnFeatureEnablingSucceeded() { if (m_passing_criteria == FeatureEnabled) { ST_passed(); } else { ST_failed("Unexpected OnFeatureEnablingSucceeded"); } m_timer.Stop(); } virtual void OnFeatureSettingsChangeSucceeded() { m_timer.Stop(); if (m_passing_criteria == FeatureSettingsChanged) { ST_passed(); } else { ST_failed("Unexpected OnFeatureSettingsChangeSucceeded"); } } //=== helper functions === void SetPassingCriteria(PassingCriteria passing_criteria, UINT32 time_out) { m_passing_criteria = passing_criteria; m_timer.Start(time_out); } // OpTimerListener virtual void OnTimeOut(OpTimer* timer) { if (timer == &m_timer) { ST_failed("Timed out"); } } private: PassingCriteria m_passing_criteria; OpTimer m_timer; }; /*********************************************************************************** ** @class FakeWebServerConnector ** @brief ************************************************************************************/ class FakeWebServerConnector : public WebServerConnector { #ifdef WEBSERVER_RENDEZVOUS_SUPPORT virtual OP_STATUS Start(WebserverListeningMode mode, const char *shared_secret = NULL) { return OpStatus::OK; } // todo: stub #else virtual OP_STATUS Start(WebserverListeningMode mode) { return OpStatus::OK; } // todo: stub #endif virtual OP_STATUS Stop(WebserverStatus status = WEBSERVER_OK) { return OpStatus::OK; } // todo: stub virtual OP_STATUS AddWebserverListener(WebserverEventListener *listener) { return OpStatus::OK; } // todo: stub virtual void RemoveWebserverListener(WebserverEventListener *listener) {} // todo: stub #ifdef WEB_UPLOAD_SERVICE_LIST virtual OP_STATUS StartServiceDiscovery(const OpStringC &sentral_server_uri, const OpStringC8 &session_token) { return OpStatus::OK; } // todo: stub virtual void StopServiceDiscovery() {} // todo: stub #endif //WEB_UPLOAD_SERVICE_LIST #ifdef TRANSFERS_TYPE virtual TRANSFERS_TYPE GetBytesUploaded() { return 0; } // todo: stub virtual TRANSFERS_TYPE GetBytesDownloaded() { return 0; } // todo: stub #endif virtual UINT32 GetLastUsersCount(UINT32 seconds) { return 0; } // todo: stub }; /*********************************************************************************** ** @class FakeWebServerPrefsConnector ** @brief ************************************************************************************/ class FakeWebServerPrefsConnector : public WebServerPrefsConnector { public: FakeWebServerPrefsConnector() : WebServerPrefsConnector(), m_device_name(), m_empty_str(), m_webserver_enabled(FALSE), m_use_opera_account(TRUE) {} FakeWebServerPrefsConnector(const OpStringC & device_name, BOOL webserver_enabled, BOOL use_opera_account) : WebServerPrefsConnector(), m_device_name(), m_empty_str(), m_webserver_enabled(webserver_enabled), m_use_opera_account(use_opera_account) {} virtual BOOL ResetStringL(PrefsCollectionWebserver::stringpref which) { return TRUE; } // todo: stub virtual void GetStringPrefL(PrefsCollectionWebserver::stringpref which, OpString &result) const { switch(which) { case PrefsCollectionWebserver::WebserverDevice: { result.Set(m_device_name.CStr()); break; } default: result.Empty(); } } virtual const OpStringC GetStringPref(PrefsCollectionWebserver::stringpref which) const { switch(which) { case PrefsCollectionWebserver::WebserverDevice: { return m_device_name; break; } default: return m_empty_str; } } virtual OP_STATUS WriteStringL(PrefsCollectionWebserver::stringpref which, const OpStringC &value) { switch(which) { case PrefsCollectionWebserver::WebserverDevice: { return m_device_name.Set(value.CStr()); } default: return OpStatus::ERR; } } virtual int GetIntegerPref(PrefsCollectionWebserver::integerpref which) const { switch(which) { case PrefsCollectionWebserver::WebserverEnable: { return m_webserver_enabled; } // FIXME: tkupczyk - merging Extensions Phase 2 case PrefsCollectionWebserver::UseOperaAccount: { return m_use_opera_account; } default: return 0; } } virtual OP_STATUS WriteIntegerL(PrefsCollectionWebserver::integerpref which, int value) { return OpStatus::OK; } // todo: stub virtual void CommitL() {} // todo: stub private: OpString m_device_name; OpString m_empty_str; BOOL m_webserver_enabled; BOOL m_use_opera_account; }; /*********************************************************************************** ** @class FakeWebServerUIConnector ** @brief ************************************************************************************/ class FakeWebServerUIConnector : public WebServerUIConnector { public: FakeWebServerUIConnector() : m_wants_takeover(TRUE), m_wants_reconnect(TRUE) {} // blocking if webserver_enabled != NULL virtual OP_STATUS ShowSetupWizard(WebServerManager * manager, BOOL * webserver_enabled, const WebServerSettingsContext & settings_context, OperaAccountController * account_controller, OperaAccountContext* account_context) { // TODO: stub return OpStatus::OK; } virtual OP_STATUS ShowSettingsDialog(WebServerManager * manager, const WebServerSettingsContext & settings_context, OperaAccountController * account_controller, OperaAccountContext* account_context) { // TODO: stub return OpStatus::OK; } virtual OP_STATUS ShowLoginDialog(WebServerManager * manager, const WebServerSettingsContext & settings_context, OperaAccountController * account_controller, OperaAccountContext* account_context, BOOL * logged_in) { // TODO: stub return OpStatus::OK; } virtual OP_STATUS ShowStatus(WebServerManager * manager, OperaAccountManager::OAM_Status status) { // TODO: stub return OpStatus::OK; } virtual BOOL UserWantsFeatureEnabling(DesktopWindow * parent_window = NULL) { return m_wants_enabling; } virtual BOOL UserWantsInvalidUsernamesChange(OperaAccountContext * account_context, DesktopWindow * parent_window = NULL) { return m_wants_username_change; } virtual BOOL UserWantsDeviceTakeover(const OpStringC & device_name, DesktopWindow * parent_window = NULL) { return m_wants_takeover; } virtual BOOL UserWantsReconnectAfterTakeover(DesktopWindow * parent_window = NULL) { return m_wants_reconnect; } virtual void OnWebServerIsOutdated(DesktopWindow * parent_window = NULL) { } virtual OP_STATUS HandleErrorInDialog(OperaAuthError error) { return OpStatus::OK; } virtual void LogError(WebserverStatus status) { /* stub */ } virtual void LogError(UploadServiceStatus status) { /* stub */ } //=== helper functions ============== void SetWantsEnabling(BOOL enabling) { m_wants_enabling = enabling; } void SetWantsUsernameChange(BOOL change) { m_wants_username_change = change; } void SetWantsTakeover(BOOL takeover) { m_wants_takeover = takeover; } void SetWantsReconnect(BOOL reconnect) { m_wants_reconnect = reconnect; } private: BOOL m_wants_enabling; BOOL m_wants_username_change; BOOL m_wants_takeover; BOOL m_wants_reconnect; }; /*********************************************************************************** ** @class FakeOperaAccountManager ** @brief ************************************************************************************/ class FakeOperaAccountManager : public OperaAccountManager { public: virtual void SetLoggedIn(BOOL logged_in) { m_account_context.SetLoggedIn(TRUE); } virtual BOOL GetLoggedIn() { return m_account_context.IsLoggedIn(); } virtual void StopServices() {} // todo: stub virtual OperaAccountContext* GetAccountContext() { return &m_account_context; } virtual void SetUsernameAndPassword(const uni_char *username, const uni_char *password) { m_account_context.SetUsername(username); m_account_context.SetPassword(password); } virtual const uni_char* GetUsername() { return m_account_context.GetUsername().CStr(); } virtual const uni_char* GetPassword() { return m_account_context.GetPassword().CStr(); } virtual const char* GetToken() { return "token"; } // todo: stub virtual void GetInstallID(OpString &install_id) { install_id.Set("install_id"); } // todo: stub virtual OP_STATUS Authenticate(const OpStringC& username, const OpStringC& password, const OpStringC& device_name, const OpStringC& install_id, BOOL force = FALSE) { if (install_id.HasContent() && device_name.HasContent()) { if (!force && m_current_device.HasContent()) { BroadcastCreateDeviceEvent(AUTH_ACCOUNT_CREATE_DEVICE_EXISTS, m_shared_secret, m_message); } else { SetCurrentDevice(device_name); m_shared_secret.Set("secret"); BroadcastCreateDeviceEvent(AUTH_OK, m_shared_secret, m_message); } } else { BroadcastAuthEvent(AUTH_OK, m_shared_secret); } return OpStatus::OK; } virtual OP_STATUS ReleaseDevice(const OpStringC& username, const OpStringC& password, const OpStringC& devicename) { if (m_current_device.Compare(devicename) == 0) { m_current_device.Empty(); BroadcastReleaseDeviceEvent(AUTH_OK); } else { BroadcastCreateDeviceEvent(AUTH_ACCOUNT_AUTH_INVALID_KEY, m_shared_secret, m_message); } return OpStatus::OK; } virtual void LogError(INT32 error_code, const OpStringC& context, const OpStringC& message) {} // todo: stub // helper OP_STATUS SetCurrentDevice(const OpStringC & current_device) { return m_current_device.Set(current_device.CStr()); } private: OperaAccountContext m_account_context; OpString m_shared_secret; OpString m_message; OpString m_current_device; }; /*********************************************************************************** ** @class FakeDesktopGadgetManager ** @brief ************************************************************************************/ class FakeDesktopGadgetManager : public DesktopGadgetManager { public: virtual INT32 GetRunningServicesCount() { return 0; } // todo: stub virtual OP_STATUS OpenRootService(BOOL open_home_page) { return OpStatus::OK; } // todo: stub virtual void CloseRootServiceWindow(BOOL immediately = FALSE, BOOL user_initiated = FALSE, BOOL force = TRUE) {} // todo: stub virtual BOOL IsGadgetInstalled(const OpStringC &service_path) { return FALSE; } // todo: stub }; /*********************************************************************************** ** @class FakeHotlistManager ** @brief ************************************************************************************/ class FakeHotlistManager : public HotlistManager { public: FakeHotlistManager() : m_model(HotlistModel::UniteServicesRoot, TRUE) {} virtual HotlistGenericModel* GetUniteServicesModel() { return &m_model; } #ifdef WEBSERVER_SUPPORT virtual BOOL NewUniteService(const OpStringC& address, const OpStringC& orig_url, INT32* got_id, BOOL clean_uninstall, BOOL launch_after_install, const OpStringC& force_widget_name, const OpStringC& force_service_name, const OpStringC& shared_path) { OP_STATUS status; HotlistModelItem* item = m_model.AddItem(OpTreeModelItem::UNITE_SERVICE_TYPE, status, FALSE); if (OpStatus::IsError(status)) { return FALSE; } item->SetName(force_widget_name.CStr()); // todo: stub item->SetUrl(orig_url.CStr()); return TRUE; } #endif //WEBSERVER_SUPPORT HotlistModelItem * GetItemByID( INT32 id ) { return m_model.GetItemByID(id); } private: HotlistGenericModel m_model; }; /////////////////////////////////////////////////////////////////////////////////////////////////// class ST_WebServerManager : public WebServerManager { public: virtual OP_STATUS Init(OperaAccountManager * opera_account_manager, DesktopGadgetManager * desktop_gadget_manager, HotlistManager * hotlist_manager) { // deleted by WebServerManager SetWebServerConnector(OP_NEW(FakeWebServerConnector, ())); SetWebServerPrefsConnector(OP_NEW(FakeWebServerPrefsConnector, ())); SetWebServerUIConnector(OP_NEW(FakeWebServerUIConnector, ())); return WebServerManager::Init(opera_account_manager, desktop_gadget_manager, hotlist_manager); } DesktopGadgetManager * GetDesktopGadgetManager() { return m_desktop_gadget_manager; } OperaAccountManager * GetOperaAccountManager() { return m_opera_account_manager; } HotlistManager * GetHotlistManager() { return m_hotlist_manager; } }; #endif // ST_WEBSERVER_MANAGER_H
#include <cstdio> #include <iostream> #include <vector> #include <string> #include <stack> #include <unordered_map> #include <unordered_set> #include <queue> #define INT_MAX 0x7fffffff #define INT_MIN 0x80000000 using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x) ,left(NULL), right(NULL) {} }; TreeNode *helper(vector<int> &inorder, vector<int> &postorder, int istart, int iend, int pstart, int pend){ if(istart > iend || pstart > pend) return NULL; int pivot = iend; for(int i=iend;i>=istart;i--){ if(inorder[i] == postorder[pend]) pivot = i; } TreeNode *p = new TreeNode(postorder[pend]); p->left = helper(inorder,postorder,istart, pivot-1,pstart,pstart+pivot-istart-1); p->right = helper(inorder,postorder,pivot+1,iend,pstart+pivot-istart,pend-1); return p; } TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder){ if(postorder.size()==0 || inorder.size()==0) return NULL; TreeNode *res = helper(inorder,postorder,0,inorder.size()-1,0,postorder.size()-1); return res; } int main(){ }
/* -*- 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 ** */ #ifndef PKCS11_PUBKEY_H #define PKCS11_PUBKEY_H #if defined _NATIVE_SSL_SUPPORT_ && defined _SSL_USE_PKCS11_ #include "modules/libssl/external/p11/p11_man.h" class PKCS11_PublicKeyCipher : public SSL_PublicKeyCipher { private: OpSmartPointerNoDelete<PKCS_11_Manager> master; OpSmartPointerNoDelete<PKCS_11_Token> token; CK_FUNCTION_LIST_PTR functions; CK_SLOT_ID slot_id; CK_SESSION_HANDLE session; BOOL use_privatekey; uint32 templen,temppos; SSL_varvector16 tempbuffer; SSL_BulkCipherType ciphertype; private: PKCS11_PublicKeyCipher &operator =(const PKCS11_PublicKeyCipher &); //not implemented. defined to avoid default PKCS11_PublicKeyCipher(const PKCS11_PublicKeyCipher &); //not implemented. defined to avoid default public: PKCS11_PublicKeyCipher(PKCS_11_Manager *mstr, PKCS_11_Token *tokn, CK_FUNCTION_LIST_PTR func, CK_SLOT_ID slot, SSL_BulkCipherType ctyp); PKCS11_PublicKeyCipher(const PKCS11_PublicKeyCipher *); virtual ~PKCS11_PublicKeyCipher(); virtual SSL_CipherType Type() const; virtual SSL_BulkCipherType CipherID() const; SSL_BulkCipherType GetCipherType() const; virtual void SetUsePrivate(BOOL); virtual BOOL UsingPrivate() const; virtual void Login(SSL_secure_varvector32 &password); virtual BOOL Need_Login(); virtual BOOL Need_PIN(); virtual uint16 InputBlockSize() const; virtual uint16 OutputBlockSize() const; virtual void InitEncrypt(); void EncryptStep(const byte *source,uint32 len,byte *target, uint32 &len1,uint32 bufferlen); virtual byte *Encrypt(const byte *source,uint32 len,byte *target, uint32 &,uint32 bufferlen); virtual byte *FinishEncrypt(byte *target, uint32 &,uint32 bufferlen); virtual void InitDecrypt(); void DecryptStep(const byte *source,uint32 len,byte *target, uint32 &len1,uint32 bufferlen); virtual byte *Decrypt(const byte *source,uint32 len,byte *target, uint32 &,uint32 bufferlen); virtual byte *FinishDecrypt(byte *target, uint32 &,uint32 bufferlen); virtual BOOL Verify(const byte *reference,uint32 len, const byte *signature, uint32); virtual uint32 KeyBitsLength() const; virtual void LoadPublicKey(uint16, const SSL_varvector16 &); virtual uint16 PublicSize(uint16) const; #ifdef SSL_PUBKEY_DETAILS virtual uint16 PublicCount() const; virtual uint16 GeneratedPublicCount() const; virtual uint16 PrivateCount() const; virtual uint16 GeneratedPrivateCount() const; virtual uint16 PrivateSize(uint16) const; #endif virtual void LoadPrivateKey(uint16, const SSL_varvector16 &); virtual void UnLoadPublicKey(uint16, SSL_varvector16 &); virtual void UnLoadPrivateKey(uint16, SSL_varvector16 &); virtual BOOL VerifyASN1(SSL_Hash *reference, const byte *signature, uint32); virtual byte *Sign(const byte *source,uint32 len,byte *target, uint32 &, uint32 bufferlen); virtual byte *SignASN1(SSL_Hash *reference, byte *target, uint32 &, uint32 bufferlen); #ifdef SSL_DH_SUPPORT virtual void ProduceGeneratedPublicKeys(); virtual void ProduceGeneratedPrivateKeys(); #endif virtual SSL_PublicKeyCipher *Produce() const; virtual SSL_PublicKeyCipher *Fork()const ; virtual void LoadAllKeys(SSL_varvector32 &); // Vector with a DER-encoded Private key /** Return TRUE if ERROR */ BOOL CheckError(CK_RV status); BOOL Error(SSL_Alert *msg=NULL) const; private: /** Return TRUE if session was created */ BOOL CheckSession(); void CloseSession(); BOOL SetupKey(CK_OBJECT_HANDLE &key); }; #endif /* PUBKEY_H */ #endif
#ifndef ISA_HANDLERS_H #define ISA_HANDLERS_H /* * Instructio handler * perform instruction on the state / disassemle */ #include <sstream> #include <cassert> #include "definitions.h" namespace selen { namespace isa { //Base class class handler_t { public: handler_t(){} virtual ~handler_t(){} virtual void perform(State&, instruction_t) const = 0; virtual std::string disasemble(instruction_t) const = 0; }; template<class IT> /* * IT - instruction type class * * Concept: * * class IT * { * // Instruction format * struct ... format_t * * //Constructor * IT(format_t l) * * //perform on the state * void perform(State& st) * * //dump to stream mnemonic + operands * void print(std::ostream& s); * } */ class Handler : public handler_t { void perform(State& st, instruction_t instr) const { IT i = decode(instr); return i.perform(st); } std::string disasemble(instruction_t instr) const { IT i = decode(instr); static std::ostringstream out; out.str(""); i.print(out); return out.str(); } private: IT decode(instruction_t instr) const { typedef typename IT::format_t format_t; static_assert( sizeof(format_t) == sizeof(instruction_t), "decoded type must fit to instruction_t"); union { instruction_t i; format_t r; } caster = {instr}; assert(caster.r.opcode == IT::TARGET); return IT(caster.r); } }; //Handler } //namespace isa } //namespace selen #endif // ISA_HANDLERS_H
//--------------------------------------------------------------------------- #ifndef optionsH #define optionsH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> //--------------------------------------------------------------------------- class ToptionsFrm : public TForm { __published: // IDE-managed Components private: // User declarations public: // User declarations __fastcall ToptionsFrm(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE ToptionsFrm *optionsFrm; //--------------------------------------------------------------------------- #endif
std::string greet(const std::string& name){ std::string outputString = "Hello, " + name + " how are you doing today?"; return outputString; }
/** * @author:divyakhetan * @date: 10/1/2019 */ #include<bits/stdc++.h> using namespace std; int pascal(int i, int j){ if(j == 1) return 1; if(i == j ) return 1; else return pascal(i - 1, j) + pascal(i - 1, j - 1); } int main(){ int n; cin >> n; for(int i = 1; i <= n; i++){ for(int j = 1; j <= i; j++){ cout << pascal(i,j) << " "; } cout << endl; } return 0; }
#include<stdio.h> #include<iostream> #include<queue> using namespace std; char map[30][30][30]; //记录节点信息 int sta[30][30][30]; //标记是否访问 int base[6][3] = { {-1,0,0},{1,0,0},{0,-1,0},{0,1,0},{0,0,-1},{0,0,1} };//随意对应 int L, R, C; struct Piont { int x, y, z; //位置坐标 int step; //出发点到该点的步数 }; struct Piont s; //起点 struct Piont e; //终点 struct Piont curp; //跳出循环时的节点 /******************判断是否到达终点*********************/ bool success(struct Piont cur) { if (cur.x == e.x && cur.y == e.y && cur.z == e.z) return true; else return false; } /**************判断该点是否合法*************************/ bool check(int x, int y, int z) { if ((x >= 0) && (x < L) && (y >= 0) && (y < R) && (z >= 0) && (z < C) && (!sta[x][y][z]) && (map[x][y][z] == '.' || map[x][y][z] == 'E')) return true; else return false; } /*************************广搜(求最短)***************************///深搜求多组解*/ void bfs() { struct Piont next; queue<Piont>q; q.push(s); //int flag = 0; while (!q.empty()) { curp = q.front(); q.pop(); if (success(curp)) return; else { sta[curp.x][curp.y][curp.z] = 1; for (int i = 0; i < 6; i++) { next.x = curp.x + base[i][0]; next.y = curp.y + base[i][1]; next.z = curp.z + base[i][2]; if (check(next.x, next.y, next.z)) //扩展队列 { next.step = curp.step + 1; sta[next.x][next.y][next.z] = 1; q.push(next); } } } } } int main() { while (scanf("%d%d%d", &L, &R, &C)) { if((L == 0) && (R == 0) && (C == 0)) break; memset(sta, 0, sizeof(sta)); for (int i = 0; i < L; i++) { getchar(); for (int j = 0; j < R; j++) { for (int k = 0; k < C; k++) { scanf("%c", &map[i][j][k]); if (map[i][j][k] == 'S') { s.x = i; s.y = j; s.z = k; s.step = 0; } else if (map[i][j][k] == 'E') { e.x = i; e.y = j; e.z = k; } } getchar(); } } bfs(); if (curp.x == e.x && curp.y == e.y && curp.z == e.z) printf("Escaped in %d minute(s).\n", curp.step); else printf("Trapped!\n"); } return 0; }
#include "GameStartProc.h" #include "HallHandler.h" #include "Logger.h" #include "Despatch.h" #include "GameServerConnect.h" #include "PlayerManager.h" #include "GameCmd.h" #include "ProcessManager.h" #include <string> using namespace std; GameStartProc::GameStartProc() { this->name = "GameStartProc"; } GameStartProc::~GameStartProc() { } int GameStartProc::doRequest(CDLSocketHandler* client, InputPacket* pPacket, Context* pt ) { HallHandler* clientHandler = dynamic_cast<HallHandler*> (client); Player* player = PlayerManager::getInstance().getPlayer(clientHandler->uid); if(player == NULL) return 0; OutputPacket requestPacket; requestPacket.Begin(CLIENT_MSG_START_GAME, player->id); requestPacket.WriteInt(player->id); requestPacket.WriteInt(player->tid); requestPacket.End(); this->send(clientHandler, &requestPacket); LOGGER(E_LOG_DEBUG) << "player->id:" << player->id; return 0; } int GameStartProc::doResponse(CDLSocketHandler* client, InputPacket* inputPacket,Context* pt) { HallHandler* hallHandler = dynamic_cast<HallHandler*> (client); Player* player = PlayerManager::getInstance().getPlayer(hallHandler->uid); int retcode = inputPacket->ReadShort(); string retmsg = inputPacket->ReadString(); LOGGER(E_LOG_DEBUG) << "retcode=" << retcode << " retmsg=" << retmsg; if(retcode == -9 || retcode == -8) return 0; if(retcode < 0 || player == NULL) { ULOGGER(E_LOG_INFO, hallHandler->uid) << "[robot exit]"; return EXIT; } int uid = inputPacket->ReadInt(); short ustatus = inputPacket->ReadShort(); int tid = inputPacket->ReadInt(); short tstatus = inputPacket->ReadShort(); int startid = inputPacket->ReadInt(); short startstatus = inputPacket->ReadShort(); ULOGGER(E_LOG_DEBUG, uid) << "ustatus=" << ustatus << " tid=" << tid << " tstatus=" << tstatus << " startid=" << startid << " startstatus=" << startstatus; player->tstatus = tstatus; if (tid != player->tid) { ULOGGER(E_LOG_INFO, uid) << "[robot exit] tid=" << tid << " not equal player->tid=" << player->tid; return EXIT; } if(uid == startid) { player->status = startstatus; } else { for(int i = 0; i < GAME_PLAYER; ++i) { if(player->player_array[i].id == startid) { player->player_array[i].status = startstatus; break; } } } return 0; } REGISTER_PROCESS(CLIENT_MSG_START_GAME, GameStartProc)
#include <iostream> #include <string> #define SBLOGGER_LOG_LEVEL SBLOGGER_LEVEL_TRACE #include "SmallBetterLogger.hpp" int main() { // Declarations (Logger) sblogger::StreamLogger l; // Simplest way to make a logger sblogger::stream_logger logErr(sblogger::StreamType::STDERR, "[%F %T][%^er]"); // Set stream type and custom format sblogger::logger* logLog = new sblogger::StreamLogger(sblogger::StreamType::STDLOG, "[Log]"); // Making use of the abstract class // Declarations (FileLogger) sblogger::FileLogger fileLogger("example.log", "[File Log]"); //sblogger::FileLogger fileLogger2(" .txt", "[File Log]"); // Will throw error since filename is empty // Basic calls (Logger) l.WriteLine("This is a normal log to STDOUT."); l.WriteLine(); l.Indent(); // Add indent to stylize logs l.WriteLine(std::string("Hello, {0}!"), "World"); // Message to be writen can also be a variable of type std::string l.Dedent(); // Remove indent at any time from the logger l.Write("I am {0} and {1} years old.{2} {0}", "Michael", 28); // If you give more placeholders than parameters, they are just writen as is l.Write("{0}", "\n", "hey"); // If you give more parameters, they are just ignored logErr.WriteLine("stderr"); logLog->WriteLine("stdlog"); // Basic calls (FileLogger) fileLogger.ClearLogs(); // This will clear the log file utilised by the FileLogger fileLogger.WriteLine("This is a test."); // All methods previously shown can also be used with files fileLogger.Indent(); fileLogger.Write("Hello World!"); delete logLog; std::cin.get(); return 0; }
#ifndef __WATER_H__ #define __WATER_H__ class Water : public ObjectBase { D3DMATERIAL9 m_mtr; void _StencilWaterOn(void); void _StencilWateroff(void); public: enINITERROR InitVTX (void); // 버텍스 생성 void InitMaterial(void); void Control (float dTime){}; void Render (void); // 오브젝트 렌더링 void RenderAB(void); public: Water(void); virtual ~Water(void); }; #endif
/***************************************************************************************************************** * File Name : DeleteLL.h * File Location : C:\Users\AVINASH\Desktop\CC++\Programming\src\sites\geeksforgeeks\linkedlist\page04\DeleteLL.h * Created on : Dec 17, 2013 :: 11:48:13 PM * Author : AVINASH * Testing Status : TODO * URL : TODO *****************************************************************************************************************/ /************************************************ Namespaces ****************************************************/ using namespace std; using namespace __gnu_cxx; /************************************************ User Includes *************************************************/ #include <string> #include <vector> #include <cstdlib> #include <cstdio> #include <cmath> #include <algorithm> #include <ctime> #include <list> #include <map> #include <set> #include <bitset> #include <functional> #include <utility> #include <iostream> #include <fstream> #include <sstream> #include <string.h> #include <hash_map> #include <stack> #include <queue> #include <limits.h> #include <programming/ds/tree.h> #include <programming/utils/treeutils.h> /************************************************ User defined constants *******************************************/ #define null NULL /************************************************* Main code ******************************************************/ #ifndef DELETELL_H_ #define DELETELL_H_ void deleteLL(llNode *ptr){ if(ptr == NULL){ return; } if(ptr->next == NULL){ return; } deleteLL(ptr->next); free(ptr); } void deleteLLDriver(llNode **ptr){ if((*ptr) == NULL){ return; } deleteLL(ptr); (*ptr) = NULL; } void deleteLLIterative(llNode **ptr){ if((*ptr) == NULL){ return; } stack<llNode *> auxSpace; llNode *traversalPtr = ptr,*tempNode; while(!auxSpace.empty()){ auxSpace.push(traversalPtr); traversalPtr = traversalPtr->next; } auxSpace.pop(); while(!auxSpace.empty()){ tempNode = auxSpace.top()->next; auxSpace.pop(); free(tempNode); } tempNode = (*ptr); (*ptr) = NULL; free(tempNode); } void deleteLLHashmap(llNode **ptr){ if((*ptr) == NULL){ return; } vector<llNode *> nodes; llNode *tempNode; llNode *traversalPtr = (*ptr); while(traversalPtr != NULL){ nodes.push_back(traversalPtr); traversalPtr = traversalPtr->next; } for(unsigned int counter = nodes.size()-1;counter >= 0;counter--){ tempNode = nodes[counter]; free(tempNode); } (*ptr) = NULL; } #endif /* DELETELL_H_ */ /************************************************* End code *******************************************************/
#ifndef _PushForbidProc_H_ #define _PushForbidProc_H_ #include "BaseProcess.h" class PushForbidProc :public BaseProcess { public: PushForbidProc(); virtual ~PushForbidProc(); virtual int doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt) ; virtual int doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt ) ; }; #endif
//Phoenix_RK /* https://leetcode.com/problems/intersection-of-two-arrays-ii/ Given two arrays, write a function to compute their intersection. */ class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { vector<int> result; sort(nums1.begin(),nums1.end()); sort(nums2.begin(),nums2.end()); auto i1=nums1.begin(),i2=nums2.begin(); while(i1<nums1.end() && i2<nums2.end()) { if(*i1==*i2) { result.push_back(*i1); i1++; i2++; } else if(*i1<*i2) { *i1++; } else *i2++; } return result; } };
// // Created by 송지원 on 2020-02-15. // #include <iostream> long long countR(long long input, long long r) { long long ret = 0; long long r_temp = r; while (input / r_temp >= 1LL) { ret += (input / r_temp); r_temp *= r; } return ret; } int main() { long long n, m; long long cnt2 = 0, cnt5 = 0; scanf("%lld %lld", &n, &m); cnt2 = countR(n, 2LL) - countR(m, 2LL) - countR(n-m, 2LL); cnt5 = countR(n, 5LL) - countR(m, 5LL) - countR(n-m, 5LL); if (cnt2 < cnt5) { printf("%lld\n", cnt2); } else { printf("%lld\n", cnt5); } return 0; }
// the default value of new created value is the default type value class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<vector<string>> anagrams; unordered_map<string, vector<string>> umap; for (string str : strs) { umap[strIndex(str)].push_back(str); } for (const auto &iter : umap) { anagrams.push_back(iter.second); } return anagrams; } private: string strIndex(string str) { string index; vector<int> cnt(26, 0); for (char c : str) cnt[c - 'a']++; for (int n : cnt) { index += to_string(n); } return index; } };
#include <wx/wx.h> #include <wx/msgdlg.h> #include <wx/sizer.h> #include <wx/dir.h> #include <wx/filefn.h> #include <wx/stattext.h> #include <wx/textctrl.h> #include <wx/button.h> #include <wx/dialog.h> #include "clZipReader.h" #include "event_notifier.h" #include "cl_standard_paths.h" #include "file_logger.h" enum { ID_ZipPath = 2000, ID_ChooseBtn, ID_UnzipAll, ID_Unzip, ID_Help }; class ZipDialog : public wxDialog { public: ZipDialog(wxWindow *parent); ~ZipDialog(); void OnShowChoice(wxCommandEvent& event); void OnTips(wxCommandEvent& event); void OnImport(wxCommandEvent& event); void OnUnzipAll(wxCommandEvent& event); private: wxTextCtrl* zip_path; wxButton* btn_choose; wxButton* btn_ok; wxButton* btn_all; wxButton* btn_help; };
#include <iostream> #include <fstream> #include "avltree.hxx" template <class Tree> static void dump_to_dot(Tree const &tree, std::ostream &out) { out << "digraph {\n"; tree.traverse([&out](typename Tree::Node const *n) { out << "n" << n << " [label=\"" << n->value() << " [" << n->yield_height() << "]\", fontcolor=black, style=filled];\n"; if (auto const *l = n->left()) out << "n" << n << " -> n" << l << " [side=left];\n"; if (auto const *r = n->right()) out << "n" << n << " -> n" << r << " [side=right];\n"; out.flush(); }); out << "}\n"; } int main(int argc, char *argv[]) { AVLTree<int> tree; for (int i = 1; i <= 512; ++i) { tree.insert(i); } // for (int i = 1; i <= 8; ++i) { // tree.insert(i); // } // for (int i = 10; i <= 159; ++i) { // tree.insert(i); // } // for (int i = 320; i >= 160; --i) { // tree.insert(i); // } // tree.insert(2); // tree.insert(0); // tree.insert(1); // for (int i = 0; i <= 2 ; ++i) { // tree.insert(i); // } // for (int i = 0; i <= 9 ; ++i) { // tree.insert(i); // } // for (int i = 0; i <= 9 ; ++i) { // tree.insert(i); // } // std::cout << "Find 11: " << tree.find(11)->value() << std::endl; // std::cout << "Find 1100: " << tree.find(1100) << std::endl; // std::cout << "Maximum: " << tree.maximum()->value() << std::endl; // std::cout << "Minimum: " << tree.minimum()->value() << std::endl; // tree.insert(60); // tree.insert(61); // tree.insert(62); // tree.insert(63); // for (int i = 1; i <= 6; ++i) { // tree.insert(i); // } if (argc > 1) { std::ofstream os(argv[1]); dump_to_dot(tree, os); } return 0; }
#include "gtest/gtest.h" #include "../../greekjet_fadbad/GreeksFadbadHelper.h" #include "../../options/Option.hpp" #include "../../greekjet_fadbad/Func.h" #include "../../binomial_method/case/Case.hpp" #include "../../options/OptionPut.hpp" #include "../../binomial_method/case/LeisenKlassenMOT.hpp" #include "../../binomial_method/method/BinomialMethod.hpp" #include "../../binomial_method/method/regular/euro/EuroBinomialMethod.hpp" #include "../../options/OptionCall.hpp" #include "../../black_scholes/BlackScholesMertonPut.hpp" #include "../../black_scholes/BlackScholesMertonCall.hpp" #define STEPS 1400 template<class T> class FuncRegularPutA : public Func<T> { public: T operator()( const T &s, const T &t, const T &r, const T &sigma ) { T E(10.); Option<T> *option = new OptionPut<T>(t, s, r, sigma, E); Case<T> *_case = new LeisenKlassenMOT<T>(option, STEPS); BinomialMethod<T> *method = new EuroBinomialMethod<T>(_case); method->solve(); T result = method->getResult(); delete option, _case, method; return result; } }; template<class T> class FuncRegularCallA : public Func<T> { public: T operator()( const T &s, const T &t, const T &r, const T &sigma ) { T E(10.); Option<T> *option = new OptionCall<T>(t, s, r, sigma, E); Case<T> *_case = new LeisenKlassenMOT<T>(option, STEPS); BinomialMethod<T> *method = new EuroBinomialMethod<T>(_case); method->solve(); T result = method->getResult(); delete option, _case, method; return result; } }; Func<FJet> *funcPut = new FuncRegularPutA<FJet>(); GreeksFadbadHelper *helperRegularPutA = nullptr; Func<FJet> *funcCall = new FuncRegularCallA<FJet>(); GreeksFadbadHelper *helperRegularCallA = nullptr; double s(5.), t(1.), r(0.06), sigma(0.3); TEST(FadbadGreek, EuroRegularCallA) { BlackScholesMertonCall bs(s, 10., r, sigma, t); if (helperRegularCallA == nullptr) { helperRegularCallA = new GreeksFadbadHelper(s, t, r, sigma, funcCall); } EXPECT_NEAR((*helperRegularCallA).value(), bs.calculate(0.0), 0.001); } TEST(FadbadGreek, EuroRegularPutA) { BlackScholesMertonPut bs(s, 10., r, sigma, t); if (helperRegularPutA == nullptr) { helperRegularPutA = new GreeksFadbadHelper(s, t, r, sigma, funcPut); } EXPECT_NEAR((*helperRegularPutA).value(), bs.calculate(0.0), 0.001); } /*************************************************************************/ TEST(FadbadGreek, EuroDeltaRegularCallA) { BlackScholesMertonCall bs(s, 10., r, sigma, t); if (helperRegularCallA == nullptr) { helperRegularCallA = new GreeksFadbadHelper(s, t, r, sigma, funcCall); } EXPECT_NEAR((*helperRegularCallA).delta(), bs.delta(0.0), 0.001); } TEST(FadbadGreek, EuroDeltaRegularPutA) { BlackScholesMertonPut bs(s, 10., r, sigma, t); if (helperRegularPutA == nullptr) { helperRegularPutA = new GreeksFadbadHelper(s, t, r, sigma, funcPut); } EXPECT_NEAR((*helperRegularPutA).delta(), bs.delta(0.0), 0.001); } /*************************************************************************/ TEST(FadbadGreek, EuroGammaRegularCallA) { BlackScholesMertonCall bs(s, 10., r, sigma, t); if (helperRegularCallA == nullptr) { helperRegularCallA = new GreeksFadbadHelper(s, t, r, sigma, funcCall); } EXPECT_NEAR((*helperRegularCallA).gamma(), bs.gamma(0.0), 0.001); } TEST(FadbadGreek, EuroGammaRegularPutA) { BlackScholesMertonPut bs(s, 10., r, sigma, t); if (helperRegularPutA == nullptr) { helperRegularPutA = new GreeksFadbadHelper(s, t, r, sigma, funcPut); } EXPECT_NEAR((*helperRegularPutA).gamma(), bs.gamma(0.0), 0.001); } /*************************************************************************/ TEST(FadbadGreek, EuroThetaRegularCallA) { BlackScholesMertonCall bs(s, 10., r, sigma, t); if (helperRegularCallA == nullptr) { helperRegularCallA = new GreeksFadbadHelper(s, t, r, sigma, funcCall); } EXPECT_NEAR((*helperRegularCallA).theta(), bs.theta(0.0), 0.0012); } TEST(FadbadGreek, EuroThetaRegularPutA) { BlackScholesMertonPut bs(s, 10., r, sigma, t); if (helperRegularPutA == nullptr) { helperRegularPutA = new GreeksFadbadHelper(s, t, r, sigma, funcPut); } EXPECT_NEAR((*helperRegularPutA).theta(), bs.theta(0.0), 0.0029); } /*************************************************************************/ TEST(FadbadGreek, EuroVegaRegularCallA) { BlackScholesMertonCall bs(s, 10., r, sigma, t); if (helperRegularCallA == nullptr) { helperRegularCallA = new GreeksFadbadHelper(s, t, r, sigma, funcCall); } EXPECT_NEAR((*helperRegularCallA).vega(), bs.vega(0.0), 0.0051); } TEST(FadbadGreek, EuroVegaRegularPutA) { BlackScholesMertonPut bs(s, 10., r, sigma, t); if (helperRegularCallA == nullptr) { helperRegularCallA = new GreeksFadbadHelper(s, t, r, sigma, funcCall); } EXPECT_NEAR((*helperRegularPutA).vega(), bs.vega(0.0), 0.0051); } /*************************************************************************/ TEST(FadbadGreek, EuroRhoRegularCallA) { BlackScholesMertonCall bs(s, 10., r, sigma, t); if (helperRegularCallA == nullptr) { helperRegularCallA = new GreeksFadbadHelper(s, t, r, sigma, funcCall); } EXPECT_NEAR((*helperRegularCallA).rho(), bs.rho(0.0), 0.001); } TEST(FadbadGreek, EuroRhoRegularPutA) { BlackScholesMertonPut bs(s, 10., r, sigma, t); if (helperRegularPutA == nullptr) { helperRegularPutA = new GreeksFadbadHelper(s, t, r, sigma, funcPut); } EXPECT_NEAR((*helperRegularPutA).rho(), bs.rho(0.0), 0.001); } /*************************************************************************/ TEST(FadbadGreek, EuroVannaRegularPutA) { BlackScholesMertonPut bs(s, 10., r, sigma, t); if (helperRegularPutA == nullptr) { helperRegularPutA = new GreeksFadbadHelper(s, t, r, sigma, funcPut); } EXPECT_NEAR((*helperRegularPutA).vanna(), bs.vanna(0.0), 0.0016); } /*************************************************************************/ TEST(FadbadGreek, EuroVommaRegularPutA) { BlackScholesMertonPut bs(s, 10., r, sigma, t); if (helperRegularPutA == nullptr) { helperRegularPutA = new GreeksFadbadHelper(s, t, r, sigma, funcPut); } EXPECT_NEAR((*helperRegularPutA).vomma(), bs.vomma(0.0), 0.0106); } /*************************************************************************/ TEST(FadbadGreek, EuroCharmRegularCallA) { BlackScholesMertonCall bs(s, 10., r, sigma, t); if (helperRegularCallA == nullptr) { helperRegularCallA = new GreeksFadbadHelper(s, t, r, sigma, funcCall); } EXPECT_NEAR((*helperRegularCallA).charm(), bs.charm(0.0), 0.001); } TEST(FadbadGreek, EuroCharmRegularPutA) { BlackScholesMertonPut bs(s, 10., r, sigma, t); if (helperRegularPutA == nullptr) { helperRegularPutA = new GreeksFadbadHelper(s, t, r, sigma, funcPut); } EXPECT_NEAR((*helperRegularPutA).charm(), bs.charm(0.0), 0.001); } /*************************************************************************/ TEST(FadbadGreek, EuroVetaRegularPutA) { BlackScholesMertonPut bs(s, 10., r, sigma, t); if (helperRegularPutA == nullptr) { helperRegularPutA = new GreeksFadbadHelper(s, t, r, sigma, funcPut); } EXPECT_NEAR((*helperRegularPutA).veta(), bs.veta(0.0), 0.001); } /*************************************************************************/ TEST(FadbadGreek, EuroVeraRegularPutA) { if (helperRegularPutA == nullptr) { helperRegularPutA = new GreeksFadbadHelper(s, t, r, sigma, funcPut); } EXPECT_NEAR((*helperRegularPutA).vera(), 1.9071, 0.007); } /*************************************************************************/ TEST(FadbadGreek, EuroColorRegularPutA) { BlackScholesMertonPut bs(s, 10., r, sigma, t); if (helperRegularPutA == nullptr) { helperRegularPutA = new GreeksFadbadHelper(s, t, r, sigma, funcPut); } EXPECT_NEAR((*helperRegularPutA).color(), bs.color(0.0), 0.001); } /*************************************************************************/ TEST(FadbadGreek, EuroSpeedRegularPutA) { BlackScholesMertonPut bs(s, 10., r, sigma, t); if (helperRegularPutA == nullptr) { helperRegularPutA = new GreeksFadbadHelper(s, t, r, sigma, funcPut); } EXPECT_NEAR((*helperRegularPutA).speed(), bs.speed(0.0), 0.001); } /*************************************************************************/ TEST(FadbadGreek, EuroUltimaRegularPutA) { BlackScholesMertonPut bs(s, 10., r, sigma, t); if (helperRegularPutA == nullptr) { helperRegularPutA = new GreeksFadbadHelper(s, t, r, sigma, funcPut); } EXPECT_NEAR((*helperRegularPutA).ultima(), bs.ultima(0.0), 0.11); } /*************************************************************************/ TEST(FadbadGreek, EuroZommaRegularPutA) { BlackScholesMertonPut bs(s, 10., r, sigma, t); if (helperRegularPutA == nullptr) { helperRegularPutA = new GreeksFadbadHelper(s, t, r, sigma, funcPut); } EXPECT_NEAR((*helperRegularPutA).zomma(), bs.zomma(0.0), 0.0038); }
//************************************************************************************************************* // // 画像2D処理[Image2d.h] // Author : IKUTO SEKINE // //************************************************************************************************************* #pragma once #ifndef _IMAGE2D_H_ #define _IMAGE2D_H_ //------------------------------------------------------------------------------------------------------------- // インクルードファイル //------------------------------------------------------------------------------------------------------------- #include "..\MyEngine\Component.h" _BEGIN_MYSTD //------------------------------------------------------------------------------------------------------------- // クラス定義 //------------------------------------------------------------------------------------------------------------- class Transform2D; class Image2D : public IVisualComponent { public: /* メンバ関数 */ // コンストラクタ Image2D(); // デストラクタ ~Image2D(); // 処理の開始 void Start(void); // 更新 void Update(void); // 描画 void Draw(void); private: // 頂点情報の作成 HRESULT MakeVertex(void); // 頂点位置の設定 void SetVertexPosition(VERTEX_2D *pVtx); // 頂点カラーの設定 void SetVertexColor(VERTEX_2D *pVtx); public: /* メンバ変数 */ LPDIRECT3DVERTEXBUFFER9 pVtxBuff; // 頂点バッファへのポインタ LPDIRECT3DTEXTURE9 pTexture; // テクスチャへのポインタ D3DXCOLOR color; // カラー Transform2D * pTransform; // トランスフォームポインタ VERTEX_2D* pVtx; // 頂点ポインタ }; _END_MYSTD #endif
//@author Timofey #include "TXLib.h" void drawKing (int x, int y, int r, COLORREF color, COLORREF color1); int main() { txCreateWindow(1000, 800); drawKing(50,100,10, RGB(0,0,0), RGB(255,255,255));//размер королевы сделан в два раза меньше, чем короля. Поэтому переменная r у королевы должна быть ровно в 2 раза больше. } void drawKing (int x, int y, int r, COLORREF color, COLORREF color1) { txSetColor(color1,2); txSetFillColor (RGB (255, 215, 0)); //золото для короны POINT headtop[25] = {{(6*r)+x, (0*r)+y}, {(7*r)+x, (6*r)+y}, {(8*r)+x, (0*r)+y}, {(9*r)+x, (6*r)+y}, {(10*r)+x, (0*r)+y}, {(11*r)+x, (6*r)+y}, {(12*r)+x, (0*r)+y}, {(13*r)+x, (6*r)+y}, {(14*r)+x, (0*r)+y}, {(15*r)+x, (6*r)+y}, {(16*r)+x, (0*r)+y}, {(16*r)+x, (8*r)+y}, {(14*r)+x, (8*r)+y}, {(12*r)+x, (18*r)+y}, {(13*r)+x, (18*r)+y}, {(13*r)+x, (19*r)+y}, {(14*r)+x, (19*r)+y}, {(14*r)+x, (20*r)+y}, {(8*r)+x, (20*r)+y}, {(8*r)+x, (19*r)+y}, {(9*r)+x, (19*r)+y}, {(9*r)+x, (18*r)+y}, {(10*r)+x, (18*r)+y}, {(8*r)+x, (8*r)+y}, {(6*r)+x, (8*r)+y}}; //"голова", меняется в зависимости от фигуры txPolygon (headtop, 25); /*POINT headnottop[26] = {{(2*r)+x, (0*r)+y}, {(3*r)+x, (4*r)+y}, {(3*r)+x, (0*r)+y}, {(4*r)+x, (4*r)+y}, {(4*r)+x, (0*r)+y}, {(5*r)+x, (4*r)+y}, {(6*r)+x, (4*r)+y}, {(7*r)+x, (0*r)+y}, {(7*r)+x, (4*r)+y}, {(8*r)+x, (0*r)+y}, {(8*r)+x, (4*r)+y}, {(9*r)+x, (0*r)+y}, {(9*r)+x, (5*r)+y}, {(7*r)+x, (5*r)+y}, {(6*r)+x, (9*r)+y}, {(7*r)+x, (9*r)+y}, {(7*r)+x, (10*r)+y}, {(8*r)+x, (10*r)+y}, {(8*r)+x, (11*r)+y}, {(3*r)+x, (11*r)+y}, {(3*r)+x, (10*r)+y}, {(4*r)+x, (10*r)+y}, {(4*r)+x, (9*r)+y}, {(5*r)+x, (9*r)+y}, {(4*r)+x, (5*r)+y}, {(2*r)+x, (5*r)+y}}; //"голова", меняется в зависимости от фигуры txPolygon (headnottop, 26);*/ txSetFillColor (color); //основной цвет (белый) //txSetFillColor (RGB (255, 255, 255)); //основной цвет (чёрный) POINT body[4] = {{(10*r)+x, (20*r)+y}, {(12*r)+x, (20*r)+y}, {(16*r)+x, (40*r)+y}, {(6*r)+x, (40*r)+y}}; //неизменяемое тело txPolygon (body, 4); POINT stand1[4] = {{(4*r)+x, (40*r)+y}, {(18*r)+x, (40*r)+y}, {(18*r)+x, (42*r)+y}, {(4*r)+x, (42*r)+y}}; //первая подставка для всех, а у пешек только она txPolygon (stand1, 4); POINT stand2[4] = {{(2*r)+x, (42*r)+y}, {(20*r)+x, (42*r)+y}, {(20*r)+x, (44*r)+y}, {(2*r)+x, (44*r)+y}}; //вторая подставка для средних(ладья,слон,конь) и лучших txPolygon (stand2, 4); POINT stand3[4] = {{(0*r)+x, (44*r)+y}, {(22*r)+x, (44*r)+y}, {(22*r)+x, (46*r)+y}, {(0*r)+x, (46*r)+y}};//третья подставка для лучших(ферзей, королей) txPolygon (stand3, 4); }
#include "pch.h" #include "EventSystem.h" void Hourglass::EventSystem::Init() { INIT_COMPONENT_POOL(TriggerEventGroup); INIT_COMPONENT_POOL(TimeTrigger); } void Hourglass::EventSystem::Update() { m_TimeTriggerPool.UpdatePooled(); }
class PartOre { weight = 1; }; class PartOreSilver { weight = 1.2; }; class PartOreGold { weight = 1.5; };
#ifndef GEN_COMMAND_H #define GEN_COMMAND_H #include <iostream> #include <unistd.h> #include <cmath> #include <cstdio> #include <cstdlib> #include <stdint.h> uint32_t genCommand(const char *cmdFilePath, CmdEntry *cmdEntryBuff); void dumpCmdEntry(CmdEntry cmdEntry); void dumpTableMetas(); #endif //GEN_COMMAND_H
#include "equationNode.h" #include "parser.h" #include <iostream> #include <string> #include <vector> #include <unordered_map> #include <algorithm> using namespace std; // initializing static members of class EquationNode unordered_map<string, vector<EquationNode*>*> EquationNode::_equation_map; unordered_map<string, double> EquationNode::_solution_map; vector<EquationNode*> EquationNode::_dynamic_objects; EquationNode::EquationNode(vector<string>& line_words) { _right_side_value = 0; _left_side_value = 0; // find the index of the "=" in the list of terms in the equation vector<string>::iterator equal_ptr = find(line_words.begin(), line_words.end(), "="); int equal_idx = distance(line_words.begin(), equal_ptr); _initLeftSide(line_words, equal_idx); equal_idx++; _initRightSide(line_words, equal_idx); // add this EquationNode to the _equation_map _addToEquationMap(); // check if this equation can be evaluated, and make the appropriate updates if so. _evaluateAndUpdate(); } void EquationNode::solveSystemOfEquations(vector<vector<string>>& system) { // store created objects in vector to allow them to be retrieved and deleted later for (vector<string> line : system) _dynamic_objects.push_back(new EquationNode(line)); // print out results _printSolutionMap(); // delete all allocated dynamic memory for (EquationNode* node : _dynamic_objects) delete node; for (auto it : _equation_map) delete it.second; } void EquationNode::_evaluateAndUpdate() { // check if the equation can be evaluated for a variable if (_canEvaluate()) { // if it can be evaluated, get a pair of ex <var, 3.0> pair<string,double> pair = _evaluate(); string var_name = pair.first; double var_val = pair.second; // add mapping from variable to it's value to solutions_map _solution_map[var_name] = var_val; // get the vector of equations that contains the variable we solved for vector<EquationNode* > node_vector= *(_equation_map[var_name]); // iterate through the equations, updating them with the variable's value for (auto node : node_vector) node->_updateWithValue(var_name, var_val); } } void EquationNode::_updateWithValue(const string& var_name, const double var_val){ // if variable var_name is on the left side of the equation if (_left_side_variables.count(var_name) != 0) { // get the number of times var_name appears on the left side int count = _left_side_variables[var_name]; // update the left side value by adding the value of var_name // multiplied by how many times the variable occurs. _left_side_value += count*var_val; // remove the variable from the left side of the equation _left_side_variables.erase(var_name); } // else if variable var_name is on the right side if (_right_side_variables.count(var_name) != 0) { // get the number of times var_name appears on the right side int count = _right_side_variables[var_name]; // update the right side value by adding the value of var_name // multiplied by how many times the variable occurs. _right_side_value += count*var_val; // remove the variable from right side of equation. _right_side_variables.erase(var_name); } // now that equation has been updated, check if it can be evaluated for some variable x // and if so, evaluate it and update all equations that have x _evaluateAndUpdate(); } void EquationNode::_addToEquationMap() { // loop through all the variables on the left and right side // of the equation and add mapping from the variable to this equation in // equation_map _addToEquationMapHelper(_left_side_variables); _addToEquationMapHelper(_right_side_variables); } void EquationNode::_addToEquationMapHelper(unordered_map<string, int>& map) { for (auto it : map) { string var_name = it.first; if (_equation_map.count(var_name) == 0) _equation_map[var_name] = new vector<EquationNode* >(); _equation_map[var_name]->push_back(this); } } void EquationNode::_setValAndVars(const vector<string>& line_words, const int &start_idx, const int &end_idx, double& value, double& other_value, unordered_map<string, int> & map, unordered_map<string, int> & other_map) { // this function does much of the hard work of initializing the EquationNode object // loop through the vector of terms eg ["a","+","b","=","5"] for (int i = start_idx; i < end_idx; i++) { string word = line_words[i]; if (word == "+") continue; // can skip "+" // check if the variable is a number, if so update the appropriate value if (Parser::isDouble(word)) { value += stod(word) - other_value; other_value = 0; } // check if the variable's value is already known, and if so update the appropriate value else if (_solution_map.count(word) == 1) { value += _solution_map[word] - other_value; other_value = 0; } // else,this is a term that is not a number, and is not solved for yet. else { int other_map_count = other_map.count(word); // if the other side has this variable, subtract it from other side if (other_map_count != 0) { if (other_map[word] == 1) other_map.erase(word); else { int old_count = other_map[word]; other_map[word] = --old_count; } } else // other side doesn't have the variable, so add it to this side { if ( map.count(word) == 0 ) map[word] = 1; else { int old_count = map[word]; map[word] = ++old_count; } } } } } void EquationNode::_initRightSide(const vector<string>& line_words, const int& start_idx) { // presumably, parameter start_idx is the index in line_worlds following the "=" int end_idx = (int)line_words.size(); _setValAndVars(line_words, start_idx, end_idx, _right_side_value, _left_side_value, _right_side_variables, _left_side_variables); } void EquationNode::_initLeftSide(const vector<string>& line_words, const int& end_idx) { // presumably, parameter end_idx is the index of "=" in the equation int start_idx = 0; _setValAndVars(line_words, start_idx , end_idx, _left_side_value, _right_side_value, _left_side_variables, _right_side_variables); } bool EquationNode::_canEvaluate() { int left_count = _left_side_variables.size(); int right_count = _right_side_variables.size(); // here we have 'var=5' or '5=var'; if (left_count + right_count == 1) return true; return false; } pair<string, double> EquationNode::_evaluate() { // this function assumes that the expression can be evaluated, and has form // "var = 6" or "6 = var" int left_count = _left_side_variables.size(); int right_count = _right_side_variables.size(); // check if variable is on left side, such as "2*var = 6" if (left_count == 1) { auto it = _left_side_variables.begin(); string var_name = it->first; int var_count = it->second; double var_val = (_right_side_value - _left_side_value)/var_count; return make_pair(var_name, var_val); } // else we know the variable is on the right side "6 = 2*var" else { auto it = _right_side_variables.begin(); string var_name = it->first; int var_count = it->second; double var_val = (_left_side_value - _right_side_value)/var_count; return make_pair(var_name, var_val); } } void EquationNode::_printMap(const unordered_map<string, int>& map) { // this function is presumably used to print out _left_side_variables // and _right_side_variables for (auto it: map) cout << it.second << "*" << it.first << " + "; } void EquationNode::_printEquationMap() { cout << "\t _equation_map \n"; for (auto it: EquationNode::_equation_map) { cout << it.first << ":"; for (auto ptr: *(it.second)) cout << " " << ptr; cout << "\n"; } } void EquationNode::_printSolutionMap() { vector<string> var_names; for (auto it: EquationNode::_solution_map) var_names.push_back(it.first); sort(var_names.begin(), var_names.end()); for (string var_name : var_names) { cout << var_name << " = " << _solution_map[var_name] << "\n"; } } void EquationNode::_printEquation() { _printMap(_left_side_variables); cout << _left_side_value; cout << " = "; _printMap(_right_side_variables); cout << _right_side_value; cout << "\n"; }
#include <set> #include <vector> const int MAX_VERTICES_COUNT = 32; using Vertex = int; struct Graph { std::vector<std::set<Vertex>> edges; bool HasEdge(Vertex from, Vertex to) const { return (edges[from].find(to) != edges[from].end()); } std::vector<Vertex> GetChildren(Vertex vertex) const { std::vector<Vertex> children; for (auto child : edges[vertex]) { children.push_back(child); } return children; } int GetDegree(Vertex vertex) const { return edges[vertex].size(); } };
#include "Player.h" #include <stdio.h> Player* Player::Instance() { static Player instance; return &instance; } void Player::moveCtrl() { if (getKey()->motion->getMotionForward()) { pitch += 3; if (PlayerPitch < 100)PlayerPitch += 1; } if (getKey()->motion->getMotionLeft()) { yaw += 1; if (PlayerYaw < 60)PlayerYaw += 1; } if (getKey()->motion->getMotionRight()) { yaw -= 1; if (PlayerYaw > -60)PlayerYaw -= 1; } if (getKey()->motion->getMotionBackward()) { pitch -= 3; if (PlayerPitch > -100)PlayerPitch -= 1; } if (PlayerYaw != 0) { if (!getKey()->motion->getMotionLeft() && !getKey()->motion->getMotionRight()) { if (PlayerYaw > 0)PlayerYaw -= 1; if (PlayerYaw < 0)PlayerYaw += 1; } } } void Player::PlayerCtrl() { drawPlayer(); camX += cos((yaw + 90) * TO_RADIANS); camZ -= sin((yaw + 90) * TO_RADIANS); //printf("%d", getKey()->motion->getMotionForward()); if (getKey()->motion->getMotionForward()) { if (camY < 120) camY -= cos((pitch + 90) * TO_RADIANS) / 2.0; } if (getKey()->motion->getMotionBackward()) { if (camY > 5) camY += cos((pitch + 180) * TO_RADIANS) / 2.0; } if (camY < 5)camY = 5; if (pitch >= 100) pitch = 100; if (pitch <= -100) pitch = -100; // printf("%f\n", pitch); // printf("%f\n", camX); // printf("%f\n", camY); // printf("%f\n", yaw); //ector::Instance()->SetVectorX(camX / 50); //ector::Instance()->SetVectorY(camY / 50); //ector::Instance()->SetVectorZ(camZ / 50); glRotatef(-pitch / 50, 1.0, 0.0, 0.0); //x축 중심으로 -pitch만큼 회전 glRotatef(-yaw, 0.0, 1.0, 0.0); //y축 중심으로 -yaw만큼 회전(오버플로우 위험있음) glTranslatef(-camX , -camY, -camZ); } void Player::drawPlayer() { if (getmouse()->getisPunch())isShot = true; else isShot = false; glPushMatrix(); glRotatef(PlayerPitch / 5, 1.0, 0.0, 0.0); glRotatef(PlayerYaw, 0.0, 0.0, 1.0); glTranslatef(-0.35f, 0.5f, -3); glutSolidCube(0.1f); //glLoadIdentity(); glPopMatrix(); glPushMatrix(); glRotatef(PlayerPitch / 5, 1.0, 0.0, 0.0); glRotatef(PlayerYaw, 0.0, 0.0, 1.0); glTranslatef(0.35f, 0.5f, -3); glutSolidCube(0.1f); //glLoadIdentity(); glPopMatrix(); if (isShot) { shotPower = 2.1; } else shotPower = 0; glPushMatrix(); glRotatef(PlayerPitch / 5, 1.0, 0.0, 0.0); glRotatef(PlayerYaw, 0.0, 0.0, 1.0); glTranslatef(0.43f, 0.30f, -3 - shotPower); glutWireSphere(0.05f, 50.0f, 50.0f); glPopMatrix(); glPushMatrix(); glRotatef(PlayerPitch / 5, 1.0, 0.0, 0.0); glRotatef(PlayerYaw, 0.0, 0.0, 1.0); //y축 중심으로 -yaw만큼 회전(오버플로우 위험있음) glTranslatef(0.0f, 0.5f, -3); //플래ㅔ이어 glutWireCube(0.5f); glPopMatrix(); }
#include<fstream> #include<string.h> #include<ctype.h> #include<iostream> #include<algorithm> #include<map> #include<unordered_map> #include<array> #include<deque> #include<math.h> #include<functional> #include<unordered_set> #include<set> #include<iomanip> #include<bitset> using namespace std; int i, j, k, l, ok, nr,rez,x1,x2,x3,x4,x5; unordered_map<int,int>mp; unordered_map<int,int>::iterator it; int main() { //ifstream f("file.in"); //ofstream g("file.out"); ifstream f("eqs.in"); ofstream g("eqs.out"); f >> x1 >> x2 >> x3 >> x4 >> x5; for (i = -50; i <= 50; i++) for (j = -50; j <= 50; j++) if (i != 0 && j != 0) { mp[x4 * i * i * i + x5 * j * j * j]++; } for (i = -50; i <= 50; i++) for (j = -50; j <= 50; j++) for (k = -50; k <= 50; k++) if (i != 0 && j != 0 && k != 0) { it=mp.find(i*i*i*x1 + j*j*j*x2 + k*k*k*x3); if(it!=mp.end()) rez += it->second; } g << rez; return 0; }
/** Kabuki SDK @file /.../Source/Kabuki_SDK/_2D/Point_f.cpp @author Cale McCollough @copyright Copyright © 2016 Cale McCollough @license Free and open-source. You can find a copy of the license that YOU MUST READ in the accompanying ./ReadMe.md, file incorporated herein by this reference, or online at http://www.boost.org/LICENSE_1_0.txt @brief This file contains the _2D.Point_i interface. */ #include "_2D/Point_f.h" using namespace _2D; /** Default constructor initializes with given point. */ Point_f::Point_f (float initX = 0, float initY = 0) { X = initX; Y = initY; } /** Sets the X and Y Values to the new Values. */ void Point_f::Set (float newX = 0, float newY = 0) { X = newX; Y = newY; } /** Sets the X and Y Values to the this Point_f's X and Y. */ void Point_f::Set (Point_f a) { X = a.X; Y = a.Y; } /** Compares this object's Point_f to a and returns true if the two Positions are identical. */ bool Point_f::Equals (Point_f a) { if (X != a.X || Y != a.Y) return false; return true; } /** Swaps this object's Point_f with a. */ void Point_f::Swap (Point_f a) { float tempX = a.X, tempY = a.Y; a.X = X; a.Y = Y; X = tempX; Y = tempY; }
/* * Program: Image_Equalizater.cpp */ #include "Image_Equalizater.h" /* * Usage: Construct Method * Parameters: * 1. source image * 2. type 0 for gray image input, type 1 for colorful image input */ Histogram_Equalizater::Histogram_Equalizater(CImg<unsigned char>& src, bool type){ this->srcImg = src; this->img_type = type; if(type == 0){ this->destImg = CImg<unsigned char>(src.width(), src.height(), src.depth(), 1, 0); RGBtoGray(); }else { this->destImg = CImg<unsigned char>(src.width(), src.height(), src.depth(), 3); } } void Histogram_Equalizater::RGBtoGray(){ CImg<unsigned char> gray(destImg.width(), destImg.height(), 1, 1, 0); cimg_forXY(srcImg, x, y){ gray(x, y) = srcImg(x, y, 0) * 0.299 + srcImg(x, y, 1) * 0.587 + srcImg(x, y ,2) * 0.114; } srcImg = gray; } /* * Usage: Calculate histogram for input image * Parameter: Origin image input * Output: Histogram of this image */ vector<float> Histogram_Equalizater::calculateHistogram(CImg<unsigned char>& origin){ vector<float> hist(256, 0); int total = 0; cimg_forXY(origin, x, y){ ++hist[origin(x, y)]; ++total; } // Perform probability transform for(int i=0; i<256; i++){ hist[i] = (float)hist[i] / total; } return hist; } vector<rgb> Histogram_Equalizater::calculateRGBHistogram(CImg<unsigned char>& origin){ vector<rgb> hist; int total = 0; for(int i=0; i<256; i++){ hist.push_back(rgb(0, 0, 0)); } cimg_forXY(origin, x, y){ hist[origin(x, y, 0)].r += 1; hist[origin(x, y, 1)].g += 1; hist[origin(x, y, 2)].b += 1; ++total; } // Perform probability dividing for(int i=0; i<256; i++){ hist[i].r = (float)hist[i].r / total; hist[i].g = (float)hist[i].g / total; hist[i].b = (float)hist[i].b / total; } return hist; } /* * Usage: Start Equalization */ void Histogram_Equalizater::equalization(){ if(img_type == 0){ // Perform gray image transform srcHistogram = calculateHistogram(srcImg); // Perform pixels probability adding float sum = 0; vector<int> thist(256, 0); for(int i=0; i<256; i++){ sum += srcHistogram[i]; thist[i] = (int)(sum * (256-1) + 0.5f); } // Perform filling into destination image cimg_forXY(destImg, x, y){ destImg(x, y) = thist[srcImg(x, y)]; } }else { // Perform colorful image transform vector<rgb> colorhist = calculateRGBHistogram(srcImg); float sum1 = 0, sum2 = 0, sum3 = 0; vector<rgb> thist; for(int i=0; i<256; i++){ thist.push_back(colorhist[i]); } // Adding for(int i=0; i<256; i++){ sum1 += thist[i].r; sum2 += thist[i].g; sum3 += thist[i].b; thist[i].r = (sum1 * 255 + 0.5f); thist[i].g = (sum2 * 255 + 0.5f); thist[i].b = (sum3 * 255 + 0.5f); } // Finish cimg_forXY(destImg, x, y){ destImg(x, y, 0) = (int)thist[srcImg(x, y, 0)].r; destImg(x, y, 1) = (int)thist[srcImg(x, y, 1)].g; destImg(x, y, 2) = (int)thist[srcImg(x, y, 2)].b; } } srcImg.display(); // Print histogram of input and output CImg<int> histImg = srcImg.histogram(256, 0, 255); histImg.display_graph("Source hist", 3); // Display final result destImg.display(); CImg<int> histdImg = destImg.histogram(256, 0, 255); histdImg.display_graph("Dest hist", 3); }
#pragma once #include <map> #include <string> #include <iberbar/Utility/Result.h> #include <iberbar/Poster/TextureScale9.h> #include <iberbar/Poster/Font.h> namespace iberbar { namespace Poster { class CSurface; class __iberbarExports__ CResourcesManager { public: CResourcesManager() {} ~CResourcesManager(); public: void SetFontDevice( CFontDeviceFreeType* fontDevice ) { m_fontDevice = fontDevice; } /* @cache ÊÇ·ñ»º´æÏÂÀ´ */ CResult GetTextureFromFile( const char* name, CSurface** ppOut, bool cache = true ); CResult GetTextureScale9( const char* filepath, CTextureScale9** ppOut ); CResult BuildTextureScale9( const char* filepath, const UTextureScale9Paddings& paddings ); CResult GetFont( const char* fontName, int fontSize, int fontWeight, CFont** ppOut ); CResult GetFont( const UFontDesc& fontDesc, CFont** ppOut ); void GC( bool clearAll ); private: std::map< std::string, PTR_CSurface > m_surfaces; std::map< std::string, PTR_CTextureScale9 > m_textureScale9s; std::list< PTR_CFont > m_fonts; PTR_CFontDeviceFreeType m_fontDevice; std::mutex m_mutex; //public: // static void sInit(); // static void sDestory(); // static CResourcesManager* sGetInstance() { return s_instance; } //private: // static CResourcesManager* s_instance; }; } }
#include "ros/ros.h" #include "std_msgs/String.h" #include "beginner_tutorials/Num.h" #include "custom_messages/driveMessage.h" #include "std_msgs/Float32.h" #include "std_msgs/Int16.h" #include "beginner_tutorials/driveCmd.h" #include "math.h" const float sampling_rate = 10; //sampling rate in hz const float ub = 5; // upper and lower bounds on control signal const float lb = -5; // same for throttle and steering as of now static float ff_vel = 0; //feed forward term for vel static float ff_steer = 0; //ff term for steer float SaturateSignal(float signal, const float lb, const float ub); // function to act as saturator //ros::Rate loop_rate(sampling_rate); float temp_steer_float; int temp_steer_int; void vp_listen(const std_msgs::Int16::ConstPtr& msg) { ROS_INFO("I Heard vp"); temp_steer_int = msg->data; temp_steer_float = 1.0*temp_steer_int; ff_vel = 0.4; } int main(int argc, char **argv) { ros::init(argc,argv,"PID_Euler"); ros::NodeHandle n; ros::Rate loop_rate(sampling_rate); // listen to sensor message in order to compute e(k) //Declare the publisher ros::Publisher pub_teleop = n.advertise<beginner_tutorials::driveCmd>("teleop_commands",1000); ros::Subscriber vp_subscribe = n.subscribe("vanishing_point_topic",1000,vp_listen); //The variable that has to be published beginner_tutorials::driveCmd tele_cmd; //sampling rate for PID using Euler float h = 1/sampling_rate; // variables for PID for velocity and steering static float u_km1_vel = 0; // u(k-1) static float u_k_vel = 0; // u(k) static float e_km1_vel = 0; // e(k-1) static float e_km2_vel = 0; // e(k-2) static float e_k_vel = 0; // e(k) static float u_km1_steer = 0; // u(k-1) static float u_k_steer = 0; // u(k) static float e_km1_steer = 0; // e(k-1) static float e_km2_steer = 0; // e(k-2) static float e_k_steer = 0; // e(k) // PID gains const float Kp_vel = 0; const float Kd_vel = 0; const float Ki_vel = 0; const float Kp_steer = 0.01; const float Kd_steer = 0; const float Ki_steer = 0; while(ros::ok()) { // PID for velocity // feed forward term if any for vel //ff_vel = 0.4; //error signal for velocity //progress time first, information is old e_km2_vel = e_km1_vel; e_km1_vel = e_k_vel; e_k_vel = 0; //compute e_k u_km1_vel = u_k_vel; u_k_vel = u_km1_vel + (1/h)*(Kp_vel*h + Kd_vel + Ki_vel*h*h)*e_k_vel + (1/h)*(-Kp_vel*h-2*Kd_vel)*e_km1_vel + (1/h)*Kd_vel*e_km2_vel; // PID for steering // feed forward term if any for steer ff_steer = 0; //error signal for steering //progress time first, information is old e_km2_steer = e_km1_steer; e_km1_steer = e_k_steer; e_k_steer = temp_steer_float; //compute e_k u_km1_steer = u_k_steer; u_k_steer = u_km1_steer + (1/h)*(Kp_steer*h + Kd_steer + Ki_steer*h*h)*e_k_steer + (1/h)*(-Kp_steer*h-2*Kd_steer)*e_km1_steer + (1/h)*Kd_steer*e_km2_steer; //check between -5 and +5 publish tele_cmd.steering = u_k_steer + ff_steer; tele_cmd.throttle = u_k_vel + ff_vel; tele_cmd.steering = SaturateSignal(tele_cmd.steering,ub,lb); // saturator tele_cmd.throttle = SaturateSignal(tele_cmd.throttle,ub,lb); ROS_INFO("Steering: %f; Throttle %f", tele_cmd.steering, tele_cmd.throttle); pub_teleop.publish(tele_cmd); // maintain rate ros::spinOnce(); loop_rate.sleep(); } } float SaturateSignal(float signal, const float ub, const float lb) { if(signal<=ub && signal>=lb) signal=signal; else if(signal>ub) signal = ub; else if(signal<lb) signal = lb; return signal; }