text
stringlengths
54
60.6k
<commit_before>// Copyright (c) 2016, LAAS-CNRS // Authors: Pierre Fernbach (pierre.fernbach@laas.fr) // // This file is part of hpp-core // hpp-core 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. // // hpp-core 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core If not, see // <http://www.gnu.org/licenses/>. #include <hpp/util/debug.hh> #include <hpp/model/device.hh> #include <hpp/core/config-projector.hh> #include <hpp/core/kinodynamic-path.hh> #include <hpp/core/projection-error.hh> namespace hpp { namespace core { KinodynamicPath::KinodynamicPath (const DevicePtr_t& device, ConfigurationIn_t init, ConfigurationIn_t end, value_type length, ConfigurationIn_t a1,ConfigurationIn_t t0, ConfigurationIn_t t1, ConfigurationIn_t tv, ConfigurationIn_t t2, ConfigurationIn_t vLim) : parent_t (device,init,end,length), a1_(a1),t0_(t0),t1_(t1),tv_(tv),t2_(t2),vLim_(vLim) { assert (device); assert (length >= 0); assert (!constraints ()); hppDout(notice,"Create kinodynamic path with values : "); hppDout(notice,"a1 = "<<model::displayConfig(a1_)); hppDout(notice,"t0 = "<<model::displayConfig(t0_)); hppDout(notice,"t1 = "<<model::displayConfig(t1_)); hppDout(notice,"tv = "<<model::displayConfig(tv_)); hppDout(notice,"t2 = "<<model::displayConfig(t2_)); hppDout(notice,"vLim = "<<model::displayConfig(vLim_)); } KinodynamicPath::KinodynamicPath (const DevicePtr_t& device, ConfigurationIn_t init, ConfigurationIn_t end, value_type length, ConfigurationIn_t a1, ConfigurationIn_t t0, ConfigurationIn_t t1, ConfigurationIn_t tv, ConfigurationIn_t t2, ConfigurationIn_t vLim, ConstraintSetPtr_t constraints) : parent_t (device,init,end,length,constraints), a1_(a1),t0_(t0),t1_(t1),tv_(tv),t2_(t2),vLim_(vLim) { assert (device); assert (length >= 0); } KinodynamicPath::KinodynamicPath (const KinodynamicPath& path) : parent_t (path),a1_(path.a1_),t0_(path.t0_),t1_(path.t1_),tv_(path.tv_),t2_(path.t2_),vLim_(path.vLim_) { } KinodynamicPath::KinodynamicPath (const KinodynamicPath& path, const ConstraintSetPtr_t& constraints) : parent_t (path, constraints), a1_(path.a1_),t0_(path.t0_),t1_(path.t1_),tv_(path.tv_),t2_(path.t2_),vLim_(path.vLim_) { assert (constraints->apply (initial_)); assert (constraints->apply (end_)); assert (constraints->isSatisfied (initial_)); assert (constraints->isSatisfied (end_)); } bool KinodynamicPath::impl_compute (ConfigurationOut_t result, value_type t) const { assert (result.size() == device()->configSize()); if (t == timeRange ().first || timeRange ().second == 0) { result = initial_; return true; } if (t == timeRange ().second) { result = end_; return true; } size_type configSize = device()->configSize() - device()->extraConfigSpace().dimension (); // const JointVector_t& jv (device()->getJointVector ()); double v2,t2,t1,tv; size_type indexVel; size_type indexAcc; // straight path for all the joints, except the translations of the base : value_type u = t/timeRange ().second; if (timeRange ().second == 0) u = 0; model::interpolate (device_, initial_, end_, u, result); //hppDout(notice,"path : initial = "<<model::displayConfig(initial_)); for(int id = 0 ; id < 3 ; id++){ // FIX ME : only work for freeflyer (translation part) //for (model::JointVector_t::const_iterator itJoint = jv.begin (); itJoint != jv.end (); itJoint++) { // size_type id = (*itJoint)->rankInConfiguration (); // size_type indexVel = (*itJoint)->rankInVelocity() + configSize; indexVel = id + configSize; indexAcc = id + configSize + 3; // hppDout(notice," PATH For joint "<<(*itJoint)->name()); // hppDout(notice,"PATH for joint :"<<device()->getJointAtConfigRank(id)->name()); if(device()->getJointAtConfigRank(id)->name() != "base_joint_SO3"){ //if((*itJoint)->configSize() >= 1){ // 3 case (each segment of the trajectory) : if(t <= t0_[id]){ // before first segment result[id] = initial_[id] + t*initial_[indexVel]; result[indexVel] = initial_[indexVel]; result[indexAcc] = 0; } else if(t <= (t0_[id] + t1_[id])){ // hppDout(info,"on 1° segment"); t1 = t - t0_[id]; result[id] = 0.5*t1*t1*a1_[id] + t1*initial_[indexVel] + initial_[id] + t0_[id]*initial_[indexVel]; result[indexVel] = t1*a1_[id] + initial_[indexVel]; result[indexAcc] = a1_[id]; }else if (t <= (t0_[id] + t1_[id] + tv_[id]) ){ // hppDout(info,"on constant velocity segment"); tv = t - t0_[id] - t1_[id]; result[id] = 0.5*t1_[id]*t1_[id]*a1_[id] + t1_[id]*initial_[indexVel] + initial_[id] + t0_[id]*initial_[indexVel] + (tv)*vLim_[id]; result[indexVel] = vLim_[id]; result[indexAcc] = 0.; }else if (t <= (t0_[id] + t1_[id] + tv_[id] +t2_[id]) ){ // hppDout(info,"on 3° segment"); t2 = t - tv_[id] - t1_[id] - t0_[id]; if(tv_[id] > 0 ) v2 = vLim_[id]; else v2 = t1_[id]*a1_[id] + initial_[indexVel]; result[id] = 0.5*t1_[id]*t1_[id]*a1_[id] + t1_[id]*initial_[indexVel] + initial_[id] + t0_[id]*initial_[indexVel] + tv_[id]*vLim_[id] - 0.5*t2*t2*a1_[id] + t2*v2; result[indexVel] = v2 - t2 * a1_[id]; result[indexAcc] = -a1_[id]; }else{ // after last segment result[id] = end_[id]; result[indexVel] = end_[indexVel]; result[indexAcc] = 0; } }// if not quaternion joint // }// if joint config size > 1 }// for all joints return true; } PathPtr_t KinodynamicPath::extract (const interval_t& subInterval) const throw (projection_error) { // Length is assumed to be proportional to interval range value_type l = fabs (subInterval.second - subInterval.first); hppDout(notice,"%% EXTRACT PATH :"); bool success; Configuration_t q1 ((*this) (subInterval.first, success)); if (!success) throw projection_error ("Failed to apply constraints in KinodynamicPath::extract"); Configuration_t q2 ((*this) (subInterval.second, success)); // set acceleration to 0 for initial and end config : size_type configSize = device()->configSize() - device()->extraConfigSpace().dimension (); q1[configSize+3] = 0.0; q1[configSize+4] = 0.0; q1[configSize+5] = 0.0; q2[configSize+3] = 0.0; q2[configSize+4] = 0.0; q2[configSize+5] = 0.0; hppDout(info,"from : "); hppDout(info,"q1 = "<<model::displayConfig(initial_)); hppDout(info,"q2 = "<<model::displayConfig(end_)); hppDout(info,"to : "); hppDout(info,"q1 = "<<model::displayConfig(q1)); hppDout(info,"q2 = "<<model::displayConfig(q2)); if (!success) throw projection_error ("Failed to apply constraints in KinodynamicPath::extract"); if(subInterval.first > subInterval.second){ // reversed path hppDout(notice,"%% REVERSE PATH, not implemented yet !"); std::cout<<"ERROR, you shouldn't call reverse() on a kinodynamic path"<<std::endl; return PathPtr_t(); } double ti,tf,oldT0,oldT2,oldT1,oldTv; hppDout(notice,"%% subinterval PATH"); // new timebounds Configuration_t t0(t0_); Configuration_t t1(t1_); Configuration_t t2(t2_); Configuration_t tv(tv_); Configuration_t a1(a1_); for(int i = 0 ; i < a1_.size() ; ++i){ // adjust times bounds ti = subInterval.first - timeRange_.first; tf = timeRange_.second - subInterval.second; t0[i] = t0_[i] - ti; if(t0[i] <= 0){ t0[i] = 0; ti = ti - t0_[i]; t1[i] = t1_[i] - ti; if(t1[i] <= 0){ t1[i] = 0; ti = ti - t1_[i]; tv[i] = tv_[i] - ti; if(tv[i] <= 0 ){ tv[i] = 0; ti = ti - tv_[i]; t2[i] = t2_[i] - ti; if(t2[i] <= 0) t2[i] = 0; } } } oldT0 = t0[i]; oldT1 = t1[i]; oldT2 = t2[i]; oldTv = tv[i]; t2[i] = oldT2 - tf; if(t2[i] <= 0 ){ t2[i] = 0 ; tf = tf - oldT2; tv[i] = oldTv - tf; if(tv[i] <= 0){ tv[i] = 0; tf = tf - oldTv; t1[i] = oldT1 - tf; if(t1[i] <= 0 ){ t1[i] = 0; tf = tf - oldT1; t0[i] = oldT0 - tf; } } } } // for all joints PathPtr_t result = KinodynamicPath::create (device_, q1, q2, l,a1,t0,t1,tv,t2,vLim_, constraints ()); return result; } } // namespace core } // namespace hpp <commit_msg>Add assertion in kinodynamicPath constructors<commit_after>// Copyright (c) 2016, LAAS-CNRS // Authors: Pierre Fernbach (pierre.fernbach@laas.fr) // // This file is part of hpp-core // hpp-core 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. // // hpp-core 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core If not, see // <http://www.gnu.org/licenses/>. #include <hpp/util/debug.hh> #include <hpp/model/device.hh> #include <hpp/core/config-projector.hh> #include <hpp/core/kinodynamic-path.hh> #include <hpp/core/projection-error.hh> namespace hpp { namespace core { KinodynamicPath::KinodynamicPath (const DevicePtr_t& device, ConfigurationIn_t init, ConfigurationIn_t end, value_type length, ConfigurationIn_t a1,ConfigurationIn_t t0, ConfigurationIn_t t1, ConfigurationIn_t tv, ConfigurationIn_t t2, ConfigurationIn_t vLim) : parent_t (device,init,end,length), a1_(a1),t0_(t0),t1_(t1),tv_(tv),t2_(t2),vLim_(vLim) { assert (device); assert (length >= 0); assert (!constraints ()); hppDout(notice,"Create kinodynamic path with values : "); hppDout(notice,"a1 = "<<model::displayConfig(a1_)); hppDout(notice,"t0 = "<<model::displayConfig(t0_)); hppDout(notice,"t1 = "<<model::displayConfig(t1_)); hppDout(notice,"tv = "<<model::displayConfig(tv_)); hppDout(notice,"t2 = "<<model::displayConfig(t2_)); hppDout(notice,"length = "<<length); hppDout(notice,"vLim = "<<model::displayConfig(vLim_)); // for now, this class only deal with the translation part of a freeflyer : assert(a1.size()==3 && t0.size()==3 && t1.size()==3 && tv.size()==3 && t2.size()==3 && vLim.size()==3 && "Inputs vector of kinodynamicPath are not of size 3"); for(size_t i = 3 ; i < 3 ; i++){ assert(fabs(length - (t0[i] + t1[i] + tv[i] + t2[i])) < std::numeric_limits <float>::epsilon () && "Kinodynamic path : length is not coherent with switch times"); } } KinodynamicPath::KinodynamicPath (const DevicePtr_t& device, ConfigurationIn_t init, ConfigurationIn_t end, value_type length, ConfigurationIn_t a1, ConfigurationIn_t t0, ConfigurationIn_t t1, ConfigurationIn_t tv, ConfigurationIn_t t2, ConfigurationIn_t vLim, ConstraintSetPtr_t constraints) : parent_t (device,init,end,length,constraints), a1_(a1),t0_(t0),t1_(t1),tv_(tv),t2_(t2),vLim_(vLim) { assert (device); assert (length >= 0); hppDout(notice,"Create kinodynamic path with constraints, with values : "); hppDout(notice,"a1 = "<<model::displayConfig(a1_)); hppDout(notice,"t0 = "<<model::displayConfig(t0_)); hppDout(notice,"t1 = "<<model::displayConfig(t1_)); hppDout(notice,"tv = "<<model::displayConfig(tv_)); hppDout(notice,"t2 = "<<model::displayConfig(t2_)); hppDout(notice,"length = "<<length); hppDout(notice,"vLim = "<<model::displayConfig(vLim_)); // for now, this class only deal with the translation part of a freeflyer : assert(a1.size()==3 && t0.size()==3 && t1.size()==3 && tv.size()==3 && t2.size()==3 && vLim.size()==3 && "Inputs vector of kinodynamicPath are not of size 3"); for(size_t i = 3 ; i < 3 ; i++){ assert(fabs(length - (t0[i] + t1[i] + tv[i] + t2[i])) < std::numeric_limits <float>::epsilon () && "Kinodynamic path : length is not coherent with switch times"); } } KinodynamicPath::KinodynamicPath (const KinodynamicPath& path) : parent_t (path),a1_(path.a1_),t0_(path.t0_),t1_(path.t1_),tv_(path.tv_),t2_(path.t2_),vLim_(path.vLim_) { } KinodynamicPath::KinodynamicPath (const KinodynamicPath& path, const ConstraintSetPtr_t& constraints) : parent_t (path, constraints), a1_(path.a1_),t0_(path.t0_),t1_(path.t1_),tv_(path.tv_),t2_(path.t2_),vLim_(path.vLim_) { assert (constraints->apply (initial_)); assert (constraints->apply (end_)); assert (constraints->isSatisfied (initial_)); assert (constraints->isSatisfied (end_)); } bool KinodynamicPath::impl_compute (ConfigurationOut_t result, value_type t) const { assert (result.size() == device()->configSize()); if (t == timeRange ().first || timeRange ().second == 0) { result = initial_; return true; } if (t == timeRange ().second) { result = end_; return true; } size_type configSize = device()->configSize() - device()->extraConfigSpace().dimension (); // const JointVector_t& jv (device()->getJointVector ()); double v2,t2,t1,tv; size_type indexVel; size_type indexAcc; // straight path for all the joints, except the translations of the base : value_type u = t/timeRange ().second; if (timeRange ().second == 0) u = 0; model::interpolate (device_, initial_, end_, u, result); //hppDout(notice,"path : initial = "<<model::displayConfig(initial_)); for(int id = 0 ; id < 3 ; id++){ // FIX ME : only work for freeflyer (translation part) //for (model::JointVector_t::const_iterator itJoint = jv.begin (); itJoint != jv.end (); itJoint++) { // size_type id = (*itJoint)->rankInConfiguration (); // size_type indexVel = (*itJoint)->rankInVelocity() + configSize; indexVel = id + configSize; indexAcc = id + configSize + 3; // hppDout(notice," PATH For joint "<<(*itJoint)->name()); // hppDout(notice,"PATH for joint :"<<device()->getJointAtConfigRank(id)->name()); if(device()->getJointAtConfigRank(id)->name() != "base_joint_SO3"){ //if((*itJoint)->configSize() >= 1){ // 3 case (each segment of the trajectory) : if(t <= t0_[id]){ // before first segment result[id] = initial_[id] + t*initial_[indexVel]; result[indexVel] = initial_[indexVel]; result[indexAcc] = 0; } else if(t <= (t0_[id] + t1_[id])){ // hppDout(info,"on 1° segment"); t1 = t - t0_[id]; result[id] = 0.5*t1*t1*a1_[id] + t1*initial_[indexVel] + initial_[id] + t0_[id]*initial_[indexVel]; result[indexVel] = t1*a1_[id] + initial_[indexVel]; result[indexAcc] = a1_[id]; }else if (t <= (t0_[id] + t1_[id] + tv_[id]) ){ // hppDout(info,"on constant velocity segment"); tv = t - t0_[id] - t1_[id]; result[id] = 0.5*t1_[id]*t1_[id]*a1_[id] + t1_[id]*initial_[indexVel] + initial_[id] + t0_[id]*initial_[indexVel] + (tv)*vLim_[id]; result[indexVel] = vLim_[id]; result[indexAcc] = 0.; }else if (t <= (t0_[id] + t1_[id] + tv_[id] +t2_[id]) ){ // hppDout(info,"on 3° segment"); t2 = t - tv_[id] - t1_[id] - t0_[id]; if(tv_[id] > 0 ) v2 = vLim_[id]; else v2 = t1_[id]*a1_[id] + initial_[indexVel]; result[id] = 0.5*t1_[id]*t1_[id]*a1_[id] + t1_[id]*initial_[indexVel] + initial_[id] + t0_[id]*initial_[indexVel] + tv_[id]*vLim_[id] - 0.5*t2*t2*a1_[id] + t2*v2; result[indexVel] = v2 - t2 * a1_[id]; result[indexAcc] = -a1_[id]; }else{ // after last segment result[id] = end_[id]; result[indexVel] = end_[indexVel]; result[indexAcc] = 0; } }// if not quaternion joint // }// if joint config size > 1 }// for all joints return true; } PathPtr_t KinodynamicPath::extract (const interval_t& subInterval) const throw (projection_error) { // Length is assumed to be proportional to interval range value_type l = fabs (subInterval.second - subInterval.first); hppDout(notice,"%% EXTRACT PATH :"); bool success; Configuration_t q1 ((*this) (subInterval.first, success)); if (!success) throw projection_error ("Failed to apply constraints in KinodynamicPath::extract"); Configuration_t q2 ((*this) (subInterval.second, success)); // set acceleration to 0 for initial and end config : size_type configSize = device()->configSize() - device()->extraConfigSpace().dimension (); q1[configSize+3] = 0.0; q1[configSize+4] = 0.0; q1[configSize+5] = 0.0; q2[configSize+3] = 0.0; q2[configSize+4] = 0.0; q2[configSize+5] = 0.0; hppDout(info,"from : "); hppDout(info,"q1 = "<<model::displayConfig(initial_)); hppDout(info,"q2 = "<<model::displayConfig(end_)); hppDout(info,"to : "); hppDout(info,"q1 = "<<model::displayConfig(q1)); hppDout(info,"q2 = "<<model::displayConfig(q2)); if (!success) throw projection_error ("Failed to apply constraints in KinodynamicPath::extract"); if(subInterval.first > subInterval.second){ // reversed path hppDout(notice,"%% REVERSE PATH, not implemented yet !"); std::cout<<"ERROR, you shouldn't call reverse() on a kinodynamic path"<<std::endl; return PathPtr_t(); } double ti,tf,oldT0,oldT2,oldT1,oldTv; hppDout(notice,"%% subinterval PATH"); // new timebounds Configuration_t t0(t0_); Configuration_t t1(t1_); Configuration_t t2(t2_); Configuration_t tv(tv_); Configuration_t a1(a1_); for(int i = 0 ; i < a1_.size() ; ++i){ // adjust times bounds ti = subInterval.first - timeRange_.first; tf = timeRange_.second - subInterval.second; t0[i] = t0_[i] - ti; if(t0[i] <= 0){ t0[i] = 0; ti = ti - t0_[i]; t1[i] = t1_[i] - ti; if(t1[i] <= 0){ t1[i] = 0; ti = ti - t1_[i]; tv[i] = tv_[i] - ti; if(tv[i] <= 0 ){ tv[i] = 0; ti = ti - tv_[i]; t2[i] = t2_[i] - ti; if(t2[i] <= 0) t2[i] = 0; } } } oldT0 = t0[i]; oldT1 = t1[i]; oldT2 = t2[i]; oldTv = tv[i]; t2[i] = oldT2 - tf; if(t2[i] <= 0 ){ t2[i] = 0 ; tf = tf - oldT2; tv[i] = oldTv - tf; if(tv[i] <= 0){ tv[i] = 0; tf = tf - oldTv; t1[i] = oldT1 - tf; if(t1[i] <= 0 ){ t1[i] = 0; tf = tf - oldT1; t0[i] = oldT0 - tf; } } } } // for all joints PathPtr_t result = KinodynamicPath::create (device_, q1, q2, l,a1,t0,t1,tv,t2,vLim_, constraints ()); return result; } } // namespace core } // namespace hpp <|endoftext|>
<commit_before>/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2016 INRIA. * * 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 "SiconosConfig.h" #ifdef SICONOS_INT64 #define CS_LONG #endif #include "cs.h" #include "SiconosMatrix.hpp" #include "SiconosAlgebra.hpp" #include <boost/numeric/ublas/matrix_sparse.hpp> #include "BlockMatrix.hpp" // Constructor with the type-number SiconosMatrix::SiconosMatrix(unsigned int type): _num(type) {} const SP::Index SiconosMatrix::tabRow() const { SiconosMatrixException::selfThrow("SiconosMatrix::tabRow() : not implemented for this type of matrix (Simple?) reserved to BlockMatrix."); // fake to avoid error on warning. return SP::Index(); } const SP::Index SiconosMatrix::tabCol() const { SiconosMatrixException::selfThrow("SiconosMatrix::tabCol() : not implemented for this type of matrix (Simple?) reserved to BlockMatrix."); // fake to avoid error on warning. return SP::Index(); } //===================== // matrices comparison //===================== bool isComparableTo(const SiconosMatrix& m1, const SiconosMatrix& m2) { // return: // - true if one of the matrices is a Simple and if they have the same dimensions. // - true if both are block but with blocks which are facing each other of the same size. // - false in other cases if ((!m1.isBlock() || !m2.isBlock()) && (m1.size(0) == m2.size(0)) && (m1.size(1) == m2.size(1))) return true; const SP::Index I1R = m1.tabRow(); const SP::Index I2R = m2.tabRow(); const SP::Index I1C = m1.tabCol(); const SP::Index I2C = m2.tabCol(); return ((*I1R == *I2R) && (*I1C == *I2C)); } SiconosMatrix& operator *=(SiconosMatrix& m, const double& s) { if (m._num == 0) // BlockMatrix { BlockMatrix& mB = static_cast<BlockMatrix&>(m); BlocksMat::iterator1 it; BlocksMat::iterator2 it2; for (it = mB._mat->begin1(); it != mB._mat->end1(); ++it) { for (it2 = it.begin(); it2 != it.end(); ++it2) (**it2) *= s; } } else if (m._num == 1) *m.dense() *= s; else if (m._num == 2) *m.triang() *= s; else if (m._num == 3) *m.sym() *= s; else if (m._num == 4) *m.sparse() *= s; else if (m._num == 5) *m.banded() *= s; else if (m._num == 6) {} // nothing! else //if(_num == 7) SiconosMatrixException::selfThrow(" SP::SiconosMatrix = (double) : invalid type of matrix"); return m; } SiconosMatrix& operator /=(SiconosMatrix& m, const double& s) { if (m._num == 0) // BlockMatrix { BlockMatrix& mB = static_cast<BlockMatrix&>(m); BlocksMat::iterator1 it; BlocksMat::iterator2 it2; for (it = mB._mat->begin1(); it != mB._mat->end1(); ++it) { for (it2 = it.begin(); it2 != it.end(); ++it2) (**it2) /= s; } } else if (m._num == 1) *m.dense() /= s; else if (m._num == 2) *m.triang() /= s; else if (m._num == 3) *m.sym() /= s; else if (m._num == 4) *m.sparse() /= s; else if (m._num == 5) *m.banded() /= s; else if (m._num == 6) {} // nothing! else //if(_num == 7) SiconosMatrixException::selfThrow(" SiconosMatrix *= (double) : invalid type of matrix"); return m; } size_t SiconosMatrix::nnz(double tol) { size_t nnz = 0; if (_num == 1) //dense { double* arr = getArray(); for (size_t i = 0; i < size(0)*size(1); ++i) { if (fabs(arr[i]) > tol) { nnz++; } } } else if (_num == 4) { nnz = sparse()->nnz(); } else { SiconosMatrixException::selfThrow("SiconosMatrix::nnz not implemented for the given matrix type"); } return nnz; } bool SiconosMatrix::fillCSC(CSparseMatrix* csc, size_t row_off, size_t col_off, double tol) { assert(csc); double* Mx = csc->x; // data CS_INT* Mi = csc->i; // row indx CS_INT* Mp = csc->p; // column pointers assert(Mp[col_off] >= 0); size_t nz = csc->p[col_off]; size_t nrow = size(0); size_t ncol = size(1); CS_INT pval = Mp[col_off]; if (_num == 1) //dense { double* arr = getArray(); for (size_t j = 0, joff = col_off; j < ncol; ++j) { for (size_t i = 0; i < nrow; ++i) { // col-major double elt_val = arr[i + j*nrow]; // std::cout << " a(i=" << i << ",j=" << j << ") = "<< elt_val << std::endl; if (fabs(elt_val) > tol) { Mx[pval] = elt_val; Mi[pval] = i + row_off; // std::cout << "Mx[" <<pval <<"] = " << Mx[pval]<< std::endl; // std::cout << "Mp[" <<pval <<"] = " << Mi[pval]<< std::endl; ++pval; } } // std::cout << "joff" << joff << std::endl; Mp[++joff] = pval; } } else if (_num == 4) { const Index& ptr = sparse()->index1_data(); const Index& indx = sparse()->index2_data(); const ublas::unbounded_array<double>& vals = sparse()->value_data(); size_t nnz = sparse()->nnz(); assert(ptr.size() == ncol + 1); assert(indx.size() == nnz); assert(vals.size() == nnz); for (size_t i = 0; i < nnz; ++i) { Mx[pval] = vals[i]; Mi[pval++] = row_off + indx[i]; } for (size_t j = 1, joff = col_off + 1; j < ncol+1; ++j, ++joff) { Mp[joff] = nz + ptr[j]; } } else { SiconosMatrixException::selfThrow("SiconosMatrix::fillCSC not implemented for the given matrix type"); } return true; } bool SiconosMatrix::fillTriplet(CSparseMatrix* triplet, size_t row_off, size_t col_off, double tol) { assert(triplet); size_t nrow = size(0); size_t ncol = size(1); if (_num == 1) //dense { double* arr = getArray(); for (size_t j = 0; j < ncol; ++j) { for (size_t i = 0; i < nrow; ++i) { // col-major cs_zentry(triplet, i + row_off, j + col_off, arr[i + j*nrow] ); } } } else { SiconosMatrixException::selfThrow("SiconosMatrix::fillCSC not implemented for the given matrix type"); } return true; } std::ostream& operator<<(std::ostream& os, const SiconosMatrix& sm) { os << sm.toString(); return os; } <commit_msg>[kernel] disable complex part of CXSparse when using from C++.<commit_after>/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2016 INRIA. * * 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 "SiconosConfig.h" #ifdef SICONOS_INT64 #define CS_LONG #endif #define NCOMPLEX #include "cs.h" #include "SiconosMatrix.hpp" #include "SiconosAlgebra.hpp" #include <boost/numeric/ublas/matrix_sparse.hpp> #include "BlockMatrix.hpp" // Constructor with the type-number SiconosMatrix::SiconosMatrix(unsigned int type): _num(type) {} const SP::Index SiconosMatrix::tabRow() const { SiconosMatrixException::selfThrow("SiconosMatrix::tabRow() : not implemented for this type of matrix (Simple?) reserved to BlockMatrix."); // fake to avoid error on warning. return SP::Index(); } const SP::Index SiconosMatrix::tabCol() const { SiconosMatrixException::selfThrow("SiconosMatrix::tabCol() : not implemented for this type of matrix (Simple?) reserved to BlockMatrix."); // fake to avoid error on warning. return SP::Index(); } //===================== // matrices comparison //===================== bool isComparableTo(const SiconosMatrix& m1, const SiconosMatrix& m2) { // return: // - true if one of the matrices is a Simple and if they have the same dimensions. // - true if both are block but with blocks which are facing each other of the same size. // - false in other cases if ((!m1.isBlock() || !m2.isBlock()) && (m1.size(0) == m2.size(0)) && (m1.size(1) == m2.size(1))) return true; const SP::Index I1R = m1.tabRow(); const SP::Index I2R = m2.tabRow(); const SP::Index I1C = m1.tabCol(); const SP::Index I2C = m2.tabCol(); return ((*I1R == *I2R) && (*I1C == *I2C)); } SiconosMatrix& operator *=(SiconosMatrix& m, const double& s) { if (m._num == 0) // BlockMatrix { BlockMatrix& mB = static_cast<BlockMatrix&>(m); BlocksMat::iterator1 it; BlocksMat::iterator2 it2; for (it = mB._mat->begin1(); it != mB._mat->end1(); ++it) { for (it2 = it.begin(); it2 != it.end(); ++it2) (**it2) *= s; } } else if (m._num == 1) *m.dense() *= s; else if (m._num == 2) *m.triang() *= s; else if (m._num == 3) *m.sym() *= s; else if (m._num == 4) *m.sparse() *= s; else if (m._num == 5) *m.banded() *= s; else if (m._num == 6) {} // nothing! else //if(_num == 7) SiconosMatrixException::selfThrow(" SP::SiconosMatrix = (double) : invalid type of matrix"); return m; } SiconosMatrix& operator /=(SiconosMatrix& m, const double& s) { if (m._num == 0) // BlockMatrix { BlockMatrix& mB = static_cast<BlockMatrix&>(m); BlocksMat::iterator1 it; BlocksMat::iterator2 it2; for (it = mB._mat->begin1(); it != mB._mat->end1(); ++it) { for (it2 = it.begin(); it2 != it.end(); ++it2) (**it2) /= s; } } else if (m._num == 1) *m.dense() /= s; else if (m._num == 2) *m.triang() /= s; else if (m._num == 3) *m.sym() /= s; else if (m._num == 4) *m.sparse() /= s; else if (m._num == 5) *m.banded() /= s; else if (m._num == 6) {} // nothing! else //if(_num == 7) SiconosMatrixException::selfThrow(" SiconosMatrix *= (double) : invalid type of matrix"); return m; } size_t SiconosMatrix::nnz(double tol) { size_t nnz = 0; if (_num == 1) //dense { double* arr = getArray(); for (size_t i = 0; i < size(0)*size(1); ++i) { if (fabs(arr[i]) > tol) { nnz++; } } } else if (_num == 4) { nnz = sparse()->nnz(); } else { SiconosMatrixException::selfThrow("SiconosMatrix::nnz not implemented for the given matrix type"); } return nnz; } bool SiconosMatrix::fillCSC(CSparseMatrix* csc, size_t row_off, size_t col_off, double tol) { assert(csc); double* Mx = csc->x; // data CS_INT* Mi = csc->i; // row indx CS_INT* Mp = csc->p; // column pointers assert(Mp[col_off] >= 0); size_t nz = csc->p[col_off]; size_t nrow = size(0); size_t ncol = size(1); CS_INT pval = Mp[col_off]; if (_num == 1) //dense { double* arr = getArray(); for (size_t j = 0, joff = col_off; j < ncol; ++j) { for (size_t i = 0; i < nrow; ++i) { // col-major double elt_val = arr[i + j*nrow]; // std::cout << " a(i=" << i << ",j=" << j << ") = "<< elt_val << std::endl; if (fabs(elt_val) > tol) { Mx[pval] = elt_val; Mi[pval] = i + row_off; // std::cout << "Mx[" <<pval <<"] = " << Mx[pval]<< std::endl; // std::cout << "Mp[" <<pval <<"] = " << Mi[pval]<< std::endl; ++pval; } } // std::cout << "joff" << joff << std::endl; Mp[++joff] = pval; } } else if (_num == 4) { const Index& ptr = sparse()->index1_data(); const Index& indx = sparse()->index2_data(); const ublas::unbounded_array<double>& vals = sparse()->value_data(); size_t nnz = sparse()->nnz(); assert(ptr.size() == ncol + 1); assert(indx.size() == nnz); assert(vals.size() == nnz); for (size_t i = 0; i < nnz; ++i) { Mx[pval] = vals[i]; Mi[pval++] = row_off + indx[i]; } for (size_t j = 1, joff = col_off + 1; j < ncol+1; ++j, ++joff) { Mp[joff] = nz + ptr[j]; } } else { SiconosMatrixException::selfThrow("SiconosMatrix::fillCSC not implemented for the given matrix type"); } return true; } bool SiconosMatrix::fillTriplet(CSparseMatrix* triplet, size_t row_off, size_t col_off, double tol) { assert(triplet); size_t nrow = size(0); size_t ncol = size(1); if (_num == 1) //dense { double* arr = getArray(); for (size_t j = 0; j < ncol; ++j) { for (size_t i = 0; i < nrow; ++i) { // col-major cs_zentry(triplet, i + row_off, j + col_off, arr[i + j*nrow] ); } } } else { SiconosMatrixException::selfThrow("SiconosMatrix::fillCSC not implemented for the given matrix type"); } return true; } std::ostream& operator<<(std::ostream& os, const SiconosMatrix& sm) { os << sm.toString(); return os; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: lateinitthread.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 21:30:47 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library 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 for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef __FILTER_CONFIG_LATEINITTHREAD_HXX_ #define __FILTER_CONFIG_LATEINITTHREAD_HXX_ //_______________________________________________ // includes #include "filtercache.hxx" #ifndef _SALHELPER_SINGLETONREF_HXX_ #include <salhelper/singletonref.hxx> #endif #ifndef _THREAD_HXX_ #include <osl/thread.hxx> #endif //_______________________________________________ // namespace namespace filter{ namespace config{ //_______________________________________________ // definitions //_______________________________________________ /** @short implements a thread, which will update the global filter cache of an office, after its startup was finished. @descr Its started by a LateInitListener instance ... @see LateInitListener @attention The filter cache will be blocked during this thrad runs! */ class LateInitThread : public ::osl::Thread { //------------------------------------------- // native interface public: //--------------------------------------- // ctor/dtor /** @short initialize new instance of this class. */ LateInitThread(); //--------------------------------------- /** @short standard dtor. */ virtual ~LateInitThread(); //--------------------------------------- /** @short thread function. */ virtual void SAL_CALL run(); }; } // namespace config } // namespace filter #endif // __FILTER_CONFIG_LATEINITTHREAD_HXX_ <commit_msg>INTEGRATION: CWS changefileheader (1.4.430); FILE MERGED 2008/04/01 15:15:53 thb 1.4.430.2: #i85898# Stripping all external header guards 2008/03/28 15:31:03 rt 1.4.430.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: lateinitthread.hxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef __FILTER_CONFIG_LATEINITTHREAD_HXX_ #define __FILTER_CONFIG_LATEINITTHREAD_HXX_ //_______________________________________________ // includes #include "filtercache.hxx" #include <salhelper/singletonref.hxx> #include <osl/thread.hxx> //_______________________________________________ // namespace namespace filter{ namespace config{ //_______________________________________________ // definitions //_______________________________________________ /** @short implements a thread, which will update the global filter cache of an office, after its startup was finished. @descr Its started by a LateInitListener instance ... @see LateInitListener @attention The filter cache will be blocked during this thrad runs! */ class LateInitThread : public ::osl::Thread { //------------------------------------------- // native interface public: //--------------------------------------- // ctor/dtor /** @short initialize new instance of this class. */ LateInitThread(); //--------------------------------------- /** @short standard dtor. */ virtual ~LateInitThread(); //--------------------------------------- /** @short thread function. */ virtual void SAL_CALL run(); }; } // namespace config } // namespace filter #endif // __FILTER_CONFIG_LATEINITTHREAD_HXX_ <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2008-2013, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and / or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_PRECOMP_H__ #define __OPENCV_PRECOMP_H__ #include "opencv2/softcascade.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/core/private.hpp" #include "opencv2/core/private.gpu.hpp" namespace cv { namespace softcascade { namespace internal { namespace rnd { typedef cv::RNG_MT19937 engine; template<typename T> struct uniform_int { uniform_int(const int _min, const int _max) : min(_min), max(_max) {} T operator() (engine& eng, const int bound) const { return (T)eng.uniform(min, bound); } T operator() (engine& eng) const { return (T)eng.uniform(min, max); } private: int min; int max; }; } struct Random { typedef rnd::engine engine; typedef uint64 seed_type; typedef rnd::uniform_int<int> uniform; }; }}} #define FEATURE_RECT_SEED 88543422U #define INDEX_ENGINE_SEED 76422434U #define DCHANNELS_SEED 314152314U #define DX_DY_SEED 65633343U #endif <commit_msg>added missing <iostream> header<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2008-2013, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and / or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_PRECOMP_H__ #define __OPENCV_PRECOMP_H__ #include <iostream> #include "opencv2/softcascade.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/core/private.hpp" #include "opencv2/core/private.gpu.hpp" namespace cv { namespace softcascade { namespace internal { namespace rnd { typedef cv::RNG_MT19937 engine; template<typename T> struct uniform_int { uniform_int(const int _min, const int _max) : min(_min), max(_max) {} T operator() (engine& eng, const int bound) const { return (T)eng.uniform(min, bound); } T operator() (engine& eng) const { return (T)eng.uniform(min, max); } private: int min; int max; }; } struct Random { typedef rnd::engine engine; typedef uint64 seed_type; typedef rnd::uniform_int<int> uniform; }; }}} #define FEATURE_RECT_SEED 88543422U #define INDEX_ENGINE_SEED 76422434U #define DCHANNELS_SEED 314152314U #define DX_DY_SEED 65633343U #endif <|endoftext|>
<commit_before>#ifndef MJOLNIR_READ_SIMULATOR #define MJOLNIR_READ_SIMULATOR #include <extlib/toml/toml.hpp> #include <mjolnir/core/MolecularDynamicsSimulator.hpp> #include <mjolnir/core/SteepestDescentSimulator.hpp> #include <mjolnir/core/SimulatedAnnealingSimulator.hpp> #include <mjolnir/util/make_unique.hpp> #include <mjolnir/util/throw_exception.hpp> #include <mjolnir/util/logger.hpp> #include <mjolnir/input/read_system.hpp> #include <mjolnir/input/read_forcefield.hpp> #include <mjolnir/input/read_integrator.hpp> #include <mjolnir/input/read_observer.hpp> #include <mjolnir/input/read_files_table.hpp> namespace mjolnir { template<typename traitsT> std::unique_ptr<SimulatorBase> read_molecular_dynamics_simulator( const toml::table& root, const toml::value& simulator) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_SCOPE(read_molecular_dynamics_simulator(), 0); using real_type = typename traitsT::real_type; const auto integrator = toml::find<std::string>(simulator, "integrator"); const auto tstep = toml::find<std::size_t>(simulator, "total_step"); const auto sstep = toml::find<std::size_t>(simulator, "save_step"); MJOLNIR_LOG_NOTICE("total step is ", tstep); MJOLNIR_LOG_NOTICE("save step is ", sstep); if(integrator == "Newtonian") { MJOLNIR_LOG_NOTICE("Integrator is Newtonian."); using integrator_t = VelocityVerletStepper<traitsT>; using simulator_t = MolecularDynamicsSimulator<traitsT, integrator_t>; return make_unique<simulator_t>( tstep, sstep, read_system<traitsT>(root, 0), read_forcefield<traitsT>(root, 0), read_velocity_verlet_stepper<traitsT>(simulator), read_observer<traitsT>(root)); } else if(integrator == "Underdamped Langevin") { MJOLNIR_LOG_NOTICE("Integrator is Underdamped Langevin."); using integrator_t = UnderdampedLangevinStepper<traitsT>; using simulator_t = MolecularDynamicsSimulator<traitsT, integrator_t>; return make_unique<simulator_t>( tstep, sstep, read_system<traitsT>(root, 0), read_forcefield<traitsT>(root, 0), read_underdamped_langevin_stepper<traitsT>(simulator), read_observer<traitsT>(root)); } else { throw_exception<std::runtime_error>(toml::format_error("[error] " "mjolnir::read_molecular_dynamics_simulator: invalid integrator: ", toml::find(simulator, "integrator"), "here", { "expected value is one of the following.", "- \"Newtonian\" : simple and standard Velocity Verlet integrator.", "- \"Underdamped Langevin\": simple Underdamped Langevin Integrator" " based on the Velocity Verlet" })); } } template<typename traitsT> std::unique_ptr<SimulatorBase> read_steepest_descent_simulator( const toml::table& root, const toml::value& simulator) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_SCOPE(read_steepest_descent_simulator(), 0); using real_type = typename traitsT::real_type; using simulator_type = SteepestDescentSimulator<traitsT>; const auto step_lim = toml::find<std::size_t>(simulator, "step_limit"); const auto save_step = toml::find<std::size_t>(simulator, "save_step"); const auto delta = toml::find<real_type >(simulator, "delta"); const auto threshold = toml::find<real_type >(simulator, "threshold"); MJOLNIR_LOG_NOTICE("step_limit is ", step_lim); MJOLNIR_LOG_NOTICE("save_step is ", save_step); MJOLNIR_LOG_NOTICE("delta is ", delta); MJOLNIR_LOG_NOTICE("threshold is ", threshold); return make_unique<simulator_type>( delta, threshold, step_lim, save_step, read_system<traitsT>(root, 0), read_forcefield<traitsT>(root, 0), read_observer<traitsT>(root)); } template<typename traitsT> std::unique_ptr<SimulatorBase> read_simulated_annealing_simulator( const toml::table& root, const toml::value& simulator) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_SCOPE(read_simulated_annealing_simulator(), 0); using real_type = typename traitsT::real_type; const auto integrator = toml::find<std::string>(simulator, "integrator"); const auto tstep = toml::find<std::size_t>(simulator, "total_step"); const auto sstep = toml::find<std::size_t>(simulator, "save_step"); MJOLNIR_LOG_NOTICE("total step is ", tstep); MJOLNIR_LOG_NOTICE("save step is ", sstep); const auto schedule = toml::find<std::string>(simulator, "schedule"); const auto T_begin = toml::find<real_type> (simulator, "T_begin"); const auto T_end = toml::find<real_type> (simulator, "T_end"); const auto each_step = toml::find<std::size_t>(simulator, "each_step"); MJOLNIR_LOG_NOTICE("temperature from ", T_begin); MJOLNIR_LOG_NOTICE("temperature to ", T_end); MJOLNIR_LOG_INFO("update temperature for each ", each_step, " steps"); if(schedule == "linear") { MJOLNIR_LOG_NOTICE("temparing schedule is linear."); if(integrator == "Newtonian") { MJOLNIR_LOG_ERROR("Simulated Annealing + NVE Newtonian"); MJOLNIR_LOG_ERROR("NVE Newtonian doesn't have temperature control."); throw_exception<std::runtime_error>(toml::format_error("[error] " "mjolnir::read_simulated_annealing_simulator: invalid integrator: ", toml::find(simulator, "integrator"), "here", { "Newtonian Integrator does not controls temperature." "expected value is one of the following.", "- \"Underdamped Langevin\": simple Underdamped Langevin Integrator" " based on the Velocity Verlet" })); } else if(integrator == "Underdamped Langevin") { using integrator_t = UnderdampedLangevinStepper<traitsT>; using simulator_t = SimulatedAnnealingSimulator< traitsT, integrator_t, linear_schedule>; MJOLNIR_LOG_NOTICE("Integrator is Underdamped Langevin."); return make_unique<simulator_t>(tstep, sstep, each_step, linear_schedule<real_type>(T_begin, T_end), read_system<traitsT>(root, 0), read_forcefield<traitsT>(root, 0), read_underdamped_langevin_stepper<traitsT>(simulator), read_observer<traitsT>(root)); } else { throw_exception<std::runtime_error>(toml::format_error("[error] " "mjolnir::read_simulated_annealing_simulator: invalid integrator: ", toml::find(simulator, "integrator"), "here", { "expected value is one of the following.", "- \"Underdamped Langevin\": simple Underdamped Langevin Integrator" " based on the Velocity Verlet" })); } } else { throw_exception<std::runtime_error>(toml::format_error("[error] " "mjolnir::read_simulated_annealing_simulator: invalid schedule", toml::find<toml::value>(simulator, "schedule"), "here", { "expected value is one of the following.", "- \"linear\" : simple linear temperature scheduling", })); } } template<typename traitsT> std::unique_ptr<SimulatorBase> read_simulator_from_table(const toml::table& root, const toml::value& simulator) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_SCOPE(read_simulator_from_table(), 0); const auto type = toml::find<std::string>(simulator, "type"); if(type == "Molecular Dynamics") { MJOLNIR_LOG_NOTICE("Simulator type is Molecular Dynamics."); return read_molecular_dynamics_simulator<traitsT>(root, simulator); } else if(type == "Steepest Descent") { MJOLNIR_LOG_NOTICE("Simulator type is Steepest Descent."); return read_steepest_descent_simulator<traitsT>(root, simulator); } else if(type == "Simulated Annealing") { MJOLNIR_LOG_NOTICE("Simulator type is Simulated Annealing."); return read_simulated_annealing_simulator<traitsT>(root, simulator); } else { throw_exception<std::runtime_error>(toml::format_error("[error] " "mjolnir::read_simulator: invalid type", toml::find<toml::value>(simulator, "type"), "here", { "expected value is one of the following.", "- \"Molecular Dynamcis\" : standard MD simulation", "- \"Steepest Descent\" : energy minimization by gradient method", "- \"Simulated Annealing\": energy minimization by Annealing", })); } } template<typename traitsT> std::unique_ptr<SimulatorBase> read_simulator(const toml::table& root) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_SCOPE(read_simulator(), 0); using real_type = typename traitsT::real_type; const auto& simulator = toml::find(root, "simulator"); if(toml::get<toml::table>(simulator).count("file_name") == 1) { MJOLNIR_SCOPE(simulator.count("file_name") == 1, 1); const auto input_path = read_input_path(root); const auto file_name = toml::find<std::string>(simulator, "file_name"); MJOLNIR_LOG_INFO("file_name = ", file_name); if(toml::get<toml::table>(simulator).size() != 1) { MJOLNIR_LOG_WARN("[simulator] has `file_name` key and other keys."); MJOLNIR_LOG_WARN("When `file_name` is provided, other values are " "ignored because those are read from the specified" " file (", input_path, file_name, ")."); } MJOLNIR_LOG_NOTICE("simulator is defined in ", input_path, file_name); const auto simfile = toml::parse(input_path + file_name); if(simfile.count("simulator") != 1) { throw_exception<std::out_of_range>("[error] mjolnir::read_simulator: " "table [simulator] not found in the toml file\n --> ", input_path, file_name, "\n | the file should define [simulator] " "table and define values in it."); } return read_simulator_from_table<traitsT>(root, simfile.at("simulator")); } else { return read_simulator_from_table<traitsT>(root, simulator); } } } // mjolnir #endif// MJOLNIR_READ_SIMULATOR <commit_msg>add log_notice to read_simulator<commit_after>#ifndef MJOLNIR_READ_SIMULATOR #define MJOLNIR_READ_SIMULATOR #include <extlib/toml/toml.hpp> #include <mjolnir/core/MolecularDynamicsSimulator.hpp> #include <mjolnir/core/SteepestDescentSimulator.hpp> #include <mjolnir/core/SimulatedAnnealingSimulator.hpp> #include <mjolnir/util/make_unique.hpp> #include <mjolnir/util/throw_exception.hpp> #include <mjolnir/util/logger.hpp> #include <mjolnir/input/read_system.hpp> #include <mjolnir/input/read_forcefield.hpp> #include <mjolnir/input/read_integrator.hpp> #include <mjolnir/input/read_observer.hpp> #include <mjolnir/input/read_files_table.hpp> namespace mjolnir { template<typename traitsT> std::unique_ptr<SimulatorBase> read_molecular_dynamics_simulator( const toml::table& root, const toml::value& simulator) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_SCOPE(read_molecular_dynamics_simulator(), 0); using real_type = typename traitsT::real_type; const auto integrator = toml::find<std::string>(simulator, "integrator"); const auto tstep = toml::find<std::size_t>(simulator, "total_step"); const auto sstep = toml::find<std::size_t>(simulator, "save_step"); MJOLNIR_LOG_NOTICE("total step is ", tstep); MJOLNIR_LOG_NOTICE("save step is ", sstep); if(integrator == "Newtonian") { MJOLNIR_LOG_NOTICE("Integrator is Newtonian."); using integrator_t = VelocityVerletStepper<traitsT>; using simulator_t = MolecularDynamicsSimulator<traitsT, integrator_t>; return make_unique<simulator_t>( tstep, sstep, read_system<traitsT>(root, 0), read_forcefield<traitsT>(root, 0), read_velocity_verlet_stepper<traitsT>(simulator), read_observer<traitsT>(root)); } else if(integrator == "Underdamped Langevin") { MJOLNIR_LOG_NOTICE("Integrator is Underdamped Langevin."); using integrator_t = UnderdampedLangevinStepper<traitsT>; using simulator_t = MolecularDynamicsSimulator<traitsT, integrator_t>; return make_unique<simulator_t>( tstep, sstep, read_system<traitsT>(root, 0), read_forcefield<traitsT>(root, 0), read_underdamped_langevin_stepper<traitsT>(simulator), read_observer<traitsT>(root)); } else { throw_exception<std::runtime_error>(toml::format_error("[error] " "mjolnir::read_molecular_dynamics_simulator: invalid integrator: ", toml::find(simulator, "integrator"), "here", { "expected value is one of the following.", "- \"Newtonian\" : simple and standard Velocity Verlet integrator.", "- \"Underdamped Langevin\": simple Underdamped Langevin Integrator" " based on the Velocity Verlet" })); } } template<typename traitsT> std::unique_ptr<SimulatorBase> read_steepest_descent_simulator( const toml::table& root, const toml::value& simulator) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_SCOPE(read_steepest_descent_simulator(), 0); using real_type = typename traitsT::real_type; using simulator_type = SteepestDescentSimulator<traitsT>; const auto step_lim = toml::find<std::size_t>(simulator, "step_limit"); const auto save_step = toml::find<std::size_t>(simulator, "save_step"); const auto delta = toml::find<real_type >(simulator, "delta"); const auto threshold = toml::find<real_type >(simulator, "threshold"); MJOLNIR_LOG_NOTICE("step_limit is ", step_lim); MJOLNIR_LOG_NOTICE("save_step is ", save_step); MJOLNIR_LOG_NOTICE("delta is ", delta); MJOLNIR_LOG_NOTICE("threshold is ", threshold); return make_unique<simulator_type>( delta, threshold, step_lim, save_step, read_system<traitsT>(root, 0), read_forcefield<traitsT>(root, 0), read_observer<traitsT>(root)); } template<typename traitsT> std::unique_ptr<SimulatorBase> read_simulated_annealing_simulator( const toml::table& root, const toml::value& simulator) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_SCOPE(read_simulated_annealing_simulator(), 0); using real_type = typename traitsT::real_type; const auto integrator = toml::find<std::string>(simulator, "integrator"); const auto tstep = toml::find<std::size_t>(simulator, "total_step"); const auto sstep = toml::find<std::size_t>(simulator, "save_step"); MJOLNIR_LOG_NOTICE("total step is ", tstep); MJOLNIR_LOG_NOTICE("save step is ", sstep); const auto schedule = toml::find<std::string>(simulator, "schedule"); const auto T_begin = toml::find<real_type> (simulator, "T_begin"); const auto T_end = toml::find<real_type> (simulator, "T_end"); const auto each_step = toml::find<std::size_t>(simulator, "each_step"); MJOLNIR_LOG_NOTICE("temperature from ", T_begin); MJOLNIR_LOG_NOTICE("temperature to ", T_end); MJOLNIR_LOG_INFO("update temperature for each ", each_step, " steps"); if(schedule == "linear") { MJOLNIR_LOG_NOTICE("temparing schedule is linear."); if(integrator == "Newtonian") { MJOLNIR_LOG_ERROR("Simulated Annealing + NVE Newtonian"); MJOLNIR_LOG_ERROR("NVE Newtonian doesn't have temperature control."); throw_exception<std::runtime_error>(toml::format_error("[error] " "mjolnir::read_simulated_annealing_simulator: invalid integrator: ", toml::find(simulator, "integrator"), "here", { "Newtonian Integrator does not controls temperature." "expected value is one of the following.", "- \"Underdamped Langevin\": simple Underdamped Langevin Integrator" " based on the Velocity Verlet" })); } else if(integrator == "Underdamped Langevin") { using integrator_t = UnderdampedLangevinStepper<traitsT>; using simulator_t = SimulatedAnnealingSimulator< traitsT, integrator_t, linear_schedule>; MJOLNIR_LOG_NOTICE("Integrator is Underdamped Langevin."); return make_unique<simulator_t>(tstep, sstep, each_step, linear_schedule<real_type>(T_begin, T_end), read_system<traitsT>(root, 0), read_forcefield<traitsT>(root, 0), read_underdamped_langevin_stepper<traitsT>(simulator), read_observer<traitsT>(root)); } else { throw_exception<std::runtime_error>(toml::format_error("[error] " "mjolnir::read_simulated_annealing_simulator: invalid integrator: ", toml::find(simulator, "integrator"), "here", { "expected value is one of the following.", "- \"Underdamped Langevin\": simple Underdamped Langevin Integrator" " based on the Velocity Verlet" })); } } else { throw_exception<std::runtime_error>(toml::format_error("[error] " "mjolnir::read_simulated_annealing_simulator: invalid schedule", toml::find<toml::value>(simulator, "schedule"), "here", { "expected value is one of the following.", "- \"linear\" : simple linear temperature scheduling", })); } } template<typename traitsT> std::unique_ptr<SimulatorBase> read_simulator_from_table(const toml::table& root, const toml::value& simulator) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_SCOPE(read_simulator_from_table(), 0); const auto type = toml::find<std::string>(simulator, "type"); if(type == "Molecular Dynamics") { MJOLNIR_LOG_NOTICE("Simulator type is Molecular Dynamics."); return read_molecular_dynamics_simulator<traitsT>(root, simulator); } else if(type == "Steepest Descent") { MJOLNIR_LOG_NOTICE("Simulator type is Steepest Descent."); return read_steepest_descent_simulator<traitsT>(root, simulator); } else if(type == "Simulated Annealing") { MJOLNIR_LOG_NOTICE("Simulator type is Simulated Annealing."); return read_simulated_annealing_simulator<traitsT>(root, simulator); } else { throw_exception<std::runtime_error>(toml::format_error("[error] " "mjolnir::read_simulator: invalid type", toml::find<toml::value>(simulator, "type"), "here", { "expected value is one of the following.", "- \"Molecular Dynamcis\" : standard MD simulation", "- \"Steepest Descent\" : energy minimization by gradient method", "- \"Simulated Annealing\": energy minimization by Annealing", })); } } template<typename traitsT> std::unique_ptr<SimulatorBase> read_simulator(const toml::table& root) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_SCOPE(read_simulator(), 0); using real_type = typename traitsT::real_type; const auto& simulator = toml::find(root, "simulator"); if(toml::get<toml::table>(simulator).count("file_name") == 1) { MJOLNIR_SCOPE(simulator.count("file_name") == 1, 1); const auto input_path = read_input_path(root); const auto file_name = toml::find<std::string>(simulator, "file_name"); MJOLNIR_LOG_INFO("file_name = ", file_name); if(toml::get<toml::table>(simulator).size() != 1) { MJOLNIR_LOG_WARN("[simulator] has `file_name` key and other keys."); MJOLNIR_LOG_WARN("When `file_name` is provided, other values are " "ignored because those are read from the specified" " file (", input_path, file_name, ")."); } MJOLNIR_LOG_NOTICE("simulator is defined in ", input_path, file_name); MJOLNIR_LOG_NOTICE_NO_LF("reading ", input_path, file_name, " ..."); const auto simfile = toml::parse(input_path + file_name); MJOLNIR_LOG_NOTICE(" done."); if(simfile.count("simulator") != 1) { throw_exception<std::out_of_range>("[error] mjolnir::read_simulator: " "table [simulator] not found in the toml file\n --> ", input_path, file_name, "\n | the file should define [simulator] " "table and define values in it."); } return read_simulator_from_table<traitsT>(root, simfile.at("simulator")); } else { return read_simulator_from_table<traitsT>(root, simulator); } } } // mjolnir #endif// MJOLNIR_READ_SIMULATOR <|endoftext|>
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM 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) version 2.1 dated February 1999. #ifndef MFEM_GSLIB #define MFEM_GSLIB #include "gridfunc.hpp" #include "pgridfunc.hpp" #ifdef MFEM_USE_GSLIB #include "gslib.h" namespace mfem { class findpts_gslib { private: IntegrationRule ir; Vector gllmesh; struct findpts_data_2 *fda; struct findpts_data_3 *fdb; int dim, nel, qo, msz; struct comm cc; public: findpts_gslib(); #ifdef MFEM_USE_MPI findpts_gslib(MPI_Comm _comm); #endif /** Initializes the internal mesh in gslib, by sending the positions of the Gauss-Lobatto nodes of @a mesh. Note: not tested with periodic (DG meshes). Note: the given @a mesh must have Nodes set. @param[in] bb_t Relative size of bounding box around each element. @param[in] newt_tol Newton tolerance for the gslib search methods. @param[in] npt_max Number of points for simultaneous iteration. This alters performance and memory footprint. */ void gslib_findpts_setup(Mesh &mesh, double bb_t, double newt_tol, int npt_max); /** Searches positions given in physical space by @a point_pos. All output Arrays and Vectors are expected to have the correct size. @param[in] point_pos Positions to be found. Must by ordered by nodes (XXX...,YYY...,ZZZ). @param[out] codes Return codes for each point: inside element (0), element boundary (1), not found (2). @param[out] proc_ids MPI proc ids where the points were found. @param[out] elem_ids Element ids where the points were found. @param[out] ref_pos Reference coordinates of the found point. Ordered by vdim (XYZ,XYZ,XYZ...). @param[out] dist Distance between the seeked and the found point in physical space. */ void gslib_findpts(Vector &point_pos, Array<uint> &codes, Array<uint> &proc_ids, Array<uint> &elem_ids, Vector &ref_pos, Vector &dist); // Interpolates fieldin for given r,s,t,e,p and puts it in fieldout void gslib_findpts_eval (Vector *fieldout,Array<uint> *pcode,Array<uint> *pproc, Array<uint> *pel,Vector *pr,Vector *fieldin, int nxyz); // Interpolates ParGrudFunction for given r,s,t,e,p and puts it in fieldout #ifdef MFEM_USE_MPI void gslib_findpts_eval (Vector *fieldout,Array<uint> *pcode,Array<uint> *pproc, Array<uint> *pel,Vector *pr,ParGridFunction *fieldin, int nxyz); #else void gslib_findpts_eval (Vector *fieldout,Array<uint> *pcode,Array<uint> *pproc, Array<uint> *pel,Vector *pr,GridFunction *fieldin, int nxyz); #endif // Convert gridfunction to double #ifdef MFEM_USE_MPI void gf2vec(ParGridFunction *fieldin, Vector *fieldout); #else void gf2vec(GridFunction *fieldin, Vector *fieldout); #endif // Get inline int GetFptMeshSize() const { return msz; } inline int GetQorder() const { return qo; } // clears up memory void gslib_findpts_free(); ~findpts_gslib(); }; } // namespace mfem #endif //MFEM_USE_GSLIB #endif //MFEM_GSLIB guard <commit_msg>Comment.<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM 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) version 2.1 dated February 1999. #ifndef MFEM_GSLIB #define MFEM_GSLIB #include "gridfunc.hpp" #include "pgridfunc.hpp" #ifdef MFEM_USE_GSLIB #include "gslib.h" namespace mfem { class findpts_gslib { private: IntegrationRule ir; Vector gllmesh; struct findpts_data_2 *fda; struct findpts_data_3 *fdb; int dim, nel, qo, msz; struct comm cc; public: findpts_gslib(); #ifdef MFEM_USE_MPI findpts_gslib(MPI_Comm _comm); #endif /** Initializes the internal mesh in gslib, by sending the positions of the Gauss-Lobatto nodes of @a mesh. Note: not tested with periodic (DG meshes). Note: the given @a mesh must have Nodes set. @param[in] bb_t Relative size of bounding box around each element. @param[in] newt_tol Newton tolerance for the gslib search methods. @param[in] npt_max Number of points for simultaneous iteration. This alters performance and memory footprint. */ void gslib_findpts_setup(Mesh &mesh, double bb_t, double newt_tol, int npt_max); /** Searches positions given in physical space by @a point_pos. All output Arrays and Vectors are expected to have the correct size. @param[in] point_pos Positions to be found. Must by ordered by nodes (XXX...,YYY...,ZZZ). @param[out] codes Return codes for each point: inside element (0), element boundary (1), not found (2). @param[out] proc_ids MPI proc ids where the points were found. @param[out] elem_ids Element ids where the points were found. @param[out] ref_pos Reference coordinates of the found point. Ordered by vdim (XYZ,XYZ,XYZ...). Note: the gslib reference frame is [-1,1]. @param[out] dist Distance between the seeked and the found point in physical space. */ void gslib_findpts(Vector &point_pos, Array<uint> &codes, Array<uint> &proc_ids, Array<uint> &elem_ids, Vector &ref_pos, Vector &dist); // Interpolates fieldin for given r,s,t,e,p and puts it in fieldout void gslib_findpts_eval (Vector *fieldout,Array<uint> *pcode,Array<uint> *pproc, Array<uint> *pel,Vector *pr,Vector *fieldin, int nxyz); // Interpolates ParGrudFunction for given r,s,t,e,p and puts it in fieldout #ifdef MFEM_USE_MPI void gslib_findpts_eval (Vector *fieldout,Array<uint> *pcode,Array<uint> *pproc, Array<uint> *pel,Vector *pr,ParGridFunction *fieldin, int nxyz); #else void gslib_findpts_eval (Vector *fieldout,Array<uint> *pcode,Array<uint> *pproc, Array<uint> *pel,Vector *pr,GridFunction *fieldin, int nxyz); #endif // Convert gridfunction to double #ifdef MFEM_USE_MPI void gf2vec(ParGridFunction *fieldin, Vector *fieldout); #else void gf2vec(GridFunction *fieldin, Vector *fieldout); #endif // Get inline int GetFptMeshSize() const { return msz; } inline int GetQorder() const { return qo; } // clears up memory void gslib_findpts_free(); ~findpts_gslib(); }; } // namespace mfem #endif //MFEM_USE_GSLIB #endif //MFEM_GSLIB guard <|endoftext|>
<commit_before>#include <occa/internal/lang/statement/ifStatement.hpp> #include <occa/internal/lang/statement/elifStatement.hpp> #include <occa/internal/lang/statement/elseStatement.hpp> namespace occa { namespace lang { ifStatement::ifStatement(blockStatement *up_, token_t *source_) : blockStatement(up_, source_), condition(NULL), elseSmnt(NULL) {} ifStatement::ifStatement(blockStatement *up_, const ifStatement &other) : blockStatement(up_, other.source), condition(&(other.condition->clone(this))), elseSmnt(NULL) { copyFrom(other); const int elifCount = (int) other.elifSmnts.size(); for (int i = 0; i < elifCount; ++i) { elifStatement &elifSmnt = (other.elifSmnts[i] ->clone(this) .to<elifStatement>()); elifSmnts.push_back(&elifSmnt); } if (other.elseSmnt) { elseSmnt = &((elseStatement&) other.elseSmnt->clone(this)); } } ifStatement::~ifStatement() { delete condition; delete elseSmnt; const int elifCount = (int) elifSmnts.size(); for (int i = 0; i < elifCount; ++i) { delete elifSmnts[i]; } } void ifStatement::setCondition(statement_t *condition_) { condition = condition_; } void ifStatement::addElif(elifStatement &elifSmnt) { elifSmnts.push_back(&elifSmnt); } void ifStatement::addElse(elseStatement &elseSmnt_) { delete elseSmnt; elseSmnt = &elseSmnt_; } statement_t& ifStatement::clone_(blockStatement *up_) const { return *(new ifStatement(up_, *this)); } int ifStatement::type() const { return statementType::if_; } std::string ifStatement::statementName() const { return "if"; } statementArray ifStatement::getInnerStatements() { statementArray arr; for (statement_t *elifSmnt : elifSmnts) { arr.push(elifSmnt); } if (elseSmnt) { arr.push(elseSmnt); } return arr; } void ifStatement::print(printer &pout) const { pout.printStartIndentation(); pout << "if ("; pout.pushInlined(true); condition->print(pout); pout << ')'; blockStatement::print(pout); pout.popInlined(); const int elifCount = (int) elifSmnts.size(); for (int i = 0; i < elifCount; ++i) { pout << *(elifSmnts[i]); } if (elseSmnt) { pout << (*elseSmnt); } } } } <commit_msg>[Lang] Adding missing if statment condition to inner statement array (#456)<commit_after>#include <occa/internal/lang/statement/ifStatement.hpp> #include <occa/internal/lang/statement/elifStatement.hpp> #include <occa/internal/lang/statement/elseStatement.hpp> namespace occa { namespace lang { ifStatement::ifStatement(blockStatement *up_, token_t *source_) : blockStatement(up_, source_), condition(NULL), elseSmnt(NULL) {} ifStatement::ifStatement(blockStatement *up_, const ifStatement &other) : blockStatement(up_, other.source), condition(&(other.condition->clone(this))), elseSmnt(NULL) { copyFrom(other); const int elifCount = (int) other.elifSmnts.size(); for (int i = 0; i < elifCount; ++i) { elifStatement &elifSmnt = (other.elifSmnts[i] ->clone(this) .to<elifStatement>()); elifSmnts.push_back(&elifSmnt); } if (other.elseSmnt) { elseSmnt = &((elseStatement&) other.elseSmnt->clone(this)); } } ifStatement::~ifStatement() { delete condition; delete elseSmnt; const int elifCount = (int) elifSmnts.size(); for (int i = 0; i < elifCount; ++i) { delete elifSmnts[i]; } } void ifStatement::setCondition(statement_t *condition_) { condition = condition_; } void ifStatement::addElif(elifStatement &elifSmnt) { elifSmnts.push_back(&elifSmnt); } void ifStatement::addElse(elseStatement &elseSmnt_) { delete elseSmnt; elseSmnt = &elseSmnt_; } statement_t& ifStatement::clone_(blockStatement *up_) const { return *(new ifStatement(up_, *this)); } int ifStatement::type() const { return statementType::if_; } std::string ifStatement::statementName() const { return "if"; } statementArray ifStatement::getInnerStatements() { statementArray arr; if (condition) { arr.push(condition); } for (statement_t *elifSmnt : elifSmnts) { arr.push(elifSmnt); } if (elseSmnt) { arr.push(elseSmnt); } return arr; } void ifStatement::print(printer &pout) const { pout.printStartIndentation(); pout << "if ("; pout.pushInlined(true); condition->print(pout); pout << ')'; blockStatement::print(pout); pout.popInlined(); const int elifCount = (int) elifSmnts.size(); for (int i = 0; i < elifCount; ++i) { pout << *(elifSmnts[i]); } if (elseSmnt) { pout << (*elseSmnt); } } } } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/files/file_util.h" #include "base/threading/platform_thread.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/common/content_switches.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test_utils.h" #include "content/public/test/test_utils.h" #include "content/test/webrtc_content_browsertest_base.h" #include "media/audio/audio_manager.h" #include "media/base/media_switches.h" #include "net/test/embedded_test_server/embedded_test_server.h" namespace content { #if defined(OS_ANDROID) && defined(ADDRESS_SANITIZER) // Renderer crashes under Android ASAN: https://crbug.com/408496. #define MAYBE_WebRtcBrowserTest DISABLED_WebRtcBrowserTest #elif DCHECK_IS_ON() && defined(OS_WIN) // Flaky under win debug configs: http://crbug.com/517977. #define MAYBE_WebRtcBrowserTest DISABLED_WebRtcBrowserTest #else #define MAYBE_WebRtcBrowserTest WebRtcBrowserTest #endif class MAYBE_WebRtcBrowserTest : public WebRtcContentBrowserTest { public: MAYBE_WebRtcBrowserTest() {} ~MAYBE_WebRtcBrowserTest() override {} // Convenience function since most peerconnection-call.html tests just load // the page, kick off some javascript and wait for the title to change to OK. void MakeTypicalPeerConnectionCall(const std::string& javascript) { ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady()); GURL url(embedded_test_server()->GetURL("/media/peerconnection-call.html")); NavigateToURL(shell(), url); ExecuteJavascriptAndWaitForOk(javascript); } // Convenience method for making calls that detect if audio os playing (which // has some special prerequisites, such that there needs to be an audio output // device on the executing machine). void MakeAudioDetectingPeerConnectionCall(const std::string& javascript) { if (!media::AudioManager::Get()->HasAudioOutputDevices()) { // Bots with no output devices will force the audio code into a state // where it doesn't manage to set either the low or high latency path. // This test will compute useless values in that case, so skip running on // such bots (see crbug.com/326338). LOG(INFO) << "Missing output devices: skipping test..."; return; } ASSERT_TRUE(base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kUseFakeDeviceForMediaStream)) << "Must run with fake devices since the test will explicitly look " << "for the fake device signal."; MakeTypicalPeerConnectionCall(javascript); } }; // These tests will make a complete PeerConnection-based call and verify that // video is playing for the call. IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CanSetupDefaultVideoCall) { MakeTypicalPeerConnectionCall( "callAndExpectResolution({video: true}, 640, 480);"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CanSetupVideoCallWith1To1AspectRatio) { const std::string javascript = "callAndExpectResolution({video: {mandatory: {minWidth: 320," " maxWidth: 320, minHeight: 320, maxHeight: 320}}}, 320, 320);"; MakeTypicalPeerConnectionCall(javascript); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CanSetupVideoCallWith16To9AspectRatio) { const std::string javascript = "callAndExpectResolution({video: {mandatory: {minWidth: 640," " maxWidth: 640, minAspectRatio: 1.777}}}, 640, 360);"; MakeTypicalPeerConnectionCall(javascript); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CanSetupVideoCallWith4To3AspectRatio) { const std::string javascript = "callAndExpectResolution({video: {mandatory: { minWidth: 960," "maxWidth: 960, minAspectRatio: 1.333, maxAspectRatio: 1.333}}}, 960," " 720);"; MakeTypicalPeerConnectionCall(javascript); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CanSetupVideoCallAndDisableLocalVideo) { const std::string javascript = "callAndDisableLocalVideo({video: true});"; MakeTypicalPeerConnectionCall(javascript); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CanSetupAudioAndVideoCall) { MakeTypicalPeerConnectionCall("call({video: true, audio: true});"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CanSetupCallAndSendDtmf) { MakeTypicalPeerConnectionCall("callAndSendDtmf(\'123,abc\');"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CanMakeEmptyCallThenAddStreamsAndRenegotiate) { const char* kJavascript = "callEmptyThenAddOneStreamAndRenegotiate({video: true, audio: true});"; MakeTypicalPeerConnectionCall(kJavascript); } // Causes asserts in libjingle: http://crbug.com/484826. IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, DISABLED_CanMakeAudioCallAndThenRenegotiateToVideo) { const char* kJavascript = "callAndRenegotiateToVideo({audio: true}, {audio: true, video:true});"; MakeTypicalPeerConnectionCall(kJavascript); } // Causes asserts in libjingle: http://crbug.com/484826. IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, DISABLED_CanMakeVideoCallAndThenRenegotiateToAudio) { MakeAudioDetectingPeerConnectionCall( "callAndRenegotiateToAudio({audio: true, video:true}, {audio: true});"); } // This test makes a call between pc1 and pc2 where a video only stream is sent // from pc1 to pc2. The stream sent from pc1 to pc2 is cloned from the stream // received on pc2 to test that cloning of remote video tracks works as // intended and is sent back to pc1. IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CanForwardRemoteStream) { #if defined (OS_ANDROID) // This test fails on Nexus 5 devices. // TODO(henrika): see http://crbug.com/362437 and http://crbug.com/359389 // for details. base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kDisableWebRtcHWDecoding); #endif MakeTypicalPeerConnectionCall( "callAndForwardRemoteStream({video: true, audio: false});"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, NoCrashWhenConnectChromiumSinkToRemoteTrack) { MakeTypicalPeerConnectionCall("ConnectChromiumSinkToRemoteAudioTrack();"); } // This test will make a complete PeerConnection-based call but remove the // MSID and bundle attribute from the initial offer to verify that // video is playing for the call even if the initiating client don't support // MSID. http://tools.ietf.org/html/draft-alvestrand-rtcweb-msid-02 IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CanSetupAudioAndVideoCallWithoutMsidAndBundle) { MakeTypicalPeerConnectionCall("callWithoutMsidAndBundle();"); } // This test will modify the SDP offer to an unsupported codec, which should // cause SetLocalDescription to fail. IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, NegotiateUnsupportedVideoCodec) { MakeTypicalPeerConnectionCall("negotiateUnsupportedVideoCodec();"); } // This test will modify the SDP offer to use no encryption, which should // cause SetLocalDescription to fail. IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, NegotiateNonCryptoCall) { MakeTypicalPeerConnectionCall("negotiateNonCryptoCall();"); } // This test can negotiate an SDP offer that includes a b=AS:xx to control // the bandwidth for audio and video IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, NegotiateOfferWithBLine) { MakeTypicalPeerConnectionCall("negotiateOfferWithBLine();"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CanSetupLegacyCall) { MakeTypicalPeerConnectionCall("callWithLegacySdp();"); } // This test will make a PeerConnection-based call and test an unreliable text // dataChannel. // TODO(mallinath) - Remove this test after rtp based data channel is disabled. IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CallWithDataOnly) { MakeTypicalPeerConnectionCall("callWithDataOnly();"); } #if defined(MEMORY_SANITIZER) // Fails under MemorySanitizer: http://crbug.com/405951 #define MAYBE_CallWithSctpDataOnly DISABLED_CallWithSctpDataOnly #else #define MAYBE_CallWithSctpDataOnly CallWithSctpDataOnly #endif IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, MAYBE_CallWithSctpDataOnly) { MakeTypicalPeerConnectionCall("callWithSctpDataOnly();"); } // This test will make a PeerConnection-based call and test an unreliable text // dataChannel and audio and video tracks. // TODO(mallinath) - Remove this test after rtp based data channel is disabled. IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CallWithDataAndMedia) { MakeTypicalPeerConnectionCall("callWithDataAndMedia();"); } #if defined(MEMORY_SANITIZER) // Fails under MemorySanitizer: http://crbug.com/405951 #define MAYBE_CallWithSctpDataAndMedia DISABLED_CallWithSctpDataAndMedia #else #define MAYBE_CallWithSctpDataAndMedia CallWithSctpDataAndMedia #endif IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, MAYBE_CallWithSctpDataAndMedia) { MakeTypicalPeerConnectionCall("callWithSctpDataAndMedia();"); } // This test will make a PeerConnection-based call and test an unreliable text // dataChannel and later add an audio and video track. // Doesn't work, therefore disabled: https://crbug.com/293252. IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, DISABLED_CallWithDataAndLaterAddMedia) { MakeTypicalPeerConnectionCall("callWithDataAndLaterAddMedia();"); } // This test will make a PeerConnection-based call and send a new Video // MediaStream that has been created based on a MediaStream created with // getUserMedia. IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CallWithNewVideoMediaStream) { MakeTypicalPeerConnectionCall("callWithNewVideoMediaStream();"); } // This test will make a PeerConnection-based call and send a new Video // MediaStream that has been created based on a MediaStream created with // getUserMedia. When video is flowing, the VideoTrack is removed and an // AudioTrack is added instead. IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CallAndModifyStream) { MakeTypicalPeerConnectionCall( "callWithNewVideoMediaStreamLaterSwitchToAudio();"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, AddTwoMediaStreamsToOnePC) { MakeTypicalPeerConnectionCall("addTwoMediaStreamsToOneConnection();"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, EstablishAudioVideoCallAndEnsureAudioIsPlaying) { MakeAudioDetectingPeerConnectionCall( "callAndEnsureAudioIsPlaying({audio:true, video:true});"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, EstablishAudioOnlyCallAndEnsureAudioIsPlaying) { MakeAudioDetectingPeerConnectionCall( "callAndEnsureAudioIsPlaying({audio:true});"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, EstablishIsac16KCallAndEnsureAudioIsPlaying) { MakeAudioDetectingPeerConnectionCall( "callWithIsac16KAndEnsureAudioIsPlaying({audio:true});"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, EstablishAudioVideoCallAndVerifyRemoteMutingWorks) { MakeAudioDetectingPeerConnectionCall( "callAndEnsureRemoteAudioTrackMutingWorks();"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, EstablishAudioVideoCallAndVerifyLocalMutingWorks) { MakeAudioDetectingPeerConnectionCall( "callAndEnsureLocalAudioTrackMutingWorks();"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, EnsureLocalVideoMuteDoesntMuteAudio) { MakeAudioDetectingPeerConnectionCall( "callAndEnsureLocalVideoMutingDoesntMuteAudio();"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, EnsureRemoteVideoMuteDoesntMuteAudio) { MakeAudioDetectingPeerConnectionCall( "callAndEnsureRemoteVideoMutingDoesntMuteAudio();"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, EstablishAudioVideoCallAndVerifyUnmutingWorks) { MakeAudioDetectingPeerConnectionCall( "callAndEnsureAudioTrackUnmutingWorks();"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CallAndVerifyVideoMutingWorks) { MakeTypicalPeerConnectionCall("callAndEnsureVideoTrackMutingWorks();"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CreateOfferWithOfferOptions) { MakeTypicalPeerConnectionCall("testCreateOfferOptions();"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CallInsideIframe) { MakeTypicalPeerConnectionCall("callInsideIframe({video: true, audio:true});"); } } // namespace content <commit_msg>Speculatively re-enabling flaky WebRTC tests.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/files/file_util.h" #include "base/threading/platform_thread.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/common/content_switches.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test_utils.h" #include "content/public/test/test_utils.h" #include "content/test/webrtc_content_browsertest_base.h" #include "media/audio/audio_manager.h" #include "media/base/media_switches.h" #include "net/test/embedded_test_server/embedded_test_server.h" namespace content { #if defined(OS_ANDROID) && defined(ADDRESS_SANITIZER) // Renderer crashes under Android ASAN: https://crbug.com/408496. #define MAYBE_WebRtcBrowserTest DISABLED_WebRtcBrowserTest #else #define MAYBE_WebRtcBrowserTest WebRtcBrowserTest #endif class MAYBE_WebRtcBrowserTest : public WebRtcContentBrowserTest { public: MAYBE_WebRtcBrowserTest() {} ~MAYBE_WebRtcBrowserTest() override {} // Convenience function since most peerconnection-call.html tests just load // the page, kick off some javascript and wait for the title to change to OK. void MakeTypicalPeerConnectionCall(const std::string& javascript) { ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady()); GURL url(embedded_test_server()->GetURL("/media/peerconnection-call.html")); NavigateToURL(shell(), url); ExecuteJavascriptAndWaitForOk(javascript); } // Convenience method for making calls that detect if audio os playing (which // has some special prerequisites, such that there needs to be an audio output // device on the executing machine). void MakeAudioDetectingPeerConnectionCall(const std::string& javascript) { if (!media::AudioManager::Get()->HasAudioOutputDevices()) { // Bots with no output devices will force the audio code into a state // where it doesn't manage to set either the low or high latency path. // This test will compute useless values in that case, so skip running on // such bots (see crbug.com/326338). LOG(INFO) << "Missing output devices: skipping test..."; return; } ASSERT_TRUE(base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kUseFakeDeviceForMediaStream)) << "Must run with fake devices since the test will explicitly look " << "for the fake device signal."; MakeTypicalPeerConnectionCall(javascript); } }; // These tests will make a complete PeerConnection-based call and verify that // video is playing for the call. IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CanSetupDefaultVideoCall) { MakeTypicalPeerConnectionCall( "callAndExpectResolution({video: true}, 640, 480);"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CanSetupVideoCallWith1To1AspectRatio) { const std::string javascript = "callAndExpectResolution({video: {mandatory: {minWidth: 320," " maxWidth: 320, minHeight: 320, maxHeight: 320}}}, 320, 320);"; MakeTypicalPeerConnectionCall(javascript); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CanSetupVideoCallWith16To9AspectRatio) { const std::string javascript = "callAndExpectResolution({video: {mandatory: {minWidth: 640," " maxWidth: 640, minAspectRatio: 1.777}}}, 640, 360);"; MakeTypicalPeerConnectionCall(javascript); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CanSetupVideoCallWith4To3AspectRatio) { const std::string javascript = "callAndExpectResolution({video: {mandatory: { minWidth: 960," "maxWidth: 960, minAspectRatio: 1.333, maxAspectRatio: 1.333}}}, 960," " 720);"; MakeTypicalPeerConnectionCall(javascript); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CanSetupVideoCallAndDisableLocalVideo) { const std::string javascript = "callAndDisableLocalVideo({video: true});"; MakeTypicalPeerConnectionCall(javascript); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CanSetupAudioAndVideoCall) { MakeTypicalPeerConnectionCall("call({video: true, audio: true});"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CanSetupCallAndSendDtmf) { MakeTypicalPeerConnectionCall("callAndSendDtmf(\'123,abc\');"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CanMakeEmptyCallThenAddStreamsAndRenegotiate) { const char* kJavascript = "callEmptyThenAddOneStreamAndRenegotiate({video: true, audio: true});"; MakeTypicalPeerConnectionCall(kJavascript); } // Causes asserts in libjingle: http://crbug.com/484826. IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, DISABLED_CanMakeAudioCallAndThenRenegotiateToVideo) { const char* kJavascript = "callAndRenegotiateToVideo({audio: true}, {audio: true, video:true});"; MakeTypicalPeerConnectionCall(kJavascript); } // Causes asserts in libjingle: http://crbug.com/484826. IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, DISABLED_CanMakeVideoCallAndThenRenegotiateToAudio) { MakeAudioDetectingPeerConnectionCall( "callAndRenegotiateToAudio({audio: true, video:true}, {audio: true});"); } // This test makes a call between pc1 and pc2 where a video only stream is sent // from pc1 to pc2. The stream sent from pc1 to pc2 is cloned from the stream // received on pc2 to test that cloning of remote video tracks works as // intended and is sent back to pc1. IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CanForwardRemoteStream) { #if defined (OS_ANDROID) // This test fails on Nexus 5 devices. // TODO(henrika): see http://crbug.com/362437 and http://crbug.com/359389 // for details. base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kDisableWebRtcHWDecoding); #endif MakeTypicalPeerConnectionCall( "callAndForwardRemoteStream({video: true, audio: false});"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, NoCrashWhenConnectChromiumSinkToRemoteTrack) { MakeTypicalPeerConnectionCall("ConnectChromiumSinkToRemoteAudioTrack();"); } // This test will make a complete PeerConnection-based call but remove the // MSID and bundle attribute from the initial offer to verify that // video is playing for the call even if the initiating client don't support // MSID. http://tools.ietf.org/html/draft-alvestrand-rtcweb-msid-02 IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CanSetupAudioAndVideoCallWithoutMsidAndBundle) { MakeTypicalPeerConnectionCall("callWithoutMsidAndBundle();"); } // This test will modify the SDP offer to an unsupported codec, which should // cause SetLocalDescription to fail. IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, NegotiateUnsupportedVideoCodec) { MakeTypicalPeerConnectionCall("negotiateUnsupportedVideoCodec();"); } // This test will modify the SDP offer to use no encryption, which should // cause SetLocalDescription to fail. IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, NegotiateNonCryptoCall) { MakeTypicalPeerConnectionCall("negotiateNonCryptoCall();"); } // This test can negotiate an SDP offer that includes a b=AS:xx to control // the bandwidth for audio and video IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, NegotiateOfferWithBLine) { MakeTypicalPeerConnectionCall("negotiateOfferWithBLine();"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CanSetupLegacyCall) { MakeTypicalPeerConnectionCall("callWithLegacySdp();"); } // This test will make a PeerConnection-based call and test an unreliable text // dataChannel. // TODO(mallinath) - Remove this test after rtp based data channel is disabled. IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CallWithDataOnly) { MakeTypicalPeerConnectionCall("callWithDataOnly();"); } #if defined(MEMORY_SANITIZER) // Fails under MemorySanitizer: http://crbug.com/405951 #define MAYBE_CallWithSctpDataOnly DISABLED_CallWithSctpDataOnly #else #define MAYBE_CallWithSctpDataOnly CallWithSctpDataOnly #endif IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, MAYBE_CallWithSctpDataOnly) { MakeTypicalPeerConnectionCall("callWithSctpDataOnly();"); } // This test will make a PeerConnection-based call and test an unreliable text // dataChannel and audio and video tracks. // TODO(mallinath) - Remove this test after rtp based data channel is disabled. IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CallWithDataAndMedia) { MakeTypicalPeerConnectionCall("callWithDataAndMedia();"); } #if defined(MEMORY_SANITIZER) // Fails under MemorySanitizer: http://crbug.com/405951 #define MAYBE_CallWithSctpDataAndMedia DISABLED_CallWithSctpDataAndMedia #else #define MAYBE_CallWithSctpDataAndMedia CallWithSctpDataAndMedia #endif IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, MAYBE_CallWithSctpDataAndMedia) { MakeTypicalPeerConnectionCall("callWithSctpDataAndMedia();"); } // This test will make a PeerConnection-based call and test an unreliable text // dataChannel and later add an audio and video track. // Doesn't work, therefore disabled: https://crbug.com/293252. IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, DISABLED_CallWithDataAndLaterAddMedia) { MakeTypicalPeerConnectionCall("callWithDataAndLaterAddMedia();"); } // This test will make a PeerConnection-based call and send a new Video // MediaStream that has been created based on a MediaStream created with // getUserMedia. IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CallWithNewVideoMediaStream) { MakeTypicalPeerConnectionCall("callWithNewVideoMediaStream();"); } // This test will make a PeerConnection-based call and send a new Video // MediaStream that has been created based on a MediaStream created with // getUserMedia. When video is flowing, the VideoTrack is removed and an // AudioTrack is added instead. IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CallAndModifyStream) { MakeTypicalPeerConnectionCall( "callWithNewVideoMediaStreamLaterSwitchToAudio();"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, AddTwoMediaStreamsToOnePC) { MakeTypicalPeerConnectionCall("addTwoMediaStreamsToOneConnection();"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, EstablishAudioVideoCallAndEnsureAudioIsPlaying) { MakeAudioDetectingPeerConnectionCall( "callAndEnsureAudioIsPlaying({audio:true, video:true});"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, EstablishAudioOnlyCallAndEnsureAudioIsPlaying) { MakeAudioDetectingPeerConnectionCall( "callAndEnsureAudioIsPlaying({audio:true});"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, EstablishIsac16KCallAndEnsureAudioIsPlaying) { MakeAudioDetectingPeerConnectionCall( "callWithIsac16KAndEnsureAudioIsPlaying({audio:true});"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, EstablishAudioVideoCallAndVerifyRemoteMutingWorks) { MakeAudioDetectingPeerConnectionCall( "callAndEnsureRemoteAudioTrackMutingWorks();"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, EstablishAudioVideoCallAndVerifyLocalMutingWorks) { MakeAudioDetectingPeerConnectionCall( "callAndEnsureLocalAudioTrackMutingWorks();"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, EnsureLocalVideoMuteDoesntMuteAudio) { MakeAudioDetectingPeerConnectionCall( "callAndEnsureLocalVideoMutingDoesntMuteAudio();"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, EnsureRemoteVideoMuteDoesntMuteAudio) { MakeAudioDetectingPeerConnectionCall( "callAndEnsureRemoteVideoMutingDoesntMuteAudio();"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, EstablishAudioVideoCallAndVerifyUnmutingWorks) { MakeAudioDetectingPeerConnectionCall( "callAndEnsureAudioTrackUnmutingWorks();"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CallAndVerifyVideoMutingWorks) { MakeTypicalPeerConnectionCall("callAndEnsureVideoTrackMutingWorks();"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CreateOfferWithOfferOptions) { MakeTypicalPeerConnectionCall("testCreateOfferOptions();"); } IN_PROC_BROWSER_TEST_F(MAYBE_WebRtcBrowserTest, CallInsideIframe) { MakeTypicalPeerConnectionCall("callInsideIframe({video: true, audio:true});"); } } // namespace content <|endoftext|>
<commit_before>/** * \file * \brief MutexControlBlock class implementation * * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-01-12 */ #include "distortos/synchronization/MutexControlBlock.hpp" #include "distortos/scheduler/getScheduler.hpp" #include "distortos/scheduler/Scheduler.hpp" #include <cerrno> namespace distortos { namespace synchronization { /*---------------------------------------------------------------------------------------------------------------------+ | public functions +---------------------------------------------------------------------------------------------------------------------*/ MutexControlBlock::MutexControlBlock(const Protocol protocol, const uint8_t priorityCeiling) : blockedList_{scheduler::getScheduler().getThreadControlBlockListAllocator(), scheduler::ThreadControlBlock::State::BlockedOnMutex}, list_{}, iterator_{}, owner_{}, protocol_{protocol}, priorityCeiling_{priorityCeiling} { } void MutexControlBlock::block() { if (protocol_ == Protocol::PriorityInheritance) priorityInheritanceBeforeBlock(); scheduler::getScheduler().block(blockedList_); } int MutexControlBlock::blockUntil(const TickClock::time_point timePoint) { if (protocol_ == Protocol::PriorityInheritance) priorityInheritanceBeforeBlock(); auto& scheduler = scheduler::getScheduler(); const auto ret = scheduler.blockUntil(blockedList_, timePoint); if (protocol_ == Protocol::PriorityInheritance) { // waiting for mutex timed-out and mutex is still locked? if (ret == ETIMEDOUT && owner_ != nullptr) owner_->updateBoostedPriority(); scheduler.getCurrentThreadControlBlock().setPriorityInheritanceMutexControlBlock(nullptr); } return ret; } uint8_t MutexControlBlock::getBoostedPriority() const { if (protocol_ == Protocol::PriorityInheritance) { if (blockedList_.empty() == true) return 0; return blockedList_.begin()->get().getEffectivePriority(); } if (protocol_ == Protocol::PriorityProtect) return priorityCeiling_; return 0; } void MutexControlBlock::lock() { auto& scheduler = scheduler::getScheduler(); owner_ = &scheduler.getCurrentThreadControlBlock(); if (protocol_ == Protocol::None) return; scheduler.getMutexControlBlockListAllocatorPool().feed(link_); list_ = &owner_->getOwnedProtocolMutexControlBlocksList(); list_->emplace_front(*this); iterator_ = list_->begin(); if (protocol_ == Protocol::PriorityProtect) owner_->updateBoostedPriority(); } void MutexControlBlock::unlockOrTransferLock() { auto& oldOwner = *owner_; if (blockedList_.empty() == false) transferLock(); else unlock(); if (protocol_ == Protocol::None) return; oldOwner.updateBoostedPriority(); if (owner_ == nullptr) return; owner_->updateBoostedPriority(); } /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ void MutexControlBlock::priorityInheritanceBeforeBlock() const { auto& currentThreadControlBlock = scheduler::getScheduler().getCurrentThreadControlBlock(); currentThreadControlBlock.setPriorityInheritanceMutexControlBlock(this); // calling thread is not yet on the blocked list, that's why it's effective priority is given explicitly owner_->updateBoostedPriority(currentThreadControlBlock.getEffectivePriority()); } void MutexControlBlock::transferLock() { owner_ = &blockedList_.begin()->get(); // pass ownership to the unblocked thread scheduler::getScheduler().unblock(blockedList_.begin()); if (list_ == nullptr) return; auto& oldList = *list_; list_ = &owner_->getOwnedProtocolMutexControlBlocksList(); list_->splice(list_->begin(), oldList, iterator_); if (protocol_ == Protocol::PriorityInheritance) owner_->setPriorityInheritanceMutexControlBlock(nullptr); } void MutexControlBlock::unlock() { owner_ = nullptr; if (list_ == nullptr) return; list_->erase(iterator_); list_ = nullptr; } } // namespace synchronization } // namespace distortos <commit_msg>MutexControlBlock: add local PriorityInheritanceMutexControlBlockUnblockFunctor class<commit_after>/** * \file * \brief MutexControlBlock class implementation * * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-02-01 */ #include "distortos/synchronization/MutexControlBlock.hpp" #include "distortos/scheduler/getScheduler.hpp" #include "distortos/scheduler/Scheduler.hpp" #include <cerrno> namespace distortos { namespace synchronization { namespace { /*---------------------------------------------------------------------------------------------------------------------+ | local types +---------------------------------------------------------------------------------------------------------------------*/ /// PriorityInheritanceMutexControlBlockUnblockFunctor is a functor executed when unblocking a thread that is blocked on /// a mutex with PriorityInheritance protocol class PriorityInheritanceMutexControlBlockUnblockFunctor : public scheduler::ThreadControlBlock::UnblockFunctor { public: /** * \brief PriorityInheritanceMutexControlBlockUnblockFunctor's constructor * * \param [in] mutexControlBlock is a reference to MutexControlBlock that blocked the thread */ constexpr explicit PriorityInheritanceMutexControlBlockUnblockFunctor(const MutexControlBlock& mutexControlBlock) : mutexControlBlock_(mutexControlBlock) { } /** * \brief PriorityInheritanceMutexControlBlockUnblockFunctor's function call operator * * If the wait for mutex was interrupted, requests update of boosted priority of current owner of the mutex. Pointer * to MutexControlBlock with PriorityInheritance protocol which caused the thread to block is reset to nullptr. * * \param [in] threadControlBlock is a reference to ThreadControlBlock that is being unblocked */ void operator()(scheduler::ThreadControlBlock& threadControlBlock) const override { const auto owner = mutexControlBlock_.getOwner(); // waiting for mutex was interrupted and some thread still holds it? if (threadControlBlock.getUnblockReason() != scheduler::ThreadControlBlock::UnblockReason::UnblockRequest && owner != nullptr) owner->updateBoostedPriority(); threadControlBlock.setPriorityInheritanceMutexControlBlock(nullptr); } private: /// reference to MutexControlBlock that blocked the thread const MutexControlBlock& mutexControlBlock_; }; } // namespace /*---------------------------------------------------------------------------------------------------------------------+ | public functions +---------------------------------------------------------------------------------------------------------------------*/ MutexControlBlock::MutexControlBlock(const Protocol protocol, const uint8_t priorityCeiling) : blockedList_{scheduler::getScheduler().getThreadControlBlockListAllocator(), scheduler::ThreadControlBlock::State::BlockedOnMutex}, list_{}, iterator_{}, owner_{}, protocol_{protocol}, priorityCeiling_{priorityCeiling} { } void MutexControlBlock::block() { if (protocol_ == Protocol::PriorityInheritance) priorityInheritanceBeforeBlock(); scheduler::getScheduler().block(blockedList_); } int MutexControlBlock::blockUntil(const TickClock::time_point timePoint) { if (protocol_ == Protocol::PriorityInheritance) priorityInheritanceBeforeBlock(); auto& scheduler = scheduler::getScheduler(); const auto ret = scheduler.blockUntil(blockedList_, timePoint); if (protocol_ == Protocol::PriorityInheritance) { // waiting for mutex timed-out and mutex is still locked? if (ret == ETIMEDOUT && owner_ != nullptr) owner_->updateBoostedPriority(); scheduler.getCurrentThreadControlBlock().setPriorityInheritanceMutexControlBlock(nullptr); } return ret; } uint8_t MutexControlBlock::getBoostedPriority() const { if (protocol_ == Protocol::PriorityInheritance) { if (blockedList_.empty() == true) return 0; return blockedList_.begin()->get().getEffectivePriority(); } if (protocol_ == Protocol::PriorityProtect) return priorityCeiling_; return 0; } void MutexControlBlock::lock() { auto& scheduler = scheduler::getScheduler(); owner_ = &scheduler.getCurrentThreadControlBlock(); if (protocol_ == Protocol::None) return; scheduler.getMutexControlBlockListAllocatorPool().feed(link_); list_ = &owner_->getOwnedProtocolMutexControlBlocksList(); list_->emplace_front(*this); iterator_ = list_->begin(); if (protocol_ == Protocol::PriorityProtect) owner_->updateBoostedPriority(); } void MutexControlBlock::unlockOrTransferLock() { auto& oldOwner = *owner_; if (blockedList_.empty() == false) transferLock(); else unlock(); if (protocol_ == Protocol::None) return; oldOwner.updateBoostedPriority(); if (owner_ == nullptr) return; owner_->updateBoostedPriority(); } /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ void MutexControlBlock::priorityInheritanceBeforeBlock() const { auto& currentThreadControlBlock = scheduler::getScheduler().getCurrentThreadControlBlock(); currentThreadControlBlock.setPriorityInheritanceMutexControlBlock(this); // calling thread is not yet on the blocked list, that's why it's effective priority is given explicitly owner_->updateBoostedPriority(currentThreadControlBlock.getEffectivePriority()); } void MutexControlBlock::transferLock() { owner_ = &blockedList_.begin()->get(); // pass ownership to the unblocked thread scheduler::getScheduler().unblock(blockedList_.begin()); if (list_ == nullptr) return; auto& oldList = *list_; list_ = &owner_->getOwnedProtocolMutexControlBlocksList(); list_->splice(list_->begin(), oldList, iterator_); if (protocol_ == Protocol::PriorityInheritance) owner_->setPriorityInheritanceMutexControlBlock(nullptr); } void MutexControlBlock::unlock() { owner_ = nullptr; if (list_ == nullptr) return; list_->erase(iterator_); list_ = nullptr; } } // namespace synchronization } // namespace distortos <|endoftext|>
<commit_before>#include "StdAfx.h" #include <algorithm> #include <common/rhoconf.h> #include "BrowserFactory.h" #include "CEBrowserEngine.h" #include "IEBrowserEngine.h" ////////////////////////////////////////////////////////////////////////// extern "C" HINSTANCE rho_wmimpl_get_appinstance(); extern "C" const char* rho_wmimpl_get_webengine(); extern "C" const char* get_app_build_config_item(const char* key); #if defined(APP_BUILD_CAPABILITY_MOTOROLA) extern "C" void rho_wm_impl_CheckLicenseWithBarcode(HWND hParent, HINSTANCE hLicenseInstance); extern "C" void rho_wm_impl_CheckLicenseWithBarcodeWoWebkit(HWND hParent, HINSTANCE hLicenseInstance); #endif extern rho::IBrowserEngine* rho_wmimpl_get_webkitBrowserEngine(HWND hwndParent, HINSTANCE rhoAppInstance); ////////////////////////////////////////////////////////////////////////// const char* rho::BrowserFactory::IETag = "ie"; const char* rho::BrowserFactory::webkitTag = "webkit"; ////////////////////////////////////////////////////////////////////////// namespace rho { BrowserFactory* BrowserFactory::g_browserFactory = 0; IBrowserFactory* BrowserFactory::getInstance() { if (g_browserFactory == 0) { g_browserFactory = new BrowserFactory(); } return g_browserFactory; } IBrowserEngine* BrowserFactory::createWebkit(HWND hwndParent) { return rho_wmimpl_get_webkitBrowserEngine(hwndParent, rho_wmimpl_get_appinstance()); } IBrowserEngine* BrowserFactory::createIE(HWND hwndParent) { if (RHO_IS_WMDEVICE) { return CIEBrowserEngine::getInstance(hwndParent, rho_wmimpl_get_appinstance()); } else { return new CEBrowserEngine(hwndParent, rho_wmimpl_get_appinstance()); } } EBrowserEngineType BrowserFactory::convertBrowserType(rho::String browserType) { rho::String browserTypeTag; std::transform(browserType.begin(), browserType.end(), std::back_inserter(browserTypeTag), ::tolower); if (browserTypeTag == String(IETag)) { return eIE; } else if (browserTypeTag == String(webkitTag)) { return eWebkit; } return eNone; } void BrowserFactory::checkLicense(HWND hParent, HINSTANCE hLicenseInstance) { #if defined(APP_BUILD_CAPABILITY_MOTOROLA) if(!m_bLicenseChecked) { switch(m_selBrowserType) { case eIE: rho_wm_impl_CheckLicenseWithBarcodeWoWebkit(hParent, hLicenseInstance); break; case eWebkit: rho_wm_impl_CheckLicenseWithBarcode(hParent, hLicenseInstance); break; default: LOG(INFO) + "check license failed. browser engine was not selected."; } } #endif } IBrowserEngine* BrowserFactory::create(HWND hwndParent) { EBrowserEngineType selBrowserType = eNone; String xmlConfigType = rho_wmimpl_get_webengine(); String rhoConfigType = RHOCONF().getString("webengine"); String buildConfigType = get_app_build_config_item("webengine"); if (buildConfigType.empty()) { if (xmlConfigType.empty()) { selBrowserType = convertBrowserType(rhoConfigType); } else { selBrowserType = convertBrowserType(xmlConfigType); } } else { selBrowserType = convertBrowserType(buildConfigType); } if (selBrowserType == eNone) { selBrowserType = eWebkit; LOG(INFO) + "Browser engine was not set in config`s. Selected Webkit engine automatically."; } m_selBrowserType = selBrowserType; switch (selBrowserType) { case eWebkit: LOG(INFO) + "Webkit browser engine was created."; return createWebkit(hwndParent); break; case eIE: LOG(INFO) + "IE browser engine was created."; return createIE(hwndParent); break; case eNone: LOG(ERROR) + "Browser engine was not selected."; break; } return 0; } EBrowserEngineType BrowserFactory::getBrowserType() const { return m_selBrowserType; } EBrowserEngineType BrowserFactory::getCurrentBrowserType() { if (getInstance()) { return BrowserFactory::g_browserFactory->getBrowserType(); } return eNone; } }//end of rho ////////////////////////////////////////////////////////////////////////// extern "C" bool rho_wmimpl_is_browser_ieforwm() { return (bool)(rho::eIE == rho::BrowserFactory::getCurrentBrowserType()); }<commit_msg>fix crash in browser selection<commit_after>#include "StdAfx.h" #include <algorithm> #include <common/rhoconf.h> #include "BrowserFactory.h" #include "CEBrowserEngine.h" #include "IEBrowserEngine.h" ////////////////////////////////////////////////////////////////////////// extern "C" HINSTANCE rho_wmimpl_get_appinstance(); extern "C" const char* rho_wmimpl_get_webengine(); extern "C" const char* get_app_build_config_item(const char* key); #if defined(APP_BUILD_CAPABILITY_MOTOROLA) extern "C" void rho_wm_impl_CheckLicenseWithBarcode(HWND hParent, HINSTANCE hLicenseInstance); extern "C" void rho_wm_impl_CheckLicenseWithBarcodeWoWebkit(HWND hParent, HINSTANCE hLicenseInstance); #endif extern rho::IBrowserEngine* rho_wmimpl_get_webkitBrowserEngine(HWND hwndParent, HINSTANCE rhoAppInstance); ////////////////////////////////////////////////////////////////////////// const char* rho::BrowserFactory::IETag = "ie"; const char* rho::BrowserFactory::webkitTag = "webkit"; ////////////////////////////////////////////////////////////////////////// namespace rho { BrowserFactory* BrowserFactory::g_browserFactory = 0; IBrowserFactory* BrowserFactory::getInstance() { if (g_browserFactory == 0) { g_browserFactory = new BrowserFactory(); } return g_browserFactory; } IBrowserEngine* BrowserFactory::createWebkit(HWND hwndParent) { return rho_wmimpl_get_webkitBrowserEngine(hwndParent, rho_wmimpl_get_appinstance()); } IBrowserEngine* BrowserFactory::createIE(HWND hwndParent) { if (RHO_IS_WMDEVICE) { return CIEBrowserEngine::getInstance(hwndParent, rho_wmimpl_get_appinstance()); } else { return new CEBrowserEngine(hwndParent, rho_wmimpl_get_appinstance()); } } EBrowserEngineType BrowserFactory::convertBrowserType(rho::String browserType) { rho::String browserTypeTag; std::transform(browserType.begin(), browserType.end(), std::back_inserter(browserTypeTag), ::tolower); if (browserTypeTag == String(IETag)) { return eIE; } else if (browserTypeTag == String(webkitTag)) { return eWebkit; } return eNone; } void BrowserFactory::checkLicense(HWND hParent, HINSTANCE hLicenseInstance) { #if defined(APP_BUILD_CAPABILITY_MOTOROLA) if(!m_bLicenseChecked) { switch(m_selBrowserType) { case eIE: rho_wm_impl_CheckLicenseWithBarcodeWoWebkit(hParent, hLicenseInstance); break; case eWebkit: rho_wm_impl_CheckLicenseWithBarcode(hParent, hLicenseInstance); break; default: LOG(INFO) + "check license failed. browser engine was not selected."; } } #endif } IBrowserEngine* BrowserFactory::create(HWND hwndParent) { EBrowserEngineType selBrowserType = eNone; String xmlConfigType = rho_wmimpl_get_webengine(); String rhoConfigType = RHOCONF().getString("webengine"); String buildConfigType; if (get_app_build_config_item("webengine")) buildConfigType = get_app_build_config_item("webengine"); if (buildConfigType.empty()) { if (xmlConfigType.empty()) { selBrowserType = convertBrowserType(rhoConfigType); } else { selBrowserType = convertBrowserType(xmlConfigType); } } else { selBrowserType = convertBrowserType(buildConfigType); } if (selBrowserType == eNone) { selBrowserType = eWebkit; LOG(INFO) + "Browser engine was not set in config`s. Selected Webkit engine automatically."; } m_selBrowserType = selBrowserType; switch (selBrowserType) { case eWebkit: LOG(INFO) + "Webkit browser engine was created."; return createWebkit(hwndParent); break; case eIE: LOG(INFO) + "IE browser engine was created."; return createIE(hwndParent); break; case eNone: LOG(ERROR) + "Browser engine was not selected."; break; } return 0; } EBrowserEngineType BrowserFactory::getBrowserType() const { return m_selBrowserType; } EBrowserEngineType BrowserFactory::getCurrentBrowserType() { if (getInstance()) { return BrowserFactory::g_browserFactory->getBrowserType(); } return eNone; } }//end of rho ////////////////////////////////////////////////////////////////////////// extern "C" bool rho_wmimpl_is_browser_ieforwm() { return (bool)(rho::eIE == rho::BrowserFactory::getCurrentBrowserType()); }<|endoftext|>
<commit_before><?hh namespace Plenty\Plugin\Routing; use Dingo\Api\Routing\Router; /** * Api router service */ abstract class ApiRouter { abstract public function version( array<string> $version, mixed $second, mixed $third = NULL ):void; /** * Register a new GET route with the router. */ abstract public function get( string $uri, mixed $action ):\Plenty\Plugin\Routing\Route; /** * Register a new POST route with the router. */ abstract public function post( string $uri, mixed $action ):\Plenty\Plugin\Routing\Route; /** * Register a new PUT route with the router. */ abstract public function put( string $uri, mixed $action ):\Plenty\Plugin\Routing\Route; /** * Register a new PATCH route with the router. */ abstract public function patch( string $uri, mixed $action ):\Plenty\Plugin\Routing\Route; /** * Register a new DELETE route with the router. */ abstract public function delete( string $uri, mixed $action ):\Plenty\Plugin\Routing\Route; /** * Register a new OPTIONS route with the router. */ abstract public function options( string $uri, mixed $action ):\Plenty\Plugin\Routing\Route; /** * Register a new route responding to all verbs. */ abstract public function any( string $uri, mixed $action ):\Plenty\Plugin\Routing\Route; /** * Register a new route with the given verbs. */ abstract public function match( array<string> $methods, string $uri, mixed $action ):\Plenty\Plugin\Routing\Route; }<commit_msg>NEW build for branch beta7<commit_after><?hh namespace Plenty\Plugin\Routing; use Dingo\Api\Routing\Router; /** * Api router service */ abstract class ApiRouter { abstract public function version( array<string> $version, mixed $second, mixed $third = NULL ):void; /** * Register a new GET route with the router. */ abstract public function get( string $uri, mixed $action ):\Plenty\Plugin\Routing\Route; /** * Register a new POST route with the router. */ abstract public function post( string $uri, mixed $action ):\Plenty\Plugin\Routing\Route; /** * Register a new PUT route with the router. */ abstract public function put( string $uri, mixed $action ):\Plenty\Plugin\Routing\Route; /** * Register a new PATCH route with the router. */ abstract public function patch( string $uri, mixed $action ):\Plenty\Plugin\Routing\Route; /** * Register a new DELETE route with the router. */ abstract public function delete( string $uri, mixed $action ):\Plenty\Plugin\Routing\Route; /** * Register a new OPTIONS route with the router. */ abstract public function options( string $uri, mixed $action ):\Plenty\Plugin\Routing\Route; /** * Register a new route responding to all verbs. */ abstract public function any( string $uri, mixed $action ):\Plenty\Plugin\Routing\Route; /** * Route a resource to a controller. */ abstract public function resource( string $name, string $controller, array<string> $options = [] ):void; /** * Register a new route with the given verbs. */ abstract public function match( array<string> $methods, string $uri, mixed $action ):\Plenty\Plugin\Routing\Route; }<|endoftext|>
<commit_before>/* Chemfiles, an efficient IO library for chemistry file formats * Copyright (C) 2015 Guillaume Fraux * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ #include <cmath> #include <functional> #include "chemfiles/Error.hpp" #include "chemfiles/selections/expr.hpp" namespace chemfiles { namespace selections { std::ostream& operator<<(std::ostream& out, const std::unique_ptr<Expr>& expr) { out << expr->print(); return out; } //! Get the associated string to a binary operator static std::string binop_str(BinOp op) { switch (op) { case BinOp::EQ: return "=="; case BinOp::NEQ: return "!="; case BinOp::LT: return "<"; case BinOp::LE: return "<="; case BinOp::GT: return ">"; case BinOp::GE: return ">="; default: throw std::runtime_error("Hit the default case in binop_str"); } } //! Get the associated function to a binary operator for type `T` template<typename T> std::function<bool(T, T)> binop_comparison(BinOp op) { switch (op) { case BinOp::EQ: return std::equal_to<T>(); case BinOp::NEQ: return std::not_equal_to<T>(); case BinOp::LT: return std::less<T>(); case BinOp::LE: return std::less_equal<T>(); case BinOp::GT: return std::greater<T>(); case BinOp::GE: return std::greater_equal<T>(); default: throw std::runtime_error("Hit the default case in binop_str"); } } /****************************************************************************************/ std::string AllExpr::print(unsigned) const { return "all"; } std::vector<Bool> AllExpr::evaluate(const Frame& frame) const { return std::vector<Bool>(frame.natoms(), true); } template<> Ast parse<AllExpr>(token_iterator_t& begin, const token_iterator_t& end) { assert(end - begin >= 1); assert(begin->is_ident()); assert(begin->ident() == "all"); begin += 1; return Ast(new AllExpr()); } /****************************************************************************************/ std::string NoneExpr::print(unsigned) const { return "none"; } std::vector<Bool> NoneExpr::evaluate(const Frame& frame) const { return std::vector<Bool>(frame.natoms(), false); } template<> Ast parse<NoneExpr>(token_iterator_t& begin, const token_iterator_t& end) { assert(end - begin >= 1); assert(begin->is_ident()); assert(begin->ident() == "none"); begin += 1; return Ast(new NoneExpr()); } /****************************************************************************************/ std::string NameExpr::print(unsigned) const { if (equals_) { return "name == " + name_; } else { return "name != " + name_; } } std::vector<Bool> NameExpr::evaluate(const Frame& frame) const { auto res = std::vector<Bool>(frame.natoms(), false); auto topology = frame.topology(); for (size_t i=0; i<frame.natoms(); i++) { res[i] = ((topology[i].name() == name_) == equals_); } return res; } template<> Ast parse<NameExpr>(token_iterator_t& begin, const token_iterator_t& end) { assert(end - begin >= 3); assert(begin[2].is_ident()); assert(begin[2].ident() == "name"); if (!begin[1].is_ident() || !(begin[0].type() == Token::EQ || begin[0].type() == Token::NEQ)) { throw ParserError("Name selection must follow the pattern: 'name == {name} | name != {name}'"); } auto equals = (begin[0].type() == Token::EQ); auto name = begin[1].ident(); begin += 3; return Ast(new NameExpr(name, equals)); } /****************************************************************************************/ std::string PositionExpr::print(unsigned) const { return coord_.to_string() + " " + binop_str(op_) + " " + std::to_string(val_); } std::vector<Bool> PositionExpr::evaluate(const Frame& frame) const { auto res = std::vector<Bool>(frame.natoms(), false); auto compare = binop_comparison<double>(op_); auto j = coord_.as_index(); auto positions = frame.positions(); for (size_t i=0; i<frame.natoms(); i++) { res[i] = compare(positions[i][j], val_); } return res; } template<> Ast parse<PositionExpr>(token_iterator_t& begin, const token_iterator_t& end) { assert(end - begin >= 3); assert(begin[2].is_ident()); assert(begin[2].ident() == "x" || begin[2].ident() == "y" || begin[2].ident() == "z"); assert(begin->is_binary_op()); auto coord = Coordinate(begin[2].ident()); auto op = BinOp(begin[0].type()); if (!begin[1].is_number()) { throw ParserError("Position selection can only contain number as criterium."); } auto val = begin[1].number(); begin += 3; return Ast(new PositionExpr(coord, op, val)); } /****************************************************************************************/ std::string VelocityExpr::print(unsigned) const { return "v" + coord_.to_string() + " " + binop_str(op_) + " " + std::to_string(val_); } std::vector<Bool> VelocityExpr::evaluate(const Frame& frame) const { auto res = std::vector<Bool>(frame.natoms(), false); if (frame.velocities()) { auto compare = binop_comparison<double>(op_); auto j = coord_.as_index(); auto velocities = *frame.velocities(); for (size_t i=0; i<frame.natoms(); i++) { res[i] = compare(velocities[i][j], val_); } } return res; } template<> Ast parse<VelocityExpr>(token_iterator_t& begin, const token_iterator_t& end) { assert(end - begin >= 3); assert(begin[2].is_ident()); assert(begin[2].ident() == "vx" || begin[2].ident() == "vy" || begin[2].ident() == "vz"); assert(begin->is_binary_op()); auto coord = Coordinate(begin[2].ident().substr(1)); auto op = BinOp(begin[0].type()); if (!begin[1].is_number()) { throw ParserError("Veclocity selection can only contain number as criterium."); } auto val = begin[1].number(); begin += 3; return Ast(new VelocityExpr(coord, op, val));; } /****************************************************************************************/ std::string IndexExpr::print(unsigned) const { return "index " + binop_str(op_) + " " + std::to_string(val_); } std::vector<Bool> IndexExpr::evaluate(const Frame& frame) const { auto res = std::vector<Bool>(frame.natoms(), false); auto compare = binop_comparison<size_t>(op_); for (size_t i=0; i<frame.natoms(); i++) { res[i] = compare(i, val_); } return res; } template<> Ast parse<IndexExpr>(token_iterator_t& begin, const token_iterator_t& end) { assert(end - begin >= 3); assert(begin[2].is_ident()); assert(begin[2].ident() == "index"); assert(begin->is_binary_op()); auto op = BinOp(begin[0].type()); if (begin[1].is_number()) { auto num = begin[1].number(); if (ceil(num) != num) { throw ParserError("Index selection should contain an integer"); } } else { throw ParserError("Index selection should contain an integer"); } auto val = static_cast<std::size_t>(begin[1].number()); begin += 3; return Ast(new IndexExpr(op, val));; } /****************************************************************************************/ std::string MassExpr::print(unsigned) const { return "mass " + binop_str(op_) + " " + std::to_string(val_); } std::vector<Bool> MassExpr::evaluate(const Frame& frame) const { auto res = std::vector<Bool>(frame.natoms(), false); auto compare = binop_comparison<double>(op_); auto topology = frame.topology(); for (size_t i=0; i<frame.natoms(); i++) { res[i] = compare(topology[i].mass(), val_); } return res; } template<> Ast parse<MassExpr>(token_iterator_t& begin, const token_iterator_t& end) { assert(end - begin >= 3); assert(begin[2].is_ident()); assert(begin[2].ident() == "mass"); assert(begin[0].is_binary_op()); if (!begin[1].is_number()) { throw ParserError("Mass selection should contain a number"); } auto op = BinOp(begin[0].type()); auto val = static_cast<std::size_t>(begin[1].number()); begin += 3; return Ast(new MassExpr(op, val));; } /****************************************************************************************/ std::string AndExpr::print(unsigned delta) const { auto lhs = lhs_->print(7); auto rhs = rhs_->print(7); return "and -> " + lhs + "\n" + std::string(delta, ' ') + " -> " + rhs; } std::vector<Bool> AndExpr::evaluate(const Frame& frame) const { auto lhs = lhs_->evaluate(frame); auto rhs = rhs_->evaluate(frame); assert(lhs.size() == rhs.size()); assert(lhs.size() == frame.natoms()); for (size_t i=0; i<frame.natoms(); i++) { lhs[i] = lhs[i] && rhs[i]; } return lhs; } template<> Ast parse<AndExpr>(token_iterator_t& begin, const token_iterator_t& end) { assert(begin[0].type() == Token::AND); begin += 1; if (begin == end) throw ParserError("Missing right-hand side operand to 'and'"); Ast rhs = nullptr; try { rhs = dispatch_parsing(begin, end); } catch (const ParserError& e) { throw ParserError(std::string("Error in right-hand side operand to 'and': ") + e.what()); } if (begin == end) throw ParserError("Missing left-hand side operand to 'and'"); Ast lhs = nullptr; try { lhs = dispatch_parsing(begin, end); } catch (const ParserError& e) { throw ParserError(std::string("Error in left-hand side operand to 'and': ") + e.what()); } return Ast(new AndExpr(std::move(lhs), std::move(rhs))); } /****************************************************************************************/ std::string OrExpr::print(unsigned delta) const { auto lhs = lhs_->print(6); auto rhs = rhs_->print(6); return "or -> " + lhs + "\n" + std::string(delta, ' ') + " -> " + rhs; } std::vector<Bool> OrExpr::evaluate(const Frame& frame) const { auto lhs = lhs_->evaluate(frame); auto rhs = rhs_->evaluate(frame); assert(lhs.size() == rhs.size()); assert(lhs.size() == frame.natoms()); for (size_t i=0; i<frame.natoms(); i++) { lhs[i] = lhs[i] || rhs[i]; } return lhs; } template<> Ast parse<OrExpr>(token_iterator_t& begin, const token_iterator_t& end) { assert(begin[0].type() == Token::OR); begin += 1; if (begin == end) throw ParserError("Missing right-hand side operand to 'or'"); Ast rhs = nullptr; try { rhs = dispatch_parsing(begin, end); } catch (const ParserError& e) { throw ParserError(std::string("Error in right-hand side operand to 'or': ") + e.what()); } if (begin == end) throw ParserError("Missing left-hand side operand to 'or'"); Ast lhs = nullptr; try { lhs = dispatch_parsing(begin, end); } catch (const ParserError& e) { throw ParserError(std::string("Error in left-hand side operand to 'or': ") + e.what()); } return Ast(new OrExpr(std::move(lhs), std::move(rhs))); } /****************************************************************************************/ std::string NotExpr::print(unsigned) const { auto ast = ast_->print(4); return "not " + ast; } std::vector<Bool> NotExpr::evaluate(const Frame& frame) const { auto res = ast_->evaluate(frame); assert(res.size() == frame.natoms()); for (size_t i=0; i<frame.natoms(); i++) { res[i] = !res[i]; } return res; } template<> Ast parse<NotExpr>(token_iterator_t& begin, const token_iterator_t& end) { assert(begin[0].type() == Token::NOT); begin += 1; if (begin == end) throw ParserError("Missing operand to 'not'"); Ast ast = nullptr; try { ast = dispatch_parsing(begin, end); } catch (const ParserError& e) { throw ParserError(std::string("Error in operand of 'not': ") + e.what()); } return Ast(new NotExpr(std::move(ast))); } }} // namespace chemfiles && namespace selections <commit_msg>A mass is a float, not an integer<commit_after>/* Chemfiles, an efficient IO library for chemistry file formats * Copyright (C) 2015 Guillaume Fraux * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ #include <cmath> #include <functional> #include "chemfiles/Error.hpp" #include "chemfiles/selections/expr.hpp" namespace chemfiles { namespace selections { std::ostream& operator<<(std::ostream& out, const std::unique_ptr<Expr>& expr) { out << expr->print(); return out; } //! Get the associated string to a binary operator static std::string binop_str(BinOp op) { switch (op) { case BinOp::EQ: return "=="; case BinOp::NEQ: return "!="; case BinOp::LT: return "<"; case BinOp::LE: return "<="; case BinOp::GT: return ">"; case BinOp::GE: return ">="; default: throw std::runtime_error("Hit the default case in binop_str"); } } //! Get the associated function to a binary operator for type `T` template<typename T> std::function<bool(T, T)> binop_comparison(BinOp op) { switch (op) { case BinOp::EQ: return std::equal_to<T>(); case BinOp::NEQ: return std::not_equal_to<T>(); case BinOp::LT: return std::less<T>(); case BinOp::LE: return std::less_equal<T>(); case BinOp::GT: return std::greater<T>(); case BinOp::GE: return std::greater_equal<T>(); default: throw std::runtime_error("Hit the default case in binop_str"); } } /****************************************************************************************/ std::string AllExpr::print(unsigned) const { return "all"; } std::vector<Bool> AllExpr::evaluate(const Frame& frame) const { return std::vector<Bool>(frame.natoms(), true); } template<> Ast parse<AllExpr>(token_iterator_t& begin, const token_iterator_t& end) { assert(end - begin >= 1); assert(begin->is_ident()); assert(begin->ident() == "all"); begin += 1; return Ast(new AllExpr()); } /****************************************************************************************/ std::string NoneExpr::print(unsigned) const { return "none"; } std::vector<Bool> NoneExpr::evaluate(const Frame& frame) const { return std::vector<Bool>(frame.natoms(), false); } template<> Ast parse<NoneExpr>(token_iterator_t& begin, const token_iterator_t& end) { assert(end - begin >= 1); assert(begin->is_ident()); assert(begin->ident() == "none"); begin += 1; return Ast(new NoneExpr()); } /****************************************************************************************/ std::string NameExpr::print(unsigned) const { if (equals_) { return "name == " + name_; } else { return "name != " + name_; } } std::vector<Bool> NameExpr::evaluate(const Frame& frame) const { auto res = std::vector<Bool>(frame.natoms(), false); auto topology = frame.topology(); for (size_t i=0; i<frame.natoms(); i++) { res[i] = ((topology[i].name() == name_) == equals_); } return res; } template<> Ast parse<NameExpr>(token_iterator_t& begin, const token_iterator_t& end) { assert(end - begin >= 3); assert(begin[2].is_ident()); assert(begin[2].ident() == "name"); if (!begin[1].is_ident() || !(begin[0].type() == Token::EQ || begin[0].type() == Token::NEQ)) { throw ParserError("Name selection must follow the pattern: 'name == {name} | name != {name}'"); } auto equals = (begin[0].type() == Token::EQ); auto name = begin[1].ident(); begin += 3; return Ast(new NameExpr(name, equals)); } /****************************************************************************************/ std::string PositionExpr::print(unsigned) const { return coord_.to_string() + " " + binop_str(op_) + " " + std::to_string(val_); } std::vector<Bool> PositionExpr::evaluate(const Frame& frame) const { auto res = std::vector<Bool>(frame.natoms(), false); auto compare = binop_comparison<double>(op_); auto j = coord_.as_index(); auto positions = frame.positions(); for (size_t i=0; i<frame.natoms(); i++) { res[i] = compare(positions[i][j], val_); } return res; } template<> Ast parse<PositionExpr>(token_iterator_t& begin, const token_iterator_t& end) { assert(end - begin >= 3); assert(begin[2].is_ident()); assert(begin[2].ident() == "x" || begin[2].ident() == "y" || begin[2].ident() == "z"); assert(begin->is_binary_op()); auto coord = Coordinate(begin[2].ident()); auto op = BinOp(begin[0].type()); if (!begin[1].is_number()) { throw ParserError("Position selection can only contain number as criterium."); } auto val = begin[1].number(); begin += 3; return Ast(new PositionExpr(coord, op, val)); } /****************************************************************************************/ std::string VelocityExpr::print(unsigned) const { return "v" + coord_.to_string() + " " + binop_str(op_) + " " + std::to_string(val_); } std::vector<Bool> VelocityExpr::evaluate(const Frame& frame) const { auto res = std::vector<Bool>(frame.natoms(), false); if (frame.velocities()) { auto compare = binop_comparison<double>(op_); auto j = coord_.as_index(); auto velocities = *frame.velocities(); for (size_t i=0; i<frame.natoms(); i++) { res[i] = compare(velocities[i][j], val_); } } return res; } template<> Ast parse<VelocityExpr>(token_iterator_t& begin, const token_iterator_t& end) { assert(end - begin >= 3); assert(begin[2].is_ident()); assert(begin[2].ident() == "vx" || begin[2].ident() == "vy" || begin[2].ident() == "vz"); assert(begin->is_binary_op()); auto coord = Coordinate(begin[2].ident().substr(1)); auto op = BinOp(begin[0].type()); if (!begin[1].is_number()) { throw ParserError("Veclocity selection can only contain number as criterium."); } auto val = begin[1].number(); begin += 3; return Ast(new VelocityExpr(coord, op, val));; } /****************************************************************************************/ std::string IndexExpr::print(unsigned) const { return "index " + binop_str(op_) + " " + std::to_string(val_); } std::vector<Bool> IndexExpr::evaluate(const Frame& frame) const { auto res = std::vector<Bool>(frame.natoms(), false); auto compare = binop_comparison<size_t>(op_); for (size_t i=0; i<frame.natoms(); i++) { res[i] = compare(i, val_); } return res; } template<> Ast parse<IndexExpr>(token_iterator_t& begin, const token_iterator_t& end) { assert(end - begin >= 3); assert(begin[2].is_ident()); assert(begin[2].ident() == "index"); assert(begin->is_binary_op()); auto op = BinOp(begin[0].type()); if (begin[1].is_number()) { auto num = begin[1].number(); if (ceil(num) != num) { throw ParserError("Index selection should contain an integer"); } } else { throw ParserError("Index selection should contain an integer"); } auto val = static_cast<std::size_t>(begin[1].number()); begin += 3; return Ast(new IndexExpr(op, val));; } /****************************************************************************************/ std::string MassExpr::print(unsigned) const { return "mass " + binop_str(op_) + " " + std::to_string(val_); } std::vector<Bool> MassExpr::evaluate(const Frame& frame) const { auto res = std::vector<Bool>(frame.natoms(), false); auto compare = binop_comparison<double>(op_); auto topology = frame.topology(); for (size_t i=0; i<frame.natoms(); i++) { res[i] = compare(topology[i].mass(), val_); } return res; } template<> Ast parse<MassExpr>(token_iterator_t& begin, const token_iterator_t& end) { assert(end - begin >= 3); assert(begin[2].is_ident()); assert(begin[2].ident() == "mass"); assert(begin[0].is_binary_op()); if (!begin[1].is_number()) { throw ParserError("Mass selection should contain a number"); } auto op = BinOp(begin[0].type()); auto val = begin[1].number(); begin += 3; return Ast(new MassExpr(op, val));; } /****************************************************************************************/ std::string AndExpr::print(unsigned delta) const { auto lhs = lhs_->print(7); auto rhs = rhs_->print(7); return "and -> " + lhs + "\n" + std::string(delta, ' ') + " -> " + rhs; } std::vector<Bool> AndExpr::evaluate(const Frame& frame) const { auto lhs = lhs_->evaluate(frame); auto rhs = rhs_->evaluate(frame); assert(lhs.size() == rhs.size()); assert(lhs.size() == frame.natoms()); for (size_t i=0; i<frame.natoms(); i++) { lhs[i] = lhs[i] && rhs[i]; } return lhs; } template<> Ast parse<AndExpr>(token_iterator_t& begin, const token_iterator_t& end) { assert(begin[0].type() == Token::AND); begin += 1; if (begin == end) throw ParserError("Missing right-hand side operand to 'and'"); Ast rhs = nullptr; try { rhs = dispatch_parsing(begin, end); } catch (const ParserError& e) { throw ParserError(std::string("Error in right-hand side operand to 'and': ") + e.what()); } if (begin == end) throw ParserError("Missing left-hand side operand to 'and'"); Ast lhs = nullptr; try { lhs = dispatch_parsing(begin, end); } catch (const ParserError& e) { throw ParserError(std::string("Error in left-hand side operand to 'and': ") + e.what()); } return Ast(new AndExpr(std::move(lhs), std::move(rhs))); } /****************************************************************************************/ std::string OrExpr::print(unsigned delta) const { auto lhs = lhs_->print(6); auto rhs = rhs_->print(6); return "or -> " + lhs + "\n" + std::string(delta, ' ') + " -> " + rhs; } std::vector<Bool> OrExpr::evaluate(const Frame& frame) const { auto lhs = lhs_->evaluate(frame); auto rhs = rhs_->evaluate(frame); assert(lhs.size() == rhs.size()); assert(lhs.size() == frame.natoms()); for (size_t i=0; i<frame.natoms(); i++) { lhs[i] = lhs[i] || rhs[i]; } return lhs; } template<> Ast parse<OrExpr>(token_iterator_t& begin, const token_iterator_t& end) { assert(begin[0].type() == Token::OR); begin += 1; if (begin == end) throw ParserError("Missing right-hand side operand to 'or'"); Ast rhs = nullptr; try { rhs = dispatch_parsing(begin, end); } catch (const ParserError& e) { throw ParserError(std::string("Error in right-hand side operand to 'or': ") + e.what()); } if (begin == end) throw ParserError("Missing left-hand side operand to 'or'"); Ast lhs = nullptr; try { lhs = dispatch_parsing(begin, end); } catch (const ParserError& e) { throw ParserError(std::string("Error in left-hand side operand to 'or': ") + e.what()); } return Ast(new OrExpr(std::move(lhs), std::move(rhs))); } /****************************************************************************************/ std::string NotExpr::print(unsigned) const { auto ast = ast_->print(4); return "not " + ast; } std::vector<Bool> NotExpr::evaluate(const Frame& frame) const { auto res = ast_->evaluate(frame); assert(res.size() == frame.natoms()); for (size_t i=0; i<frame.natoms(); i++) { res[i] = !res[i]; } return res; } template<> Ast parse<NotExpr>(token_iterator_t& begin, const token_iterator_t& end) { assert(begin[0].type() == Token::NOT); begin += 1; if (begin == end) throw ParserError("Missing operand to 'not'"); Ast ast = nullptr; try { ast = dispatch_parsing(begin, end); } catch (const ParserError& e) { throw ParserError(std::string("Error in operand of 'not': ") + e.what()); } return Ast(new NotExpr(std::move(ast))); } }} // namespace chemfiles && namespace selections <|endoftext|>
<commit_before>#include "Stdafx.h" using namespace System; using namespace System::Reflection; using namespace System::Runtime::CompilerServices; using namespace System::Runtime::InteropServices; using namespace System::Security::Permissions; [assembly:AssemblyTitle("CefSharp")]; [assembly:AssemblyCompany("Anthony Taranto")]; [assembly:AssemblyProduct("CefSharp")]; [assembly:AssemblyCopyright("Copyright (c) Anthony Taranto 2013")]; [assembly:AssemblyVersion("1.25.2.*")]; [assembly:ComVisible(false)]; [assembly:CLSCompliant(true)]; [assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)]; <commit_msg>Fixed version number and copyright (shouldn't refer to a single person, but rather the CefSharp project as a legal "virtual entity" :)<commit_after>#include "Stdafx.h" using namespace System; using namespace System::Reflection; using namespace System::Runtime::CompilerServices; using namespace System::Runtime::InteropServices; using namespace System::Security::Permissions; [assembly:AssemblyTitle("CefSharp")]; [assembly:AssemblyCompany("The CefSharp Project")]; [assembly:AssemblyProduct("CefSharp")]; [assembly:AssemblyCopyright("Copyright (c) The CefSharp Project 2010-2013")]; [assembly:AssemblyVersion("3.27.2.*")]; [assembly:ComVisible(false)]; [assembly:CLSCompliant(true)]; [assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)]; <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2006 Torus Knot Software Ltd Also see acknowledgements in Readme.html This program 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 2 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser 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, or go to http://www.gnu.org/copyleft/lesser.txt. You may alternatively use this source under the terms of a specific version of the OGRE Unrestricted License provided you have obtained such a license from Torus Knot Software Ltd. ----------------------------------------------------------------------------- OgrePCZFrustum.cpp - PCZ Supplemental culling Frustum This isn't really a traditional "frustum", but more a collection of extra culling planes used by the PCZ Scene Manager for supplementing the camera culling and light zone culling by creating extra culling planes from visible portals. Since portals are 4 sided, the extra culling planes tend to form frustums (pyramids) but nothing in the code really assumes that the culling planes are frustums. They are just treated as planes. The "originPlane" is a culling plane which passes through the origin point specified. It is used to cull portals which are close to, but behind the camera view. (the nature of the culling routine doesn't give correct results if you just use the "near" plane of the standard camera frustum (unless that near plane distance is 0.0, but that is highly not recommended for other reasons having to do with having a legal view frustum). ----------------------------------------------------------------------------- begin : Tue May 29 2007 author : Eric Cha email : ericc@xenopi.com ----------------------------------------------------------------------------- */ #include "OgrePCZFrustum.h" #include "OgrePortal.h" namespace Ogre { PCZFrustum::PCZFrustum() : mProjType(PT_PERSPECTIVE), mUseOriginPlane(false) { } PCZFrustum::~PCZFrustum() { removeAllCullingPlanes(); // clear out the culling plane reservoir PCPlaneList::iterator pit = mCullingPlaneReservoir.begin(); while ( pit != mCullingPlaneReservoir.end() ) { PCPlane * plane = *pit; // go to next entry pit++; //delete the entry in the list OGRE_DELETE_T(plane, PCPlane, MEMCATEGORY_SCENE_CONTROL); } mCullingPlaneReservoir.clear(); } bool PCZFrustum::isVisible( const AxisAlignedBox & bound) const { // Get centre of the box Vector3 centre = bound.getCenter(); // Get the half-size of the box Vector3 halfSize = bound.getHalfSize(); // Check originplane if told to if (mUseOriginPlane) { Plane::Side side = mOriginPlane.getSide(centre, halfSize); if (side == Plane::NEGATIVE_SIDE) { return false; } } // For each extra active culling plane, see if the entire aabb is on the negative side // If so, object is not visible PCPlaneList::const_iterator pit = mActiveCullingPlanes.begin(); while ( pit != mActiveCullingPlanes.end() ) { PCPlane * plane = *pit; Plane::Side xside = plane->getSide(centre, halfSize); if (xside == Plane::NEGATIVE_SIDE) { return false; } pit++; } return true; } bool PCZFrustum::isVisible( const Sphere & bound) const { // Check originplane if told to if (mUseOriginPlane) { Plane::Side side = mOriginPlane.getSide(bound.getCenter()); if (side == Plane::NEGATIVE_SIDE) { Real dist = mOriginPlane.getDistance(bound.getCenter()); if (dist > bound.getRadius()) { return false; } } } // For each extra active culling plane, see if the entire sphere is on the negative side // If so, object is not visible PCPlaneList::const_iterator pit = mActiveCullingPlanes.begin(); while ( pit != mActiveCullingPlanes.end() ) { PCPlane * plane = *pit; Plane::Side xside = plane->getSide(bound.getCenter()); if (xside == Plane::NEGATIVE_SIDE) { Real dist = plane->getDistance(bound.getCenter()); if (dist > bound.getRadius()) { return false; } } pit++; } return true; } /* isVisible() function for portals */ // NOTE: Everything needs to be updated spatially before this function is // called including portal corners, frustum planes, etc. bool PCZFrustum::isVisible(Portal * portal) { // if portal isn't open, it's not visible if (!portal->isOpen()) { return false; } // if the frustum has no planes, just return true if (mActiveCullingPlanes.size() == 0) { return true; } // check if this portal is already in the list of active culling planes (avoid // infinite recursion case) PCPlaneList::const_iterator pit = mActiveCullingPlanes.begin(); while ( pit != mActiveCullingPlanes.end() ) { PCPlane * plane = *pit; if (plane->getPortal() == portal) { return false; } pit++; } // if portal is of type AABB or Sphere, then use simple bound check against planes if (portal->getType() == Portal::PORTAL_TYPE_AABB) { AxisAlignedBox aabb; aabb.setExtents(portal->getDerivedCorner(0), portal->getDerivedCorner(1)); return isVisible(aabb); } else if (portal->getType() == Portal::PORTAL_TYPE_SPHERE) { return isVisible(portal->getDerivedSphere()); } // check if the portal norm is facing the frustum Vector3 frustumToPortal = portal->getDerivedCP() - mOrigin; Vector3 portalDirection = portal->getDerivedDirection(); Real dotProduct = frustumToPortal.dotProduct(portalDirection); if ( dotProduct > 0 ) { // portal is faced away from Frustum return false; } // check against frustum culling planes bool visible_flag; // Check originPlane if told to if (mUseOriginPlane) { // set the visible flag to false visible_flag = false; // we have to check each corner of the portal for (int corner = 0; corner < 4; corner++) { Plane::Side side = mOriginPlane.getSide(portal->getDerivedCorner(corner)); if (side != Plane::NEGATIVE_SIDE) { visible_flag = true; } } // if the visible_flag is still false, then the origin plane // culled all the portal points if (visible_flag == false) { // ALL corners on negative side therefore out of view return false; } } // For each active culling plane, see if all portal points are on the negative // side. If so, the portal is not visible pit = mActiveCullingPlanes.begin(); while ( pit != mActiveCullingPlanes.end() ) { PCPlane * plane = *pit; // set the visible flag to false visible_flag = false; // we have to check each corner of the portal for (int corner = 0; corner < 4; corner++) { Plane::Side side =plane->getSide(portal->getDerivedCorner(corner)); if (side != Plane::NEGATIVE_SIDE) { visible_flag = true; } } // if the visible_flag is still false, then this plane // culled all the portal points if (visible_flag == false) { // ALL corners on negative side therefore out of view return false; } pit++; } // no plane culled all the portal points and the norm // was facing the frustum, so this portal is visible return true; } /* A 'more detailed' check for visibility of an AAB. This function returns none, partial, or full for visibility of the box. This is useful for stuff like Octree leaf culling */ PCZFrustum::Visibility PCZFrustum::getVisibility( const AxisAlignedBox &bound ) { // Null boxes always invisible if ( bound.isNull() ) return NONE; // Get centre of the box Vector3 centre = bound.getCenter(); // Get the half-size of the box Vector3 halfSize = bound.getHalfSize(); bool all_inside = true; // Check originplane if told to if (mUseOriginPlane) { Plane::Side side = mOriginPlane.getSide(centre, halfSize); if (side == Plane::NEGATIVE_SIDE) { return NONE; } // We can't return now as the box could be later on the negative side of another plane. if(side == Plane::BOTH_SIDE) { all_inside = false; } } // For each active culling plane, see if the entire aabb is on the negative side // If so, object is not visible PCPlaneList::iterator pit = mActiveCullingPlanes.begin(); while ( pit != mActiveCullingPlanes.end() ) { PCPlane * plane = *pit; Plane::Side xside = plane->getSide(centre, halfSize); if(xside == Plane::NEGATIVE_SIDE) { return NONE; } // We can't return now as the box could be later on the negative side of a plane. if(xside == Plane::BOTH_SIDE) { all_inside = false; } pit++; } if ( all_inside ) return FULL; else return PARTIAL; } // calculate culling planes from portal and frustum // origin and add to list of culling planes // NOTE: returns 0 if portal was completely culled by existing planes // returns > 0 if culling planes are added (# is planes added) int PCZFrustum::addPortalCullingPlanes(Portal * portal) { int addedcullingplanes = 0; // If portal is of type aabb or sphere, add a plane which is same as frustum // origin plane (ie. redundant). We do this because we need the plane as a flag // to prevent infinite recursion if (portal->getType() == Portal::PORTAL_TYPE_AABB || portal->getType() == Portal::PORTAL_TYPE_SPHERE) { PCPlane * newPlane = getUnusedCullingPlane(); newPlane->setFromOgrePlane(mOriginPlane); newPlane->setPortal(portal); mActiveCullingPlanes.push_front(newPlane); addedcullingplanes++; return addedcullingplanes; } // For portal Quads: Up to 4 planes can be added by the sides of a portal quad. // Each plane is created from 2 corners (world space) of the portal and the // frustum origin (world space). int i,j; Plane::Side pt0_side, pt1_side; bool visible; PCPlaneList::iterator pit; for (i=0;i<4;i++) { // first check if both corners are outside of one of the existing planes j = i+1; if (j > 3) { j = 0; } visible = true; pit = mActiveCullingPlanes.begin(); while ( pit != mActiveCullingPlanes.end() ) { PCPlane * plane = *pit; pt0_side = plane->getSide(portal->getDerivedCorner(i)); pt1_side = plane->getSide(portal->getDerivedCorner(j)); if (pt0_side == Plane::NEGATIVE_SIDE && pt1_side == Plane::NEGATIVE_SIDE) { // the portal edge was actually completely culled by one of culling planes visible = false; } pit++; } if (visible) { // add the plane created from the two portal corner points and the frustum location // to the culling plane PCPlane * newPlane = getUnusedCullingPlane(); if (mProjType == PT_ORTHOGRAPHIC) // use camera direction if projection is orthographic. { newPlane->redefine(portal->getDerivedCorner(j) + mOriginPlane.normal, portal->getDerivedCorner(j), portal->getDerivedCorner(i)); } else { newPlane->redefine(mOrigin, portal->getDerivedCorner(j), portal->getDerivedCorner(i)); } newPlane->setPortal(portal); mActiveCullingPlanes.push_front(newPlane); addedcullingplanes++; } } // if we added ANY planes from the quad portal, we should add the plane of the // portal itself as an additional culling plane. if (addedcullingplanes > 0) { PCPlane * newPlane = getUnusedCullingPlane(); newPlane->redefine(portal->getDerivedCorner(2), portal->getDerivedCorner(1), portal->getDerivedCorner(0)); newPlane->setPortal(portal); mActiveCullingPlanes.push_back(newPlane); addedcullingplanes++; } return addedcullingplanes; } // remove culling planes created from the given portal void PCZFrustum::removePortalCullingPlanes(Portal *portal) { PCPlaneList::iterator pit = mActiveCullingPlanes.begin(); while ( pit != mActiveCullingPlanes.end() ) { PCPlane * plane = *pit; if (plane->getPortal() == portal) { // put the plane back in the reservoir mCullingPlaneReservoir.push_front(plane); // erase the entry from the active culling plane list pit = mActiveCullingPlanes.erase(pit); } else { pit++; } } } // remove all active extra culling planes // NOTE: Does not change the use of the originPlane! void PCZFrustum::removeAllCullingPlanes(void) { PCPlaneList::iterator pit = mActiveCullingPlanes.begin(); while ( pit != mActiveCullingPlanes.end() ) { PCPlane * plane = *pit; // put the plane back in the reservoir mCullingPlaneReservoir.push_front(plane); // go to next entry pit++; } mActiveCullingPlanes.clear(); } // set the origin plane void PCZFrustum::setOriginPlane(const Vector3 &rkNormal, const Vector3 &rkPoint) { mOriginPlane.redefine(rkNormal, rkPoint); } // get an unused PCPlane from the CullingPlane Reservoir // note that this removes the PCPlane from the reservoir! PCPlane * PCZFrustum::getUnusedCullingPlane(void) { PCPlane * plane = 0; if (mCullingPlaneReservoir.size() > 0) { PCPlaneList::iterator pit = mCullingPlaneReservoir.begin(); plane = *pit; mCullingPlaneReservoir.erase(pit); return plane; } // no available planes! create one plane = OGRE_NEW_T(PCPlane, MEMCATEGORY_SCENE_CONTROL); return plane; } }<commit_msg>Backport PCZ fix from trunk: cater for null and infinite AABBs<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2006 Torus Knot Software Ltd Also see acknowledgements in Readme.html This program 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 2 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser 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, or go to http://www.gnu.org/copyleft/lesser.txt. You may alternatively use this source under the terms of a specific version of the OGRE Unrestricted License provided you have obtained such a license from Torus Knot Software Ltd. ----------------------------------------------------------------------------- OgrePCZFrustum.cpp - PCZ Supplemental culling Frustum This isn't really a traditional "frustum", but more a collection of extra culling planes used by the PCZ Scene Manager for supplementing the camera culling and light zone culling by creating extra culling planes from visible portals. Since portals are 4 sided, the extra culling planes tend to form frustums (pyramids) but nothing in the code really assumes that the culling planes are frustums. They are just treated as planes. The "originPlane" is a culling plane which passes through the origin point specified. It is used to cull portals which are close to, but behind the camera view. (the nature of the culling routine doesn't give correct results if you just use the "near" plane of the standard camera frustum (unless that near plane distance is 0.0, but that is highly not recommended for other reasons having to do with having a legal view frustum). ----------------------------------------------------------------------------- begin : Tue May 29 2007 author : Eric Cha email : ericc@xenopi.com ----------------------------------------------------------------------------- */ #include "OgrePCZFrustum.h" #include "OgrePortal.h" namespace Ogre { PCZFrustum::PCZFrustum() : mProjType(PT_PERSPECTIVE), mUseOriginPlane(false) { } PCZFrustum::~PCZFrustum() { removeAllCullingPlanes(); // clear out the culling plane reservoir PCPlaneList::iterator pit = mCullingPlaneReservoir.begin(); while ( pit != mCullingPlaneReservoir.end() ) { PCPlane * plane = *pit; // go to next entry pit++; //delete the entry in the list OGRE_DELETE_T(plane, PCPlane, MEMCATEGORY_SCENE_CONTROL); } mCullingPlaneReservoir.clear(); } bool PCZFrustum::isVisible( const AxisAlignedBox & bound) const { // Null boxes are always invisible if (bound.isNull()) return false; // Infinite boxes are always visible if (bound.isInfinite()) return true; // Get centre of the box Vector3 centre = bound.getCenter(); // Get the half-size of the box Vector3 halfSize = bound.getHalfSize(); // Check originplane if told to if (mUseOriginPlane) { Plane::Side side = mOriginPlane.getSide(centre, halfSize); if (side == Plane::NEGATIVE_SIDE) { return false; } } // For each extra active culling plane, see if the entire aabb is on the negative side // If so, object is not visible PCPlaneList::const_iterator pit = mActiveCullingPlanes.begin(); while ( pit != mActiveCullingPlanes.end() ) { PCPlane * plane = *pit; Plane::Side xside = plane->getSide(centre, halfSize); if (xside == Plane::NEGATIVE_SIDE) { return false; } pit++; } return true; } bool PCZFrustum::isVisible( const Sphere & bound) const { // Check originplane if told to if (mUseOriginPlane) { Plane::Side side = mOriginPlane.getSide(bound.getCenter()); if (side == Plane::NEGATIVE_SIDE) { Real dist = mOriginPlane.getDistance(bound.getCenter()); if (dist > bound.getRadius()) { return false; } } } // For each extra active culling plane, see if the entire sphere is on the negative side // If so, object is not visible PCPlaneList::const_iterator pit = mActiveCullingPlanes.begin(); while ( pit != mActiveCullingPlanes.end() ) { PCPlane * plane = *pit; Plane::Side xside = plane->getSide(bound.getCenter()); if (xside == Plane::NEGATIVE_SIDE) { Real dist = plane->getDistance(bound.getCenter()); if (dist > bound.getRadius()) { return false; } } pit++; } return true; } /* isVisible() function for portals */ // NOTE: Everything needs to be updated spatially before this function is // called including portal corners, frustum planes, etc. bool PCZFrustum::isVisible(Portal * portal) { // if portal isn't open, it's not visible if (!portal->isOpen()) { return false; } // if the frustum has no planes, just return true if (mActiveCullingPlanes.size() == 0) { return true; } // check if this portal is already in the list of active culling planes (avoid // infinite recursion case) PCPlaneList::const_iterator pit = mActiveCullingPlanes.begin(); while ( pit != mActiveCullingPlanes.end() ) { PCPlane * plane = *pit; if (plane->getPortal() == portal) { return false; } pit++; } // if portal is of type AABB or Sphere, then use simple bound check against planes if (portal->getType() == Portal::PORTAL_TYPE_AABB) { AxisAlignedBox aabb; aabb.setExtents(portal->getDerivedCorner(0), portal->getDerivedCorner(1)); return isVisible(aabb); } else if (portal->getType() == Portal::PORTAL_TYPE_SPHERE) { return isVisible(portal->getDerivedSphere()); } // check if the portal norm is facing the frustum Vector3 frustumToPortal = portal->getDerivedCP() - mOrigin; Vector3 portalDirection = portal->getDerivedDirection(); Real dotProduct = frustumToPortal.dotProduct(portalDirection); if ( dotProduct > 0 ) { // portal is faced away from Frustum return false; } // check against frustum culling planes bool visible_flag; // Check originPlane if told to if (mUseOriginPlane) { // set the visible flag to false visible_flag = false; // we have to check each corner of the portal for (int corner = 0; corner < 4; corner++) { Plane::Side side = mOriginPlane.getSide(portal->getDerivedCorner(corner)); if (side != Plane::NEGATIVE_SIDE) { visible_flag = true; } } // if the visible_flag is still false, then the origin plane // culled all the portal points if (visible_flag == false) { // ALL corners on negative side therefore out of view return false; } } // For each active culling plane, see if all portal points are on the negative // side. If so, the portal is not visible pit = mActiveCullingPlanes.begin(); while ( pit != mActiveCullingPlanes.end() ) { PCPlane * plane = *pit; // set the visible flag to false visible_flag = false; // we have to check each corner of the portal for (int corner = 0; corner < 4; corner++) { Plane::Side side =plane->getSide(portal->getDerivedCorner(corner)); if (side != Plane::NEGATIVE_SIDE) { visible_flag = true; } } // if the visible_flag is still false, then this plane // culled all the portal points if (visible_flag == false) { // ALL corners on negative side therefore out of view return false; } pit++; } // no plane culled all the portal points and the norm // was facing the frustum, so this portal is visible return true; } /* A 'more detailed' check for visibility of an AAB. This function returns none, partial, or full for visibility of the box. This is useful for stuff like Octree leaf culling */ PCZFrustum::Visibility PCZFrustum::getVisibility( const AxisAlignedBox &bound ) { // Null boxes always invisible if ( bound.isNull() ) return NONE; // Get centre of the box Vector3 centre = bound.getCenter(); // Get the half-size of the box Vector3 halfSize = bound.getHalfSize(); bool all_inside = true; // Check originplane if told to if (mUseOriginPlane) { Plane::Side side = mOriginPlane.getSide(centre, halfSize); if (side == Plane::NEGATIVE_SIDE) { return NONE; } // We can't return now as the box could be later on the negative side of another plane. if(side == Plane::BOTH_SIDE) { all_inside = false; } } // For each active culling plane, see if the entire aabb is on the negative side // If so, object is not visible PCPlaneList::iterator pit = mActiveCullingPlanes.begin(); while ( pit != mActiveCullingPlanes.end() ) { PCPlane * plane = *pit; Plane::Side xside = plane->getSide(centre, halfSize); if(xside == Plane::NEGATIVE_SIDE) { return NONE; } // We can't return now as the box could be later on the negative side of a plane. if(xside == Plane::BOTH_SIDE) { all_inside = false; } pit++; } if ( all_inside ) return FULL; else return PARTIAL; } // calculate culling planes from portal and frustum // origin and add to list of culling planes // NOTE: returns 0 if portal was completely culled by existing planes // returns > 0 if culling planes are added (# is planes added) int PCZFrustum::addPortalCullingPlanes(Portal * portal) { int addedcullingplanes = 0; // If portal is of type aabb or sphere, add a plane which is same as frustum // origin plane (ie. redundant). We do this because we need the plane as a flag // to prevent infinite recursion if (portal->getType() == Portal::PORTAL_TYPE_AABB || portal->getType() == Portal::PORTAL_TYPE_SPHERE) { PCPlane * newPlane = getUnusedCullingPlane(); newPlane->setFromOgrePlane(mOriginPlane); newPlane->setPortal(portal); mActiveCullingPlanes.push_front(newPlane); addedcullingplanes++; return addedcullingplanes; } // For portal Quads: Up to 4 planes can be added by the sides of a portal quad. // Each plane is created from 2 corners (world space) of the portal and the // frustum origin (world space). int i,j; Plane::Side pt0_side, pt1_side; bool visible; PCPlaneList::iterator pit; for (i=0;i<4;i++) { // first check if both corners are outside of one of the existing planes j = i+1; if (j > 3) { j = 0; } visible = true; pit = mActiveCullingPlanes.begin(); while ( pit != mActiveCullingPlanes.end() ) { PCPlane * plane = *pit; pt0_side = plane->getSide(portal->getDerivedCorner(i)); pt1_side = plane->getSide(portal->getDerivedCorner(j)); if (pt0_side == Plane::NEGATIVE_SIDE && pt1_side == Plane::NEGATIVE_SIDE) { // the portal edge was actually completely culled by one of culling planes visible = false; } pit++; } if (visible) { // add the plane created from the two portal corner points and the frustum location // to the culling plane PCPlane * newPlane = getUnusedCullingPlane(); if (mProjType == PT_ORTHOGRAPHIC) // use camera direction if projection is orthographic. { newPlane->redefine(portal->getDerivedCorner(j) + mOriginPlane.normal, portal->getDerivedCorner(j), portal->getDerivedCorner(i)); } else { newPlane->redefine(mOrigin, portal->getDerivedCorner(j), portal->getDerivedCorner(i)); } newPlane->setPortal(portal); mActiveCullingPlanes.push_front(newPlane); addedcullingplanes++; } } // if we added ANY planes from the quad portal, we should add the plane of the // portal itself as an additional culling plane. if (addedcullingplanes > 0) { PCPlane * newPlane = getUnusedCullingPlane(); newPlane->redefine(portal->getDerivedCorner(2), portal->getDerivedCorner(1), portal->getDerivedCorner(0)); newPlane->setPortal(portal); mActiveCullingPlanes.push_back(newPlane); addedcullingplanes++; } return addedcullingplanes; } // remove culling planes created from the given portal void PCZFrustum::removePortalCullingPlanes(Portal *portal) { PCPlaneList::iterator pit = mActiveCullingPlanes.begin(); while ( pit != mActiveCullingPlanes.end() ) { PCPlane * plane = *pit; if (plane->getPortal() == portal) { // put the plane back in the reservoir mCullingPlaneReservoir.push_front(plane); // erase the entry from the active culling plane list pit = mActiveCullingPlanes.erase(pit); } else { pit++; } } } // remove all active extra culling planes // NOTE: Does not change the use of the originPlane! void PCZFrustum::removeAllCullingPlanes(void) { PCPlaneList::iterator pit = mActiveCullingPlanes.begin(); while ( pit != mActiveCullingPlanes.end() ) { PCPlane * plane = *pit; // put the plane back in the reservoir mCullingPlaneReservoir.push_front(plane); // go to next entry pit++; } mActiveCullingPlanes.clear(); } // set the origin plane void PCZFrustum::setOriginPlane(const Vector3 &rkNormal, const Vector3 &rkPoint) { mOriginPlane.redefine(rkNormal, rkPoint); } // get an unused PCPlane from the CullingPlane Reservoir // note that this removes the PCPlane from the reservoir! PCPlane * PCZFrustum::getUnusedCullingPlane(void) { PCPlane * plane = 0; if (mCullingPlaneReservoir.size() > 0) { PCPlaneList::iterator pit = mCullingPlaneReservoir.begin(); plane = *pit; mCullingPlaneReservoir.erase(pit); return plane; } // no available planes! create one plane = OGRE_NEW_T(PCPlane, MEMCATEGORY_SCENE_CONTROL); return plane; } }<|endoftext|>
<commit_before>#include <iostream> #include <cstring> // memcmp() #include <string> #include <queue> #include <limits> #include <openssl/sha.h> #include <byteswap.h> #include <mpi.h> using namespace std; #include "alphabet.h" #include "brute.h" // clear text password entered by user string pwd; // contains the hash of the unknown password char pwdHash[SHA256_DIGEST_LENGTH]; // contains the hash of a bruteforced string char bruteHash[SHA256_DIGEST_LENGTH]; enum MpiMsgTag { task, success, // hashes match fail }; int totalProcesses = 0; /** * @brief prints 32 bytes of memory * * prints a hex dump of 32 bytes of memory pointed to * * @param[in] pbuf: pointer to some memory, usually containing an SHA256 hash */ void printSHAHash(const unsigned int *const pbuf) { // byteswap the integer pointed to, to display hex dump in correct order // TODO: how to deal with big endian machines cout << std::hex << std::uppercase << bswap_32(*(pbuf)) << bswap_32(*(pbuf+1)) << bswap_32(*(pbuf+2)) << bswap_32(*(pbuf+3)) << bswap_32(*(pbuf+4)) << bswap_32(*(pbuf+5)) << bswap_32(*(pbuf+6)) << bswap_32(*(pbuf+7)) << endl; } /** * @brief generates an SHA256 hash * * generates an SHA256 hash using openSSL * * @param[in] input: a const pointer to const block of data, usually a char array of which the hash is being generated * @param[in] length: the number of bytes the that input points to holds * @param[in,out] hashStr: const pointer to an array of SHA256_DIGEST_LENGTH bytes that will receive the hash * * @return returns true if the hash has been generated successfully; returns false if input or hashStr is NULL or length==0; else: false */ bool generateSHA256(const void *const input, const size_t &length, char *const hashStr) { if(!hashStr || !input || length==0) { return false; } SHA256_CTX hash; if(!SHA256_Init(&hash)) { return false; } if(!SHA256_Update(&hash, input, length)) { return false; } if(!SHA256_Final(reinterpret_cast<unsigned char*>(hashStr), &hash)) { return false; } return true; } /** * @brief checks equality of two hashes * * calculates the SHA256 hash of 'password' and compares it * with the initial password hash * * @param[in] password: a const string containing a guessed password * * @return returns true if hashes match; false if generation of hash failed or hashes not match */ bool checkPassword(const string &password) { #ifdef VERBOSE cout << "checking " << password << endl; #endif // VERBOSE // generate sha hash from entered string and write it to pwdHash if(!generateSHA256(password.c_str(), password.length(), bruteHash)) { cerr << "Error when generating SHA256 from \"" << password << "\"" << endl; return false; } if (!memcmp(bruteHash, pwdHash, SHA256_DIGEST_LENGTH)) { cout << "match [" << password << "]" << endl << "hash: " << endl; printSHAHash((unsigned int*)bruteHash); return true; } return false; } //TODO: has to be deleted somewhere bool * firstTime; void CallMPIProcess(string guessedPwd) { static int currentProcess=0; if(currentProcess == MasterProcess) { currentProcess++; } // wait in case currentProzess hasnt finished yet and this is not the first call // if(!firstTime[currentProcess]) // { // MPI_Wait(&request[currentProcess], &status[currentProcess]); // } // else // { // firstTime[currentProcess]=false; // } // ...evil const_cast... MPI_Send(const_cast<char*>(guessedPwd.c_str()), guessedPwd.length(), MPI_BYTE, currentProcess, task, MPI_COMM_WORLD);//, &request[currentProcess]); currentProcess++; // actually: currentProcess >= totalProcesses if(currentProcess == totalProcesses) { currentProcess=0; } } /** * @brief recursive implementation of bruteforce * * recursive implementation of bruteforce attack * call it as follows: bruteRecursive(string(""), width); * * @param[in] baseString: a const string indicates the prefix of a string to be checked * @param[in] width: the maximum number of characters you wish to be checked */ volatile bool strFound = false; void bruteRecursive(const string baseString, const unsigned int width) { for(int i=0; (i<SizeAlphabet) && (!strFound); i++) { if (baseString.length()+1 < width) { bruteRecursive(baseString+alphabet[i], width); } if(checkPassword(baseString+alphabet[i])) { strFound = true; } } } /** * @brief iterative implementation of bruteforce * * iterative implementation of bruteforce attack * call it as follows: bruteIterative(width); * * @param[in] width: the maximum number of characters you wish to be checked * * @return return true if the password was found */ bool bruteIterative(const unsigned int width) { queue<string> myQueue; // myQueue must contain at least one element when entering loop // else: SIGSEGV // hence, start checking with an empty string myQueue.push(""); do { string baseString = myQueue.front(); myQueue.pop(); for(int i=0; i<SizeAlphabet; i++) { if (baseString.length()+1 < width) { myQueue.push(baseString+alphabet[i]); } // if(checkPassword(baseString+alphabet[i])) // { // return true; // } CallMPIProcess(baseString+alphabet[i]); } } while(!myQueue.empty()); return false; } void worker() { char* buf=NULL; MPI_Status state; while(true) { int len=numeric_limits<int>::max(); // check for new msg MPI_Probe(MasterProcess, task, MPI_COMM_WORLD, &state); // now check status to determine how many bytes were actually received MPI_Get_count(&state, MPI_BYTE, &len); // allocate len bytes buf=new char[len]; // receive len bytes MPI_Recv(buf, len, MPI_BYTE, MasterProcess, task, MPI_COMM_WORLD, &state); string str(buf, len); delete [] buf; if(checkPassword(str)) { //success, tell master //MPI_Send(const_cast<char*>(str.c_str()), str.length(), MPI_CHAR, MasterProcess, success, MPI_COMM_WORLD); cout << "Password found: " << str << endl; MPI_Abort(MPI_COMM_WORLD, 0); break; } } } <commit_msg>remove unused code<commit_after>#include <iostream> #include <cstring> // memcmp() #include <string> #include <queue> #include <limits> #include <openssl/sha.h> #include <byteswap.h> #include <mpi.h> using namespace std; #include "alphabet.h" #include "brute.h" // clear text password entered by user string pwd; // contains the hash of the unknown password char pwdHash[SHA256_DIGEST_LENGTH]; // contains the hash of a bruteforced string char bruteHash[SHA256_DIGEST_LENGTH]; enum MpiMsgTag { task, success, // hashes match fail }; int totalProcesses = 0; /** * @brief prints 32 bytes of memory * * prints a hex dump of 32 bytes of memory pointed to * * @param[in] pbuf: pointer to some memory, usually containing an SHA256 hash */ void printSHAHash(const unsigned int *const pbuf) { // byteswap the integer pointed to, to display hex dump in correct order // TODO: how to deal with big endian machines cout << std::hex << std::uppercase << bswap_32(*(pbuf)) << bswap_32(*(pbuf+1)) << bswap_32(*(pbuf+2)) << bswap_32(*(pbuf+3)) << bswap_32(*(pbuf+4)) << bswap_32(*(pbuf+5)) << bswap_32(*(pbuf+6)) << bswap_32(*(pbuf+7)) << endl; } /** * @brief generates an SHA256 hash * * generates an SHA256 hash using openSSL * * @param[in] input: a const pointer to const block of data, usually a char array of which the hash is being generated * @param[in] length: the number of bytes the that input points to holds * @param[in,out] hashStr: const pointer to an array of SHA256_DIGEST_LENGTH bytes that will receive the hash * * @return returns true if the hash has been generated successfully; returns false if input or hashStr is NULL or length==0; else: false */ bool generateSHA256(const void *const input, const size_t &length, char *const hashStr) { if(!hashStr || !input || length==0) { return false; } SHA256_CTX hash; if(!SHA256_Init(&hash)) { return false; } if(!SHA256_Update(&hash, input, length)) { return false; } if(!SHA256_Final(reinterpret_cast<unsigned char*>(hashStr), &hash)) { return false; } return true; } /** * @brief checks equality of two hashes * * calculates the SHA256 hash of 'password' and compares it * with the initial password hash * * @param[in] password: a const string containing a guessed password * * @return returns true if hashes match; false if generation of hash failed or hashes not match */ bool checkPassword(const string &password) { #ifdef VERBOSE cout << "checking " << password << endl; #endif // VERBOSE // generate sha hash from entered string and write it to pwdHash if(!generateSHA256(password.c_str(), password.length(), bruteHash)) { cerr << "Error when generating SHA256 from \"" << password << "\"" << endl; return false; } if (!memcmp(bruteHash, pwdHash, SHA256_DIGEST_LENGTH)) { cout << "match [" << password << "]" << endl << "hash: " << endl; printSHAHash((unsigned int*)bruteHash); return true; } return false; } void CallMPIProcess(string guessedPwd) { static int currentProcess=0; if(currentProcess == MasterProcess) { currentProcess++; } // ...evil const_cast... MPI_Send(const_cast<char*>(guessedPwd.c_str()), guessedPwd.length(), MPI_BYTE, currentProcess, task, MPI_COMM_WORLD);//, &request[currentProcess]); currentProcess++; if(currentProcess >= totalProcesses) { currentProcess=0; } } /** * @brief iterative implementation of bruteforce * * iterative implementation of bruteforce attack * call it as follows: bruteIterative(width); * * @param[in] width: the maximum number of characters you wish to be checked * * @return return true if the password was found */ bool bruteIterative(const unsigned int width) { queue<string> myQueue; // myQueue must contain at least one element when entering loop // else: SIGSEGV // hence, start checking with an empty string myQueue.push(""); do { string baseString = myQueue.front(); myQueue.pop(); for(int i=0; i<SizeAlphabet; i++) { if (baseString.length()+1 < width) { myQueue.push(baseString+alphabet[i]); } CallMPIProcess(baseString+alphabet[i]); } } while(!myQueue.empty()); return false; } void worker() { char* buf=NULL; MPI_Status state; while(true) { int len=numeric_limits<int>::max(); // check for new msg MPI_Probe(MasterProcess, task, MPI_COMM_WORLD, &state); // now check status to determine how many bytes were actually received MPI_Get_count(&state, MPI_BYTE, &len); // allocate len bytes buf=new char[len]; // receive len bytes MPI_Recv(buf, len, MPI_BYTE, MasterProcess, task, MPI_COMM_WORLD, &state); string str(buf, len); delete [] buf; if(checkPassword(str)) { //success, tell master //MPI_Send(const_cast<char*>(str.c_str()), str.length(), MPI_CHAR, MasterProcess, success, MPI_COMM_WORLD); cout << "Password found: " << str << endl; MPI_Abort(MPI_COMM_WORLD, 0); break; } } } <|endoftext|>
<commit_before>#include <bonefish/dealer/wamp_dealer.hpp> #include <bonefish/dealer/wamp_dealer_invocation.hpp> #include <bonefish/dealer/wamp_dealer_registration.hpp> #include <bonefish/messages/wamp_call_message.hpp> #include <bonefish/messages/wamp_error_message.hpp> #include <bonefish/messages/wamp_invocation_message.hpp> #include <bonefish/messages/wamp_register_message.hpp> #include <bonefish/messages/wamp_registered_message.hpp> #include <bonefish/messages/wamp_result_message.hpp> #include <bonefish/messages/wamp_unregister_message.hpp> #include <bonefish/messages/wamp_unregistered_message.hpp> #include <bonefish/messages/wamp_yield_message.hpp> #include <bonefish/session/wamp_session.hpp> #include <iostream> #include <stdexcept> namespace bonefish { wamp_dealer::wamp_dealer(boost::asio::io_service& io_service) : m_request_id_generator() , m_registration_id_generator() , m_sessions() , m_session_registrations() , m_procedure_registrations() , m_registered_procedures() , m_io_service(io_service) , m_pending_invocations() { } wamp_dealer::~wamp_dealer() { } void wamp_dealer::attach_session(const std::shared_ptr<wamp_session>& session) { std::cerr << "attach session: " << session->get_session_id() << std::endl; auto result = m_sessions.insert(std::make_pair(session->get_session_id(), session)); if (!result.second) { throw std::logic_error("dealer session already registered"); } } void wamp_dealer::detach_session(const wamp_session_id& session_id) { std::cerr << "detach session:" << session_id << std::endl; auto session_itr = m_sessions.find(session_id); if (session_itr == m_sessions.end()) { throw std::logic_error("broker session does not exist"); } auto session_registration_itr = m_session_registrations.find(session_id); if (session_registration_itr != m_session_registrations.end()) { auto registered_procedures_itr = m_registered_procedures.find(session_registration_itr->second); if (registered_procedures_itr == m_registered_procedures.end()) { throw std::logic_error("dealer registered procedures out of sync"); } auto procedure_registrations_itr = m_procedure_registrations.find(registered_procedures_itr->second); if (procedure_registrations_itr == m_procedure_registrations.end()) { throw std::logic_error("dealer procedure registrations out of sync"); } m_procedure_registrations.erase(procedure_registrations_itr); m_registered_procedures.erase(registered_procedures_itr); m_session_registrations.erase(session_registration_itr); } m_sessions.erase(session_itr); } void wamp_dealer::process_call_message(const wamp_session_id& session_id, const wamp_call_message* call_message) { auto session_itr = m_sessions.find(session_id); if (session_itr == m_sessions.end()) { throw std::logic_error("dealer session does not exist"); } const auto procedure = call_message->get_procedure(); if (!is_valid_uri(procedure)) { return send_error(session_itr->second->get_transport(), call_message->get_type(), call_message->get_request_id(), "wamp.error.invalid_uri"); } auto procedure_registrations_itr = m_procedure_registrations.find(procedure); if (procedure_registrations_itr == m_procedure_registrations.end()) { return send_error(session_itr->second->get_transport(), call_message->get_type(), call_message->get_request_id(), "wamp.error.no_such_procedure"); } // TODO: Check for invalid call arguments. If they are invalid then send an // error back to the caller. const wamp_request_id request_id = m_request_id_generator.generate(); std::unique_ptr<wamp_dealer_invocation> dealer_invocation( new wamp_dealer_invocation(m_io_service)); dealer_invocation->set_session(session_itr->second); dealer_invocation->set_request_id(call_message->get_request_id()); dealer_invocation->set_timeout( std::bind(&wamp_dealer::invocation_timeout_handler, this, request_id, std::placeholders::_1), 30); m_pending_invocations.insert(std::make_pair(request_id, std::move(dealer_invocation))); const std::shared_ptr<wamp_session>& session = procedure_registrations_itr->second->get_session(); const wamp_registration_id& registration_id = procedure_registrations_itr->second->get_registration_id(); std::unique_ptr<wamp_invocation_message> invocation_message(new wamp_invocation_message); invocation_message->set_request_id(request_id); invocation_message->set_registration_id(registration_id); session->get_transport()->send_message(invocation_message.get()); } void wamp_dealer::process_error_message(const wamp_session_id& session_id, const wamp_error_message* error_message) { auto session_itr = m_sessions.find(session_id); if (session_itr == m_sessions.end()) { throw std::logic_error("dealer session does not exist"); } const auto request_id = error_message->get_request_id(); auto pending_invocations_itr = m_pending_invocations.find(request_id); if (pending_invocations_itr == m_pending_invocations.end()) { std::cerr << "unable to find invocation ... ignoring error" << std::endl; return; } const auto& dealer_invocation = pending_invocations_itr->second; const auto& session = dealer_invocation->get_session(); std::unique_ptr<wamp_error_message> caller_error_message(new wamp_error_message); caller_error_message->set_request_type(wamp_message_type::CALL); caller_error_message->set_request_id(dealer_invocation->get_request_id()); caller_error_message->set_details(error_message->get_details()); caller_error_message->set_error(error_message->get_error()); caller_error_message->set_arguments(error_message->get_arguments()); caller_error_message->set_arguments_kw(error_message->get_arguments_kw()); session->get_transport()->send_message(caller_error_message.get()); m_pending_invocations.erase(pending_invocations_itr); } void wamp_dealer::process_register_message(const wamp_session_id& session_id, const wamp_register_message* register_message) { auto session_itr = m_sessions.find(session_id); if (session_itr == m_sessions.end()) { throw std::logic_error("dealer session does not exist"); } const auto procedure = register_message->get_procedure(); if (!is_valid_uri(procedure)) { return send_error(session_itr->second->get_transport(), register_message->get_type(), register_message->get_request_id(), "wamp.error.invalid_uri"); } auto procedure_registrations_itr = m_procedure_registrations.find(procedure); if (procedure_registrations_itr != m_procedure_registrations.end()) { return send_error(session_itr->second->get_transport(), register_message->get_type(), register_message->get_request_id(), "wamp.error.procedure_already_exists"); } const wamp_registration_id registration_id = m_registration_id_generator.generate(); std::unique_ptr<wamp_dealer_registration> dealer_registration( new wamp_dealer_registration(session_itr->second, registration_id)); m_procedure_registrations[procedure] = std::move(dealer_registration); m_session_registrations[session_id] = registration_id; m_registered_procedures[registration_id] = procedure; std::unique_ptr<wamp_registered_message> registered_message(new wamp_registered_message); registered_message->set_request_id(register_message->get_request_id()); registered_message->set_registration_id(registration_id); session_itr->second->get_transport()->send_message(registered_message.get()); } void wamp_dealer::process_unregister_message(const wamp_session_id& session_id, const wamp_unregister_message* unregister_message) { auto session_itr = m_sessions.find(session_id); if (session_itr == m_sessions.end()) { throw std::logic_error("dealer session does not exist"); } auto session_registration_itr = m_session_registrations.find(session_id); if (session_registration_itr == m_session_registrations.end()) { return send_error(session_itr->second->get_transport(), unregister_message->get_type(), unregister_message->get_request_id(), "wamp.error.no_such_registration"); } auto registered_procedures_itr = m_registered_procedures.find(session_registration_itr->second); if (registered_procedures_itr == m_registered_procedures.end()) { std::cerr << "warning: dealer registered procedures out of sync" << std::endl; } else { auto procedure_registrations_itr = m_procedure_registrations.find(registered_procedures_itr->second); if (procedure_registrations_itr == m_procedure_registrations.end()) { std::cerr << "error: dealer procedure registrations out of sync" << std::endl; } else { m_procedure_registrations.erase(procedure_registrations_itr); } m_registered_procedures.erase(registered_procedures_itr); } m_session_registrations.erase(session_registration_itr); std::unique_ptr<wamp_unregistered_message> unregistered_message(new wamp_unregistered_message); unregistered_message->set_request_id(unregister_message->get_request_id()); session_itr->second->get_transport()->send_message(unregistered_message.get()); } void wamp_dealer::process_yield_message(const wamp_session_id& session_id, const wamp_yield_message* yield_message) { auto session_itr = m_sessions.find(session_id); if (session_itr == m_sessions.end()) { throw std::logic_error("dealer session does not exist"); } const auto request_id = yield_message->get_request_id(); auto pending_invocations_itr = m_pending_invocations.find(request_id); if (pending_invocations_itr == m_pending_invocations.end()) { std::cerr << "unable to find invocation ... timed out or session closed" << std::endl; return; } const auto& dealer_invocation = pending_invocations_itr->second; const auto& session = dealer_invocation->get_session(); std::unique_ptr<wamp_result_message> result_message(new wamp_result_message); result_message->set_request_id(dealer_invocation->get_request_id()); result_message->set_arguments(yield_message->get_arguments()); result_message->set_arguments_kw(yield_message->get_arguments_kw()); session->get_transport()->send_message(result_message.get()); m_pending_invocations.erase(pending_invocations_itr); } void wamp_dealer::send_error(const std::unique_ptr<wamp_transport>& transport, const wamp_message_type request_type, const wamp_request_id& request_id, const std::string& error) const { std::unique_ptr<wamp_error_message> error_message(new wamp_error_message); error_message->set_request_type(request_type); error_message->set_request_id(request_id); error_message->set_error(error); transport->send_message(error_message.get()); } void wamp_dealer::invocation_timeout_handler(const wamp_request_id& request_id, const boost::system::error_code& error) { if (error == boost::asio::error::operation_aborted) { return; } auto pending_invocations_itr = m_pending_invocations.find(request_id); if (pending_invocations_itr == m_pending_invocations.end()) { std::cerr << "error: unable to find pending invocation" << std::endl; } std::cerr << "timing out a pending invocation" << std::endl; const auto& call_request_id = pending_invocations_itr->second->get_request_id(); const std::shared_ptr<wamp_session>& session = pending_invocations_itr->second->get_session(); send_error(session->get_transport(), wamp_message_type::CALL, call_request_id, "wamp.error.call_timed_out"); m_pending_invocations.erase(pending_invocations_itr); } } // namespace bonefish <commit_msg>Propagate call message parameters on to the invocation message.<commit_after>#include <bonefish/dealer/wamp_dealer.hpp> #include <bonefish/dealer/wamp_dealer_invocation.hpp> #include <bonefish/dealer/wamp_dealer_registration.hpp> #include <bonefish/messages/wamp_call_message.hpp> #include <bonefish/messages/wamp_error_message.hpp> #include <bonefish/messages/wamp_invocation_message.hpp> #include <bonefish/messages/wamp_register_message.hpp> #include <bonefish/messages/wamp_registered_message.hpp> #include <bonefish/messages/wamp_result_message.hpp> #include <bonefish/messages/wamp_unregister_message.hpp> #include <bonefish/messages/wamp_unregistered_message.hpp> #include <bonefish/messages/wamp_yield_message.hpp> #include <bonefish/session/wamp_session.hpp> #include <iostream> #include <stdexcept> namespace bonefish { wamp_dealer::wamp_dealer(boost::asio::io_service& io_service) : m_request_id_generator() , m_registration_id_generator() , m_sessions() , m_session_registrations() , m_procedure_registrations() , m_registered_procedures() , m_io_service(io_service) , m_pending_invocations() { } wamp_dealer::~wamp_dealer() { } void wamp_dealer::attach_session(const std::shared_ptr<wamp_session>& session) { std::cerr << "attach session: " << session->get_session_id() << std::endl; auto result = m_sessions.insert(std::make_pair(session->get_session_id(), session)); if (!result.second) { throw std::logic_error("dealer session already registered"); } } void wamp_dealer::detach_session(const wamp_session_id& session_id) { std::cerr << "detach session:" << session_id << std::endl; auto session_itr = m_sessions.find(session_id); if (session_itr == m_sessions.end()) { throw std::logic_error("broker session does not exist"); } auto session_registration_itr = m_session_registrations.find(session_id); if (session_registration_itr != m_session_registrations.end()) { auto registered_procedures_itr = m_registered_procedures.find(session_registration_itr->second); if (registered_procedures_itr == m_registered_procedures.end()) { throw std::logic_error("dealer registered procedures out of sync"); } auto procedure_registrations_itr = m_procedure_registrations.find(registered_procedures_itr->second); if (procedure_registrations_itr == m_procedure_registrations.end()) { throw std::logic_error("dealer procedure registrations out of sync"); } m_procedure_registrations.erase(procedure_registrations_itr); m_registered_procedures.erase(registered_procedures_itr); m_session_registrations.erase(session_registration_itr); } m_sessions.erase(session_itr); } void wamp_dealer::process_call_message(const wamp_session_id& session_id, const wamp_call_message* call_message) { auto session_itr = m_sessions.find(session_id); if (session_itr == m_sessions.end()) { throw std::logic_error("dealer session does not exist"); } const auto procedure = call_message->get_procedure(); if (!is_valid_uri(procedure)) { return send_error(session_itr->second->get_transport(), call_message->get_type(), call_message->get_request_id(), "wamp.error.invalid_uri"); } auto procedure_registrations_itr = m_procedure_registrations.find(procedure); if (procedure_registrations_itr == m_procedure_registrations.end()) { return send_error(session_itr->second->get_transport(), call_message->get_type(), call_message->get_request_id(), "wamp.error.no_such_procedure"); } // TODO: Check for invalid call arguments. If they are invalid then send an // error back to the caller. const wamp_request_id request_id = m_request_id_generator.generate(); std::unique_ptr<wamp_dealer_invocation> dealer_invocation( new wamp_dealer_invocation(m_io_service)); dealer_invocation->set_session(session_itr->second); dealer_invocation->set_request_id(call_message->get_request_id()); dealer_invocation->set_timeout( std::bind(&wamp_dealer::invocation_timeout_handler, this, request_id, std::placeholders::_1), 30); m_pending_invocations.insert(std::make_pair(request_id, std::move(dealer_invocation))); const std::shared_ptr<wamp_session>& session = procedure_registrations_itr->second->get_session(); const wamp_registration_id& registration_id = procedure_registrations_itr->second->get_registration_id(); std::unique_ptr<wamp_invocation_message> invocation_message(new wamp_invocation_message); invocation_message->set_request_id(request_id); invocation_message->set_registration_id(registration_id); invocation_message->set_arguments(call_message->get_arguments()); invocation_message->set_arguments_kw(call_message->get_arguments_kw()); session->get_transport()->send_message(invocation_message.get()); } void wamp_dealer::process_error_message(const wamp_session_id& session_id, const wamp_error_message* error_message) { auto session_itr = m_sessions.find(session_id); if (session_itr == m_sessions.end()) { throw std::logic_error("dealer session does not exist"); } const auto request_id = error_message->get_request_id(); auto pending_invocations_itr = m_pending_invocations.find(request_id); if (pending_invocations_itr == m_pending_invocations.end()) { std::cerr << "unable to find invocation ... ignoring error" << std::endl; return; } const auto& dealer_invocation = pending_invocations_itr->second; const auto& session = dealer_invocation->get_session(); std::unique_ptr<wamp_error_message> caller_error_message(new wamp_error_message); caller_error_message->set_request_type(wamp_message_type::CALL); caller_error_message->set_request_id(dealer_invocation->get_request_id()); caller_error_message->set_details(error_message->get_details()); caller_error_message->set_error(error_message->get_error()); caller_error_message->set_arguments(error_message->get_arguments()); caller_error_message->set_arguments_kw(error_message->get_arguments_kw()); session->get_transport()->send_message(caller_error_message.get()); m_pending_invocations.erase(pending_invocations_itr); } void wamp_dealer::process_register_message(const wamp_session_id& session_id, const wamp_register_message* register_message) { auto session_itr = m_sessions.find(session_id); if (session_itr == m_sessions.end()) { throw std::logic_error("dealer session does not exist"); } const auto procedure = register_message->get_procedure(); if (!is_valid_uri(procedure)) { return send_error(session_itr->second->get_transport(), register_message->get_type(), register_message->get_request_id(), "wamp.error.invalid_uri"); } auto procedure_registrations_itr = m_procedure_registrations.find(procedure); if (procedure_registrations_itr != m_procedure_registrations.end()) { return send_error(session_itr->second->get_transport(), register_message->get_type(), register_message->get_request_id(), "wamp.error.procedure_already_exists"); } const wamp_registration_id registration_id = m_registration_id_generator.generate(); std::unique_ptr<wamp_dealer_registration> dealer_registration( new wamp_dealer_registration(session_itr->second, registration_id)); m_procedure_registrations[procedure] = std::move(dealer_registration); m_session_registrations[session_id] = registration_id; m_registered_procedures[registration_id] = procedure; std::unique_ptr<wamp_registered_message> registered_message(new wamp_registered_message); registered_message->set_request_id(register_message->get_request_id()); registered_message->set_registration_id(registration_id); session_itr->second->get_transport()->send_message(registered_message.get()); } void wamp_dealer::process_unregister_message(const wamp_session_id& session_id, const wamp_unregister_message* unregister_message) { auto session_itr = m_sessions.find(session_id); if (session_itr == m_sessions.end()) { throw std::logic_error("dealer session does not exist"); } auto session_registration_itr = m_session_registrations.find(session_id); if (session_registration_itr == m_session_registrations.end()) { return send_error(session_itr->second->get_transport(), unregister_message->get_type(), unregister_message->get_request_id(), "wamp.error.no_such_registration"); } auto registered_procedures_itr = m_registered_procedures.find(session_registration_itr->second); if (registered_procedures_itr == m_registered_procedures.end()) { std::cerr << "warning: dealer registered procedures out of sync" << std::endl; } else { auto procedure_registrations_itr = m_procedure_registrations.find(registered_procedures_itr->second); if (procedure_registrations_itr == m_procedure_registrations.end()) { std::cerr << "error: dealer procedure registrations out of sync" << std::endl; } else { m_procedure_registrations.erase(procedure_registrations_itr); } m_registered_procedures.erase(registered_procedures_itr); } m_session_registrations.erase(session_registration_itr); std::unique_ptr<wamp_unregistered_message> unregistered_message(new wamp_unregistered_message); unregistered_message->set_request_id(unregister_message->get_request_id()); session_itr->second->get_transport()->send_message(unregistered_message.get()); } void wamp_dealer::process_yield_message(const wamp_session_id& session_id, const wamp_yield_message* yield_message) { auto session_itr = m_sessions.find(session_id); if (session_itr == m_sessions.end()) { throw std::logic_error("dealer session does not exist"); } const auto request_id = yield_message->get_request_id(); auto pending_invocations_itr = m_pending_invocations.find(request_id); if (pending_invocations_itr == m_pending_invocations.end()) { std::cerr << "unable to find invocation ... timed out or session closed" << std::endl; return; } const auto& dealer_invocation = pending_invocations_itr->second; const auto& session = dealer_invocation->get_session(); std::unique_ptr<wamp_result_message> result_message(new wamp_result_message); result_message->set_request_id(dealer_invocation->get_request_id()); result_message->set_arguments(yield_message->get_arguments()); result_message->set_arguments_kw(yield_message->get_arguments_kw()); session->get_transport()->send_message(result_message.get()); m_pending_invocations.erase(pending_invocations_itr); } void wamp_dealer::send_error(const std::unique_ptr<wamp_transport>& transport, const wamp_message_type request_type, const wamp_request_id& request_id, const std::string& error) const { std::unique_ptr<wamp_error_message> error_message(new wamp_error_message); error_message->set_request_type(request_type); error_message->set_request_id(request_id); error_message->set_error(error); transport->send_message(error_message.get()); } void wamp_dealer::invocation_timeout_handler(const wamp_request_id& request_id, const boost::system::error_code& error) { if (error == boost::asio::error::operation_aborted) { return; } auto pending_invocations_itr = m_pending_invocations.find(request_id); if (pending_invocations_itr == m_pending_invocations.end()) { std::cerr << "error: unable to find pending invocation" << std::endl; } std::cerr << "timing out a pending invocation" << std::endl; const auto& call_request_id = pending_invocations_itr->second->get_request_id(); const std::shared_ptr<wamp_session>& session = pending_invocations_itr->second->get_session(); send_error(session->get_transport(), wamp_message_type::CALL, call_request_id, "wamp.error.call_timed_out"); m_pending_invocations.erase(pending_invocations_itr); } } // namespace bonefish <|endoftext|>
<commit_before>#ifndef __CMD_ARGS_HPP__ #define __CMD_ARGS_HPP__ #include "config/args.hpp" #include <stdint.h> #include <sys/types.h> #include <string> #include <vector> #include "serializer/types.hpp" #include "arch/arch.hpp" #define NEVER_FLUSH -1 /* Private serializer dynamic configuration values */ struct log_serializer_private_dynamic_config_t { std::string db_filename; #ifdef SEMANTIC_SERIALIZER_CHECK std::string semantic_filename; #endif }; /* Configuration for the serializer that can change from run to run */ struct log_serializer_dynamic_config_t { /* When the proportion of garbage blocks hits gc_high_ratio, then the serializer will collect garbage until it reaches gc_low_ratio. */ float gc_low_ratio, gc_high_ratio; /* How many data block extents the serializer will be writing to at once */ unsigned num_active_data_extents; /* If file_size is nonzero and the serializer is not running on a block device, then it will pretend to be running on a block device by immediately resizing the file to file_size and then zoning it like a block device. */ size_t file_size; /* How big to make each zone if the database is on a block device or if file_size is given */ size_t file_zone_size; /* Which i/o backend should the log serializer use for accessing files? */ platform_io_config_t::io_backend_t io_backend; /* Enable reading more data than requested to let the cache warmup more quickly esp. on rotational drives */ bool read_ahead; }; /* Configuration for the serializer that is set when the database is created */ struct log_serializer_static_config_t { uint64_t block_size_; uint64_t extent_size_; uint64_t blocks_per_extent() const { return extent_size_ / block_size_; } int block_index(off64_t offset) const { return (offset % extent_size_) / block_size_; } int extent_index(off64_t offset) const { return offset / extent_size_; } // Minimize calls to these. block_size_t block_size() const { return block_size_t::unsafe_make(block_size_); } uint64_t extent_size() const { return extent_size_; } // Avoid calls to these. uint64_t& unsafe_block_size() { return block_size_; } uint64_t& unsafe_extent_size() { return extent_size_; } }; /* Configuration for the cache (it can all change from run to run) */ struct mirrored_cache_config_t { // Max amount of memory that will be used for the cache, in bytes. long long max_size; // If wait_for_flush is true, then write operations will not return until after the data is // safely sitting on the disk. bool wait_for_flush; // flush_timer_ms is how long (in milliseconds) the cache will allow modified data to sit in // memory before flushing it to disk. If it is NEVER_FLUSH, then data will be allowed to sit in // memory indefinitely. int flush_timer_ms; // max_dirty_size is the most unsaved data that is allowed in memory before the cache will // throttle write transactions. It's in bytes. long long max_dirty_size; // flush_dirty_size is the amount of unsaved data that will trigger an immediate flush. It // should be much less than max_dirty_size. It's in bytes. long long flush_dirty_size; // flush_waiting_threshold is the maximal number of transactions which can wait // for a sync before a flush gets triggered on any single slice. As transactions only wait for // sync with wait_for_flush enabled, this option plays a role only then. int flush_waiting_threshold; // If wait_for_flush is true, concurrent flushing can be used to reduce the latency // of each single flush. max_concurrent_flushes controls how many flushes can be active // on a specific slice at any given time. int max_concurrent_flushes; // per-cache priorities used for i/o accounts // each cache uses two IO accounts: // one account for writes, and one account for reads. int io_priority_reads; int io_priority_writes; }; /* This part of the serializer is part of the on-disk serializer_config_block and can only be set at creation time of a database */ struct mirrored_cache_static_config_t { // How many blocks of each slice are allocated to the patch log? int32_t n_patch_log_blocks; }; /* Configuration for the btree that is set when the database is created and serialized in the serializer */ struct btree_config_t { int32_t n_slices; }; /* Configuration for the store (btree, cache, and serializers) that can be changed from run to run */ struct btree_key_value_store_dynamic_config_t { log_serializer_dynamic_config_t serializer; /* Vector of per-serializer database information structures */ std::vector<log_serializer_private_dynamic_config_t> serializer_private; mirrored_cache_config_t cache; int64_t total_delete_queue_limit; }; /* Configuration for the store (btree, cache, and serializers) that is set at database creation time */ struct btree_key_value_store_static_config_t { log_serializer_static_config_t serializer; btree_config_t btree; mirrored_cache_static_config_t cache; }; /* Configuration for replication */ struct replication_config_t { char hostname[MAX_HOSTNAME_LEN]; int port; bool active; /* Terminate the connection if no heartbeat is received within this many milliseconds */ int heartbeat_timeout; }; /* Configuration for failover */ struct failover_config_t { char failover_script_path[MAX_PATH_LEN]; /* !< script to be called when the other server goes down */ bool active; bool no_rogue; /* whether to go rogue when the master is struggling to stay up */ failover_config_t() : active(false), no_rogue(false) { *failover_script_path = 0; } }; /* Configuration for import */ struct import_config_t { bool do_import; std::vector<std::string> file; import_config_t() : do_import(false) { } void add_import_file(std::string s) { file.push_back(s); } }; /* All the configuration together */ struct cmd_config_t { /* Methods */ cmd_config_t(); // Automatically initializes to default values void print(); void print_runtime_flags(); void print_database_flags(); void print_system_spec(); /* Attributes */ int port; int n_workers; char log_file_name[MAX_LOG_FILE_NAME]; // Log messages below this level aren't printed //log_level min_log_level; // Configuration information for the btree btree_key_value_store_dynamic_config_t store_dynamic_config; btree_key_value_store_static_config_t store_static_config; bool create_store, force_create, shutdown_after_creation; //replication configuration replication_config_t replication_config; int replication_master_listen_port; bool replication_master_active; // Configuration for failover failover_config_t failover_config; // Configuration for import import_config_t import_config; bool verbose; }; // This variant adds parsing functionality and also validates the values given class parsing_cmd_config_t : public cmd_config_t { public: parsing_cmd_config_t(); void set_cores(const char* value); void set_port(const char* value); void set_log_file(const char* value); void set_slices(const char* value); void set_max_cache_size(const char* value); void set_wait_for_flush(const char* value); void set_unsaved_data_limit(const char* value); void set_flush_timer(const char* value); void set_flush_waiting_threshold(const char* value); void set_max_concurrent_flushes(const char* value); void set_gc_range(const char* value); void set_active_data_extents(const char* value); void set_block_size(const char* value); void set_extent_size(const char* value); void set_read_ahead(const char* value); void set_coroutine_stack_size(const char* value); #ifdef SEMANTIC_SERIALIZER_CHECK void set_last_semantic_file(const char* value); #endif void set_master_listen_port(const char *value); void set_master_addr(const char *value); void set_heartbeat_timeout(const char *value); void set_total_delete_queue_limit(const char *value); void set_failover_file(const char* value); void set_elb_port(const char* value); void set_io_backend(const char* value); void push_private_config(const char* value); long long parse_diff_log_size(const char* value); private: bool parsing_failed; int parse_int(const char* value); long long int parse_longlong(const char* value); template<typename T> bool is_positive(const T value) const; template<typename T> bool is_in_range(const T value, const T minimum_value, const T maximum_value) const; template<typename T> bool is_at_least(const T value, const T minimum_value) const; template<typename T> bool is_at_most(const T value, const T maximum_value) const; }; cmd_config_t parse_cmd_args(int argc, char *argv[]); void usage_serve(); void usage_create(); void usage_import(); #endif // __CMD_ARGS_HPP__ <commit_msg>Check that we can access memcached import files on startup. (we still segfault if the file becomes inaccessible while we are starting up but that should be acceptable) (affects #359)<commit_after>#ifndef __CMD_ARGS_HPP__ #define __CMD_ARGS_HPP__ #include "config/args.hpp" #include <stdint.h> #include <sys/types.h> #include <string> #include <vector> #include "serializer/types.hpp" #include "arch/arch.hpp" #define NEVER_FLUSH -1 /* Private serializer dynamic configuration values */ struct log_serializer_private_dynamic_config_t { std::string db_filename; #ifdef SEMANTIC_SERIALIZER_CHECK std::string semantic_filename; #endif }; /* Configuration for the serializer that can change from run to run */ struct log_serializer_dynamic_config_t { /* When the proportion of garbage blocks hits gc_high_ratio, then the serializer will collect garbage until it reaches gc_low_ratio. */ float gc_low_ratio, gc_high_ratio; /* How many data block extents the serializer will be writing to at once */ unsigned num_active_data_extents; /* If file_size is nonzero and the serializer is not running on a block device, then it will pretend to be running on a block device by immediately resizing the file to file_size and then zoning it like a block device. */ size_t file_size; /* How big to make each zone if the database is on a block device or if file_size is given */ size_t file_zone_size; /* Which i/o backend should the log serializer use for accessing files? */ platform_io_config_t::io_backend_t io_backend; /* Enable reading more data than requested to let the cache warmup more quickly esp. on rotational drives */ bool read_ahead; }; /* Configuration for the serializer that is set when the database is created */ struct log_serializer_static_config_t { uint64_t block_size_; uint64_t extent_size_; uint64_t blocks_per_extent() const { return extent_size_ / block_size_; } int block_index(off64_t offset) const { return (offset % extent_size_) / block_size_; } int extent_index(off64_t offset) const { return offset / extent_size_; } // Minimize calls to these. block_size_t block_size() const { return block_size_t::unsafe_make(block_size_); } uint64_t extent_size() const { return extent_size_; } // Avoid calls to these. uint64_t& unsafe_block_size() { return block_size_; } uint64_t& unsafe_extent_size() { return extent_size_; } }; /* Configuration for the cache (it can all change from run to run) */ struct mirrored_cache_config_t { // Max amount of memory that will be used for the cache, in bytes. long long max_size; // If wait_for_flush is true, then write operations will not return until after the data is // safely sitting on the disk. bool wait_for_flush; // flush_timer_ms is how long (in milliseconds) the cache will allow modified data to sit in // memory before flushing it to disk. If it is NEVER_FLUSH, then data will be allowed to sit in // memory indefinitely. int flush_timer_ms; // max_dirty_size is the most unsaved data that is allowed in memory before the cache will // throttle write transactions. It's in bytes. long long max_dirty_size; // flush_dirty_size is the amount of unsaved data that will trigger an immediate flush. It // should be much less than max_dirty_size. It's in bytes. long long flush_dirty_size; // flush_waiting_threshold is the maximal number of transactions which can wait // for a sync before a flush gets triggered on any single slice. As transactions only wait for // sync with wait_for_flush enabled, this option plays a role only then. int flush_waiting_threshold; // If wait_for_flush is true, concurrent flushing can be used to reduce the latency // of each single flush. max_concurrent_flushes controls how many flushes can be active // on a specific slice at any given time. int max_concurrent_flushes; // per-cache priorities used for i/o accounts // each cache uses two IO accounts: // one account for writes, and one account for reads. int io_priority_reads; int io_priority_writes; }; /* This part of the serializer is part of the on-disk serializer_config_block and can only be set at creation time of a database */ struct mirrored_cache_static_config_t { // How many blocks of each slice are allocated to the patch log? int32_t n_patch_log_blocks; }; /* Configuration for the btree that is set when the database is created and serialized in the serializer */ struct btree_config_t { int32_t n_slices; }; /* Configuration for the store (btree, cache, and serializers) that can be changed from run to run */ struct btree_key_value_store_dynamic_config_t { log_serializer_dynamic_config_t serializer; /* Vector of per-serializer database information structures */ std::vector<log_serializer_private_dynamic_config_t> serializer_private; mirrored_cache_config_t cache; int64_t total_delete_queue_limit; }; /* Configuration for the store (btree, cache, and serializers) that is set at database creation time */ struct btree_key_value_store_static_config_t { log_serializer_static_config_t serializer; btree_config_t btree; mirrored_cache_static_config_t cache; }; /* Configuration for replication */ struct replication_config_t { char hostname[MAX_HOSTNAME_LEN]; int port; bool active; /* Terminate the connection if no heartbeat is received within this many milliseconds */ int heartbeat_timeout; }; /* Configuration for failover */ struct failover_config_t { char failover_script_path[MAX_PATH_LEN]; /* !< script to be called when the other server goes down */ bool active; bool no_rogue; /* whether to go rogue when the master is struggling to stay up */ failover_config_t() : active(false), no_rogue(false) { *failover_script_path = 0; } }; /* Configuration for import */ struct import_config_t { bool do_import; std::vector<std::string> file; import_config_t() : do_import(false) { } void add_import_file(std::string s) { // See if we can open the file at this path with read permissions FILE* import_file = fopen(s.c_str(), "r"); if (import_file == NULL) fail_due_to_user_error("Inaccessible or invalid import file: \"%s\": %s", s.c_str(), strerror(errno)); else fclose(import_file); file.push_back(s); } }; /* All the configuration together */ struct cmd_config_t { /* Methods */ cmd_config_t(); // Automatically initializes to default values void print(); void print_runtime_flags(); void print_database_flags(); void print_system_spec(); /* Attributes */ int port; int n_workers; char log_file_name[MAX_LOG_FILE_NAME]; // Log messages below this level aren't printed //log_level min_log_level; // Configuration information for the btree btree_key_value_store_dynamic_config_t store_dynamic_config; btree_key_value_store_static_config_t store_static_config; bool create_store, force_create, shutdown_after_creation; //replication configuration replication_config_t replication_config; int replication_master_listen_port; bool replication_master_active; // Configuration for failover failover_config_t failover_config; // Configuration for import import_config_t import_config; bool verbose; }; // This variant adds parsing functionality and also validates the values given class parsing_cmd_config_t : public cmd_config_t { public: parsing_cmd_config_t(); void set_cores(const char* value); void set_port(const char* value); void set_log_file(const char* value); void set_slices(const char* value); void set_max_cache_size(const char* value); void set_wait_for_flush(const char* value); void set_unsaved_data_limit(const char* value); void set_flush_timer(const char* value); void set_flush_waiting_threshold(const char* value); void set_max_concurrent_flushes(const char* value); void set_gc_range(const char* value); void set_active_data_extents(const char* value); void set_block_size(const char* value); void set_extent_size(const char* value); void set_read_ahead(const char* value); void set_coroutine_stack_size(const char* value); #ifdef SEMANTIC_SERIALIZER_CHECK void set_last_semantic_file(const char* value); #endif void set_master_listen_port(const char *value); void set_master_addr(const char *value); void set_heartbeat_timeout(const char *value); void set_total_delete_queue_limit(const char *value); void set_failover_file(const char* value); void set_elb_port(const char* value); void set_io_backend(const char* value); void push_private_config(const char* value); long long parse_diff_log_size(const char* value); private: bool parsing_failed; int parse_int(const char* value); long long int parse_longlong(const char* value); template<typename T> bool is_positive(const T value) const; template<typename T> bool is_in_range(const T value, const T minimum_value, const T maximum_value) const; template<typename T> bool is_at_least(const T value, const T minimum_value) const; template<typename T> bool is_at_most(const T value, const T maximum_value) const; }; cmd_config_t parse_cmd_args(int argc, char *argv[]); void usage_serve(); void usage_create(); void usage_import(); #endif // __CMD_ARGS_HPP__ <|endoftext|>
<commit_before>/* Resembla https://github.com/tuem/resembla Copyright 2017 Takashi Uemura 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. */ #ifndef RESEMBLA_FEATURE_AGGREGATOR_HPP #define RESEMBLA_FEATURE_AGGREGATOR_HPP #include <unordered_map> #include <memory> #include <initializer_list> #include "../feature.hpp" #include "../../string_util.hpp" namespace resembla { class FeatureAggregator { public: using input_type = StringFeatureMap; using output_type = FeatureMap; struct Function { virtual ~Function(){} virtual Feature::real_type operator()(const Feature::text_type& target, const Feature::text_type& reference) const = 0; }; template<class F> struct StringsToRealFunction: public Function { StringsToRealFunction(){} StringsToRealFunction(F f): f(f){} Feature::real_type operator()(const Feature::text_type& target, const Feature::text_type& reference) const { return f(Feature::toReal(target), Feature::toReal(reference)); } private: F f; }; void append(Feature::key_type key, std::shared_ptr<Function> func); output_type operator()(const input_type& target, const input_type& reference) const; protected: std::unordered_map<Feature::key_type, std::shared_ptr<Function>> functions; }; } #endif <commit_msg>delete unused include declaration<commit_after>/* Resembla https://github.com/tuem/resembla Copyright 2017 Takashi Uemura 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. */ #ifndef RESEMBLA_FEATURE_AGGREGATOR_HPP #define RESEMBLA_FEATURE_AGGREGATOR_HPP #include <unordered_map> #include <memory> #include "../feature.hpp" #include "../../string_util.hpp" namespace resembla { class FeatureAggregator { public: using input_type = StringFeatureMap; using output_type = FeatureMap; struct Function { virtual ~Function(){} virtual Feature::real_type operator()(const Feature::text_type& target, const Feature::text_type& reference) const = 0; }; template<class F> struct StringsToRealFunction: public Function { StringsToRealFunction(){} StringsToRealFunction(F f): f(f){} Feature::real_type operator()(const Feature::text_type& target, const Feature::text_type& reference) const { return f(Feature::toReal(target), Feature::toReal(reference)); } private: F f; }; void append(Feature::key_type key, std::shared_ptr<Function> func); output_type operator()(const input_type& target, const input_type& reference) const; protected: std::unordered_map<Feature::key_type, std::shared_ptr<Function>> functions; }; } #endif <|endoftext|>
<commit_before>// Fill out your copyright notice in the Description page of Project Settings. #include "UE4_TurnBased.h" #include "TB_AimComponent.h" #include "TB_Character.h" #include "TB_Weapon.h" #include "TB_Library.h" #include <algorithm> #include <cmath> void UTB_AimComponent::UpdateValues() { Character = (ATB_Character *)GetAttachmentRootActor(); Weapon = Character->Weapon; if (EnemyTarget && Weapon) { FinalHitChance = Character->RangedAttackSkill; FinalDamage = Weapon->BaseDamage; RangeToTarget = Character->GetDistanceTo(EnemyTarget); RangeHitModifier = Weapon->HitModifier(RangeToTarget); FinalHitChance += RangeHitModifier; RangeDamageModifier = Weapon->DamageModifier(RangeToTarget); FinalDamage += RangeDamageModifier; CoverHitModifier = CoverModifier(EnemyTarget); FinalHitChance += CoverHitModifier; CoverDamageModifier = 0; } else { RangeToTarget = 0; RangeHitModifier = 0; RangeDamageModifier = 0; CoverHitModifier = 0; CoverDamageModifier = 0; FinalHitChance = 0; FinalDamage = 0; } } int32 UTB_AimComponent::CoverModifier(ATB_Character *Target) { UWorld *World = GetWorld(); // Ignore collisions with the aiming character and its weapon FCollisionQueryParams Params; Params.bTraceComplex = true; Params.AddIgnoredActor(Character); if (Weapon) { Params.AddIgnoredActor(Weapon); } if (Target->Weapon) { Params.AddIgnoredActor(Target->Weapon); } // uncomment to draw debug lines /* FName TraceTag("CoverTrace"); World->DebugDrawTraceTag = TraceTag; Params.TraceTag = TraceTag; */ FCollisionObjectQueryParams ObjectParams; FHitResult HitResult; TArray<FVector> HitLocations; Target->GetHitLocations(HitLocations); FVector StartLocation = GetComponentLocation(); int Hidden = 0; for (auto HitLocation : HitLocations) { bool HitSomething = World->LineTraceSingle(HitResult, StartLocation, HitLocation, Params, ObjectParams); if (HitSomething && Target->GetUniqueID() != HitResult.Actor->GetUniqueID()) { Hidden++; } } return (Hidden * -100) / std::max(HitLocations.Num(), 1); } void UTB_AimComponent::TargetNextEnemy() { if (VisibleEnemies.Num()) { int32 Index = VisibleEnemies.Find(EnemyTarget); //INDEX_NONE (-1) if not found Index = (Index + 1) % VisibleEnemies.Num(); EnemyTarget = VisibleEnemies[Index]; } else { EnemyTarget = NULL; } } void UTB_AimComponent::UpdateVisibleEnemies() { VisibleEnemies.Empty(); Character = (ATB_Character *)GetAttachmentRootActor(); Weapon = Character->Weapon; bool EnemyTargetVisible = false; for (TActorIterator<ATB_Character> Iter(GetWorld(), ATB_Character::StaticClass()); Iter; ++Iter) { ATB_Character *Enemy = *Iter; if (Enemy->HitPoints > 0 && Enemy->TeamName != Character->TeamName && CoverModifier(Enemy) > -100) { VisibleEnemies.Add(Enemy); if (Enemy == EnemyTarget) { EnemyTargetVisible = true; } } } if (!EnemyTargetVisible) { EnemyTarget = NULL; } } void UTB_AimComponent::HitLineTrace(FHitResult &OutHit) { if (!EnemyTarget) { UE_LOG(TB_Log, Error, TEXT("HitLineTrace(): EnemyTarget == NULL")); return; } //find the hit locations TArray<FVector> HitLocations; EnemyTarget->GetHitLocations(HitLocations); // shuffle them and do line traces until we get a hit UTB_Library::Shuffle(HitLocations); FCollisionQueryParams Params; InitCollisionQueryParams(Params); FCollisionObjectQueryParams ObjectParams; FVector StartLocation = GetComponentLocation(); for (auto HitLocation : HitLocations) { bool HitSomething = World->LineTraceSingle(OutHit, StartLocation, HitLocation, Params, ObjectParams); if (HitSomething && EnemyTarget->GetUniqueID() == OutHit.Actor->GetUniqueID()) { return; } } UE_LOG(TB_Log, Error, TEXT("HitLineTrace(): Could not find a hitting line trace")); } bool UTB_AimComponent::MissLineTrace(FHitResult &OutHit) { if (!EnemyTarget) { UE_LOG(TB_Log, Error, TEXT("MissLineTrace(): EnemyTarget == NULL")); return false; } //Pick a HitLocation at random TArray<FVector> HitLocations; EnemyTarget->GetHitLocations(HitLocations); UTB_Library::Shuffle(HitLocations); FCollisionQueryParams Params; InitCollisionQueryParams(Params); FCollisionObjectQueryParams ObjectParams; FVector StartLocation = GetComponentLocation(); float Offset = 30; for (auto HitLocation : HitLocations) { bool HitSomething = World->LineTraceSingle(OutHit, StartLocation, HitLocation, Params, ObjectParams); if (HitSomething) { if (EnemyTarget->GetUniqueID() != OutHit.Actor->GetUniqueID()) { //we've hit something we didn't aim for \o/ return true; } else { //get our direction and rotate it so we miss by Offest UUs FVector Direction; float Length; (StartLocation - HitLocation).ToDirectionAndLength(Direction, Length); float OffsetRad = atan2f(Offset, Length); FRotator Rotator(0, OffsetRad * 180 / PI, 0); if (FMath::FRand() < 0.5f) { Rotator *= -1; } FVector AdjustedDirection = Rotator.RotateVector(Direction); //use the weapon range as length AdjustedDirection *= Weapon->MaxRange; //ensure that we dont hit the target HitSomething = World->LineTraceSingle(OutHit, StartLocation, StartLocation + AdjustedDirection, Params, ObjectParams); if (HitSomething && EnemyTarget->GetUniqueID() != OutHit.Actor->GetUniqueID()) { //we're still hitting the target, pray that we'll miss it when we look at the other targetpoints continue; } else { return HitSomething; } } } } UE_LOG(TB_Log, Warning, TEXT("MissLineTrace(): Can't find a way to miss")); return false; } void UTB_AimComponent::InitCollisionQueryParams(FCollisionQueryParams &Params) { // remember to set the physical material in phat for skeletal meshes // (the collision channels for the character might also need to be tuned) Params.bTraceComplex = true; Params.bReturnPhysicalMaterial = true; // Ignore collisions with the aiming character and its weapon Params.AddIgnoredActor(Character); if (Weapon) { Params.AddIgnoredActor(Weapon); } if (EnemyTarget->Weapon) { Params.AddIgnoredActor(EnemyTarget->Weapon); } }<commit_msg>adjusted HitModifiers<commit_after>// Fill out your copyright notice in the Description page of Project Settings. #include "UE4_TurnBased.h" #include "TB_AimComponent.h" #include "TB_Character.h" #include "TB_Weapon.h" #include "TB_Library.h" #include <algorithm> #include <cmath> void UTB_AimComponent::UpdateValues() { Character = (ATB_Character *)GetAttachmentRootActor(); Weapon = Character->Weapon; if (EnemyTarget && Weapon) { // Base Values FinalHitChance = Character->RangedAttackSkill; FinalDamage = Weapon->BaseDamage; // Range RangeToTarget = Character->GetDistanceTo(EnemyTarget); RangeHitModifier = Weapon->HitModifier(RangeToTarget); FinalHitChance += RangeHitModifier; RangeDamageModifier = Weapon->DamageModifier(RangeToTarget); FinalDamage += RangeDamageModifier; // Cover CoverHitModifier = CoverModifier(EnemyTarget); FinalHitChance += CoverHitModifier; CoverDamageModifier = 0; // Final sanity check FinalHitChance = std::max(0, FinalHitChance); if (FinalDamage < 0) { FinalDamage = 0; } } else { RangeToTarget = 0; RangeHitModifier = 0; RangeDamageModifier = 0; CoverHitModifier = 0; CoverDamageModifier = 0; FinalHitChance = 0; FinalDamage = 0; } } int32 UTB_AimComponent::CoverModifier(ATB_Character *Target) { UWorld *World = GetWorld(); // Ignore collisions with the aiming character and its weapon FCollisionQueryParams Params; Params.bTraceComplex = true; Params.AddIgnoredActor(Character); if (Weapon) { Params.AddIgnoredActor(Weapon); } if (Target->Weapon) { Params.AddIgnoredActor(Target->Weapon); } // uncomment to draw debug lines /* FName TraceTag("CoverTrace"); World->DebugDrawTraceTag = TraceTag; Params.TraceTag = TraceTag; */ FCollisionObjectQueryParams ObjectParams; FHitResult HitResult; TArray<FVector> HitLocations; Target->GetHitLocations(HitLocations); FVector StartLocation = GetComponentLocation(); int Hidden = 0; for (auto HitLocation : HitLocations) { bool HitSomething = World->LineTraceSingle(HitResult, StartLocation, HitLocation, Params, ObjectParams); if (HitSomething && Target->GetUniqueID() != HitResult.Actor->GetUniqueID()) { Hidden++; } } if (Hidden < HitLocations.Num()) { // reduce cover by half if we can see the enemy at all // a penalty above 60 makes an enemy virtually impossible to hit Hidden -= (Hidden / 3); } return (Hidden * -100) / std::max(HitLocations.Num(), 1); } void UTB_AimComponent::TargetNextEnemy() { if (VisibleEnemies.Num()) { int32 Index = VisibleEnemies.Find(EnemyTarget); //INDEX_NONE (-1) if not found Index = (Index + 1) % VisibleEnemies.Num(); EnemyTarget = VisibleEnemies[Index]; } else { EnemyTarget = NULL; } } void UTB_AimComponent::UpdateVisibleEnemies() { VisibleEnemies.Empty(); Character = (ATB_Character *)GetAttachmentRootActor(); Weapon = Character->Weapon; bool EnemyTargetVisible = false; for (TActorIterator<ATB_Character> Iter(GetWorld(), ATB_Character::StaticClass()); Iter; ++Iter) { ATB_Character *Enemy = *Iter; if (Enemy->HitPoints > 0 && Enemy->TeamName != Character->TeamName && CoverModifier(Enemy) > -100) { VisibleEnemies.Add(Enemy); if (Enemy == EnemyTarget) { EnemyTargetVisible = true; } } } if (!EnemyTargetVisible) { EnemyTarget = NULL; } } void UTB_AimComponent::HitLineTrace(FHitResult &OutHit) { if (!EnemyTarget) { UE_LOG(TB_Log, Error, TEXT("HitLineTrace(): EnemyTarget == NULL")); return; } //find the hit locations TArray<FVector> HitLocations; EnemyTarget->GetHitLocations(HitLocations); // shuffle them and do line traces until we get a hit UTB_Library::Shuffle(HitLocations); FCollisionQueryParams Params; InitCollisionQueryParams(Params); FCollisionObjectQueryParams ObjectParams; FVector StartLocation = GetComponentLocation(); for (auto HitLocation : HitLocations) { bool HitSomething = World->LineTraceSingle(OutHit, StartLocation, HitLocation, Params, ObjectParams); if (HitSomething && EnemyTarget->GetUniqueID() == OutHit.Actor->GetUniqueID()) { return; } } UE_LOG(TB_Log, Error, TEXT("HitLineTrace(): Could not find a hitting line trace")); } bool UTB_AimComponent::MissLineTrace(FHitResult &OutHit) { if (!EnemyTarget) { UE_LOG(TB_Log, Error, TEXT("MissLineTrace(): EnemyTarget == NULL")); return false; } //Pick a HitLocation at random TArray<FVector> HitLocations; EnemyTarget->GetHitLocations(HitLocations); UTB_Library::Shuffle(HitLocations); FCollisionQueryParams Params; InitCollisionQueryParams(Params); FCollisionObjectQueryParams ObjectParams; FVector StartLocation = GetComponentLocation(); float Offset = 30; for (auto HitLocation : HitLocations) { bool HitSomething = World->LineTraceSingle(OutHit, StartLocation, HitLocation, Params, ObjectParams); if (HitSomething) { if (EnemyTarget->GetUniqueID() != OutHit.Actor->GetUniqueID()) { //we've hit something we didn't aim for \o/ return true; } else { //get our direction and rotate it so we miss by Offest UUs FVector Direction; float Length; (StartLocation - HitLocation).ToDirectionAndLength(Direction, Length); float OffsetRad = atan2f(Offset, Length); FRotator Rotator(0, OffsetRad * 180 / PI, 0); if (FMath::FRand() < 0.5f) { Rotator *= -1; } FVector AdjustedDirection = Rotator.RotateVector(Direction); //use the weapon range as length AdjustedDirection *= Weapon->MaxRange; //ensure that we dont hit the target HitSomething = World->LineTraceSingle(OutHit, StartLocation, StartLocation + AdjustedDirection, Params, ObjectParams); if (HitSomething && EnemyTarget->GetUniqueID() != OutHit.Actor->GetUniqueID()) { //we're still hitting the target, pray that we'll miss it when we look at the other targetpoints continue; } else { return HitSomething; } } } } UE_LOG(TB_Log, Warning, TEXT("MissLineTrace(): Can't find a way to miss")); return false; } void UTB_AimComponent::InitCollisionQueryParams(FCollisionQueryParams &Params) { // remember to set the physical material in phat for skeletal meshes // (the collision channels for the character might also need to be tuned) Params.bTraceComplex = true; Params.bReturnPhysicalMaterial = true; // Ignore collisions with the aiming character and its weapon Params.AddIgnoredActor(Character); if (Weapon) { Params.AddIgnoredActor(Weapon); } if (EnemyTarget->Weapon) { Params.AddIgnoredActor(EnemyTarget->Weapon); } }<|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Jolla Ltd. ** Contact: Vesa-Matti Hartikainen <vesa-matti.hartikainen@jollamobile.com> ** ****************************************************************************/ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ // QtCore #include <QtCore/QDateTime> #include <QtCore/QDir> #include <QtCore/QFile> #include <QtCore/QFileInfo> #include <QtCore/QLocale> #include <QtCore/QSettings> #include <QtCore/QStandardPaths> #include <QtCore/QStringList> #include <QtCore/QtMath> #include <QtCore/QVariant> #include <QtCore/QVariantMap> // QtGui #include <QtGui/QClipboard> #include <QtGui/QGuiApplication> #include <QtGui/QScreen> #include <webengine.h> #include <webenginesettings.h> #include <math.h> #include "declarativewebutils.h" #include "browserpaths.h" static const QString gSystemComponentsTimeStamp("/var/lib/_MOZEMBED_CACHE_CLEAN_"); static const QString gProfilePath("/.mozilla/mozembed"); static DeclarativeWebUtils *gSingleton = 0; static bool fileExists(QString fileName) { QFile file(fileName); return file.exists(); } DeclarativeWebUtils::DeclarativeWebUtils() : QObject() , m_homePage("/apps/sailfish-browser/settings/home_page", this) { updateWebEngineSettings(); connect(SailfishOS::WebEngine::instance(), &SailfishOS::WebEngine::recvObserve, this, &DeclarativeWebUtils::handleObserve); QString path = BrowserPaths::dataLocation() + QStringLiteral("/.firstUseDone"); m_firstUseDone = fileExists(path); connect(&m_homePage, &MGConfItem::valueChanged, this, &DeclarativeWebUtils::homePageChanged); } DeclarativeWebUtils::~DeclarativeWebUtils() { gSingleton = 0; } int DeclarativeWebUtils::getLightness(QColor color) const { return color.lightness(); } void DeclarativeWebUtils::clearStartupCacheIfNeeded() { QFileInfo systemStamp(gSystemComponentsTimeStamp); if (systemStamp.exists()) { QString mostProfilePath = QDir::homePath() + gProfilePath; QString localStampString(mostProfilePath + QString("/_CACHE_CLEAN_")); QFileInfo localStamp(localStampString); if (localStamp.exists() && systemStamp.lastModified() > localStamp.lastModified()) { QDir cacheDir(mostProfilePath + "/startupCache"); cacheDir.removeRecursively(); QFile(localStampString).remove(); } } } void DeclarativeWebUtils::handleDumpMemoryInfoRequest(QString fileName) { if (qApp->arguments().contains("-debugMode")) { emit dumpMemoryInfo(fileName); } } void DeclarativeWebUtils::updateWebEngineSettings() { SailfishOS::WebEngineSettings *webEngineSettings = SailfishOS::WebEngineSettings::instance(); SailfishOS::WebEngine *webEngine = SailfishOS::WebEngine::instance(); webEngineSettings->setPreference(QStringLiteral("general.useragent.updates.url"), QStringLiteral("https://browser.sailfishos.org/gecko/%APP_VERSION%/ua-update.json")); webEngineSettings->setPreference(QStringLiteral("general.useragent.updates.interval"), QVariant(604800)); // 1 week webEngineSettings->setPreference(QStringLiteral("general.useragent.updates.retry"), QVariant(86400)); // 1 day // Without this pref placeholders get cleaned as soon as a character gets committed // by VKB and that happens only when Enter is pressed or comma/space/dot is entered. webEngineSettings->setPreference(QString("dom.placeholder.show_on_focus"), QVariant(false)); webEngineSettings->setPreference(QString("security.alternate_certificate_error_page"), QString("certerror")); webEngineSettings->setPreference(QString("geo.wifi.scan"), QVariant(false)); webEngineSettings->setPreference(QString("media.resource_handler_disabled"), QVariant(true)); // subscribe to gecko messages webEngine->addObservers(QStringList() << "clipboard:setdata" << "media-decoder-info" << "embed:download" << "embed:allprefs" << "embed:search"); // Enable internet search webEngineSettings->setPreference(QString("keyword.enabled"), QVariant(true)); setRenderingPreferences(); // Disable SSLv3 webEngineSettings->setPreference(QString("security.tls.version.min"), QVariant(1)); // Content Security Policy is enabled by default, // this enables the spec compliant mode. webEngineSettings->setPreference(QString("security.csp.speccompliant"), QVariant(true)); } void DeclarativeWebUtils::setFirstUseDone(bool firstUseDone) { QString path = BrowserPaths::dataLocation() + QStringLiteral("/.firstUseDone"); if (m_firstUseDone != firstUseDone) { m_firstUseDone = firstUseDone; if (!firstUseDone) { QFile f(path); f.remove(); } else { QProcess process; process.startDetached("touch", QStringList() << path); } emit firstUseDoneChanged(); } } qreal DeclarativeWebUtils::cssPixelRatio() const { SailfishOS::WebEngineSettings *webEngineSettings = SailfishOS::WebEngineSettings::instance(); if (webEngineSettings) { return webEngineSettings->pixelRatio(); } return 1.0; } bool DeclarativeWebUtils::firstUseDone() const { return m_firstUseDone; } QString DeclarativeWebUtils::homePage() const { return m_homePage.value("http://jolla.com").value<QString>(); } DeclarativeWebUtils *DeclarativeWebUtils::instance() { if (!gSingleton) { gSingleton = new DeclarativeWebUtils(); } return gSingleton; } QString DeclarativeWebUtils::displayableUrl(QString fullUrl) const { QUrl url(fullUrl); // Leaving only the scheme, host address, and port (if present). QString returnUrl = url.toDisplayString(QUrl::RemoveUserInfo | QUrl::RemovePath | QUrl::RemoveQuery | QUrl::RemoveFragment | QUrl::StripTrailingSlash); returnUrl.remove(0, returnUrl.lastIndexOf("/") + 1); if (returnUrl.indexOf("www.") == 0) { return returnUrl.remove(0, 4); } else if (returnUrl.indexOf("m.") == 0 && returnUrl.length() > 2) { return returnUrl.remove(0, 2); } else if (returnUrl.indexOf("mobile.") == 0 && returnUrl.length() > 7) { return returnUrl.remove(0, 7); } return !returnUrl.isEmpty() ? returnUrl : fullUrl; } void DeclarativeWebUtils::handleObserve(const QString message, const QVariant data) { const QVariantMap dataMap = data.toMap(); if (message == "clipboard:setdata") { QClipboard *clipboard = QGuiApplication::clipboard(); // check if we copied password if (!dataMap.value("private").toBool()) { clipboard->setText(dataMap.value("data").toString()); } } } void DeclarativeWebUtils::setRenderingPreferences() { SailfishOS::WebEngineSettings *webEngineSettings = SailfishOS::WebEngineSettings::instance(); // Use external Qt window for rendering content webEngineSettings->setPreference(QString("gfx.compositor.external-window"), QVariant(true)); webEngineSettings->setPreference(QString("gfx.compositor.clear-context"), QVariant(false)); webEngineSettings->setPreference(QString("embedlite.compositor.external_gl_context"), QVariant(true)); if (webEngineSettings->pixelRatio() >= 2.0) { // Don't use too small low precision buffers for high dpi devices. This reduces // a bit the blurriness. webEngineSettings->setPreference(QString("layers.low-precision-resolution"), QString("0.5f")); } } <commit_msg>[sailfish-browser] Shorten UA update interval. Contributes to JB#39970<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Jolla Ltd. ** Contact: Vesa-Matti Hartikainen <vesa-matti.hartikainen@jollamobile.com> ** ****************************************************************************/ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ // QtCore #include <QtCore/QDateTime> #include <QtCore/QDir> #include <QtCore/QFile> #include <QtCore/QFileInfo> #include <QtCore/QLocale> #include <QtCore/QSettings> #include <QtCore/QStandardPaths> #include <QtCore/QStringList> #include <QtCore/QtMath> #include <QtCore/QVariant> #include <QtCore/QVariantMap> // QtGui #include <QtGui/QClipboard> #include <QtGui/QGuiApplication> #include <QtGui/QScreen> #include <webengine.h> #include <webenginesettings.h> #include <math.h> #include "declarativewebutils.h" #include "browserpaths.h" static const QString gSystemComponentsTimeStamp("/var/lib/_MOZEMBED_CACHE_CLEAN_"); static const QString gProfilePath("/.mozilla/mozembed"); static DeclarativeWebUtils *gSingleton = 0; static bool fileExists(QString fileName) { QFile file(fileName); return file.exists(); } DeclarativeWebUtils::DeclarativeWebUtils() : QObject() , m_homePage("/apps/sailfish-browser/settings/home_page", this) { updateWebEngineSettings(); connect(SailfishOS::WebEngine::instance(), &SailfishOS::WebEngine::recvObserve, this, &DeclarativeWebUtils::handleObserve); QString path = BrowserPaths::dataLocation() + QStringLiteral("/.firstUseDone"); m_firstUseDone = fileExists(path); connect(&m_homePage, &MGConfItem::valueChanged, this, &DeclarativeWebUtils::homePageChanged); } DeclarativeWebUtils::~DeclarativeWebUtils() { gSingleton = 0; } int DeclarativeWebUtils::getLightness(QColor color) const { return color.lightness(); } void DeclarativeWebUtils::clearStartupCacheIfNeeded() { QFileInfo systemStamp(gSystemComponentsTimeStamp); if (systemStamp.exists()) { QString mostProfilePath = QDir::homePath() + gProfilePath; QString localStampString(mostProfilePath + QString("/_CACHE_CLEAN_")); QFileInfo localStamp(localStampString); if (localStamp.exists() && systemStamp.lastModified() > localStamp.lastModified()) { QDir cacheDir(mostProfilePath + "/startupCache"); cacheDir.removeRecursively(); QFile(localStampString).remove(); } } } void DeclarativeWebUtils::handleDumpMemoryInfoRequest(QString fileName) { if (qApp->arguments().contains("-debugMode")) { emit dumpMemoryInfo(fileName); } } void DeclarativeWebUtils::updateWebEngineSettings() { SailfishOS::WebEngineSettings *webEngineSettings = SailfishOS::WebEngineSettings::instance(); SailfishOS::WebEngine *webEngine = SailfishOS::WebEngine::instance(); webEngineSettings->setPreference(QStringLiteral("general.useragent.updates.url"), QStringLiteral("https://browser.sailfishos.org/gecko/%APP_VERSION%/ua-update.json")); webEngineSettings->setPreference(QStringLiteral("general.useragent.updates.interval"), QVariant(172800)); // every 2nd day webEngineSettings->setPreference(QStringLiteral("general.useragent.updates.retry"), QVariant(86400)); // 1 day // Without this pref placeholders get cleaned as soon as a character gets committed // by VKB and that happens only when Enter is pressed or comma/space/dot is entered. webEngineSettings->setPreference(QString("dom.placeholder.show_on_focus"), QVariant(false)); webEngineSettings->setPreference(QString("security.alternate_certificate_error_page"), QString("certerror")); webEngineSettings->setPreference(QString("geo.wifi.scan"), QVariant(false)); webEngineSettings->setPreference(QString("media.resource_handler_disabled"), QVariant(true)); // subscribe to gecko messages webEngine->addObservers(QStringList() << "clipboard:setdata" << "media-decoder-info" << "embed:download" << "embed:allprefs" << "embed:search"); // Enable internet search webEngineSettings->setPreference(QString("keyword.enabled"), QVariant(true)); setRenderingPreferences(); // Disable SSLv3 webEngineSettings->setPreference(QString("security.tls.version.min"), QVariant(1)); // Content Security Policy is enabled by default, // this enables the spec compliant mode. webEngineSettings->setPreference(QString("security.csp.speccompliant"), QVariant(true)); } void DeclarativeWebUtils::setFirstUseDone(bool firstUseDone) { QString path = BrowserPaths::dataLocation() + QStringLiteral("/.firstUseDone"); if (m_firstUseDone != firstUseDone) { m_firstUseDone = firstUseDone; if (!firstUseDone) { QFile f(path); f.remove(); } else { QProcess process; process.startDetached("touch", QStringList() << path); } emit firstUseDoneChanged(); } } qreal DeclarativeWebUtils::cssPixelRatio() const { SailfishOS::WebEngineSettings *webEngineSettings = SailfishOS::WebEngineSettings::instance(); if (webEngineSettings) { return webEngineSettings->pixelRatio(); } return 1.0; } bool DeclarativeWebUtils::firstUseDone() const { return m_firstUseDone; } QString DeclarativeWebUtils::homePage() const { return m_homePage.value("http://jolla.com").value<QString>(); } DeclarativeWebUtils *DeclarativeWebUtils::instance() { if (!gSingleton) { gSingleton = new DeclarativeWebUtils(); } return gSingleton; } QString DeclarativeWebUtils::displayableUrl(QString fullUrl) const { QUrl url(fullUrl); // Leaving only the scheme, host address, and port (if present). QString returnUrl = url.toDisplayString(QUrl::RemoveUserInfo | QUrl::RemovePath | QUrl::RemoveQuery | QUrl::RemoveFragment | QUrl::StripTrailingSlash); returnUrl.remove(0, returnUrl.lastIndexOf("/") + 1); if (returnUrl.indexOf("www.") == 0) { return returnUrl.remove(0, 4); } else if (returnUrl.indexOf("m.") == 0 && returnUrl.length() > 2) { return returnUrl.remove(0, 2); } else if (returnUrl.indexOf("mobile.") == 0 && returnUrl.length() > 7) { return returnUrl.remove(0, 7); } return !returnUrl.isEmpty() ? returnUrl : fullUrl; } void DeclarativeWebUtils::handleObserve(const QString message, const QVariant data) { const QVariantMap dataMap = data.toMap(); if (message == "clipboard:setdata") { QClipboard *clipboard = QGuiApplication::clipboard(); // check if we copied password if (!dataMap.value("private").toBool()) { clipboard->setText(dataMap.value("data").toString()); } } } void DeclarativeWebUtils::setRenderingPreferences() { SailfishOS::WebEngineSettings *webEngineSettings = SailfishOS::WebEngineSettings::instance(); // Use external Qt window for rendering content webEngineSettings->setPreference(QString("gfx.compositor.external-window"), QVariant(true)); webEngineSettings->setPreference(QString("gfx.compositor.clear-context"), QVariant(false)); webEngineSettings->setPreference(QString("embedlite.compositor.external_gl_context"), QVariant(true)); if (webEngineSettings->pixelRatio() >= 2.0) { // Don't use too small low precision buffers for high dpi devices. This reduces // a bit the blurriness. webEngineSettings->setPreference(QString("layers.low-precision-resolution"), QString("0.5f")); } } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2009, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" #include "IECore/NumericParameter.h" #include "IECore/CompoundObject.h" #include "IECore/bindings/IntrusivePtrPatch.h" #include "IECore/bindings/ParameterBinding.h" #include "IECore/bindings/RunTimeTypedBinding.h" using namespace std; using namespace boost; using namespace boost::python; namespace IECore { template<class T> static ParameterPtr numericConstructor( const std::string &name, const std::string &description, T defaultValue, T minValue, T maxValue, const object &presets, bool presetsOnly, object userData ) { typename NumericParameter<T>::PresetsContainer p = parameterPresets<typename NumericParameter<T>::PresetsContainer>( presets ); // get the optional userData parameter. ConstCompoundObjectPtr ptrUserData = 0; if (userData != object()) { extract<CompoundObjectPtr> elem(userData); // try if elem is an exact CompoundObjectPtr if (elem.check()) { ptrUserData = elem(); } else { // now try for ConstCompoundObjectPtr extract<ConstCompoundObjectPtr> elem(userData); if (elem.check()) { ptrUserData = elem(); } else { PyErr_SetString(PyExc_TypeError, "Parameter userData is not an instance of CompoundObject!"); throw_error_already_set(); ParameterPtr res; return res; } } } return new NumericParameter<T>( name, description, defaultValue, minValue, maxValue, p, presetsOnly, ptrUserData ); } template<typename T> static void bindNumericParameter( const char *name ) { typedef class_< NumericParameter<T>, typename NumericParameter<T>::Ptr, boost::noncopyable, bases<Parameter> > NumericParameterPyClass; NumericParameterPyClass( name, no_init ) .def( "__init__", make_constructor( &numericConstructor<T>, default_call_policies(), ( boost::python::arg_( "name" ), boost::python::arg_( "description" ), boost::python::arg_( "defaultValue" ) = T(), boost::python::arg_( "minValue" ) = Imath::limits<T>::min(), boost::python::arg_( "maxValue" ) = Imath::limits<T>::max(), boost::python::arg_( "presets" ) = boost::python::tuple(), boost::python::arg_( "presetsOnly" ) = false, boost::python::arg_( "userData" ) = object() ) ) ) .add_property( "numericDefaultValue", &NumericParameter<T>::numericDefaultValue ) .def( "getNumericValue", &NumericParameter<T>::getNumericValue ) .def( "setNumericValue", &NumericParameter<T>::setNumericValue ) .def( "getTypedValue", &NumericParameter<T>::getNumericValue ) // added for consistency .def( "setTypedValue", &NumericParameter<T>::setNumericValue ) // added for consistency .IE_COREPYTHON_DEFPARAMETERWRAPPERFNS( NumericParameter<T> ) .def( "hasMinValue", &NumericParameter<T>::hasMinValue ) .def( "hasMaxValue", &NumericParameter<T>::hasMaxValue ) .add_property( "minValue", &NumericParameter<T>::minValue ) .add_property( "maxValue", &NumericParameter<T>::maxValue ) .IE_COREPYTHON_DEFRUNTIMETYPEDSTATICMETHODS( NumericParameter<T> ) ; INTRUSIVE_PTR_PATCH( NumericParameter<T>, typename NumericParameterPyClass ); implicitly_convertible<typename NumericParameter<T>::Ptr, ParameterPtr>(); } void bindNumericParameter() { bindNumericParameter<int>( "IntParameter" ); bindNumericParameter<float>( "FloatParameter" ); bindNumericParameter<double>( "DoubleParameter" ); } }; <commit_msg>Updated NumericParameter binding<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2009, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" #include "IECore/bindings/ParameterBinding.h" #include "IECore/NumericParameter.h" #include "IECore/CompoundObject.h" #include "IECore/bindings/Wrapper.h" #include "IECore/bindings/IntrusivePtrPatch.h" #include "IECore/bindings/WrapperToPython.h" #include "IECore/bindings/RunTimeTypedBinding.h" using namespace std; using namespace boost; using namespace boost::python; namespace IECore { template<typename T> class NumericParameterWrap : public NumericParameter<T>, public Wrapper<NumericParameter<T> > { public : NumericParameterWrap( PyObject *self, const std::string &n, const std::string &d, T v = T(), T minValue = Imath::limits<T>::min(), T maxValue = Imath::limits<T>::max(), const object &p = boost::python::tuple(), bool po = false, CompoundObjectPtr ud = 0 ) : NumericParameter<T>( n, d, v, minValue, maxValue, parameterPresets<typename NumericParameter<T>::PresetsContainer>( p ), po, ud ), Wrapper<NumericParameter<T> >( self, this ) {}; IE_COREPYTHON_PARAMETERWRAPPERFNS( NumericParameter<T> ); IE_CORE_DECLAREMEMBERPTR( NumericParameterWrap<T> ); }; template<typename T> static void bindNumericParameter( const char *name ) { using boost::python::arg; typedef class_< NumericParameter<T>, typename NumericParameterWrap<T>::Ptr, boost::noncopyable, bases<Parameter> > NumericParameterPyClass; NumericParameterPyClass( name, no_init ) .def( init<const std::string &, const std::string &, boost::python::optional< T, T, T, const object &, bool, CompoundObjectPtr> > ( ( arg( "name" ), arg( "description" ), arg( "defaultValue" ) = T(), arg( "minValue" ) = Imath::limits<T>::min(), arg( "maxValue" ) = Imath::limits<T>::max(), arg( "presets" ) = boost::python::tuple(), arg( "presetsOnly" ) = false, arg( "userData" ) = CompoundObject::Ptr( 0 ) ) ) ) .add_property( "numericDefaultValue", &NumericParameter<T>::numericDefaultValue ) .def( "getNumericValue", &NumericParameter<T>::getNumericValue ) .def( "setNumericValue", &NumericParameter<T>::setNumericValue ) .def( "getTypedValue", &NumericParameter<T>::getNumericValue ) // added for consistency .def( "setTypedValue", &NumericParameter<T>::setNumericValue ) // added for consistency .IE_COREPYTHON_DEFPARAMETERWRAPPERFNS( NumericParameter<T> ) .def( "hasMinValue", &NumericParameter<T>::hasMinValue ) .def( "hasMaxValue", &NumericParameter<T>::hasMaxValue ) .add_property( "minValue", &NumericParameter<T>::minValue ) .add_property( "maxValue", &NumericParameter<T>::maxValue ) .IE_COREPYTHON_DEFRUNTIMETYPEDSTATICMETHODS( NumericParameter<T> ) ; INTRUSIVE_PTR_PATCH( NumericParameter<T>, typename NumericParameterPyClass ); implicitly_convertible<typename NumericParameter<T>::Ptr, ParameterPtr>(); implicitly_convertible<typename NumericParameter<T>::Ptr, typename NumericParameter<T>::ConstPtr>(); } void bindNumericParameter() { bindNumericParameter<int>( "IntParameter" ); bindNumericParameter<float>( "FloatParameter" ); bindNumericParameter<double>( "DoubleParameter" ); } }; <|endoftext|>
<commit_before>#include "MainFrame.h" #include "RGBModel.h" #include "HSLModel.h" #include "CMYKModel.h" #include "HtmlHexOutput.h" #include <wx/aboutdlg.h> #include <wx/dcscreen.h> #include <wx/graphics.h> #include <wx/dcmemory.h> #include <wx/dialog.h> #include <wx/gdicmn.h> #include <wx/dnd.h> #include <wx/dataobj.h> #include <wx/colordlg.h> #include <wx/colourdata.h> struct ZoomMenuFunctor { ZoomPanel* panel; int zoom; ZoomMenuFunctor(ZoomPanel* p, int z) : panel(p), zoom(z) { } void operator()(wxCommandEvent& event) { panel->SetZoom(zoom); } }; MainFrame::MainFrame(wxWindow* parent) : MainFrameBaseClass(parent), capturing(false), refreshTimer(this) { Bind(wxEVT_TIMER, &MainFrame::OnRefreshTimerEvent, this, refreshTimer.GetId()); RestorePosition(); colorOutput = new HtmlHexOutput; AddColorOutput(colorOutput); colorModel = new RGBModel; AddColorModel(colorModel); AddColorModel(new HSLModel); AddColorModel(new CMYKModel); UpdateColorModel(); SetColor(wxColour( config.ReadLong("Main/Color/R", 0), config.ReadLong("Main/Color/G", 0), config.ReadLong("Main/Color/B", 0) )); m_zoomPanel->SetPoi(wxPoint( config.ReadLong("Main/ZoomPanel/X", 0), config.ReadLong("Main/ZoomPanel/Y", 0) )); m_zoomPanel->SetZoom(config.ReadLong("Main/ZoomPanel/Zoom", 4)); } MainFrame::~MainFrame() { wxPoint pos = GetPosition(); config.Write("Main/Position/X", pos.x); config.Write("Main/Position/Y", pos.y); wxColour col = GetColor(); config.Write("Main/Color/R", col.Red()); config.Write("Main/Color/G", col.Green()); config.Write("Main/Color/B", col.Blue()); wxPoint poi = m_zoomPanel->GetPoi(); config.Write("Main/ZoomPanel/X", poi.x); config.Write("Main/ZoomPanel/Y", poi.y); config.Write("Main/ZoomPanel/Zoom", m_zoomPanel->GetZoom()); } void MainFrame::RestorePosition() { int x = config.ReadLong("Main/Position/X", GetPosition().x); int y = config.ReadLong("Main/Position/Y", GetPosition().y); wxSize screenSize = wxGetDisplaySize(); wxSize windowSize = GetSize(); if (x < 0) x = 0; if (y < 0) y = 0; if (x > (screenSize.x - windowSize.x)) x = screenSize.x - windowSize.x; if (y > (screenSize.y - windowSize.y)) y = screenSize.y - windowSize.y; SetPosition(wxPoint(x, y)); } void MainFrame::AddColorModel(IColorModel* colorModel) { wxWindowID id = wxIdManager::ReserveId(); colorModels[id] = colorModel; wxMenuItem* menuItem = new wxMenuItem(m_colorModelMenu, id, colorModel->getName(), wxT(""), wxITEM_RADIO); m_colorModelMenu->Append(menuItem); m_colorModelMenu->Bind(wxEVT_COMMAND_MENU_SELECTED, &MainFrame::OnSelectColorModel, this, menuItem->GetId()); } void MainFrame::AddColorOutput(IColorOutput* colorOutput) { wxWindowID id = wxIdManager::ReserveId(); colorOutputs[id] = colorOutput; wxMenuItem* menuItem = new wxMenuItem(m_colorOutputMenu, id, colorOutput->getName(), wxT(""), wxITEM_RADIO); m_colorOutputMenu->Append(menuItem); m_colorOutputMenu->Bind(wxEVT_COMMAND_MENU_SELECTED, &MainFrame::OnSelectColorOutput, this, menuItem->GetId()); } void MainFrame::SetColorModel(IColorModel* colorModel) { this->colorModel = colorModel; UpdateColorModel(); } void MainFrame::SetColorOutput(IColorOutput* colorOutput) { this->colorOutput = colorOutput; } void update_label_and_ctrl(int i, IColorModel* colorModel, wxStaticText* label, wxSpinCtrl* ctrl) { if (colorModel->getNumComponents() > i) { label->Show(true); ctrl->Show(true); std::string labelStr = colorModel->getLabel(i); label->SetLabel(labelStr.substr(0, 1).append(":")); label->SetToolTip(labelStr); ctrl->SetToolTip(labelStr); ctrl->SetMin(colorModel->getMin(i)); ctrl->SetMax(colorModel->getMax(i)); } else { label->Show(false); ctrl->Show(false); } } void MainFrame::UpdateColorModel() { update_label_and_ctrl(0, colorModel, m_firstLabel, m_firstCtrl); update_label_and_ctrl(1, colorModel, m_secondLabel, m_secondCtrl); update_label_and_ctrl(2, colorModel, m_thirdLabel, m_thirdCtrl); update_label_and_ctrl(3, colorModel, m_fourthLabel, m_fourthCtrl); SetColor(GetColor()); } void MainFrame::OnExit(wxCommandEvent& event) { wxUnusedVar(event); Close(); } void MainFrame::OnAbout(wxCommandEvent& event) { wxUnusedVar(event); wxAboutDialogInfo info; info.SetName("ColorGrab"); info.SetVersion("0.1-dev"); info.SetWebSite("http://nielssp.dk"); info.SetCopyright(_("(C) 2015 Niels Sonnich Poulsen")); info.SetLicence(_("MIT License")); info.SetDescription(_("Free color picker tool.")); ::wxAboutBox(info); } wxBitmap GetScreenShot() { wxSize screenSize = wxGetDisplaySize(); wxBitmap bitmap(screenSize.x, screenSize.y); wxScreenDC dc; wxMemoryDC memDC; memDC.SelectObject(bitmap); memDC.Blit(0, 0, screenSize.x, screenSize.y, &dc, 0, 0); memDC.SelectObject(wxNullBitmap); return bitmap; } void MainFrame::UpdateZoomArea() { m_zoomPanel->SetPoi(wxGetMousePosition()); } void MainFrame::SetColorFromMouse() { int x, y; wxGetMousePosition(&x, &y); SetColorFromPixel(x, y); } void MainFrame::SetColorFromPixel(wxCoord x, wxCoord y) { wxColor color; wxScreenDC dc; dc.GetPixel(x, y, &color); SetColor(color); } wxColor MainFrame::GetColor() const { return m_colorButton->GetBackgroundColour(); } void MainFrame::SetColor(const wxColor& color, bool updateInputs, bool updateOutput) { // m_colourPicker->SetColour(color); m_colorButton->SetBackgroundColour(color); m_colorButton->Refresh(); colorModel->setColor(color); if (updateInputs) { m_firstCtrl->SetValue(colorModel->getValue(0)); m_secondCtrl->SetValue(colorModel->getValue(1)); m_thirdCtrl->SetValue(colorModel->getValue(2)); m_fourthCtrl->SetValue(colorModel->getValue(3)); } colorOutput->setColor(color); if (updateOutput) m_formatText->ChangeValue(colorOutput->getOutput()); } void MainFrame::OnColorChange(wxCommandEvent& event) { colorModel->setValue(0, m_firstCtrl->GetValue()); colorModel->setValue(1, m_secondCtrl->GetValue()); colorModel->setValue(2, m_thirdCtrl->GetValue()); colorModel->setValue(3, m_fourthCtrl->GetValue()); SetColor(colorModel->getColor(), false); } void MainFrame::OnCaptureStart(wxMouseEvent& event) { SetColorFromMouse(); UpdateZoomArea(); CaptureMouse(); SetCursor(*wxCROSS_CURSOR); capturing = true; SetFocus(); } void MainFrame::OnCaptureEnd(wxMouseEvent& event) { if (capturing) { SetColorFromMouse(); UpdateZoomArea(); ReleaseMouse(); capturing = false; SetCursor(wxNullCursor); } } void MainFrame::OnCaptureMove(wxMouseEvent& event) { if (capturing) { SetColorFromMouse(); UpdateZoomArea(); } } void MainFrame::OnSystemColorPicker(wxCommandEvent& event) { wxColourDialog dialog(this); dialog.GetColourData().SetColour(GetColor()); dialog.ShowModal(); SetColor(dialog.GetColourData().GetColour()); } void MainFrame::OnFormatChoose(wxMenuEvent& event) { } void MainFrame::OnFormatClick(wxCommandEvent& event) { } void MainFrame::OnCaptureZoom(wxMouseEvent& event) { if (capturing) OnZoomPanelZoom(event); } void MainFrame::OnZoomSelect(wxCommandEvent& event) { m_zoomPanel->SetZoom(2); } void MainFrame::OnZoomPanelDown(wxMouseEvent& event) { m_zoomPanel->ShowPoi(false); SetColorFromMouse(); capturing = true; } void MainFrame::OnZoomPanelMove(wxMouseEvent& event) { if (capturing) SetColorFromMouse(); } void MainFrame::OnZoomPanelUp(wxMouseEvent& event) { SetColorFromMouse(); capturing = false; } void MainFrame::OnZoomPanelZoom(wxMouseEvent& event) { int zoom = m_zoomPanel->GetZoom(); if (event.GetWheelRotation() > 0 && zoom < 64) zoom *= 2; else if (event.GetWheelRotation() < 0 && zoom > 1) zoom /= 2; m_zoomPanel->SetZoom(zoom); } void MainFrame::OnSelectColorModel(wxCommandEvent& event) { SetColorModel(colorModels[event.GetId()]); } void MainFrame::OnSelectColorOutput(wxCommandEvent& event) { SetColorOutput(colorOutputs[event.GetId()]); } void MainFrame::OnColorOutputChange(wxCommandEvent& event) { colorOutput->setOutput(m_formatText->GetValue().ToStdString()); SetColor(colorOutput->getColor(), true, false); } void MainFrame::OnInputOutputBlur(wxFocusEvent& event) { SetColor(GetColor()); event.Skip(); } void MainFrame::OnInputOutputEnter(wxCommandEvent& event) { SetColor(GetColor()); } void MainFrame::OnZoomIn(wxCommandEvent& event) { int zoom = m_zoomPanel->GetZoom(); if (zoom < 64) zoom *= 2; m_zoomPanel->SetZoom(zoom); } void MainFrame::OnZoomOut(wxCommandEvent& event) { int zoom = m_zoomPanel->GetZoom(); if (zoom > 1) zoom /= 2; m_zoomPanel->SetZoom(zoom); } void MainFrame::OnRefreshImage(wxCommandEvent& event) { m_zoomPanel->Update(); } void MainFrame::OnSelectTiming(wxCommandEvent& event) { int interval = timerIntervals[event.GetId()]; m_timerButton->Disable(); refreshTimer.Start(interval * 1000); } void MainFrame::OnTimerRefreshImage(wxCommandEvent& event) { wxMenu menu(_("Refresh image in...")); timerIntervals.clear(); int intervals [] = {1, 2, 5}; for (int i = 0; i < 3; i++) { wxMenuItem* item; if (i == 1) item = menu.Append(wxID_ANY, wxString::Format(_("%d second"), intervals[i])); else item = menu.Append(wxID_ANY, wxString::Format(_("%d seconds"), intervals[i])); menu.Bind(wxEVT_COMMAND_MENU_SELECTED, &MainFrame::OnSelectTiming, this, item->GetId()); timerIntervals[item->GetId()] = intervals[i]; } m_timerButton->PopupMenu(&menu); } void MainFrame::OnRefreshTimerEvent(wxTimerEvent& event) { m_zoomPanel->Update(); m_timerButton->Enable(); refreshTimer.Stop(); }<commit_msg>Fix zoom panel focus bug.<commit_after>#include "MainFrame.h" #include "RGBModel.h" #include "HSLModel.h" #include "CMYKModel.h" #include "HtmlHexOutput.h" #include <wx/aboutdlg.h> #include <wx/dcscreen.h> #include <wx/graphics.h> #include <wx/dcmemory.h> #include <wx/dialog.h> #include <wx/gdicmn.h> #include <wx/dnd.h> #include <wx/dataobj.h> #include <wx/colordlg.h> #include <wx/colourdata.h> struct ZoomMenuFunctor { ZoomPanel* panel; int zoom; ZoomMenuFunctor(ZoomPanel* p, int z) : panel(p), zoom(z) { } void operator()(wxCommandEvent& event) { panel->SetZoom(zoom); } }; MainFrame::MainFrame(wxWindow* parent) : MainFrameBaseClass(parent), capturing(false), refreshTimer(this) { Bind(wxEVT_TIMER, &MainFrame::OnRefreshTimerEvent, this, refreshTimer.GetId()); RestorePosition(); colorOutput = new HtmlHexOutput; AddColorOutput(colorOutput); colorModel = new RGBModel; AddColorModel(colorModel); AddColorModel(new HSLModel); AddColorModel(new CMYKModel); UpdateColorModel(); SetColor(wxColour( config.ReadLong("Main/Color/R", 0), config.ReadLong("Main/Color/G", 0), config.ReadLong("Main/Color/B", 0) )); m_zoomPanel->SetPoi(wxPoint( config.ReadLong("Main/ZoomPanel/X", 0), config.ReadLong("Main/ZoomPanel/Y", 0) )); m_zoomPanel->SetZoom(config.ReadLong("Main/ZoomPanel/Zoom", 4)); } MainFrame::~MainFrame() { wxPoint pos = GetPosition(); config.Write("Main/Position/X", pos.x); config.Write("Main/Position/Y", pos.y); wxColour col = GetColor(); config.Write("Main/Color/R", col.Red()); config.Write("Main/Color/G", col.Green()); config.Write("Main/Color/B", col.Blue()); wxPoint poi = m_zoomPanel->GetPoi(); config.Write("Main/ZoomPanel/X", poi.x); config.Write("Main/ZoomPanel/Y", poi.y); config.Write("Main/ZoomPanel/Zoom", m_zoomPanel->GetZoom()); } void MainFrame::RestorePosition() { int x = config.ReadLong("Main/Position/X", GetPosition().x); int y = config.ReadLong("Main/Position/Y", GetPosition().y); wxSize screenSize = wxGetDisplaySize(); wxSize windowSize = GetSize(); if (x < 0) x = 0; if (y < 0) y = 0; if (x > (screenSize.x - windowSize.x)) x = screenSize.x - windowSize.x; if (y > (screenSize.y - windowSize.y)) y = screenSize.y - windowSize.y; SetPosition(wxPoint(x, y)); } void MainFrame::AddColorModel(IColorModel* colorModel) { wxWindowID id = wxIdManager::ReserveId(); colorModels[id] = colorModel; wxMenuItem* menuItem = new wxMenuItem(m_colorModelMenu, id, colorModel->getName(), wxT(""), wxITEM_RADIO); m_colorModelMenu->Append(menuItem); m_colorModelMenu->Bind(wxEVT_COMMAND_MENU_SELECTED, &MainFrame::OnSelectColorModel, this, menuItem->GetId()); } void MainFrame::AddColorOutput(IColorOutput* colorOutput) { wxWindowID id = wxIdManager::ReserveId(); colorOutputs[id] = colorOutput; wxMenuItem* menuItem = new wxMenuItem(m_colorOutputMenu, id, colorOutput->getName(), wxT(""), wxITEM_RADIO); m_colorOutputMenu->Append(menuItem); m_colorOutputMenu->Bind(wxEVT_COMMAND_MENU_SELECTED, &MainFrame::OnSelectColorOutput, this, menuItem->GetId()); } void MainFrame::SetColorModel(IColorModel* colorModel) { this->colorModel = colorModel; UpdateColorModel(); } void MainFrame::SetColorOutput(IColorOutput* colorOutput) { this->colorOutput = colorOutput; } void update_label_and_ctrl(int i, IColorModel* colorModel, wxStaticText* label, wxSpinCtrl* ctrl) { if (colorModel->getNumComponents() > i) { label->Show(true); ctrl->Show(true); std::string labelStr = colorModel->getLabel(i); label->SetLabel(labelStr.substr(0, 1).append(":")); label->SetToolTip(labelStr); ctrl->SetToolTip(labelStr); ctrl->SetMin(colorModel->getMin(i)); ctrl->SetMax(colorModel->getMax(i)); } else { label->Show(false); ctrl->Show(false); } } void MainFrame::UpdateColorModel() { update_label_and_ctrl(0, colorModel, m_firstLabel, m_firstCtrl); update_label_and_ctrl(1, colorModel, m_secondLabel, m_secondCtrl); update_label_and_ctrl(2, colorModel, m_thirdLabel, m_thirdCtrl); update_label_and_ctrl(3, colorModel, m_fourthLabel, m_fourthCtrl); SetColor(GetColor()); } void MainFrame::OnExit(wxCommandEvent& event) { wxUnusedVar(event); Close(); } void MainFrame::OnAbout(wxCommandEvent& event) { wxUnusedVar(event); wxAboutDialogInfo info; info.SetName("ColorGrab"); info.SetVersion("0.1-dev"); info.SetWebSite("http://nielssp.dk"); info.SetCopyright(_("(C) 2015 Niels Sonnich Poulsen")); info.SetLicence(_("MIT License")); info.SetDescription(_("Free color picker tool.")); ::wxAboutBox(info); } wxBitmap GetScreenShot() { wxSize screenSize = wxGetDisplaySize(); wxBitmap bitmap(screenSize.x, screenSize.y); wxScreenDC dc; wxMemoryDC memDC; memDC.SelectObject(bitmap); memDC.Blit(0, 0, screenSize.x, screenSize.y, &dc, 0, 0); memDC.SelectObject(wxNullBitmap); return bitmap; } void MainFrame::UpdateZoomArea() { m_zoomPanel->SetPoi(wxGetMousePosition()); } void MainFrame::SetColorFromMouse() { int x, y; wxGetMousePosition(&x, &y); SetColorFromPixel(x, y); } void MainFrame::SetColorFromPixel(wxCoord x, wxCoord y) { wxColor color; wxScreenDC dc; dc.GetPixel(x, y, &color); SetColor(color); } wxColor MainFrame::GetColor() const { return m_colorButton->GetBackgroundColour(); } void MainFrame::SetColor(const wxColor& color, bool updateInputs, bool updateOutput) { // m_colourPicker->SetColour(color); m_colorButton->SetBackgroundColour(color); m_colorButton->Refresh(); colorModel->setColor(color); if (updateInputs) { m_firstCtrl->SetValue(colorModel->getValue(0)); m_secondCtrl->SetValue(colorModel->getValue(1)); m_thirdCtrl->SetValue(colorModel->getValue(2)); m_fourthCtrl->SetValue(colorModel->getValue(3)); } colorOutput->setColor(color); if (updateOutput) m_formatText->ChangeValue(colorOutput->getOutput()); } void MainFrame::OnColorChange(wxCommandEvent& event) { colorModel->setValue(0, m_firstCtrl->GetValue()); colorModel->setValue(1, m_secondCtrl->GetValue()); colorModel->setValue(2, m_thirdCtrl->GetValue()); colorModel->setValue(3, m_fourthCtrl->GetValue()); SetColor(colorModel->getColor(), false); } void MainFrame::OnCaptureStart(wxMouseEvent& event) { SetColorFromMouse(); UpdateZoomArea(); CaptureMouse(); SetCursor(*wxCROSS_CURSOR); capturing = true; SetFocus(); } void MainFrame::OnCaptureEnd(wxMouseEvent& event) { if (capturing) { SetColorFromMouse(); UpdateZoomArea(); ReleaseMouse(); capturing = false; SetCursor(wxNullCursor); } } void MainFrame::OnCaptureMove(wxMouseEvent& event) { if (capturing) { SetColorFromMouse(); UpdateZoomArea(); } } void MainFrame::OnSystemColorPicker(wxCommandEvent& event) { wxColourDialog dialog(this); dialog.GetColourData().SetColour(GetColor()); dialog.ShowModal(); SetColor(dialog.GetColourData().GetColour()); } void MainFrame::OnFormatChoose(wxMenuEvent& event) { } void MainFrame::OnFormatClick(wxCommandEvent& event) { } void MainFrame::OnCaptureZoom(wxMouseEvent& event) { if (capturing) OnZoomPanelZoom(event); } void MainFrame::OnZoomSelect(wxCommandEvent& event) { m_zoomPanel->SetZoom(2); } void MainFrame::OnZoomPanelDown(wxMouseEvent& event) { m_zoomPanel->ShowPoi(false); m_zoomPanel->SetFocus(); SetColorFromMouse(); capturing = true; } void MainFrame::OnZoomPanelMove(wxMouseEvent& event) { m_zoomPanel->SetFocus(); if (capturing) SetColorFromMouse(); } void MainFrame::OnZoomPanelUp(wxMouseEvent& event) { SetColorFromMouse(); capturing = false; } void MainFrame::OnZoomPanelZoom(wxMouseEvent& event) { int zoom = m_zoomPanel->GetZoom(); if (event.GetWheelRotation() > 0 && zoom < 64) zoom *= 2; else if (event.GetWheelRotation() < 0 && zoom > 1) zoom /= 2; m_zoomPanel->SetZoom(zoom); } void MainFrame::OnSelectColorModel(wxCommandEvent& event) { SetColorModel(colorModels[event.GetId()]); } void MainFrame::OnSelectColorOutput(wxCommandEvent& event) { SetColorOutput(colorOutputs[event.GetId()]); } void MainFrame::OnColorOutputChange(wxCommandEvent& event) { colorOutput->setOutput(m_formatText->GetValue().ToStdString()); SetColor(colorOutput->getColor(), true, false); } void MainFrame::OnInputOutputBlur(wxFocusEvent& event) { SetColor(GetColor()); event.Skip(); } void MainFrame::OnInputOutputEnter(wxCommandEvent& event) { SetColor(GetColor()); } void MainFrame::OnZoomIn(wxCommandEvent& event) { int zoom = m_zoomPanel->GetZoom(); if (zoom < 64) zoom *= 2; m_zoomPanel->SetZoom(zoom); } void MainFrame::OnZoomOut(wxCommandEvent& event) { int zoom = m_zoomPanel->GetZoom(); if (zoom > 1) zoom /= 2; m_zoomPanel->SetZoom(zoom); } void MainFrame::OnRefreshImage(wxCommandEvent& event) { m_zoomPanel->Update(); } void MainFrame::OnSelectTiming(wxCommandEvent& event) { int interval = timerIntervals[event.GetId()]; m_timerButton->Disable(); refreshTimer.Start(interval * 1000); } void MainFrame::OnTimerRefreshImage(wxCommandEvent& event) { wxMenu menu(_("Refresh image in...")); timerIntervals.clear(); int intervals [] = {1, 2, 5}; for (int i = 0; i < 3; i++) { wxMenuItem* item; if (i == 1) item = menu.Append(wxID_ANY, wxString::Format(_("%d second"), intervals[i])); else item = menu.Append(wxID_ANY, wxString::Format(_("%d seconds"), intervals[i])); menu.Bind(wxEVT_COMMAND_MENU_SELECTED, &MainFrame::OnSelectTiming, this, item->GetId()); timerIntervals[item->GetId()] = intervals[i]; } m_timerButton->PopupMenu(&menu); } void MainFrame::OnRefreshTimerEvent(wxTimerEvent& event) { m_zoomPanel->Update(); m_timerButton->Enable(); refreshTimer.Stop(); }<|endoftext|>
<commit_before>/* Siconos-IO, Copyright INRIA 2005-2011. * Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * Siconos is a 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 2 of the License, or * (at your option) any later version. * Siconos 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 Siconos; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr */ #ifndef SiconosFullNumerics_hpp #define SiconosFullNumerics_hpp #include "Register.hpp" SICONOS_IO_REGISTER(NumericsOptions, (verboseMode)); template <class Archive> void siconos_io(Archive& ar, Callback&v, unsigned int version) { } REGISTER_BOOST_SERIALIZATION(Callback); template <class Archive> void siconos_io(Archive& ar, _SolverOptions&v, unsigned int version) { SERIALIZE(v, (solverId)(isSet)(iSize)(dSize)(filterOn)(numberOfInternalSolvers)(numericsOptions)(callback), ar); SERIALIZE_C_ARRAY(v.iSize, v, iparam, ar); SERIALIZE_C_ARRAY(v.dSize, v, dparam, ar); SERIALIZE_C_ARRAY(v.numberOfInternalSolvers, v, internalSolvers, ar); } REGISTER_BOOST_SERIALIZATION(_SolverOptions); template <class Archive> void siconos_io(Archive& ar, LinearComplementarityProblem& v, unsigned int version) { SERIALIZE(v, (size)(M), ar); SERIALIZE_C_ARRAY(v.size, v, q, ar); } REGISTER_BOOST_SERIALIZATION(LinearComplementarityProblem); template <class Archive> void siconos_io(Archive& ar, FrictionContactProblem& p, const unsigned int file_version) { SERIALIZE(p, (dimension)(numberOfContacts)(M), ar); if (Archive::is_loading::value) { p.q = (double *) malloc(p.dimension * p.numberOfContacts * sizeof(double)); p.mu = (double *) malloc(p.numberOfContacts * sizeof(double)); } SERIALIZE_C_ARRAY(p.dimension * p.numberOfContacts, p, q, ar); SERIALIZE_C_ARRAY(p.dimension, p, mu, ar); } REGISTER_BOOST_SERIALIZATION(FrictionContactProblem); template <class Archive> void siconos_io(Archive& ar, SparseBlockStructuredMatrix& v, unsigned int version) { SERIALIZE(v, (nbblocks)(blocknumber0)(blocknumber1)(filled1)(filled2), ar); if (Archive::is_loading::value) { v.block = (double **) malloc(v.nbblocks * sizeof(double *)); v.blocksize1 = (unsigned int *) malloc (v.blocknumber1* sizeof(unsigned int)); v.blocksize0 = (unsigned int *) malloc (v.blocknumber0* sizeof(unsigned int)); SERIALIZE_C_ARRAY(v.blocknumber1, v, blocksize1, ar); SERIALIZE_C_ARRAY(v.blocknumber0, v, blocksize0, ar); int diagonalblocknumber = v.blocknumber1 + ((v.blocknumber0 - v.blocknumber1) & -(v.blocknumber0 < v.blocknumber1)); for (unsigned int i=0; i< diagonalblocknumber; ++i) { unsigned int size0 = v.blocksize0[i]; if (i != 0) size0 -= v.blocksize0[i - 1]; unsigned int size1 = v.blocksize1[i]; if (i != 0) size1 -= v.blocksize1[i - 1]; v.block[i] = (double*) malloc(size0 * size1 * sizeof(double)); } v.index1_data = (size_t *) malloc (v.filled1 * sizeof(size_t)); v.index2_data = (size_t *) malloc (v.filled2 * sizeof(size_t)); } else { SERIALIZE_C_ARRAY(v.blocknumber1, v, blocksize1, ar); SERIALIZE_C_ARRAY(v.blocknumber0, v, blocksize0, ar); } for (unsigned int i=0; i<v.nbblocks; ++i) { unsigned int size0 = v.blocksize0[i]; if (i != 0) size0 -= v.blocksize0[i - 1]; unsigned int size1 = v.blocksize1[i]; if (i != 0) size1 -= v.blocksize1[i - 1]; ar & ::boost::serialization::make_nvp("block", (long&) v.block[i]); for (unsigned int k=0; k<size0 * size1; ++k) { ar & ::boost::serialization::make_nvp("item", v.block[i][k]); } } SERIALIZE_C_ARRAY(v.filled1, v, index1_data, ar); SERIALIZE_C_ARRAY(v.filled2, v, index2_data, ar); } REGISTER_BOOST_SERIALIZATION(SparseBlockStructuredMatrix); template <class Archive> void siconos_io(Archive&ar, NumericsMatrix& v, unsigned int version) { SERIALIZE(v, (storageType)(size0)(size1), ar); if (v.storageType == 0) { if (Archive::is_loading::value) { v.matrix0 = (double *) malloc(v.size0 * v.size1 * sizeof(double)); v.matrix1 = NULL; v.matrix2 = NULL; v.matrix3 = NULL; } SERIALIZE_C_ARRAY(v.size0 * v.size1, v, matrix0, ar); } else { { SERIALIZE(v, (matrix1), ar); if (Archive::is_loading::value) { /* only matrix1! -> fix */ v.matrix0 = NULL; v.matrix2 = NULL; v.matrix3 = NULL; } } } } REGISTER_BOOST_SERIALIZATION(NumericsMatrix); template <class Archive> void siconos_io_register_Numerics(Archive& ar) { ar.register_type(static_cast<_SolverOptions*>(NULL)); ar.register_type(static_cast<LinearComplementarityProblem*>(NULL)); ar.register_type(static_cast<NumericsMatrix*>(NULL)); ar.register_type(static_cast<SparseBlockStructuredMatrix*>(NULL)); ar.register_type(static_cast<FrictionContactProblem*>(NULL)); } #endif <commit_msg>IO : fix bug in SparseBlockStructuredMatrix serialization<commit_after>/* Siconos-IO, Copyright INRIA 2005-2011. * Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * Siconos is a 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 2 of the License, or * (at your option) any later version. * Siconos 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 Siconos; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr */ #ifndef SiconosFullNumerics_hpp #define SiconosFullNumerics_hpp #include "Register.hpp" SICONOS_IO_REGISTER(NumericsOptions, (verboseMode)); template <class Archive> void siconos_io(Archive& ar, Callback&v, unsigned int version) { } REGISTER_BOOST_SERIALIZATION(Callback); template <class Archive> void siconos_io(Archive& ar, _SolverOptions&v, unsigned int version) { SERIALIZE(v, (solverId)(isSet)(iSize)(dSize)(filterOn)(numberOfInternalSolvers)(numericsOptions)(callback), ar); SERIALIZE_C_ARRAY(v.iSize, v, iparam, ar); SERIALIZE_C_ARRAY(v.dSize, v, dparam, ar); SERIALIZE_C_ARRAY(v.numberOfInternalSolvers, v, internalSolvers, ar); } REGISTER_BOOST_SERIALIZATION(_SolverOptions); template <class Archive> void siconos_io(Archive& ar, LinearComplementarityProblem& v, unsigned int version) { SERIALIZE(v, (size)(M), ar); SERIALIZE_C_ARRAY(v.size, v, q, ar); } REGISTER_BOOST_SERIALIZATION(LinearComplementarityProblem); template <class Archive> void siconos_io(Archive& ar, FrictionContactProblem& p, const unsigned int file_version) { SERIALIZE(p, (dimension)(numberOfContacts)(M), ar); if (Archive::is_loading::value) { p.q = (double *) malloc(p.dimension * p.numberOfContacts * sizeof(double)); p.mu = (double *) malloc(p.numberOfContacts * sizeof(double)); } SERIALIZE_C_ARRAY(p.dimension * p.numberOfContacts, p, q, ar); SERIALIZE_C_ARRAY(p.dimension, p, mu, ar); } REGISTER_BOOST_SERIALIZATION(FrictionContactProblem); template <class Archive> void siconos_io(Archive& ar, SparseBlockStructuredMatrix& v, unsigned int version) { SERIALIZE(v, (nbblocks)(blocknumber0)(blocknumber1)(filled1)(filled2), ar); if (Archive::is_loading::value) { v.block = (double **) malloc(v.nbblocks * sizeof(double *)); v.blocksize1 = (unsigned int *) malloc (v.blocknumber1* sizeof(unsigned int)); v.blocksize0 = (unsigned int *) malloc (v.blocknumber0* sizeof(unsigned int)); SERIALIZE_C_ARRAY(v.blocknumber1, v, blocksize1, ar); SERIALIZE_C_ARRAY(v.blocknumber0, v, blocksize0, ar); int diagonalblocknumber = v.blocknumber1 + ((v.blocknumber0 - v.blocknumber1) & -(v.blocknumber0 < v.blocknumber1)); for (unsigned int i=0; i< diagonalblocknumber; ++i) { unsigned int size0 = v.blocksize0[i]; if (i != 0) size0 -= v.blocksize0[i - 1]; unsigned int size1 = v.blocksize1[i]; if (i != 0) size1 -= v.blocksize1[i - 1]; v.block[i] = (double*) malloc(size0 * size1 * sizeof(double)); } v.index1_data = (size_t *) malloc (v.filled1 * sizeof(size_t)); v.index2_data = (size_t *) malloc (v.filled2 * sizeof(size_t)); } else { SERIALIZE_C_ARRAY(v.blocknumber1, v, blocksize1, ar); SERIALIZE_C_ARRAY(v.blocknumber0, v, blocksize0, ar); } int diagonalblocknumber = v.blocknumber1 + ((v.blocknumber0 - v.blocknumber1) & -(v.blocknumber0 < v.blocknumber1)); for (unsigned int i=0; i< v.nbblocks; ++i) { ar & ::boost::serialization::make_nvp("block", (long&) v.block[i]); } for (unsigned int i=0; i< diagonalblocknumber; ++i) { unsigned int size0 = v.blocksize0[i]; if (i != 0) size0 -= v.blocksize0[i - 1]; unsigned int size1 = v.blocksize1[i]; if (i != 0) size1 -= v.blocksize1[i - 1]; for (unsigned int k=0; k<size0 * size1; ++k) { ar & ::boost::serialization::make_nvp("item", v.block[i][k]); } } SERIALIZE_C_ARRAY(v.filled1, v, index1_data, ar); SERIALIZE_C_ARRAY(v.filled2, v, index2_data, ar); } REGISTER_BOOST_SERIALIZATION(SparseBlockStructuredMatrix); template <class Archive> void siconos_io(Archive&ar, NumericsMatrix& v, unsigned int version) { SERIALIZE(v, (storageType)(size0)(size1), ar); if (v.storageType == 0) { if (Archive::is_loading::value) { v.matrix0 = (double *) malloc(v.size0 * v.size1 * sizeof(double)); v.matrix1 = NULL; v.matrix2 = NULL; v.matrix3 = NULL; } SERIALIZE_C_ARRAY(v.size0 * v.size1, v, matrix0, ar); } else { { SERIALIZE(v, (matrix1), ar); if (Archive::is_loading::value) { /* only matrix1! -> fix */ v.matrix0 = NULL; v.matrix2 = NULL; v.matrix3 = NULL; } } } } REGISTER_BOOST_SERIALIZATION(NumericsMatrix); template <class Archive> void siconos_io_register_Numerics(Archive& ar) { ar.register_type(static_cast<_SolverOptions*>(NULL)); ar.register_type(static_cast<LinearComplementarityProblem*>(NULL)); ar.register_type(static_cast<NumericsMatrix*>(NULL)); ar.register_type(static_cast<SparseBlockStructuredMatrix*>(NULL)); ar.register_type(static_cast<FrictionContactProblem*>(NULL)); } #endif <|endoftext|>
<commit_before>// // IWM.hpp // Clock Signal // // Created by Thomas Harte on 05/05/2019. // Copyright © 2019 Thomas Harte. All rights reserved. // #ifndef IWM_hpp #define IWM_hpp #include "../../ClockReceiver/ClockReceiver.hpp" #include "../../ClockReceiver/ClockingHintSource.hpp" #include "../../Storage/Disk/Drive.hpp" #include <cstdint> namespace Apple { /*! Defines the drive interface used by the IWM, derived from the external pinout as per e.g. https://old.pinouts.ru/HD/MacExtDrive_pinout.shtml These are subclassed of Storage::Disk::Drive, so accept any disk the emulator supports, and provide the usual read/write interface for on-disk data. */ struct IWMDrive: public Storage::Disk::Drive { IWMDrive(int input_clock_rate, int number_of_heads) : Storage::Disk::Drive(input_clock_rate, number_of_heads) {} enum Line: int { CA0 = 1 << 0, CA1 = 1 << 1, CA2 = 1 << 2, LSTRB = 1 << 3, SEL = 1 << 4, }; virtual void set_enabled(bool) = 0; virtual void set_control_lines(int) = 0; virtual bool read() = 0; }; class IWM: public Storage::Disk::Drive::EventDelegate, public ClockingHint::Observer { public: IWM(int clock_rate); /// Sets the current external value of the data bus. void write(int address, uint8_t value); /*! Submits an access to address @c address. @returns The 8-bit value loaded to the data bus by the IWM. */ uint8_t read(int address); /*! Sets the current input of the IWM's SEL line. */ void set_select(bool enabled); /// Advances the controller by @c cycles. void run_for(const Cycles cycles); /// Connects a drive to the IWM. void set_drive(int slot, IWMDrive *drive); private: // Storage::Disk::Drive::EventDelegate. void process_event(const Storage::Disk::Drive::Event &event) override; const int clock_rate_; uint8_t data_register_ = 0; uint8_t mode_ = 0; bool read_write_ready_ = true; bool write_overran_ = false; int state_ = 0; int active_drive_ = 0; IWMDrive *drives_[2] = {nullptr, nullptr}; bool drive_is_rotating_[2] = {false, false}; void set_component_prefers_clocking(ClockingHint::Source *component, ClockingHint::Preference clocking) override; Cycles cycles_until_disable_; uint8_t write_handshake_ = 0x80; void access(int address); uint8_t shift_register_ = 0; uint8_t next_output_ = 0; int output_bits_remaining_ = 0; void propose_shift(uint8_t bit); Cycles cycles_since_shift_; Cycles bit_length_; void push_drive_state(); enum class ShiftMode { Reading, Writing, CheckingWriteProtect } shift_mode_; uint8_t sense(); void select_shift_mode(); }; } #endif /* IWM_hpp */ <commit_msg>Ensures an initial non-zero value.<commit_after>// // IWM.hpp // Clock Signal // // Created by Thomas Harte on 05/05/2019. // Copyright © 2019 Thomas Harte. All rights reserved. // #ifndef IWM_hpp #define IWM_hpp #include "../../ClockReceiver/ClockReceiver.hpp" #include "../../ClockReceiver/ClockingHintSource.hpp" #include "../../Storage/Disk/Drive.hpp" #include <cstdint> namespace Apple { /*! Defines the drive interface used by the IWM, derived from the external pinout as per e.g. https://old.pinouts.ru/HD/MacExtDrive_pinout.shtml These are subclassed of Storage::Disk::Drive, so accept any disk the emulator supports, and provide the usual read/write interface for on-disk data. */ struct IWMDrive: public Storage::Disk::Drive { IWMDrive(int input_clock_rate, int number_of_heads) : Storage::Disk::Drive(input_clock_rate, number_of_heads) {} enum Line: int { CA0 = 1 << 0, CA1 = 1 << 1, CA2 = 1 << 2, LSTRB = 1 << 3, SEL = 1 << 4, }; virtual void set_enabled(bool) = 0; virtual void set_control_lines(int) = 0; virtual bool read() = 0; }; class IWM: public Storage::Disk::Drive::EventDelegate, public ClockingHint::Observer { public: IWM(int clock_rate); /// Sets the current external value of the data bus. void write(int address, uint8_t value); /*! Submits an access to address @c address. @returns The 8-bit value loaded to the data bus by the IWM. */ uint8_t read(int address); /*! Sets the current input of the IWM's SEL line. */ void set_select(bool enabled); /// Advances the controller by @c cycles. void run_for(const Cycles cycles); /// Connects a drive to the IWM. void set_drive(int slot, IWMDrive *drive); private: // Storage::Disk::Drive::EventDelegate. void process_event(const Storage::Disk::Drive::Event &event) override; const int clock_rate_; uint8_t data_register_ = 0; uint8_t mode_ = 0; bool read_write_ready_ = true; bool write_overran_ = false; int state_ = 0; int active_drive_ = 0; IWMDrive *drives_[2] = {nullptr, nullptr}; bool drive_is_rotating_[2] = {false, false}; void set_component_prefers_clocking(ClockingHint::Source *component, ClockingHint::Preference clocking) override; Cycles cycles_until_disable_; uint8_t write_handshake_ = 0x80; void access(int address); uint8_t shift_register_ = 0; uint8_t next_output_ = 0; int output_bits_remaining_ = 0; void propose_shift(uint8_t bit); Cycles cycles_since_shift_; Cycles bit_length_ = Cycles(16); void push_drive_state(); enum class ShiftMode { Reading, Writing, CheckingWriteProtect } shift_mode_; uint8_t sense(); void select_shift_mode(); }; } #endif /* IWM_hpp */ <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2016 Ian Rees <ian.rees@gmail.com> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library 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 Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #include "DlgSettingsImportExportImp.h" #include "ui_DlgSettingsImportExport.h" #include <App/Application.h> using namespace MeshGui; DlgSettingsImportExport::DlgSettingsImportExport(QWidget* parent) : PreferencePage(parent), ui(new Ui_DlgSettingsImportExport) { ui->setupUi(this); } DlgSettingsImportExport::~DlgSettingsImportExport() { // no need to delete child widgets, Qt does it all for us } void DlgSettingsImportExport::saveSettings() { ParameterGrp::handle handle = App::GetApplication().GetParameterGroupByPath ("User parameter:BaseApp/Preferences/Mod/Mesh"); double value = ui->maxDeviationExport->value().getValue(); handle->SetFloat("MaxDeviationExport", value); ui->exportAmfCompressed->onSave(); } void DlgSettingsImportExport::loadSettings() { ParameterGrp::handle handle = App::GetApplication().GetParameterGroupByPath ("User parameter:BaseApp/Preferences/Mod/Mesh"); double value = ui->maxDeviationExport->value().getValue(); value = handle->GetFloat("MaxDeviationExport", value); ui->maxDeviationExport->setValue(value); ui->exportAmfCompressed->onRestore(); } /** * Sets the strings of the subwidgets using the current language. */ void DlgSettingsImportExport::changeEvent(QEvent *e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); } else { QWidget::changeEvent(e); } } #include "moc_DlgSettingsImportExportImp.cpp" <commit_msg>fixes 0003838: missing tooltip in mesh preferences dialog<commit_after>/*************************************************************************** * Copyright (c) 2016 Ian Rees <ian.rees@gmail.com> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library 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 Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #include "DlgSettingsImportExportImp.h" #include "ui_DlgSettingsImportExport.h" #include <App/Application.h> using namespace MeshGui; DlgSettingsImportExport::DlgSettingsImportExport(QWidget* parent) : PreferencePage(parent), ui(new Ui_DlgSettingsImportExport) { ui->setupUi(this); ui->exportAmfCompressed->setToolTip(tr("This parameter indicates whether ZIP compression\n" "is used when writing a file in AMF format")); } DlgSettingsImportExport::~DlgSettingsImportExport() { // no need to delete child widgets, Qt does it all for us } void DlgSettingsImportExport::saveSettings() { ParameterGrp::handle handle = App::GetApplication().GetParameterGroupByPath ("User parameter:BaseApp/Preferences/Mod/Mesh"); double value = ui->maxDeviationExport->value().getValue(); handle->SetFloat("MaxDeviationExport", value); ui->exportAmfCompressed->onSave(); } void DlgSettingsImportExport::loadSettings() { ParameterGrp::handle handle = App::GetApplication().GetParameterGroupByPath ("User parameter:BaseApp/Preferences/Mod/Mesh"); double value = ui->maxDeviationExport->value().getValue(); value = handle->GetFloat("MaxDeviationExport", value); ui->maxDeviationExport->setValue(value); ui->exportAmfCompressed->onRestore(); } /** * Sets the strings of the subwidgets using the current language. */ void DlgSettingsImportExport::changeEvent(QEvent *e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); } else { QWidget::changeEvent(e); } } #include "moc_DlgSettingsImportExportImp.cpp" <|endoftext|>
<commit_before>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/CopasiDataModel/CCopasiDataModel.cpp,v $ $Revision: 1.7 $ $Name: $ $Author: shoops $ $Date: 2005/02/24 19:38:29 $ End CVS Header */ #include "copasi.h" #include "copasiversion.h" #include "CCopasiDataModel.h" #include "commandline/COptions.h" #include "function/CFunctionDB.h" #include "model/CModel.h" #include "utilities/CCopasiVector.h" #include "utilities/CCopasiTask.h" #include "utilities/CCopasiProblem.h" #include "steadystate/CSteadyStateTask.h" #include "trajectory/CTrajectoryTask.h" #include "scan/CScanTask.h" #include "optimization/COptTask.h" #include "steadystate/CMCATask.h" #include "steadystate/CMCAMethod.h" #include "report/CReportDefinitionVector.h" #include "plot/CPlotSpecification.h" #include "xml/CCopasiXML.h" #include "sbml/SBMLImporter.h" #include "sbml/SBMLExporter.h" CCopasiDataModel * CCopasiDataModel::Global = NULL; CCopasiDataModel::CCopasiDataModel(const bool withGUI): mpVersion(new CVersion), mpFunctionList(new CFunctionDB), mpModel(NULL), mpTaskList(NULL), mpReportDefinitionList(NULL), mpPlotDefinitionList(NULL), mWithGUI(withGUI), mpGUI(NULL), mChanged(false), mAutoSaveNeeded(false), pOldMetabolites(new CCopasiVectorS < CMetabOld >) { mpVersion->setVersion(COPASI_VERSION_MAJOR, COPASI_VERSION_MINOR, COPASI_VERSION_BUILD); mpFunctionList->load(); newModel(); } CCopasiDataModel::~CCopasiDataModel() { pdelete(mpVersion); pdelete(mpFunctionList); pdelete(mpModel); pdelete(mpTaskList); pdelete(mpReportDefinitionList); pdelete(mpPlotDefinitionList); pdelete(mpGUI); pdelete(pOldMetabolites); } bool CCopasiDataModel::loadModel(const std::string & fileName) { std::ifstream File(fileName.c_str()); if (File.fail()) { CCopasiMessage Message(CCopasiMessage::RAW, "File error when opening '%s'.", fileName.c_str()); return false; } std::string Line; File >> Line; if (!Line.compare(0, 8, "Version=")) { if (fileName.rfind(".gps") == fileName.length() - 4 || fileName.rfind(".GPS") == fileName.length() - 4) mSaveFileName = fileName.substr(0, fileName.length() - 4) + ".cps"; else mSaveFileName = fileName + ".cps"; File.close(); CReadConfig inbuf(fileName.c_str()); newModel(); mpModel->load(inbuf); dynamic_cast<CSteadyStateTask *>((*mpTaskList)["Steady-State"])->load(inbuf); dynamic_cast<CTrajectoryTask *>((*mpTaskList)["Time-Course"])->load(inbuf); } else if (!Line.compare(0, 5, "<?xml")) { mSaveFileName = fileName; std::cout << "XML Format" << std::endl; File.seekg(0, std::ios_base::beg); CCopasiXML XML; XML.setFunctionList(mpFunctionList->loadedFunctions()); if (!XML.load(File)) return false; newModel(); XML.setGUI(* mpGUI); if (XML.getModel()) { pdelete(mpModel); mpModel = XML.getModel(); } if (XML.getTaskList()) { pdelete(mpTaskList); mpTaskList = XML.getTaskList(); mpTaskList->setObjectName("TaskList"); mpTaskList->setObjectParent(CCopasiContainer::Root); addDefaultTasks(); } if (XML.getReportList()) { pdelete(mpReportDefinitionList); mpReportDefinitionList = new CReportDefinitionVector; *static_cast< CCopasiVector< CReportDefinition > * >(mpReportDefinitionList) = *XML.getReportList(); } if (XML.getPlotList()) { pdelete(mpPlotDefinitionList); mpPlotDefinitionList = XML.getPlotList(); } } if (mpModel) mpModel->setCompileFlag(); changed(false); return true; } bool CCopasiDataModel::saveModel(const std::string & fileName, const bool & autoSave) { std::string FileName = (fileName != "") ? fileName : mSaveFileName; mpModel->compileIfNecessary(); CCopasiXML XML; XML.setModel(*mpModel); XML.setTaskList(*mpTaskList); XML.setReportList(*mpReportDefinitionList); XML.setPlotList(*mpPlotDefinitionList); XML.setGUI(*mpGUI); // We are first writing to a temporary stream to prevent accidental // destruction of an existing file in case the save command fails. std::ostringstream tmp; if (!XML.save(tmp)) return false; std::ofstream os(FileName.c_str()); if (os.fail()) return false; os << tmp.str(); if (os.fail()) return false; if (!autoSave) changed(false); return true; } bool CCopasiDataModel::autoSave() { if (!mAutoSaveNeeded) return true; std::string AutoSave; int index; COptions::getValue("Tmp", AutoSave); #ifdef WIN32 AutoSave += "\\"; #else AutoSave += "/"; #endif if ((index = mSaveFileName.find_last_of('\\')) == -1) index = mSaveFileName.find_last_of('/'); //index = mSaveFileName.find_last_of('/' || '\\'); AutoSave += "tmp_" + mSaveFileName.substr(index + 1, mSaveFileName.length() - index - 5) + ".cps"; if (!saveModel(AutoSave, true)) return false; mAutoSaveNeeded = false; return true; } bool CCopasiDataModel::newModel(CModel * pModel) { pdelete(mpModel); mpModel = (pModel) ? pModel : new CModel(); pdelete(mpTaskList); mpTaskList = new CCopasiVectorN< CCopasiTask >("TaskList", CCopasiContainer::Root); // We have at least one task of every type addDefaultTasks(); pdelete(mpReportDefinitionList); mpReportDefinitionList = new CReportDefinitionVector; pdelete(mpPlotDefinitionList); mpPlotDefinitionList = new CCopasiVectorN< CPlotSpecification >; if (mWithGUI) { pdelete(mpGUI); mpGUI = new SCopasiXMLGUI; } changed(false); return true; } bool CCopasiDataModel::importSBML(const std::string & fileName) { if (fileName.rfind(".xml") == fileName.length() - 4 || fileName.rfind(".XML") == fileName.length() - 4) mSaveFileName = fileName.substr(0, fileName.length() - 4) + ".cps"; else mSaveFileName = fileName + ".cps"; SBMLImporter importer; CModel * pModel = importer.readSBML(fileName, mpFunctionList); if (pModel == NULL) return false; return newModel(pModel); } bool CCopasiDataModel::exportSBML(const std::string & fileName) { if (fileName == "") return false; SBMLExporter exporter; exporter.exportSBML(mpModel, fileName.c_str()); return true; } CModel * CCopasiDataModel::getModel() {return mpModel;} CCopasiVectorN< CCopasiTask > * CCopasiDataModel::getTaskList() {return mpTaskList;} // static CCopasiTask * CCopasiDataModel::addTask(const CCopasiTask::Type & taskType) { CCopasiTask * pTask = NULL; switch (taskType) { case CCopasiTask::steadyState: pTask = new CSteadyStateTask(mpTaskList); break; case CCopasiTask::timeCourse: pTask = new CTrajectoryTask(mpTaskList); break; case CCopasiTask::scan: pTask = new CScanTask(mpTaskList); break; case CCopasiTask::fluxMode: // :TODO: implement task for elementary flux mode analysis return pTask; break; case CCopasiTask::optimization: // :TODO: implement task for optimization return pTask; break; case CCopasiTask::parameterFitting: // :TODO: implement task for parameter fitting return pTask; break; case CCopasiTask::mca: pTask = new CMCATask(mpTaskList); // :TODO: This must be avoided. static_cast<CMCAMethod *>(pTask->getMethod())->setModel(mpModel); break; default: return pTask; } pTask->getProblem()->setModel(mpModel); mpTaskList->add(pTask); return pTask; } bool CCopasiDataModel::addDefaultTasks() { if (mpTaskList->getIndex("Steady-State") == C_INVALID_INDEX) addTask(CCopasiTask::steadyState); if (mpTaskList->getIndex("Time-Course") == C_INVALID_INDEX) addTask(CCopasiTask::timeCourse); if (mpTaskList->getIndex("Scan") == C_INVALID_INDEX) addTask(CCopasiTask::scan); if (mpTaskList->getIndex("Elementary Flux Modes") == C_INVALID_INDEX) addTask(CCopasiTask::fluxMode); if (mpTaskList->getIndex("Optimization") == C_INVALID_INDEX) addTask(CCopasiTask::optimization); if (mpTaskList->getIndex("Parameter Fitting") == C_INVALID_INDEX) addTask(CCopasiTask::parameterFitting); if (mpTaskList->getIndex("Metabolic Control Analysis") == C_INVALID_INDEX) addTask(CCopasiTask::mca); return true; } CReportDefinitionVector * CCopasiDataModel::getReportDefinitionList() {return mpReportDefinitionList;} CCopasiVectorN<CPlotSpecification> * CCopasiDataModel::getPlotDefinitionList() {return mpPlotDefinitionList;} CFunctionDB * CCopasiDataModel::getFunctionList() {return mpFunctionList;} SCopasiXMLGUI * CCopasiDataModel::getGUI() {return mpGUI;} CVersion * CCopasiDataModel::getVersion() {return mpVersion;} bool CCopasiDataModel::isChanged() const {return mChanged;} void CCopasiDataModel::changed(const bool & changed) { mChanged = changed; mAutoSaveNeeded = changed; } <commit_msg>Fixed handling of GUI information in loadModel.<commit_after>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/CopasiDataModel/CCopasiDataModel.cpp,v $ $Revision: 1.8 $ $Name: $ $Author: shoops $ $Date: 2005/02/25 01:49:53 $ End CVS Header */ #include "copasi.h" #include "copasiversion.h" #include "CCopasiDataModel.h" #include "commandline/COptions.h" #include "function/CFunctionDB.h" #include "model/CModel.h" #include "utilities/CCopasiVector.h" #include "utilities/CCopasiTask.h" #include "utilities/CCopasiProblem.h" #include "steadystate/CSteadyStateTask.h" #include "trajectory/CTrajectoryTask.h" #include "scan/CScanTask.h" #include "optimization/COptTask.h" #include "steadystate/CMCATask.h" #include "steadystate/CMCAMethod.h" #include "report/CReportDefinitionVector.h" #include "plot/CPlotSpecification.h" #include "xml/CCopasiXML.h" #include "sbml/SBMLImporter.h" #include "sbml/SBMLExporter.h" CCopasiDataModel * CCopasiDataModel::Global = NULL; CCopasiDataModel::CCopasiDataModel(const bool withGUI): mpVersion(new CVersion), mpFunctionList(new CFunctionDB), mpModel(NULL), mpTaskList(NULL), mpReportDefinitionList(NULL), mpPlotDefinitionList(NULL), mWithGUI(withGUI), mpGUI(NULL), mChanged(false), mAutoSaveNeeded(false), pOldMetabolites(new CCopasiVectorS < CMetabOld >) { mpVersion->setVersion(COPASI_VERSION_MAJOR, COPASI_VERSION_MINOR, COPASI_VERSION_BUILD); mpFunctionList->load(); newModel(); } CCopasiDataModel::~CCopasiDataModel() { pdelete(mpVersion); pdelete(mpFunctionList); pdelete(mpModel); pdelete(mpTaskList); pdelete(mpReportDefinitionList); pdelete(mpPlotDefinitionList); pdelete(mpGUI); pdelete(pOldMetabolites); } bool CCopasiDataModel::loadModel(const std::string & fileName) { std::ifstream File(fileName.c_str()); if (File.fail()) { CCopasiMessage Message(CCopasiMessage::RAW, "File error when opening '%s'.", fileName.c_str()); return false; } std::string Line; File >> Line; if (!Line.compare(0, 8, "Version=")) { if (fileName.rfind(".gps") == fileName.length() - 4 || fileName.rfind(".GPS") == fileName.length() - 4) mSaveFileName = fileName.substr(0, fileName.length() - 4) + ".cps"; else mSaveFileName = fileName + ".cps"; File.close(); CReadConfig inbuf(fileName.c_str()); newModel(); mpModel->load(inbuf); dynamic_cast<CSteadyStateTask *>((*mpTaskList)["Steady-State"])->load(inbuf); dynamic_cast<CTrajectoryTask *>((*mpTaskList)["Time-Course"])->load(inbuf); } else if (!Line.compare(0, 5, "<?xml")) { mSaveFileName = fileName; std::cout << "XML Format" << std::endl; File.seekg(0, std::ios_base::beg); CCopasiXML XML; XML.setFunctionList(mpFunctionList->loadedFunctions()); SCopasiXMLGUI *pGUI = NULL; if (mWithGUI) { pGUI = new SCopasiXMLGUI; XML.setGUI(*pGUI); } if (!XML.load(File)) return false; newModel(); if (XML.getModel()) { pdelete(mpModel); mpModel = XML.getModel(); } if (XML.getTaskList()) { pdelete(mpTaskList); mpTaskList = XML.getTaskList(); mpTaskList->setObjectName("TaskList"); mpTaskList->setObjectParent(CCopasiContainer::Root); addDefaultTasks(); } if (XML.getReportList()) { pdelete(mpReportDefinitionList); mpReportDefinitionList = new CReportDefinitionVector; *static_cast< CCopasiVector< CReportDefinition > * >(mpReportDefinitionList) = *XML.getReportList(); } if (XML.getPlotList()) { pdelete(mpPlotDefinitionList); mpPlotDefinitionList = XML.getPlotList(); } if (mWithGUI) { pdelete(mpGUI); mpGUI = pGUI; } } if (mpModel) mpModel->setCompileFlag(); changed(false); return true; } bool CCopasiDataModel::saveModel(const std::string & fileName, const bool & autoSave) { std::string FileName = (fileName != "") ? fileName : mSaveFileName; mpModel->compileIfNecessary(); CCopasiXML XML; XML.setModel(*mpModel); XML.setTaskList(*mpTaskList); XML.setReportList(*mpReportDefinitionList); XML.setPlotList(*mpPlotDefinitionList); XML.setGUI(*mpGUI); // We are first writing to a temporary stream to prevent accidental // destruction of an existing file in case the save command fails. std::ostringstream tmp; if (!XML.save(tmp)) return false; std::ofstream os(FileName.c_str()); if (os.fail()) return false; os << tmp.str(); if (os.fail()) return false; if (!autoSave) changed(false); return true; } bool CCopasiDataModel::autoSave() { if (!mAutoSaveNeeded) return true; std::string AutoSave; int index; COptions::getValue("Tmp", AutoSave); #ifdef WIN32 AutoSave += "\\"; #else AutoSave += "/"; #endif if ((index = mSaveFileName.find_last_of('\\')) == -1) index = mSaveFileName.find_last_of('/'); //index = mSaveFileName.find_last_of('/' || '\\'); AutoSave += "tmp_" + mSaveFileName.substr(index + 1, mSaveFileName.length() - index - 5) + ".cps"; if (!saveModel(AutoSave, true)) return false; mAutoSaveNeeded = false; return true; } bool CCopasiDataModel::newModel(CModel * pModel) { pdelete(mpModel); mpModel = (pModel) ? pModel : new CModel(); pdelete(mpTaskList); mpTaskList = new CCopasiVectorN< CCopasiTask >("TaskList", CCopasiContainer::Root); // We have at least one task of every type addDefaultTasks(); pdelete(mpReportDefinitionList); mpReportDefinitionList = new CReportDefinitionVector; pdelete(mpPlotDefinitionList); mpPlotDefinitionList = new CCopasiVectorN< CPlotSpecification >; if (mWithGUI) { pdelete(mpGUI); mpGUI = new SCopasiXMLGUI; } changed(false); return true; } bool CCopasiDataModel::importSBML(const std::string & fileName) { if (fileName.rfind(".xml") == fileName.length() - 4 || fileName.rfind(".XML") == fileName.length() - 4) mSaveFileName = fileName.substr(0, fileName.length() - 4) + ".cps"; else mSaveFileName = fileName + ".cps"; SBMLImporter importer; CModel * pModel = importer.readSBML(fileName, mpFunctionList); if (pModel == NULL) return false; return newModel(pModel); } bool CCopasiDataModel::exportSBML(const std::string & fileName) { if (fileName == "") return false; SBMLExporter exporter; exporter.exportSBML(mpModel, fileName.c_str()); return true; } CModel * CCopasiDataModel::getModel() {return mpModel;} CCopasiVectorN< CCopasiTask > * CCopasiDataModel::getTaskList() {return mpTaskList;} // static CCopasiTask * CCopasiDataModel::addTask(const CCopasiTask::Type & taskType) { CCopasiTask * pTask = NULL; switch (taskType) { case CCopasiTask::steadyState: pTask = new CSteadyStateTask(mpTaskList); break; case CCopasiTask::timeCourse: pTask = new CTrajectoryTask(mpTaskList); break; case CCopasiTask::scan: pTask = new CScanTask(mpTaskList); break; case CCopasiTask::fluxMode: // :TODO: implement task for elementary flux mode analysis return pTask; break; case CCopasiTask::optimization: // :TODO: implement task for optimization return pTask; break; case CCopasiTask::parameterFitting: // :TODO: implement task for parameter fitting return pTask; break; case CCopasiTask::mca: pTask = new CMCATask(mpTaskList); // :TODO: This must be avoided. static_cast<CMCAMethod *>(pTask->getMethod())->setModel(mpModel); break; default: return pTask; } pTask->getProblem()->setModel(mpModel); mpTaskList->add(pTask); return pTask; } bool CCopasiDataModel::addDefaultTasks() { if (mpTaskList->getIndex("Steady-State") == C_INVALID_INDEX) addTask(CCopasiTask::steadyState); if (mpTaskList->getIndex("Time-Course") == C_INVALID_INDEX) addTask(CCopasiTask::timeCourse); if (mpTaskList->getIndex("Scan") == C_INVALID_INDEX) addTask(CCopasiTask::scan); if (mpTaskList->getIndex("Elementary Flux Modes") == C_INVALID_INDEX) addTask(CCopasiTask::fluxMode); if (mpTaskList->getIndex("Optimization") == C_INVALID_INDEX) addTask(CCopasiTask::optimization); if (mpTaskList->getIndex("Parameter Fitting") == C_INVALID_INDEX) addTask(CCopasiTask::parameterFitting); if (mpTaskList->getIndex("Metabolic Control Analysis") == C_INVALID_INDEX) addTask(CCopasiTask::mca); return true; } CReportDefinitionVector * CCopasiDataModel::getReportDefinitionList() {return mpReportDefinitionList;} CCopasiVectorN<CPlotSpecification> * CCopasiDataModel::getPlotDefinitionList() {return mpPlotDefinitionList;} CFunctionDB * CCopasiDataModel::getFunctionList() {return mpFunctionList;} SCopasiXMLGUI * CCopasiDataModel::getGUI() {return mpGUI;} CVersion * CCopasiDataModel::getVersion() {return mpVersion;} bool CCopasiDataModel::isChanged() const {return mChanged;} void CCopasiDataModel::changed(const bool & changed) { mChanged = changed; mAutoSaveNeeded = changed; } <|endoftext|>
<commit_before>/* * bonjour.cpp * * Copyright (C) 2014 William Markezana <william.markezana@me.com> * */ #include "bonjour.h" #include <muduo/base/Logging.h> #include <signal.h> void *avahi_service(void *arg); /* * constructor * */ bonjour::bonjour() { mIniFile = new ini_parser((string)CONFIGURATION_DIRECTORY+"config.cfg"); hostname = mIniFile->get<string>("PIXEL_STYLES","Hostname","Pixel Styles"); avahi_publish_service_pid = 0; mAvahiThread = 0; pthread_create(&mAvahiThread, NULL, avahi_service, this); delete mIniFile; } /* * destructor * */ bonjour::~bonjour() { if(kill(avahi_publish_service_pid, SIGINT) == - 1) { LOG_INFO << "Unable to kill avahi-publish-service process!"; } LOG_INFO << "Closed Service " << hostname; } /* * private callbacks * */ void *avahi_service(void *arg) { bonjour *mBonjour = (bonjour*)arg; pid_t pid; pid = fork(); if (pid < 0) return (void*)(1); else if (pid == 0) { if( execlp("avahi-publish-service", "avahi-publish-service", mBonjour->hostname.c_str(),"_PixelStyles._tcp", std::to_string(TCP_CONNECTION_PORT).c_str(), strcat((char*)"kLivePreviewUdpPort=", std::to_string(UDP_BROADCAST_PORT).c_str()), NULL) == -1 ) { LOG_INFO << "Bad error... couldn't find or failed to run: avahi-publish-service OR dns-sd OR mDNSPublish"; return (void*)(1); } } LOG_INFO << "Started avahi-publish-service with pid " << pid << " hostname '" << mBonjour->hostname << "'"; mBonjour->avahi_publish_service_pid = pid; return (void*)(1); } <commit_msg>using boost::lexical_cast<string> instead of std::to_string which does not seams to be available in some cases.<commit_after>/* * bonjour.cpp * * Copyright (C) 2014 William Markezana <william.markezana@me.com> * */ #include "bonjour.h" #include <boost/lexical_cast.hpp> #include <muduo/base/Logging.h> #include <signal.h> void *avahi_service(void *arg); /* * constructor * */ bonjour::bonjour() { mIniFile = new ini_parser((string)CONFIGURATION_DIRECTORY+"config.cfg"); hostname = mIniFile->get<string>("PIXEL_STYLES","Hostname","Pixel Styles"); avahi_publish_service_pid = 0; mAvahiThread = 0; pthread_create(&mAvahiThread, NULL, avahi_service, this); delete mIniFile; } /* * destructor * */ bonjour::~bonjour() { if(kill(avahi_publish_service_pid, SIGINT) == - 1) { LOG_INFO << "Unable to kill avahi-publish-service process!"; } LOG_INFO << "Closed Service " << hostname; } /* * private callbacks * */ void *avahi_service(void *arg) { bonjour *mBonjour = (bonjour*)arg; pid_t pid; pid = fork(); if (pid < 0) return (void*)(1); else if (pid == 0) { if( execlp("avahi-publish-service", "avahi-publish-service", mBonjour->hostname.c_str(),"_PixelStyles._tcp", boost::lexical_cast<string>(TCP_CONNECTION_PORT).c_str(), strcat((char*)"kLivePreviewUdpPort=", boost::lexical_cast<string>(UDP_BROADCAST_PORT).c_str()), NULL) == -1 ) { LOG_INFO << "Bad error... couldn't find or failed to run: avahi-publish-service OR dns-sd OR mDNSPublish"; return (void*)(1); } } LOG_INFO << "Started avahi-publish-service with pid " << pid << " hostname '" << mBonjour->hostname << "'"; mBonjour->avahi_publish_service_pid = pid; return (void*)(1); } <|endoftext|>
<commit_before>/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ // Local VOTCA includes #include "votca/xtp/rpa.h" #include "votca/xtp/aomatrix.h" #include "votca/xtp/threecenter.h" #include "votca/xtp/vc2index.h" namespace votca { namespace xtp { void RPA::UpdateRPAInputEnergies(const Eigen::VectorXd& dftenergies, const Eigen::VectorXd& gwaenergies, Index qpmin) { Index rpatotal = _rpamax - _rpamin + 1; _energies = dftenergies.segment(_rpamin, rpatotal); Index gwsize = Index(gwaenergies.size()); Index lumo = _homo + 1; Index qpmax = qpmin + gwsize - 1; _energies.segment(qpmin - _rpamin, gwsize) = gwaenergies; Eigen::VectorXd corrections_occ = _energies.segment(qpmin - _rpamin, lumo - qpmin) - dftenergies.segment(qpmin - _rpamin, lumo - qpmin); Eigen::VectorXd corrections_virt = _energies.segment(lumo - qpmin, gwsize - (lumo - qpmin)) - dftenergies.segment(lumo - qpmin, gwsize - (lumo - qpmin)); double max_correction_occ = (corrections_occ.cwiseAbs()).maxCoeff(); double max_correction_virt = (corrections_virt.cwiseAbs()).maxCoeff(); Index levelaboveqpmax = _rpamax - qpmax; Index levelbelowqpmin = qpmin - _rpamin; _energies.segment(0, levelbelowqpmin).array() -= max_correction_occ; _energies.segment(qpmax + 1 - _rpamin, levelaboveqpmax).array() += max_correction_virt; } template <bool imag> Eigen::MatrixXd RPA::calculate_epsilon(double frequency) const { const Index size = _Mmn.auxsize(); Eigen::MatrixXd result = Eigen::MatrixXd::Identity(size, size); const Index lumo = _homo + 1; const Index n_occ = lumo - _rpamin; const Index n_unocc = _rpamax - lumo + 1; const double freq2 = frequency * frequency; const double eta2 = _eta * _eta; #pragma omp parallel for schedule(dynamic) reduction(+ : result) for (Index m_level = 0; m_level < n_occ; m_level++) { const double qp_energy_m = _energies(m_level); const Eigen::MatrixXd Mmn_RPA = _Mmn[m_level].bottomRows(n_unocc); const Eigen::ArrayXd deltaE = _energies.tail(n_unocc).array() - qp_energy_m; Eigen::VectorXd denom; if (imag) { denom = 4 * deltaE / (deltaE.square() + freq2); } else { Eigen::ArrayXd deltEf = deltaE - frequency; Eigen::ArrayXd sum = deltEf / (deltEf.square() + eta2); deltEf = deltaE + frequency; sum += deltEf / (deltEf.square() + eta2); denom = 2 * sum; } result += Mmn_RPA.transpose() * denom.asDiagonal() * Mmn_RPA; } return result; } template Eigen::MatrixXd RPA::calculate_epsilon<true>(double frequency) const; template Eigen::MatrixXd RPA::calculate_epsilon<false>(double frequency) const; RPA::rpa_eigensolution RPA::Diagonalize_H2p() const { const Index lumo = _homo + 1; const Index n_occ = lumo - _rpamin; const Index n_unocc = _rpamax - lumo + 1; const Index rpasize = n_occ * n_unocc; Eigen::VectorXd AmB = Calculate_H2p_AmB(); Eigen::MatrixXd ApB = Calculate_H2p_ApB(); //double RPA_correlation_energy = -0.25 * (ApB.trace() + AmB.sum()); // C = AmB^1/2 * ApB * AmB^1/2 Eigen::MatrixXd& C = ApB; C.applyOnTheLeft(AmB.cwiseSqrt().asDiagonal()); C.applyOnTheRight(AmB.cwiseSqrt().asDiagonal()); Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es = Diagonalize_H2p_C(C); RPA::rpa_eigensolution sol; // Do not remove this line! It has to be there for MKL to not crash sol.omega = Eigen::VectorXd::Zero(es.eigenvalues().size()); sol.omega = es.eigenvalues().cwiseSqrt(); sol.ERPA_correlation = 0.25*(ApB.trace() + AmB.sum()) - 0.5*sol.omega.sum(); //RPA_correlation_energy += 0.5 * sol.omega.sum(); XTP_LOG(Log::info, _log) << TimeStamp() << " Lowest neutral excitation energy (eV): " << tools::conv::hrt2ev * sol.omega.minCoeff() << std::flush; XTP_LOG(Log::error, _log) << TimeStamp() << " RPA correlation energy (Hartree): " << sol.ERPA_correlation << std::flush; sol.XpY = Eigen::MatrixXd(rpasize, rpasize); Eigen::VectorXd AmB_sqrt = AmB.cwiseSqrt(); Eigen::VectorXd Omega_sqrt_inv = sol.omega.cwiseSqrt().cwiseInverse(); for (int s = 0; s < rpasize; s++) { sol.XpY.col(s) = Omega_sqrt_inv(s) * AmB_sqrt.cwiseProduct(es.eigenvectors().col(s)); } return sol; } Eigen::VectorXd RPA::Calculate_H2p_AmB() const { const Index lumo = _homo + 1; const Index n_occ = lumo - _rpamin; const Index n_unocc = _rpamax - lumo + 1; const Index rpasize = n_occ * n_unocc; vc2index vc = vc2index(0, 0, n_unocc); Eigen::VectorXd AmB = Eigen::VectorXd::Zero(rpasize); for (Index v = 0; v < n_occ; v++) { Index i = vc.I(v, 0); AmB.segment(i, n_unocc) = _energies.segment(n_occ, n_unocc).array() - _energies(v); } return AmB; } Eigen::MatrixXd RPA::Calculate_H2p_ApB() const { const Index lumo = _homo + 1; const Index n_occ = lumo - _rpamin; const Index n_unocc = _rpamax - lumo + 1; const Index rpasize = n_occ * n_unocc; const Index auxsize = _Mmn.auxsize(); vc2index vc = vc2index(0, 0, n_unocc); Eigen::MatrixXd ApB = Eigen::MatrixXd::Zero(rpasize, rpasize); #pragma omp parallel for schedule(guided) for (Index v2 = 0; v2 < n_occ; v2++) { Index i2 = vc.I(v2, 0); const Eigen::MatrixXd Mmn_v2T = _Mmn[v2].block(n_occ, 0, n_unocc, auxsize).transpose(); for (Index v1 = v2; v1 < n_occ; v1++) { Index i1 = vc.I(v1, 0); // Multiply with factor 2 to sum over both (identical) spin states ApB.block(i1, i2, n_unocc, n_unocc) = 2 * 2 * _Mmn[v1].block(n_occ, 0, n_unocc, auxsize) * Mmn_v2T; } } ApB.diagonal() += Calculate_H2p_AmB(); return ApB; } Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> RPA::Diagonalize_H2p_C( const Eigen::MatrixXd& C) const { XTP_LOG(Log::error, _log) << TimeStamp() << " Diagonalizing two-particle Hamiltonian " << std::flush; Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(C); // Uses lower triangle XTP_LOG(Log::error, _log) << TimeStamp() << " Diagonalization done " << std::flush; double minCoeff = es.eigenvalues().minCoeff(); if (minCoeff <= 0.0) { XTP_LOG(Log::error, _log) << TimeStamp() << " Detected non-positive eigenvalue: " << minCoeff << std::flush; throw std::runtime_error("Detected non-positive eigenvalue."); } return es; } } // namespace xtp } // namespace votca <commit_msg>fixing new structure<commit_after>/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ // Local VOTCA includes #include "votca/xtp/rpa.h" #include "votca/xtp/aomatrix.h" #include "votca/xtp/threecenter.h" #include "votca/xtp/vc2index.h" namespace votca { namespace xtp { void RPA::UpdateRPAInputEnergies(const Eigen::VectorXd& dftenergies, const Eigen::VectorXd& gwaenergies, Index qpmin) { Index rpatotal = _rpamax - _rpamin + 1; _energies = dftenergies.segment(_rpamin, rpatotal); Index gwsize = Index(gwaenergies.size()); Index lumo = _homo + 1; Index qpmax = qpmin + gwsize - 1; _energies.segment(qpmin - _rpamin, gwsize) = gwaenergies; Eigen::VectorXd corrections_occ = _energies.segment(qpmin - _rpamin, lumo - qpmin) - dftenergies.segment(qpmin - _rpamin, lumo - qpmin); Eigen::VectorXd corrections_virt = _energies.segment(lumo - qpmin, gwsize - (lumo - qpmin)) - dftenergies.segment(lumo - qpmin, gwsize - (lumo - qpmin)); double max_correction_occ = (corrections_occ.cwiseAbs()).maxCoeff(); double max_correction_virt = (corrections_virt.cwiseAbs()).maxCoeff(); Index levelaboveqpmax = _rpamax - qpmax; Index levelbelowqpmin = qpmin - _rpamin; _energies.segment(0, levelbelowqpmin).array() -= max_correction_occ; _energies.segment(qpmax + 1 - _rpamin, levelaboveqpmax).array() += max_correction_virt; } template <bool imag> Eigen::MatrixXd RPA::calculate_epsilon(double frequency) const { const Index size = _Mmn.auxsize(); Eigen::MatrixXd result = Eigen::MatrixXd::Identity(size, size); const Index lumo = _homo + 1; const Index n_occ = lumo - _rpamin; const Index n_unocc = _rpamax - lumo + 1; const double freq2 = frequency * frequency; const double eta2 = _eta * _eta; #pragma omp parallel for schedule(dynamic) reduction(+ : result) for (Index m_level = 0; m_level < n_occ; m_level++) { const double qp_energy_m = _energies(m_level); const Eigen::MatrixXd Mmn_RPA = _Mmn[m_level].bottomRows(n_unocc); const Eigen::ArrayXd deltaE = _energies.tail(n_unocc).array() - qp_energy_m; Eigen::VectorXd denom; if (imag) { denom = 4 * deltaE / (deltaE.square() + freq2); } else { Eigen::ArrayXd deltEf = deltaE - frequency; Eigen::ArrayXd sum = deltEf / (deltEf.square() + eta2); deltEf = deltaE + frequency; sum += deltEf / (deltEf.square() + eta2); denom = 2 * sum; } result += Mmn_RPA.transpose() * denom.asDiagonal() * Mmn_RPA; } return result; } template Eigen::MatrixXd RPA::calculate_epsilon<true>(double frequency) const; template Eigen::MatrixXd RPA::calculate_epsilon<false>(double frequency) const; RPA::rpa_eigensolution RPA::Diagonalize_H2p() const { const Index lumo = _homo + 1; const Index n_occ = lumo - _rpamin; const Index n_unocc = _rpamax - lumo + 1; const Index rpasize = n_occ * n_unocc; Eigen::VectorXd AmB = Calculate_H2p_AmB(); Eigen::MatrixXd ApB = Calculate_H2p_ApB(); RPA::rpa_eigensolution sol; sol.ERPA_correlation = -0.25*(ApB.trace() + AmB.sum()) ; // C = AmB^1/2 * ApB * AmB^1/2 Eigen::MatrixXd& C = ApB; C.applyOnTheLeft(AmB.cwiseSqrt().asDiagonal()); C.applyOnTheRight(AmB.cwiseSqrt().asDiagonal()); Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es = Diagonalize_H2p_C(C); // Do not remove this line! It has to be there for MKL to not crash sol.omega = Eigen::VectorXd::Zero(es.eigenvalues().size()); sol.omega = es.eigenvalues().cwiseSqrt(); sol.ERPA_correlation += 0.5*sol.omega.sum(); //RPA_correlation_energy += 0.5 * sol.omega.sum(); XTP_LOG(Log::info, _log) << TimeStamp() << " Lowest neutral excitation energy (eV): " << tools::conv::hrt2ev * sol.omega.minCoeff() << std::flush; XTP_LOG(Log::error, _log) << TimeStamp() << " RPA correlation energy (Hartree): " << sol.ERPA_correlation << std::flush; sol.XpY = Eigen::MatrixXd(rpasize, rpasize); Eigen::VectorXd AmB_sqrt = AmB.cwiseSqrt(); Eigen::VectorXd Omega_sqrt_inv = sol.omega.cwiseSqrt().cwiseInverse(); for (int s = 0; s < rpasize; s++) { sol.XpY.col(s) = Omega_sqrt_inv(s) * AmB_sqrt.cwiseProduct(es.eigenvectors().col(s)); } return sol; } Eigen::VectorXd RPA::Calculate_H2p_AmB() const { const Index lumo = _homo + 1; const Index n_occ = lumo - _rpamin; const Index n_unocc = _rpamax - lumo + 1; const Index rpasize = n_occ * n_unocc; vc2index vc = vc2index(0, 0, n_unocc); Eigen::VectorXd AmB = Eigen::VectorXd::Zero(rpasize); for (Index v = 0; v < n_occ; v++) { Index i = vc.I(v, 0); AmB.segment(i, n_unocc) = _energies.segment(n_occ, n_unocc).array() - _energies(v); } return AmB; } Eigen::MatrixXd RPA::Calculate_H2p_ApB() const { const Index lumo = _homo + 1; const Index n_occ = lumo - _rpamin; const Index n_unocc = _rpamax - lumo + 1; const Index rpasize = n_occ * n_unocc; const Index auxsize = _Mmn.auxsize(); vc2index vc = vc2index(0, 0, n_unocc); Eigen::MatrixXd ApB = Eigen::MatrixXd::Zero(rpasize, rpasize); #pragma omp parallel for schedule(guided) for (Index v2 = 0; v2 < n_occ; v2++) { Index i2 = vc.I(v2, 0); const Eigen::MatrixXd Mmn_v2T = _Mmn[v2].block(n_occ, 0, n_unocc, auxsize).transpose(); for (Index v1 = v2; v1 < n_occ; v1++) { Index i1 = vc.I(v1, 0); // Multiply with factor 2 to sum over both (identical) spin states ApB.block(i1, i2, n_unocc, n_unocc) = 2 * 2 * _Mmn[v1].block(n_occ, 0, n_unocc, auxsize) * Mmn_v2T; } } ApB.diagonal() += Calculate_H2p_AmB(); return ApB; } Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> RPA::Diagonalize_H2p_C( const Eigen::MatrixXd& C) const { XTP_LOG(Log::error, _log) << TimeStamp() << " Diagonalizing two-particle Hamiltonian " << std::flush; Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(C); // Uses lower triangle XTP_LOG(Log::error, _log) << TimeStamp() << " Diagonalization done " << std::flush; double minCoeff = es.eigenvalues().minCoeff(); if (minCoeff <= 0.0) { XTP_LOG(Log::error, _log) << TimeStamp() << " Detected non-positive eigenvalue: " << minCoeff << std::flush; throw std::runtime_error("Detected non-positive eigenvalue."); } return es; } } // namespace xtp } // namespace votca <|endoftext|>
<commit_before>#include "line_accumulator.h" #include <cassert> #include <iostream> #include <algorithm> namespace { static std::mt19937 generator; std::uint8_t getRandomIndex( const int seed, const std::uint8_t n ) { generator.seed(seed); return std::uniform_int_distribution<std::uint8_t>{0, n}(generator); } std::vector<std::uint8_t> getRandomIndizes( const int seed, const std::uint8_t n ) { generator.seed(seed); std::vector<std::uint8_t> indizes(n); std::iota(indizes.begin(), indizes.end(), 0); std::shuffle( indizes.begin(), indizes.end(), generator ); return indizes; } } namespace justify { LineAccumulator::LineAccumulator(const std::uint8_t max_length): max_length_{max_length}, length_{0}, tokens_{} { } LineAccumulator::~LineAccumulator() { this->discharge(false); } std::uint8_t LineAccumulator::getMissing() const { return this->max_length_ - this->length_; } void LineAccumulator::operator()(const std::string& token) { if ( ( this->length_ + token.length() ) > this->max_length_ ) { this->discharge(true); } this->tokens_.emplace_back(token, 0); this->length_ += token.length(); if ( this->length_ < this->max_length_ ) { this->tokens_.back().second += 1; this->length_ += 1; } } void LineAccumulator::justify() { const int seed = this->tokens_.size() + this->getMissing(); switch ( this->tokens_.size() ) { // There is no sensible block justification of null or any single token case 0: case 1: { this->length_ = this->max_length_; break; } // i.e. left align the first token and right align the second token case 2: { this->tokens_[0].second += this->getMissing(); this->length_ = this->max_length_; break; } // most common branch for normal texts, add the maximum equal amount of // spaces to all but the last token default: { const std::uint8_t base = this->getMissing() / (this->tokens_.size() - 2); std::for_each( this->tokens_.begin(), this->tokens_.end() - 2, [&, base](auto& token) { token.second += base; this->length_ += base; } ); break; } } assert(this->getMissing() < this->tokens_.size()); switch ( this->getMissing() ) { case 0: { break; } // randomly distribute missing spaces case 1: { this->tokens_[ getRandomIndex(seed, this->tokens_.size() - 2) ].second += 1; break; } default: { const auto indizes = getRandomIndizes(seed, this->tokens_.size() - 2); std::for_each( indizes.begin(), indizes.begin() + this->getMissing(), [&](std::uint8_t x) { this->tokens_[x].second += 1; this->length_ += 1; } ); break; } } } void LineAccumulator::discharge(const bool full) { this->length_ -= this->tokens_.back().second; this->tokens_.back().second = 0; if ( full ) { this->justify(); } for ( const auto& token : this->tokens_ ) { std::cout << token.first << std::string(token.second, ' '); } std::cout << '\n'; this->length_ = 0; this->tokens_.clear(); } } <commit_msg>Implement support for UTF8 multi-byte code points<commit_after>#include "line_accumulator.h" #include <cassert> #include <iostream> #include <algorithm> namespace { static std::mt19937 generator; std::uint8_t getRandomIndex( const int seed, const std::uint8_t n ) { generator.seed(seed); return std::uniform_int_distribution<std::uint8_t>{0, n}(generator); } std::vector<std::uint8_t> getRandomIndizes( const int seed, const std::uint8_t n ) { generator.seed(seed); std::vector<std::uint8_t> indizes(n); std::iota(indizes.begin(), indizes.end(), 0); std::shuffle( indizes.begin(), indizes.end(), generator ); return indizes; } std::size_t getCharacterLength(const std::string& token) { std::size_t codeUnitIndex = 0; std::size_t codePointIndex = 0; while ( token.data()[codeUnitIndex] ) { // advance `codePointIndex` if current unit is not a continuation byte // see RFC3629 for further information if ( (token.data()[codeUnitIndex] & 0b11000000 ) != 0b10000000 ) { ++codePointIndex; } ++codeUnitIndex; } return codePointIndex; } } namespace justify { LineAccumulator::LineAccumulator(const std::uint8_t max_length): max_length_{max_length}, length_{0}, tokens_{} { } LineAccumulator::~LineAccumulator() { this->discharge(false); } std::uint8_t LineAccumulator::getMissing() const { return this->max_length_ - this->length_; } void LineAccumulator::operator()(const std::string& token) { const std::size_t tokenLength = getCharacterLength(token); if ( ( this->length_ + tokenLength ) > this->max_length_ ) { this->discharge(true); } this->tokens_.emplace_back(token, 0); this->length_ += tokenLength; if ( this->length_ < this->max_length_ ) { this->tokens_.back().second += 1; this->length_ += 1; } } void LineAccumulator::justify() { const int seed = this->tokens_.size() + this->getMissing(); switch ( this->tokens_.size() ) { // There is no sensible block justification of null or any single token case 0: case 1: { this->length_ = this->max_length_; break; } // i.e. left align the first token and right align the second token case 2: { this->tokens_[0].second += this->getMissing(); this->length_ = this->max_length_; break; } // most common branch for normal texts, add the maximum equal amount of // spaces to all but the last token default: { const std::uint8_t base = this->getMissing() / (this->tokens_.size() - 2); std::for_each( this->tokens_.begin(), this->tokens_.end() - 2, [&, base](auto& token) { token.second += base; this->length_ += base; } ); break; } } assert(this->getMissing() < this->tokens_.size()); switch ( this->getMissing() ) { case 0: { break; } // randomly distribute missing spaces case 1: { this->tokens_[ getRandomIndex(seed, this->tokens_.size() - 2) ].second += 1; break; } default: { const auto indizes = getRandomIndizes(seed, this->tokens_.size() - 2); std::for_each( indizes.begin(), indizes.begin() + this->getMissing(), [&](std::uint8_t x) { this->tokens_[x].second += 1; this->length_ += 1; } ); break; } } } void LineAccumulator::discharge(const bool full) { this->length_ -= this->tokens_.back().second; this->tokens_.back().second = 0; if ( full ) { this->justify(); } for ( const auto& token : this->tokens_ ) { std::cout << token.first << std::string(token.second, ' '); } std::cout << '\n'; this->length_ = 0; this->tokens_.clear(); } } <|endoftext|>
<commit_before>#include "AliHLTPHOSDDLPackedFileWriter.h" AliHLTPHOSDDLPackedFileWriter::AliHLTPHOSDDLPackedFileWriter() { } AliHLTPHOSDDLPackedFileWriter::~AliHLTPHOSDDLPackedFileWriter() { } int AliHLTPHOSDDLPackedFileWriter::WriteFile(const AliHLTComponentEventData& evtData, const AliHLTComponentBlockData* blocks, AliHLTComponentTriggerData& trigData, int evntCnt) { } <commit_msg>Adding return statement<commit_after>#include "AliHLTPHOSDDLPackedFileWriter.h" AliHLTPHOSDDLPackedFileWriter::AliHLTPHOSDDLPackedFileWriter() { } AliHLTPHOSDDLPackedFileWriter::~AliHLTPHOSDDLPackedFileWriter() { } int AliHLTPHOSDDLPackedFileWriter::WriteFile(const AliHLTComponentEventData& evtData, const AliHLTComponentBlockData* blocks, AliHLTComponentTriggerData& trigData, int evntCnt) { return 0; } <|endoftext|>
<commit_before><commit_msg>fix Mac build<commit_after><|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkBoostBreadthFirstSearchTree.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #include "vtkBoostBreadthFirstSearchTree.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkMath.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkFloatArray.h" #include "vtkDataArray.h" #include "vtkSmartPointer.h" #include "vtkStringArray.h" #include "vtkBoostGraphAdapter.h" #include "vtkMutableDirectedGraph.h" #include "vtkUndirectedGraph.h" #include "vtkTree.h" #include <boost/graph/breadth_first_search.hpp> #include <boost/graph/reverse_graph.hpp> #include <boost/pending/queue.hpp> using namespace boost; vtkStandardNewMacro(vtkBoostBreadthFirstSearchTree); namespace { vtkIdType unwrap_edge_id(vtkEdgeType const &e) { return e.Id; } vtkIdType unwrap_edge_id(boost::detail::reverse_graph_edge_descriptor<vtkEdgeType> const &e) { return e.underlying_desc.Id; } } // Redefine the bfs visitor, the only visitor we // are using is the tree_edge visitor. template <typename IdMap> class bfs_tree_builder : public default_bfs_visitor { public: bfs_tree_builder() { } bfs_tree_builder(IdMap& g2t, IdMap& t2g, vtkGraph* g, vtkMutableDirectedGraph* t, vtkIdType root) : graph_to_tree(g2t), tree_to_graph(t2g), tree(t), graph(g) { double x[3]; graph->GetPoints()->GetPoint(root, x); tree->GetPoints()->InsertNextPoint(x); vtkIdType tree_root = t->AddVertex(); put(graph_to_tree, root, tree_root); put(tree_to_graph, tree_root, root); tree->GetVertexData()->CopyData(graph->GetVertexData(), root, tree_root); } template <typename Edge, typename Graph> void tree_edge(Edge e, const Graph& g) const { typename graph_traits<Graph>::vertex_descriptor u, v; u = source(e, g); v = target(e, g); // Get the source vertex id (it has already been visited). vtkIdType tree_u = get(graph_to_tree, u); // Add the point before the vertex so that // points match the number of vertices, so that GetPoints() // doesn't reallocate and zero-out points. double x[3]; graph->GetPoints()->GetPoint(v, x); tree->GetPoints()->InsertNextPoint(x); // Create the target vertex in the tree. vtkIdType tree_v = tree->AddVertex(); vtkEdgeType tree_e = tree->AddEdge(tree_u, tree_v); // Store the mapping from graph to tree. put(graph_to_tree, v, tree_v); put(tree_to_graph, tree_v, v); // Copy the vertex and edge data from the graph to the tree. tree->GetVertexData()->CopyData(graph->GetVertexData(), v, tree_v); tree->GetEdgeData()->CopyData(graph->GetEdgeData(), unwrap_edge_id(e), tree_e.Id); } private: IdMap graph_to_tree; IdMap tree_to_graph; vtkMutableDirectedGraph *tree; vtkGraph *graph; }; // Constructor/Destructor vtkBoostBreadthFirstSearchTree::vtkBoostBreadthFirstSearchTree() { // Default values for the origin vertex this->OriginVertexIndex = 0; this->ArrayName = 0; this->SetArrayName("Not Set"); this->ArrayNameSet = false; this->OriginValue = 0; this->CreateGraphVertexIdArray = false; this->ReverseEdges = false; } vtkBoostBreadthFirstSearchTree::~vtkBoostBreadthFirstSearchTree() { this->SetArrayName(NULL); } // Description: // Set the index (into the vertex array) of the // breadth first search 'origin' vertex. void vtkBoostBreadthFirstSearchTree::SetOriginVertex(vtkIdType index) { this->OriginVertexIndex = index; this->ArrayNameSet = false; this->Modified(); } // Description: // Set the breadth first search 'origin' vertex. // This method is basically the same as above // but allows the application to simply specify // an array name and value, instead of having to // know the specific index of the vertex. void vtkBoostBreadthFirstSearchTree::SetOriginVertex( vtkStdString arrayName, vtkVariant value) { this->SetArrayName(arrayName); this->ArrayNameSet = true; this->OriginValue = value; this->Modified(); } vtkIdType vtkBoostBreadthFirstSearchTree::GetVertexIndex( vtkAbstractArray *abstract,vtkVariant value) { // Okay now what type of array is it if (abstract->IsNumeric()) { vtkDataArray *dataArray = vtkDataArray::SafeDownCast(abstract); int intValue = value.ToInt(); for(int i=0; i<dataArray->GetNumberOfTuples(); ++i) { if (intValue == static_cast<int>(dataArray->GetTuple1(i))) { return i; } } } else { vtkStringArray *stringArray = vtkStringArray::SafeDownCast(abstract); vtkStdString stringValue(value.ToString()); for(int i=0; i<stringArray->GetNumberOfTuples(); ++i) { if (stringValue == stringArray->GetValue(i)) { return i; } } } // Failed vtkErrorMacro("Did not find a valid vertex index..."); return 0; } int vtkBoostBreadthFirstSearchTree::FillInputPortInformation( int vtkNotUsed(port), vtkInformation* info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkGraph"); return 1; } int vtkBoostBreadthFirstSearchTree::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { // get the info objects vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); vtkInformation *outInfo = outputVector->GetInformationObject(0); // get the input and output vtkGraph *input = vtkGraph::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); // Now figure out the origin vertex of the // breadth first search if (this->ArrayNameSet) { vtkAbstractArray* abstract = input->GetVertexData()->GetAbstractArray(this->ArrayName); // Does the array exist at all? if (abstract == NULL) { vtkErrorMacro("Could not find array named " << this->ArrayName); return 0; } this->OriginVertexIndex = this->GetVertexIndex(abstract,this->OriginValue); } // Create tree to graph id map array vtkIdTypeArray* treeToGraphIdMap = vtkIdTypeArray::New(); // Create graph to tree id map array vtkIdTypeArray* graphToTreeIdMap = vtkIdTypeArray::New(); // Create a color map (used for marking visited nodes) vector_property_map<default_color_type> color; // Create a queue to hand off to the BFS queue<int> q; // Create the mutable graph to build the tree vtkSmartPointer<vtkMutableDirectedGraph> temp = vtkSmartPointer<vtkMutableDirectedGraph>::New(); // Initialize copying data into tree temp->GetFieldData()->PassData(input->GetFieldData()); temp->GetVertexData()->CopyAllocate(input->GetVertexData()); temp->GetEdgeData()->CopyAllocate(input->GetEdgeData()); // Create the visitor which will build the tree bfs_tree_builder<vtkIdTypeArray*> builder( graphToTreeIdMap, treeToGraphIdMap, input, temp, this->OriginVertexIndex); // Run the algorithm if (vtkDirectedGraph::SafeDownCast(input)) { vtkDirectedGraph *g = vtkDirectedGraph::SafeDownCast(input); if (this->ReverseEdges) { #if BOOST_VERSION < 104100 // Boost 1.41.x vtkErrorMacro("ReverseEdges requires Boost 1.41.x or higher"); return 0; #else boost::reverse_graph<vtkDirectedGraph*> r(g); breadth_first_search(r, this->OriginVertexIndex, q, builder, color); #endif } else { breadth_first_search(g, this->OriginVertexIndex, q, builder, color); } } else { vtkUndirectedGraph *g = vtkUndirectedGraph::SafeDownCast(input); breadth_first_search(g, this->OriginVertexIndex, q, builder, color); } // If the user wants it, store the mapping back to graph vertices if (this->CreateGraphVertexIdArray) { treeToGraphIdMap->SetName("GraphVertexId"); temp->GetVertexData()->AddArray(treeToGraphIdMap); } // Copy the builder graph structure into the output tree vtkTree *output = vtkTree::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); if (!output->CheckedShallowCopy(temp)) { vtkErrorMacro(<<"Invalid tree."); return 0; } // Clean up output->Squeeze(); graphToTreeIdMap->Delete(); treeToGraphIdMap->Delete(); return 1; } void vtkBoostBreadthFirstSearchTree::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "OriginVertexIndex: " << this->OriginVertexIndex << endl; os << indent << "ArrayName: " << (this->ArrayName ? this->ArrayName : "(none)") << endl; os << indent << "OriginValue: " << this->OriginValue.ToString() << endl; os << indent << "ArrayNameSet: " << (this->ArrayNameSet ? "true" : "false") << endl; os << indent << "CreateGraphVertexIdArray: " << (this->CreateGraphVertexIdArray ? "on" : "off") << endl; os << indent << "ReverseEdges: " << (this->ReverseEdges ? "on" : "off") << endl; } <commit_msg>COMP: Added ifdefs for Boost versions<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkBoostBreadthFirstSearchTree.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #include "vtkBoostBreadthFirstSearchTree.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkMath.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkFloatArray.h" #include "vtkDataArray.h" #include "vtkSmartPointer.h" #include "vtkStringArray.h" #include "vtkBoostGraphAdapter.h" #include "vtkMutableDirectedGraph.h" #include "vtkUndirectedGraph.h" #include "vtkTree.h" #include <boost/graph/breadth_first_search.hpp> #include <boost/graph/reverse_graph.hpp> #include <boost/pending/queue.hpp> using namespace boost; vtkStandardNewMacro(vtkBoostBreadthFirstSearchTree); #if BOOST_VERSION >= 104800 // Boost 1.48.x namespace { vtkIdType unwrap_edge_id(vtkEdgeType const &e) { return e.Id; } vtkIdType unwrap_edge_id(boost::detail::reverse_graph_edge_descriptor<vtkEdgeType> const &e) { return e.underlying_desc.Id; } } #endif // Redefine the bfs visitor, the only visitor we // are using is the tree_edge visitor. template <typename IdMap> class bfs_tree_builder : public default_bfs_visitor { public: bfs_tree_builder() { } bfs_tree_builder(IdMap& g2t, IdMap& t2g, vtkGraph* g, vtkMutableDirectedGraph* t, vtkIdType root) : graph_to_tree(g2t), tree_to_graph(t2g), tree(t), graph(g) { double x[3]; graph->GetPoints()->GetPoint(root, x); tree->GetPoints()->InsertNextPoint(x); vtkIdType tree_root = t->AddVertex(); put(graph_to_tree, root, tree_root); put(tree_to_graph, tree_root, root); tree->GetVertexData()->CopyData(graph->GetVertexData(), root, tree_root); } template <typename Edge, typename Graph> void tree_edge(Edge e, const Graph& g) const { typename graph_traits<Graph>::vertex_descriptor u, v; u = source(e, g); v = target(e, g); // Get the source vertex id (it has already been visited). vtkIdType tree_u = get(graph_to_tree, u); // Add the point before the vertex so that // points match the number of vertices, so that GetPoints() // doesn't reallocate and zero-out points. double x[3]; graph->GetPoints()->GetPoint(v, x); tree->GetPoints()->InsertNextPoint(x); // Create the target vertex in the tree. vtkIdType tree_v = tree->AddVertex(); vtkEdgeType tree_e = tree->AddEdge(tree_u, tree_v); // Store the mapping from graph to tree. put(graph_to_tree, v, tree_v); put(tree_to_graph, tree_v, v); // Copy the vertex and edge data from the graph to the tree. tree->GetVertexData()->CopyData(graph->GetVertexData(), v, tree_v); #if BOOST_VERSION < 104800 // Boost 1.48.x tree->GetEdgeData()->CopyData(graph->GetEdgeData(), e.Id, tree_e.Id); #else tree->GetEdgeData()->CopyData(graph->GetEdgeData(), unwrap_edge_id(e), tree_e.Id); #endif } private: IdMap graph_to_tree; IdMap tree_to_graph; vtkMutableDirectedGraph *tree; vtkGraph *graph; }; // Constructor/Destructor vtkBoostBreadthFirstSearchTree::vtkBoostBreadthFirstSearchTree() { // Default values for the origin vertex this->OriginVertexIndex = 0; this->ArrayName = 0; this->SetArrayName("Not Set"); this->ArrayNameSet = false; this->OriginValue = 0; this->CreateGraphVertexIdArray = false; this->ReverseEdges = false; } vtkBoostBreadthFirstSearchTree::~vtkBoostBreadthFirstSearchTree() { this->SetArrayName(NULL); } // Description: // Set the index (into the vertex array) of the // breadth first search 'origin' vertex. void vtkBoostBreadthFirstSearchTree::SetOriginVertex(vtkIdType index) { this->OriginVertexIndex = index; this->ArrayNameSet = false; this->Modified(); } // Description: // Set the breadth first search 'origin' vertex. // This method is basically the same as above // but allows the application to simply specify // an array name and value, instead of having to // know the specific index of the vertex. void vtkBoostBreadthFirstSearchTree::SetOriginVertex( vtkStdString arrayName, vtkVariant value) { this->SetArrayName(arrayName); this->ArrayNameSet = true; this->OriginValue = value; this->Modified(); } vtkIdType vtkBoostBreadthFirstSearchTree::GetVertexIndex( vtkAbstractArray *abstract,vtkVariant value) { // Okay now what type of array is it if (abstract->IsNumeric()) { vtkDataArray *dataArray = vtkDataArray::SafeDownCast(abstract); int intValue = value.ToInt(); for(int i=0; i<dataArray->GetNumberOfTuples(); ++i) { if (intValue == static_cast<int>(dataArray->GetTuple1(i))) { return i; } } } else { vtkStringArray *stringArray = vtkStringArray::SafeDownCast(abstract); vtkStdString stringValue(value.ToString()); for(int i=0; i<stringArray->GetNumberOfTuples(); ++i) { if (stringValue == stringArray->GetValue(i)) { return i; } } } // Failed vtkErrorMacro("Did not find a valid vertex index..."); return 0; } int vtkBoostBreadthFirstSearchTree::FillInputPortInformation( int vtkNotUsed(port), vtkInformation* info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkGraph"); return 1; } int vtkBoostBreadthFirstSearchTree::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { // get the info objects vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); vtkInformation *outInfo = outputVector->GetInformationObject(0); // get the input and output vtkGraph *input = vtkGraph::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); // Now figure out the origin vertex of the // breadth first search if (this->ArrayNameSet) { vtkAbstractArray* abstract = input->GetVertexData()->GetAbstractArray(this->ArrayName); // Does the array exist at all? if (abstract == NULL) { vtkErrorMacro("Could not find array named " << this->ArrayName); return 0; } this->OriginVertexIndex = this->GetVertexIndex(abstract,this->OriginValue); } // Create tree to graph id map array vtkIdTypeArray* treeToGraphIdMap = vtkIdTypeArray::New(); // Create graph to tree id map array vtkIdTypeArray* graphToTreeIdMap = vtkIdTypeArray::New(); // Create a color map (used for marking visited nodes) vector_property_map<default_color_type> color; // Create a queue to hand off to the BFS queue<int> q; // Create the mutable graph to build the tree vtkSmartPointer<vtkMutableDirectedGraph> temp = vtkSmartPointer<vtkMutableDirectedGraph>::New(); // Initialize copying data into tree temp->GetFieldData()->PassData(input->GetFieldData()); temp->GetVertexData()->CopyAllocate(input->GetVertexData()); temp->GetEdgeData()->CopyAllocate(input->GetEdgeData()); // Create the visitor which will build the tree bfs_tree_builder<vtkIdTypeArray*> builder( graphToTreeIdMap, treeToGraphIdMap, input, temp, this->OriginVertexIndex); // Run the algorithm if (vtkDirectedGraph::SafeDownCast(input)) { vtkDirectedGraph *g = vtkDirectedGraph::SafeDownCast(input); if (this->ReverseEdges) { #if BOOST_VERSION < 104100 // Boost 1.41.x vtkErrorMacro("ReverseEdges requires Boost 1.41.x or higher"); return 0; #else boost::reverse_graph<vtkDirectedGraph*> r(g); breadth_first_search(r, this->OriginVertexIndex, q, builder, color); #endif } else { breadth_first_search(g, this->OriginVertexIndex, q, builder, color); } } else { vtkUndirectedGraph *g = vtkUndirectedGraph::SafeDownCast(input); breadth_first_search(g, this->OriginVertexIndex, q, builder, color); } // If the user wants it, store the mapping back to graph vertices if (this->CreateGraphVertexIdArray) { treeToGraphIdMap->SetName("GraphVertexId"); temp->GetVertexData()->AddArray(treeToGraphIdMap); } // Copy the builder graph structure into the output tree vtkTree *output = vtkTree::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); if (!output->CheckedShallowCopy(temp)) { vtkErrorMacro(<<"Invalid tree."); return 0; } // Clean up output->Squeeze(); graphToTreeIdMap->Delete(); treeToGraphIdMap->Delete(); return 1; } void vtkBoostBreadthFirstSearchTree::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "OriginVertexIndex: " << this->OriginVertexIndex << endl; os << indent << "ArrayName: " << (this->ArrayName ? this->ArrayName : "(none)") << endl; os << indent << "OriginValue: " << this->OriginValue.ToString() << endl; os << indent << "ArrayNameSet: " << (this->ArrayNameSet ? "true" : "false") << endl; os << indent << "CreateGraphVertexIdArray: " << (this->CreateGraphVertexIdArray ? "on" : "off") << endl; os << indent << "ReverseEdges: " << (this->ReverseEdges ? "on" : "off") << endl; } <|endoftext|>
<commit_before>// The MIT License (MIT) // Copyright (c) 2013-2016 Rapptz, ThePhD and contributors // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef SOL_RAII_HPP #define SOL_RAII_HPP #include <memory> #include "traits.hpp" namespace sol { namespace detail { struct default_construct { template<typename T, typename... Args> static void construct(T&& obj, Args&&... args) { std::allocator<meta::unqualified_t<T>> alloc{}; alloc.construct(obj, std::forward<Args>(args)...); } template<typename T, typename... Args> void operator()(T&& obj, Args&&... args) const { construct(std::forward<T>(obj), std::forward<Args>(args)...); } }; struct default_destruct { template<typename T> static void destroy(T&& obj) { std::allocator<meta::unqualified_t<T>> alloc{}; alloc.destroy(obj); } template<typename T> void operator()(T&& obj) const { destroy(std::forward<T>(obj)); } }; } // detail template <typename... Args> struct constructor_list {}; template<typename... Args> using constructors = constructor_list<Args...>; const auto default_constructor = constructors<types<>>{}; struct no_construction {}; const auto no_constructor = no_construction{}; struct call_construction {}; const auto call_constructor = call_construction{}; template <typename... Functions> struct constructor_wrapper { std::tuple<Functions...> set; template <typename... Args> constructor_wrapper(Args&&... args) : set(std::forward<Args>(args)...) {} }; template <typename... Functions> constructor_wrapper<Functions...> initializers(Functions&&... functions) { return constructor_wrapper<Functions...>(std::forward<Functions>(functions)...); } template <typename Function> struct destructor_wrapper { Function fx; template <typename... Args> destructor_wrapper(Args&&... args) : fx(std::forward<Args>(args)...) {} }; template <> struct destructor_wrapper<void> {}; const destructor_wrapper<void> default_destructor{}; template <typename Fx> inline destructor_wrapper<Fx> destructor(Fx&& fx) { return destructor_wrapper<Fx>(std::forward<Fx>(fx)); } } // sol #endif // SOL_RAII_HPP <commit_msg>Always unqualify / decay arguments<commit_after>// The MIT License (MIT) // Copyright (c) 2013-2016 Rapptz, ThePhD and contributors // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef SOL_RAII_HPP #define SOL_RAII_HPP #include <memory> #include "traits.hpp" namespace sol { namespace detail { struct default_construct { template<typename T, typename... Args> static void construct(T&& obj, Args&&... args) { std::allocator<meta::unqualified_t<T>> alloc{}; alloc.construct(obj, std::forward<Args>(args)...); } template<typename T, typename... Args> void operator()(T&& obj, Args&&... args) const { construct(std::forward<T>(obj), std::forward<Args>(args)...); } }; struct default_destruct { template<typename T> static void destroy(T&& obj) { std::allocator<meta::unqualified_t<T>> alloc{}; alloc.destroy(obj); } template<typename T> void operator()(T&& obj) const { destroy(std::forward<T>(obj)); } }; } // detail template <typename... Args> struct constructor_list {}; template<typename... Args> using constructors = constructor_list<Args...>; const auto default_constructor = constructors<types<>>{}; struct no_construction {}; const auto no_constructor = no_construction{}; struct call_construction {}; const auto call_constructor = call_construction{}; template <typename... Functions> struct constructor_wrapper { std::tuple<Functions...> set; template <typename... Args> constructor_wrapper(Args&&... args) : set(std::forward<Args>(args)...) {} }; template <typename... Functions> constructor_wrapper<Functions...> initializers(Functions&&... functions) { return constructor_wrapper<Functions...>(std::forward<Functions>(functions)...); } template <typename Function> struct destructor_wrapper { Function fx; template <typename... Args> destructor_wrapper(Args&&... args) : fx(std::forward<Args>(args)...) {} }; template <> struct destructor_wrapper<void> {}; const destructor_wrapper<void> default_destructor{}; template <typename Fx> inline destructor_wrapper<Fx> destructor(Fx&& fx) { return destructor_wrapper<std::decay_t<Fx>>(std::forward<Fx>(fx)); } } // sol #endif // SOL_RAII_HPP <|endoftext|>
<commit_before>//Convers centimeters to inches double cm2inches(double cm){ double c=0.3937; //for inches to centimeters c=2.54 return cm*c; } <commit_msg>Update cm2inches.cpp<commit_after>//Convers centimeters to inches double cm2inches(double cm){ return cm*0.3937; //for inches to centimeters c=2.54 } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkAreaPicker.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkAreaPicker.h" #include "vtkObjectFactory.h" #include "vtkMapper.h" #include "vtkAbstractVolumeMapper.h" #include "vtkAbstractMapper3D.h" #include "vtkProp.h" #include "vtkLODProp3D.h" #include "vtkActor.h" #include "vtkPropCollection.h" #include "vtkImageActor.h" #include "vtkProp3DCollection.h" #include "vtkAssemblyPath.h" #include "vtkImageData.h" #include "vtkVolume.h" #include "vtkRenderer.h" #include "vtkProperty.h" #include "vtkCommand.h" #include "vtkPlanes.h" #include "vtkPlane.h" #include "vtkPoints.h" #include "vtkExtractSelectedFrustum.h" vtkCxxRevisionMacro(vtkAreaPicker, "1.16"); vtkStandardNewMacro(vtkAreaPicker); //-------------------------------------------------------------------------- vtkAreaPicker::vtkAreaPicker() { this->FrustumExtractor = vtkExtractSelectedFrustum::New(); this->Frustum = this->FrustumExtractor->GetFrustum(); this->Frustum->Register(this); this->ClipPoints = this->FrustumExtractor->GetClipPoints(); this->ClipPoints->Register(this); this->Prop3Ds = vtkProp3DCollection::New(); this->Mapper = NULL; this->DataSet = NULL; this->X0 = 0.0; this->Y0 = 0.0; this->X1 = 0.0; this->Y1 = 0.0; } //-------------------------------------------------------------------------- vtkAreaPicker::~vtkAreaPicker() { this->Prop3Ds->Delete(); this->ClipPoints->Delete(); this->Frustum->Delete(); this->FrustumExtractor->Delete(); } //-------------------------------------------------------------------------- // Initialize the picking process. void vtkAreaPicker::Initialize() { this->vtkAbstractPropPicker::Initialize(); this->Prop3Ds->RemoveAllItems(); this->Mapper = NULL; } //-------------------------------------------------------------------------- void vtkAreaPicker::SetRenderer(vtkRenderer *renderer) { this->Renderer = renderer; } //-------------------------------------------------------------------------- void vtkAreaPicker::SetPickCoords(double x0, double y0, double x1, double y1) { this->X0 = x0; this->Y0 = y0; this->X1 = x1; this->Y1 = y1; } //-------------------------------------------------------------------------- int vtkAreaPicker::Pick() { return this->AreaPick(this->X0, this->Y0, this->X1, this->Y1, this->Renderer); } //-------------------------------------------------------------------------- // Does what this class is meant to do. int vtkAreaPicker::AreaPick(double x0, double y0, double x1, double y1, vtkRenderer *renderer) { this->Initialize(); this->X0 = x0; this->Y0 = y0; this->X1 = x1; this->Y1 = y1; if (renderer) { this->Renderer = renderer; } this->SelectionPoint[0] = (this->X0+this->X1)*0.5; this->SelectionPoint[1] = (this->Y0+this->Y1)*0.5; this->SelectionPoint[2] = 0.0; if ( this->Renderer == NULL ) { vtkErrorMacro(<<"Must specify renderer!"); return 0; } this->DefineFrustum(this->X0, this->Y0, this->X1, this->Y1, this->Renderer); return this->PickProps(this->Renderer); } //-------------------------------------------------------------------------- //Converts the given screen rectangle into a selection frustum. //Saves the results in ClipPoints and Frustum. void vtkAreaPicker::DefineFrustum(double x0, double y0, double x1, double y1, vtkRenderer *renderer) { this->X0 = (x0 < x1) ? x0 : x1; this->Y0 = (y0 < y1) ? y0 : y1; this->X1 = (x0 > x1) ? x0 : x1; this->Y1 = (y0 > y1) ? y0 : y1; if (this->X0 == this->X1) { this->X1 += 1.0; } if (this->Y0 == this->Y1) { this->Y1 += 1.0; } //compute world coordinates of the pick volume double verts[32]; renderer->SetDisplayPoint(this->X0, this->Y0, 0); renderer->DisplayToWorld(); renderer->GetWorldPoint(&verts[0]); renderer->SetDisplayPoint(this->X0, this->Y0, 1); renderer->DisplayToWorld(); renderer->GetWorldPoint(&verts[4]); renderer->SetDisplayPoint(this->X0, this->Y1, 0); renderer->DisplayToWorld(); renderer->GetWorldPoint(&verts[8]); renderer->SetDisplayPoint(this->X0, this->Y1, 1); renderer->DisplayToWorld(); renderer->GetWorldPoint(&verts[12]); renderer->SetDisplayPoint(this->X1, this->Y0, 0); renderer->DisplayToWorld(); renderer->GetWorldPoint(&verts[16]); renderer->SetDisplayPoint(this->X1, this->Y0, 1); renderer->DisplayToWorld(); renderer->GetWorldPoint(&verts[20]); renderer->SetDisplayPoint(this->X1, this->Y1, 0); renderer->DisplayToWorld(); renderer->GetWorldPoint(&verts[24]); renderer->SetDisplayPoint(this->X1, this->Y1, 1); renderer->DisplayToWorld(); renderer->GetWorldPoint(&verts[28]); //a pick point is required by vtkAbstractPicker //return center for now until a better meaning is desired double sum[3] = {0.0,0.0,0.0}; for (int i = 0; i < 8; i++) { sum[0] += verts[i*3+0]; sum[1] += verts[i*3+1]; sum[2] += verts[i*3+2]; } this->PickPosition[0] = sum[0]/8.0; this->PickPosition[1] = sum[1]/8.0; this->PickPosition[2] = sum[2]/8.0; this->FrustumExtractor->CreateFrustum(verts); } //-------------------------------------------------------------------------- //Decides which props are within the frustum. //Adds each to the prop3d list and fires pick events. //Remembers the dataset, mapper, and assembly path for the nearest. int vtkAreaPicker::PickProps(vtkRenderer *renderer) { vtkProp *prop; int picked=0; int pickable; double bounds[6]; // Initialize picking process this->Initialize(); this->Renderer = renderer; // Invoke start pick method if defined this->InvokeEvent(vtkCommand::StartPickEvent,NULL); if ( renderer == NULL ) { vtkErrorMacro(<<"Must specify renderer!"); return 0; } // Loop over all props. // vtkPropCollection *props; vtkProp *propCandidate; if ( this->PickFromList ) { props = this->GetPickList(); } else { props = renderer->GetViewProps(); } vtkImageActor *imageActor = NULL; vtkAbstractMapper3D *mapper = NULL; vtkAssemblyPath *path; double mindist = VTK_DOUBLE_MAX; vtkCollectionSimpleIterator pit; for ( props->InitTraversal(pit); (prop=props->GetNextProp(pit)); ) { for ( prop->InitPathTraversal(); (path=prop->GetNextPath()); ) { propCandidate = path->GetLastNode()->GetViewProp(); pickable = this->TypeDecipher(propCandidate, &imageActor, &mapper); // If actor can be picked, see if it is within the pick frustum. if ( pickable ) { if ( mapper ) { mapper->GetBounds(bounds); double dist; //cerr << "mapper ABFISECT" << endl; if (this->ABoxFrustumIsect(bounds, dist)) { picked = 1; if ( ! this->Prop3Ds->IsItemPresent(prop) ) { this->Prop3Ds->AddItem(static_cast<vtkProp3D *>(prop)); //cerr << "picked a mapper" << endl; if (dist < mindist) //new nearest, remember it { mindist = dist; this->SetPath(path); this->Mapper = mapper; vtkMapper *map1; vtkAbstractVolumeMapper *vmap; if ( (map1=vtkMapper::SafeDownCast(mapper)) != NULL ) { this->DataSet = map1->GetInput(); this->Mapper = map1; } else if ( (vmap=vtkAbstractVolumeMapper::SafeDownCast(mapper)) != NULL ) { this->DataSet = vmap->GetDataSetInput(); this->Mapper = vmap; } else { this->DataSet = NULL; } } static_cast<vtkProp3D *>(propCandidate)->Pick(); this->InvokeEvent(vtkCommand::PickEvent,NULL); } } }//mapper else if ( imageActor ) { imageActor->GetBounds(bounds); double dist; //cerr << "imageA ABFISECT" << endl; if (this->ABoxFrustumIsect(bounds, dist)) { picked = 1; if ( ! this->Prop3Ds->IsItemPresent(prop) ) { this->Prop3Ds->AddItem(imageActor); //cerr << "picked an imageactor" << endl; if (dist < mindist) //new nearest, remember it { mindist = dist; this->SetPath(path); this->Mapper = mapper; // mapper is null this->DataSet = imageActor->GetInput(); } imageActor->Pick(); this->InvokeEvent(vtkCommand::PickEvent,NULL); } } }//imageActor }//pickable }//for all parts }//for all props // Invoke end pick method if defined this->InvokeEvent(vtkCommand::EndPickEvent,NULL); return picked; } //------------------------------------------------------------------------------ //converts the propCandidate into either a vtkImageActor or a //vtkAbstractMapper3D and returns its pickability int vtkAreaPicker::TypeDecipher(vtkProp *propCandidate, vtkImageActor **imageActor, vtkAbstractMapper3D **mapper) { int pickable = 0; *imageActor = NULL; *mapper = NULL; vtkActor *actor; vtkLODProp3D *prop3D; vtkProperty *tempProperty; vtkVolume *volume; if ( propCandidate->GetPickable() && propCandidate->GetVisibility() ) { pickable = 1; if ( (actor=vtkActor::SafeDownCast(propCandidate)) != NULL ) { *mapper = actor->GetMapper(); if ( actor->GetProperty()->GetOpacity() <= 0.0 ) { pickable = 0; } } else if ( (prop3D=vtkLODProp3D::SafeDownCast(propCandidate)) != NULL ) { int LODId = prop3D->GetPickLODID(); *mapper = prop3D->GetLODMapper(LODId); if ( vtkMapper::SafeDownCast(*mapper) != NULL) { prop3D->GetLODProperty(LODId, &tempProperty); if ( tempProperty->GetOpacity() <= 0.0 ) { pickable = 0; } } } else if ( (volume=vtkVolume::SafeDownCast(propCandidate)) != NULL ) { *mapper = volume->GetMapper(); } else if ( (*imageActor=vtkImageActor::SafeDownCast(propCandidate)) ) { *mapper = 0; } else { pickable = 0; //only vtkProp3D's (actors and volumes) can be picked } } return pickable; } //-------------------------------------------------------------------------- //Intersect the bbox represented by the bounds with the clipping frustum. //Return true if partially inside. //Also return a distance to the near plane. int vtkAreaPicker::ABoxFrustumIsect(double *bounds, double &mindist) { if (bounds[0] > bounds[1] || bounds[2] > bounds[3] || bounds[4] > bounds[5]) { return 0; } double verts[8][3]; int x, y, z; int vid = 0; for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { for (z = 0; z < 2; z++) { verts[vid][0] = bounds[0+x]; verts[vid][1] = bounds[2+y]; verts[vid][2] = bounds[4+z]; vid++; } } } //find distance to the corner nearest the near plane for 'closest' prop mindist = -VTK_DOUBLE_MAX; vtkPlane *plane = this->Frustum->GetPlane(4); //near plane for (vid = 0; vid < 8; vid++) { double dist = plane->EvaluateFunction(verts[vid]); if (dist < 0 && dist > mindist) { mindist = dist; } } mindist = -mindist; //leave the intersection test to the frustum extractor class return this->FrustumExtractor->OverallBoundsTest(bounds); } //-------------------------------------------------------------------------- void vtkAreaPicker::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Frustum: " << this->Frustum << "\n"; os << indent << "ClipPoints: " << this->ClipPoints << "\n"; os << indent << "Mapper: " << this->Mapper << "\n"; os << indent << "DataSet: " << this->DataSet << "\n"; } <commit_msg>STYLE: remove whitespace to trigger dashboard.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkAreaPicker.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkAreaPicker.h" #include "vtkObjectFactory.h" #include "vtkMapper.h" #include "vtkAbstractVolumeMapper.h" #include "vtkAbstractMapper3D.h" #include "vtkProp.h" #include "vtkLODProp3D.h" #include "vtkActor.h" #include "vtkPropCollection.h" #include "vtkImageActor.h" #include "vtkProp3DCollection.h" #include "vtkAssemblyPath.h" #include "vtkImageData.h" #include "vtkVolume.h" #include "vtkRenderer.h" #include "vtkProperty.h" #include "vtkCommand.h" #include "vtkPlanes.h" #include "vtkPlane.h" #include "vtkPoints.h" #include "vtkExtractSelectedFrustum.h" vtkCxxRevisionMacro(vtkAreaPicker, "1.17"); vtkStandardNewMacro(vtkAreaPicker); //-------------------------------------------------------------------------- vtkAreaPicker::vtkAreaPicker() { this->FrustumExtractor = vtkExtractSelectedFrustum::New(); this->Frustum = this->FrustumExtractor->GetFrustum(); this->Frustum->Register(this); this->ClipPoints = this->FrustumExtractor->GetClipPoints(); this->ClipPoints->Register(this); this->Prop3Ds = vtkProp3DCollection::New(); this->Mapper = NULL; this->DataSet = NULL; this->X0 = 0.0; this->Y0 = 0.0; this->X1 = 0.0; this->Y1 = 0.0; } //-------------------------------------------------------------------------- vtkAreaPicker::~vtkAreaPicker() { this->Prop3Ds->Delete(); this->ClipPoints->Delete(); this->Frustum->Delete(); this->FrustumExtractor->Delete(); } //-------------------------------------------------------------------------- // Initialize the picking process. void vtkAreaPicker::Initialize() { this->vtkAbstractPropPicker::Initialize(); this->Prop3Ds->RemoveAllItems(); this->Mapper = NULL; } //-------------------------------------------------------------------------- void vtkAreaPicker::SetRenderer(vtkRenderer *renderer) { this->Renderer = renderer; } //-------------------------------------------------------------------------- void vtkAreaPicker::SetPickCoords(double x0, double y0, double x1, double y1) { this->X0 = x0; this->Y0 = y0; this->X1 = x1; this->Y1 = y1; } //-------------------------------------------------------------------------- int vtkAreaPicker::Pick() { return this->AreaPick(this->X0, this->Y0, this->X1, this->Y1, this->Renderer); } //-------------------------------------------------------------------------- // Does what this class is meant to do. int vtkAreaPicker::AreaPick(double x0, double y0, double x1, double y1, vtkRenderer *renderer) { this->Initialize(); this->X0 = x0; this->Y0 = y0; this->X1 = x1; this->Y1 = y1; if (renderer) { this->Renderer = renderer; } this->SelectionPoint[0] = (this->X0+this->X1)*0.5; this->SelectionPoint[1] = (this->Y0+this->Y1)*0.5; this->SelectionPoint[2] = 0.0; if ( this->Renderer == NULL ) { vtkErrorMacro(<<"Must specify renderer!"); return 0; } this->DefineFrustum(this->X0, this->Y0, this->X1, this->Y1, this->Renderer); return this->PickProps(this->Renderer); } //-------------------------------------------------------------------------- //Converts the given screen rectangle into a selection frustum. //Saves the results in ClipPoints and Frustum. void vtkAreaPicker::DefineFrustum(double x0, double y0, double x1, double y1, vtkRenderer *renderer) { this->X0 = (x0 < x1) ? x0 : x1; this->Y0 = (y0 < y1) ? y0 : y1; this->X1 = (x0 > x1) ? x0 : x1; this->Y1 = (y0 > y1) ? y0 : y1; if (this->X0 == this->X1) { this->X1 += 1.0; } if (this->Y0 == this->Y1) { this->Y1 += 1.0; } //compute world coordinates of the pick volume double verts[32]; renderer->SetDisplayPoint(this->X0, this->Y0, 0); renderer->DisplayToWorld(); renderer->GetWorldPoint(&verts[0]); renderer->SetDisplayPoint(this->X0, this->Y0, 1); renderer->DisplayToWorld(); renderer->GetWorldPoint(&verts[4]); renderer->SetDisplayPoint(this->X0, this->Y1, 0); renderer->DisplayToWorld(); renderer->GetWorldPoint(&verts[8]); renderer->SetDisplayPoint(this->X0, this->Y1, 1); renderer->DisplayToWorld(); renderer->GetWorldPoint(&verts[12]); renderer->SetDisplayPoint(this->X1, this->Y0, 0); renderer->DisplayToWorld(); renderer->GetWorldPoint(&verts[16]); renderer->SetDisplayPoint(this->X1, this->Y0, 1); renderer->DisplayToWorld(); renderer->GetWorldPoint(&verts[20]); renderer->SetDisplayPoint(this->X1, this->Y1, 0); renderer->DisplayToWorld(); renderer->GetWorldPoint(&verts[24]); renderer->SetDisplayPoint(this->X1, this->Y1, 1); renderer->DisplayToWorld(); renderer->GetWorldPoint(&verts[28]); //a pick point is required by vtkAbstractPicker //return center for now until a better meaning is desired double sum[3] = {0.0,0.0,0.0}; for (int i = 0; i < 8; i++) { sum[0] += verts[i*3+0]; sum[1] += verts[i*3+1]; sum[2] += verts[i*3+2]; } this->PickPosition[0] = sum[0]/8.0; this->PickPosition[1] = sum[1]/8.0; this->PickPosition[2] = sum[2]/8.0; this->FrustumExtractor->CreateFrustum(verts); } //-------------------------------------------------------------------------- //Decides which props are within the frustum. //Adds each to the prop3d list and fires pick events. //Remembers the dataset, mapper, and assembly path for the nearest. int vtkAreaPicker::PickProps(vtkRenderer *renderer) { vtkProp *prop; int picked=0; int pickable; double bounds[6]; // Initialize picking process this->Initialize(); this->Renderer = renderer; // Invoke start pick method if defined this->InvokeEvent(vtkCommand::StartPickEvent,NULL); if ( renderer == NULL ) { vtkErrorMacro(<<"Must specify renderer!"); return 0; } // Loop over all props. // vtkPropCollection *props; vtkProp *propCandidate; if ( this->PickFromList ) { props = this->GetPickList(); } else { props = renderer->GetViewProps(); } vtkImageActor *imageActor = NULL; vtkAbstractMapper3D *mapper = NULL; vtkAssemblyPath *path; double mindist = VTK_DOUBLE_MAX; vtkCollectionSimpleIterator pit; for ( props->InitTraversal(pit); (prop=props->GetNextProp(pit)); ) { for ( prop->InitPathTraversal(); (path=prop->GetNextPath()); ) { propCandidate = path->GetLastNode()->GetViewProp(); pickable = this->TypeDecipher(propCandidate, &imageActor, &mapper); // If actor can be picked, see if it is within the pick frustum. if ( pickable ) { if ( mapper ) { mapper->GetBounds(bounds); double dist; //cerr << "mapper ABFISECT" << endl; if (this->ABoxFrustumIsect(bounds, dist)) { picked = 1; if ( ! this->Prop3Ds->IsItemPresent(prop) ) { this->Prop3Ds->AddItem(static_cast<vtkProp3D *>(prop)); //cerr << "picked a mapper" << endl; if (dist < mindist) //new nearest, remember it { mindist = dist; this->SetPath(path); this->Mapper = mapper; vtkMapper *map1; vtkAbstractVolumeMapper *vmap; if ( (map1=vtkMapper::SafeDownCast(mapper)) != NULL ) { this->DataSet = map1->GetInput(); this->Mapper = map1; } else if ( (vmap=vtkAbstractVolumeMapper::SafeDownCast(mapper)) != NULL ) { this->DataSet = vmap->GetDataSetInput(); this->Mapper = vmap; } else { this->DataSet = NULL; } } static_cast<vtkProp3D *>(propCandidate)->Pick(); this->InvokeEvent(vtkCommand::PickEvent,NULL); } } }//mapper else if ( imageActor ) { imageActor->GetBounds(bounds); double dist; //cerr << "imageA ABFISECT" << endl; if (this->ABoxFrustumIsect(bounds, dist)) { picked = 1; if ( ! this->Prop3Ds->IsItemPresent(prop) ) { this->Prop3Ds->AddItem(imageActor); //cerr << "picked an imageactor" << endl; if (dist < mindist) //new nearest, remember it { mindist = dist; this->SetPath(path); this->Mapper = mapper; // mapper is null this->DataSet = imageActor->GetInput(); } imageActor->Pick(); this->InvokeEvent(vtkCommand::PickEvent,NULL); } } }//imageActor }//pickable }//for all parts }//for all props // Invoke end pick method if defined this->InvokeEvent(vtkCommand::EndPickEvent,NULL); return picked; } //------------------------------------------------------------------------------ //converts the propCandidate into either a vtkImageActor or a //vtkAbstractMapper3D and returns its pickability int vtkAreaPicker::TypeDecipher(vtkProp *propCandidate, vtkImageActor **imageActor, vtkAbstractMapper3D **mapper) { int pickable = 0; *imageActor = NULL; *mapper = NULL; vtkActor *actor; vtkLODProp3D *prop3D; vtkProperty *tempProperty; vtkVolume *volume; if ( propCandidate->GetPickable() && propCandidate->GetVisibility() ) { pickable = 1; if ( (actor=vtkActor::SafeDownCast(propCandidate)) != NULL ) { *mapper = actor->GetMapper(); if ( actor->GetProperty()->GetOpacity() <= 0.0 ) { pickable = 0; } } else if ( (prop3D=vtkLODProp3D::SafeDownCast(propCandidate)) != NULL ) { int LODId = prop3D->GetPickLODID(); *mapper = prop3D->GetLODMapper(LODId); if ( vtkMapper::SafeDownCast(*mapper) != NULL) { prop3D->GetLODProperty(LODId, &tempProperty); if ( tempProperty->GetOpacity() <= 0.0 ) { pickable = 0; } } } else if ( (volume=vtkVolume::SafeDownCast(propCandidate)) != NULL ) { *mapper = volume->GetMapper(); } else if ( (*imageActor=vtkImageActor::SafeDownCast(propCandidate)) ) { *mapper = 0; } else { pickable = 0; //only vtkProp3D's (actors and volumes) can be picked } } return pickable; } //-------------------------------------------------------------------------- //Intersect the bbox represented by the bounds with the clipping frustum. //Return true if partially inside. //Also return a distance to the near plane. int vtkAreaPicker::ABoxFrustumIsect(double *bounds, double &mindist) { if (bounds[0] > bounds[1] || bounds[2] > bounds[3] || bounds[4] > bounds[5]) { return 0; } double verts[8][3]; int x, y, z; int vid = 0; for (x = 0; x < 2; x++) { for (y = 0; y < 2; y++) { for (z = 0; z < 2; z++) { verts[vid][0] = bounds[0+x]; verts[vid][1] = bounds[2+y]; verts[vid][2] = bounds[4+z]; vid++; } } } //find distance to the corner nearest the near plane for 'closest' prop mindist = -VTK_DOUBLE_MAX; vtkPlane *plane = this->Frustum->GetPlane(4); //near plane for (vid = 0; vid < 8; vid++) { double dist = plane->EvaluateFunction(verts[vid]); if (dist < 0 && dist > mindist) { mindist = dist; } } mindist = -mindist; //leave the intersection test to the frustum extractor class return this->FrustumExtractor->OverallBoundsTest(bounds); } //-------------------------------------------------------------------------- void vtkAreaPicker::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Frustum: " << this->Frustum << "\n"; os << indent << "ClipPoints: " << this->ClipPoints << "\n"; os << indent << "Mapper: " << this->Mapper << "\n"; os << indent << "DataSet: " << this->DataSet << "\n"; } <|endoftext|>
<commit_before>/* * Copyright © 2011 Stéphane Raimbault <stephane.raimbault@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser 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 Lesser Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This library implements the Modbus protocol. * http://libmodbus.org/ */ #include <inttypes.h> #include "WProgram.h" #include "Modbusino.h" #define _MODBUS_RTU_HEADER_LENGTH 1 #define _MODBUS_RTU_PRESET_REQ_LENGTH 6 #define _MODBUS_RTU_PRESET_RSP_LENGTH 2 #define _MODBUS_RTU_CHECKSUM_LENGTH 2 #define _MODBUSINO_RTU_MAX_ADU_LENGTH 128 /* Supported function codes */ #define _FC_READ_HOLDING_REGISTERS 0x03 #define _FC_WRITE_MULTIPLE_REGISTERS 0x10 enum { _STEP_FUNCTION = 0x01, _STEP_META, _STEP_DATA }; static uint16_t crc16(uint8_t *req, int req_length) { int j; uint16_t crc; crc = 0xFFFF; while (req_length--) { crc = crc ^ *req++; for (j=0; j < 8; j++) { if (crc & 0x0001) crc = (crc >> 1) ^ 0xA001; else crc = crc >> 1; } } return (crc << 8 | crc >> 8); } ModbusinoSlave::ModbusinoSlave(uint8_t slave) { _slave = slave; } void ModbusinoSlave::setup(long baud) { Serial.begin(baud); } static int check_integrity(uint8_t *msg, const int msg_length) { uint16_t crc_calculated; uint16_t crc_received; crc_calculated = crc16(msg, msg_length - 2); crc_received = (msg[msg_length - 2] << 8) | msg[msg_length - 1]; /* Check CRC of msg */ if (crc_calculated == crc_received) { return msg_length; } else { return -1; } } static int build_response_basis(int slave, int function, uint8_t* rsp) { rsp[0] = slave; rsp[1] = function; return _MODBUS_RTU_PRESET_RSP_LENGTH; } static int send_msg(uint8_t *msg, int msg_length) { uint16_t crc = crc16(msg, msg_length); msg[msg_length++] = crc >> 8; msg[msg_length++] = crc & 0x00FF; Serial.write(msg, msg_length); } static int response_exception(int slave, int function, int exception_code, uint8_t *rsp) { int rsp_length; function = function + 0x80; rsp_length = build_response_basis(slave, function, rsp); /* Positive exception code */ rsp[rsp_length++] = exception_code; return rsp_length; } static int receive(uint8_t *req) { int length_to_read; int req_index; int step; int function; /* We need to analyse the message step by step. At the first step, we want * to reach the function code because all packets contain this * information. */ step = _STEP_FUNCTION; length_to_read = _MODBUS_RTU_HEADER_LENGTH + 1; req_index = 0; while (length_to_read != 0) { /* The timeout is defined to ~10 ms between each bytes. Precision is not that important so I rather to avoid millis() to apply the KISS principle (millis overflows after 50 days, etc) */ if (!Serial.available()) { int i = 0; while (!Serial.available()) { delay(1); if (++i == 10) { /* Too late, bye */ return -1; } } } req[req_index] = Serial.read(); /* Moves the pointer to receive other data */ req_index++; /* Computes remaining bytes */ length_to_read--; if (length_to_read == 0) { switch (step) { case _STEP_FUNCTION: /* Function code position */ function = req[_MODBUS_RTU_HEADER_LENGTH]; if (function == _FC_READ_HOLDING_REGISTERS) { length_to_read = 4; } else if (function == _FC_WRITE_MULTIPLE_REGISTERS) { length_to_read = 5; } else { /* _errno = MODBUS_EXCEPTION_ILLEGAL_FUNCTION */ return -1; } step = _STEP_META; break; case _STEP_META: length_to_read = _MODBUS_RTU_CHECKSUM_LENGTH; if (function == _FC_WRITE_MULTIPLE_REGISTERS) length_to_read += req[_MODBUS_RTU_HEADER_LENGTH + 5]; if ((req_index + length_to_read) > _MODBUSINO_RTU_MAX_ADU_LENGTH) { /* _errno = MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE */ return -1; } step = _STEP_DATA; break; default: break; } } } return check_integrity(req, req_index); } static int reply(uint16_t *tab_reg, uint8_t nb_reg, uint8_t *req, int req_length) { int offset = _MODBUS_RTU_HEADER_LENGTH; int slave = req[offset - 1]; int function = req[offset]; uint16_t address = (req[offset + 1] << 8) + req[offset + 2]; uint8_t rsp[_MODBUSINO_RTU_MAX_ADU_LENGTH]; int rsp_length = 0; /* FIXME No filtering */ req_length -= _MODBUS_RTU_CHECKSUM_LENGTH; switch (function) { case _FC_READ_HOLDING_REGISTERS: { int nb = (req[offset + 3] << 8) + req[offset + 4]; if (address + nb > nb_reg) { rsp_length = response_exception( slave, function, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp); } else { int i; rsp_length = build_response_basis(slave, function, rsp); rsp[rsp_length++] = nb << 1; for (i = address; i < address + nb; i++) { rsp[rsp_length++] = tab_reg[i] >> 8; rsp[rsp_length++] = tab_reg[i] & 0xFF; } } } break; case _FC_WRITE_MULTIPLE_REGISTERS: { int nb = (req[offset + 3] << 8) + req[offset + 4]; if ((address + nb) > nb_reg) { rsp_length = response_exception( slave, function, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp); } else { int i, j; for (i = address, j = 6; i < address + nb; i++, j += 2) { /* 6 and 7 = first value */ tab_reg[i] = (req[offset + j] << 8) + req[offset + j + 1]; } rsp_length = build_response_basis(slave, function, rsp); /* 4 to copy the address (2) and the no. of registers */ memcpy(rsp + rsp_length, req + rsp_length, 4); rsp_length += 4; } } break; } return send_msg(rsp, rsp_length); } int ModbusinoSlave::loop(uint16_t* tab_reg, uint8_t nb_reg) { int rc; uint8_t req[_MODBUSINO_RTU_MAX_ADU_LENGTH]; if (Serial.available()) { rc = receive(req); if (rc > 0) { reply(tab_reg, nb_reg, req, rc); } } return rc; } <commit_msg>Replace offset variable by constants<commit_after>/* * Copyright © 2011 Stéphane Raimbault <stephane.raimbault@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser 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 Lesser Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This library implements the Modbus protocol. * http://libmodbus.org/ */ #include <inttypes.h> #include "WProgram.h" #include "Modbusino.h" #define _MODBUS_RTU_SLAVE 0 #define _MODBUS_RTU_FUNCTION 1 #define _MODBUS_RTU_PRESET_REQ_LENGTH 6 #define _MODBUS_RTU_PRESET_RSP_LENGTH 2 #define _MODBUS_RTU_CHECKSUM_LENGTH 2 #define _MODBUSINO_RTU_MAX_ADU_LENGTH 128 /* Supported function codes */ #define _FC_READ_HOLDING_REGISTERS 0x03 #define _FC_WRITE_MULTIPLE_REGISTERS 0x10 enum { _STEP_FUNCTION = 0x01, _STEP_META, _STEP_DATA }; static uint16_t crc16(uint8_t *req, int req_length) { int j; uint16_t crc; crc = 0xFFFF; while (req_length--) { crc = crc ^ *req++; for (j=0; j < 8; j++) { if (crc & 0x0001) crc = (crc >> 1) ^ 0xA001; else crc = crc >> 1; } } return (crc << 8 | crc >> 8); } ModbusinoSlave::ModbusinoSlave(uint8_t slave) { _slave = slave; } void ModbusinoSlave::setup(long baud) { Serial.begin(baud); } static int check_integrity(uint8_t *msg, const int msg_length) { uint16_t crc_calculated; uint16_t crc_received; crc_calculated = crc16(msg, msg_length - 2); crc_received = (msg[msg_length - 2] << 8) | msg[msg_length - 1]; /* Check CRC of msg */ if (crc_calculated == crc_received) { return msg_length; } else { return -1; } } static int build_response_basis(int slave, int function, uint8_t* rsp) { rsp[0] = slave; rsp[1] = function; return _MODBUS_RTU_PRESET_RSP_LENGTH; } static int send_msg(uint8_t *msg, int msg_length) { uint16_t crc = crc16(msg, msg_length); msg[msg_length++] = crc >> 8; msg[msg_length++] = crc & 0x00FF; Serial.write(msg, msg_length); } static int response_exception(int slave, int function, int exception_code, uint8_t *rsp) { int rsp_length; rsp_length = build_response_basis(slave, function + 0x80, rsp); /* Positive exception code */ rsp[rsp_length++] = exception_code; return rsp_length; } static int receive(uint8_t *req) { int length_to_read; int req_index; int step; int function; /* We need to analyse the message step by step. At the first step, we want * to reach the function code because all packets contain this * information. */ step = _STEP_FUNCTION; length_to_read = _MODBUS_RTU_FUNCTION + 1; req_index = 0; while (length_to_read != 0) { /* The timeout is defined to ~10 ms between each bytes. Precision is not that important so I rather to avoid millis() to apply the KISS principle (millis overflows after 50 days, etc) */ if (!Serial.available()) { int i = 0; while (!Serial.available()) { delay(1); if (++i == 10) { /* Too late, bye */ return -1; } } } req[req_index] = Serial.read(); /* Moves the pointer to receive other data */ req_index++; /* Computes remaining bytes */ length_to_read--; if (length_to_read == 0) { switch (step) { case _STEP_FUNCTION: /* Function code position */ function = req[_MODBUS_RTU_FUNCTION]; if (function == _FC_READ_HOLDING_REGISTERS) { length_to_read = 4; } else if (function == _FC_WRITE_MULTIPLE_REGISTERS) { length_to_read = 5; } else { /* _errno = MODBUS_EXCEPTION_ILLEGAL_FUNCTION */ return -1; } step = _STEP_META; break; case _STEP_META: length_to_read = _MODBUS_RTU_CHECKSUM_LENGTH; if (function == _FC_WRITE_MULTIPLE_REGISTERS) length_to_read += req[_MODBUS_RTU_FUNCTION + 5]; if ((req_index + length_to_read) > _MODBUSINO_RTU_MAX_ADU_LENGTH) { /* _errno = MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE */ return -1; } step = _STEP_DATA; break; default: break; } } } return check_integrity(req, req_index); } static int reply(uint16_t *tab_reg, uint8_t nb_reg, uint8_t *req, int req_length) { int slave = req[_MODBUS_RTU_SLAVE]; int function = req[_MODBUS_RTU_FUNCTION]; uint16_t address = (req[_MODBUS_RTU_FUNCTION + 1] << 8) + req[_MODBUS_RTU_FUNCTION + 2]; uint8_t rsp[_MODBUSINO_RTU_MAX_ADU_LENGTH]; int rsp_length = 0; /* FIXME No filtering */ req_length -= _MODBUS_RTU_CHECKSUM_LENGTH; switch (function) { case _FC_READ_HOLDING_REGISTERS: { int nb = (req[_MODBUS_RTU_FUNCTION + 3] << 8) + req[_MODBUS_RTU_FUNCTION + 4]; if (address + nb > nb_reg) { rsp_length = response_exception( slave, function, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp); } else { int i; rsp_length = build_response_basis(slave, function, rsp); rsp[rsp_length++] = nb << 1; for (i = address; i < address + nb; i++) { rsp[rsp_length++] = tab_reg[i] >> 8; rsp[rsp_length++] = tab_reg[i] & 0xFF; } } } break; case _FC_WRITE_MULTIPLE_REGISTERS: { int nb = (req[_MODBUS_RTU_FUNCTION + 3] << 8) + req[_MODBUS_RTU_FUNCTION + 4]; if ((address + nb) > nb_reg) { rsp_length = response_exception( slave, function, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp); } else { int i, j; for (i = address, j = 6; i < address + nb; i++, j += 2) { /* 6 and 7 = first value */ tab_reg[i] = (req[_MODBUS_RTU_FUNCTION + j] << 8) + req[_MODBUS_RTU_FUNCTION + j + 1]; } rsp_length = build_response_basis(slave, function, rsp); /* 4 to copy the address (2) and the no. of registers */ memcpy(rsp + rsp_length, req + rsp_length, 4); rsp_length += 4; } } break; } return send_msg(rsp, rsp_length); } int ModbusinoSlave::loop(uint16_t* tab_reg, uint8_t nb_reg) { int rc; uint8_t req[_MODBUSINO_RTU_MAX_ADU_LENGTH]; if (Serial.available()) { rc = receive(req); if (rc > 0) { reply(tab_reg, nb_reg, req, rc); } } return rc; } <|endoftext|>
<commit_before> #include "ImwPlatformWindow.h" #include "ImwWindowManager.h" #include <imgui/imgui.h> #include <imgui/imgui_internal.h> using namespace ImWindow; ImwPlatformWindow::ImwPlatformWindow(bool bMain, bool bIsDragWindow) { m_bMain = bMain; m_bIsDragWindow = bIsDragWindow; m_pContainer = new ImwContainer(NULL); m_pState = NULL; m_pPreviousState = NULL; void* pTemp = ImGui::GetInternalState(); m_pState = ImwMalloc(ImGui::GetInternalStateSize()); memcpy(m_pState, ImGui::GetInternalState(), ImGui::GetInternalStateSize()); ImGui::SetInternalState(m_pState); //ImGui::SetInternalState(m_pState, true); ImGui::SetInternalState(pTemp); } ImwPlatformWindow::~ImwPlatformWindow() { ImwSafeDelete(m_pContainer); ImwSafeDelete(m_pState); } void ImwPlatformWindow::OnClose() { ImwWindowManager::GetInstance()->OnClosePlatformWindow(this); delete this; } void ImwPlatformWindow::SetState() { m_pPreviousState = ImGui::GetInternalState(); ImGui::SetInternalState(m_pState); } void ImwPlatformWindow::RestoreState() { ImGui::SetInternalState(m_pPreviousState); } void ImwPlatformWindow::Paint() { ImwWindowManager::GetInstance()->Paint(this); } bool ImwPlatformWindow::IsMain() { return m_bMain; } void ImwPlatformWindow::Dock(ImwWindow* pWindow) { m_pContainer->Dock(pWindow); } bool ImwPlatformWindow::UnDock(ImwWindow* pWindow) { return m_pContainer->UnDock(pWindow); } ImwContainer* ImwPlatformWindow::GetContainer() { return m_pContainer; } ImwContainer* ImwPlatformWindow::HasWindow(ImwWindow* pWindow) { return m_pContainer->HasWindow(pWindow); } void ImwPlatformWindow::PaintContainer() { m_pContainer->Paint(); } <commit_msg>Copy ImGuiStyle on SetState and RestoreState<commit_after> #include "ImwPlatformWindow.h" #include "ImwWindowManager.h" #include <imgui/imgui.h> #include <imgui/imgui_internal.h> using namespace ImWindow; ImwPlatformWindow::ImwPlatformWindow(bool bMain, bool bIsDragWindow) { m_bMain = bMain; m_bIsDragWindow = bIsDragWindow; m_pContainer = new ImwContainer(NULL); m_pState = NULL; m_pPreviousState = NULL; void* pTemp = ImGui::GetInternalState(); m_pState = ImwMalloc(ImGui::GetInternalStateSize()); memcpy(m_pState, ImGui::GetInternalState(), ImGui::GetInternalStateSize()); ImGui::SetInternalState(m_pState); //ImGui::SetInternalState(m_pState, true); ImGui::SetInternalState(pTemp); } ImwPlatformWindow::~ImwPlatformWindow() { ImwSafeDelete(m_pContainer); ImwSafeDelete(m_pState); } void ImwPlatformWindow::OnClose() { ImwWindowManager::GetInstance()->OnClosePlatformWindow(this); delete this; } void ImwPlatformWindow::SetState() { m_pPreviousState = ImGui::GetInternalState(); ImGui::SetInternalState(m_pState); memcpy(&((ImGuiState*)m_pState)->Style, &((ImGuiState*)m_pPreviousState)->Style, sizeof(ImGuiStyle)); } void ImwPlatformWindow::RestoreState() { memcpy(&((ImGuiState*)m_pPreviousState)->Style, &((ImGuiState*)m_pState)->Style, sizeof(ImGuiStyle)); ImGui::SetInternalState(m_pPreviousState); } void ImwPlatformWindow::Paint() { ImwWindowManager::GetInstance()->Paint(this); } bool ImwPlatformWindow::IsMain() { return m_bMain; } void ImwPlatformWindow::Dock(ImwWindow* pWindow) { m_pContainer->Dock(pWindow); } bool ImwPlatformWindow::UnDock(ImwWindow* pWindow) { return m_pContainer->UnDock(pWindow); } ImwContainer* ImwPlatformWindow::GetContainer() { return m_pContainer; } ImwContainer* ImwPlatformWindow::HasWindow(ImwWindow* pWindow) { return m_pContainer->HasWindow(pWindow); } void ImwPlatformWindow::PaintContainer() { m_pContainer->Paint(); } <|endoftext|>
<commit_before>/* * * PreferencesBackend * ledger-core * * Created by Pierre Pollastri on 10/01/2017. * * The MIT License (MIT) * * Copyright (c) 2016 Ledger * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #include "PreferencesBackend.hpp" #include "../utils/Exception.hpp" #include "../utils/LambdaRunnable.hpp" #include <leveldb/write_batch.h> #include <cstring> #include <leveldb/env.h> #include <iterator> namespace ledger { namespace core { namespace { // number of iteration to perform for PBKDF2 const uint32_t PBKDF2_ITERS = 10000; // see https://pages.nist.gov/800-63-3/sp800-63b.html#sec5 // key at which the encryption salt is found const std::string ENCRYPTION_SALT_KEY = "preferences.backend.salt"; } PreferencesChange::PreferencesChange(PreferencesChangeType t, std::vector<uint8_t> k, std::vector<uint8_t> v) : type(t), key(k), value(v) { } std::unordered_map<std::string, std::weak_ptr<leveldb::DB>> PreferencesBackend::LEVELDB_INSTANCE_POOL; std::mutex PreferencesBackend::LEVELDB_INSTANCE_POOL_MUTEX; PreferencesBackend::PreferencesBackend(const std::string &path, const std::shared_ptr<api::ExecutionContext>& writingContext, const std::shared_ptr<api::PathResolver> &resolver) { _context = writingContext; _dbName = resolver->resolvePreferencesPath(path); _db = obtainInstance(_dbName); } std::shared_ptr<leveldb::DB> PreferencesBackend::obtainInstance(const std::string &path) { std::lock_guard<std::mutex> lock(LEVELDB_INSTANCE_POOL_MUTEX); auto it = LEVELDB_INSTANCE_POOL.find(path); if (it != LEVELDB_INSTANCE_POOL.end()) { auto db = it->second.lock(); if (db != nullptr) return db; } leveldb::DB *db; leveldb::Options options; options.create_if_missing = true; auto status = leveldb::DB::Open(options, path, &db); if (!status.ok()) { throw Exception(api::ErrorCode::UNABLE_TO_OPEN_LEVELDB, status.ToString()); } auto instance = std::shared_ptr<leveldb::DB>(db); std::weak_ptr<leveldb::DB> weakInstance = instance; LEVELDB_INSTANCE_POOL[path] = weakInstance; return instance; } void PreferencesBackend::commit(const std::vector<PreferencesChange> &changes) { auto db = _db; leveldb::WriteBatch batch; leveldb::WriteOptions options; options.sync = true; for (auto& item : changes) { putPreferencesChange(batch, _cipher, item); } db->Write(options, &batch); } // Put a single PreferencesChange. void PreferencesBackend::putPreferencesChange( leveldb::WriteBatch& batch, Option<AESCipher>& cipher, const PreferencesChange& change ) { leveldb::Slice k((const char *)change.key.data(), change.key.size()); if (change.type == PreferencesChangeType::PUT_TYPE) { if (cipher.hasValue()) { auto encrypted = encrypt_preferences_change(change, *_cipher); leveldb::Slice v((const char *)encrypted.data(), encrypted.size()); batch.Put(k, v); } else { leveldb::Slice v((const char *)change.value.data(), change.value.size()); batch.Put(k, v); } } else { batch.Delete(k); } } optional<std::string> PreferencesBackend::get(const std::vector<uint8_t>& key) { leveldb::Slice k((const char *)key.data(), key.size()); std::string value; auto status = _db->Get(leveldb::ReadOptions(), k, &value); if (status.ok()) { if (_cipher.hasValue()) { auto ciphertext = std::vector<uint8_t>(value.cbegin(), value.cend()); auto plaindata = decrypt_preferences_change(ciphertext, *_cipher); auto plaintext = std::string(plaindata.cbegin(), plaindata.cend()); return optional<std::string>(plaintext); } else { return optional<std::string>(value); } } else { return optional<std::string>(); } } void PreferencesBackend::iterate(const std::vector<uint8_t> &keyPrefix, std::function<bool (leveldb::Slice &&, leveldb::Slice &&)> f) { std::unique_ptr<leveldb::Iterator> it(_db->NewIterator(leveldb::ReadOptions())); leveldb::Slice start((const char *) keyPrefix.data(), keyPrefix.size()); std::vector<uint8_t> limitRaw(keyPrefix.begin(), keyPrefix.end()); limitRaw[limitRaw.size() - 1] += 1; leveldb::Slice limit((const char *) limitRaw.data(), limitRaw.size()); for (it->Seek(start); it->Valid(); it->Next()) { if (it->key().compare(limit) > 0) { break; } if (_cipher.hasValue()) { // decrypt the value on the fly auto value = it->value().ToString(); auto ciphertext = std::vector<uint8_t>(value.cbegin(), value.cend()); auto plaindata = decrypt_preferences_change(ciphertext, *_cipher); auto plaintext = std::string(plaindata.cbegin(), plaindata.cbegin()); leveldb::Slice slice(plaintext); if (!f(it->key(), std::move(slice))) { break; } } else { if (!f(it->key(), it->value())) { break; } } } } std::shared_ptr<Preferences> PreferencesBackend::getPreferences(const std::string &name) { return std::make_shared<Preferences>(*this, std::vector<uint8_t>(name.data(), name.data() + name.size())); } std::string PreferencesBackend::createNewSalt(const std::shared_ptr<api::RandomNumberGenerator>& rng) { auto bytes = rng->getRandomBytes(128); return std::string(bytes.begin(), std::end(bytes)); } void PreferencesBackend::setEncryption( const std::shared_ptr<api::RandomNumberGenerator>& rng, const std::string& password ) { // disable encryption to check whether we have a salt already persisted unsetEncryption(); auto emptySalt = std::string(""); auto saltKey = std::vector<uint8_t>(ENCRYPTION_SALT_KEY.cbegin(), ENCRYPTION_SALT_KEY.cend()); auto salt = get(saltKey).value_or(emptySalt); if (salt == emptySalt) { leveldb::WriteBatch batch; // we don’t have a proper salt; create one salt = createNewSalt(rng); // create the AES cipher _cipher = AESCipher(rng, password, salt, PBKDF2_ITERS); // add the salt to the batch to be written auto saltData = std::vector<uint8_t>(salt.cbegin(), salt.cend()); auto noCipher = Option<AESCipher>::NONE; putPreferencesChange(batch, noCipher, PreferencesChange(PreferencesChangeType::PUT_TYPE, saltKey, saltData)); // iterate through all records already present and update them auto it = std::unique_ptr<leveldb::Iterator>(_db->NewIterator(leveldb::ReadOptions())); for (it->SeekToFirst(); it->Valid(); it->Next()) { // read the clear value auto value = it->value().ToString(); auto plain = std::vector<uint8_t>(value.cbegin(), value.cend()); auto keyStr = it->key().ToString(); auto key = std::vector<uint8_t>(keyStr.cbegin(), keyStr.cend()); // remove the key and its associated value to prevent duplication putPreferencesChange(batch, _cipher, PreferencesChange(PreferencesChangeType::DELETE_TYPE, key, {})); // encrypt putPreferencesChange(batch, _cipher, PreferencesChange(PreferencesChangeType::PUT_TYPE, key, plain)); } // atomic update leveldb::WriteOptions writeOpts; writeOpts.sync = true; _db->Write(writeOpts, &batch); } else { // the salt is already there, just create the AES cipher _cipher = AESCipher(rng, password, salt, PBKDF2_ITERS); } } void PreferencesBackend::unsetEncryption() { _cipher = Option<AESCipher>::NONE; } void PreferencesBackend::resetEncryption( const std::shared_ptr<api::RandomNumberGenerator>& rng, const std::string& oldPassword, const std::string& newPassword ) { // turn on encryption with the old password first setEncryption(rng, oldPassword); // from now on, reading data will use the old password, but we want to persist with a // brand new cipher; create it here auto newSalt = createNewSalt(rng); auto newSaltBytes = std::vector<uint8_t>(newSalt.cbegin(), newSalt.cend()); auto newCipher = Option<AESCipher>(AESCipher(rng, newPassword, newSalt, PBKDF2_ITERS)); // now we can iterate over all data, decrypt with the “old” cipher, encrypt with the // “new” cipher and generate two changes per entry: one that deletes it (to prevent to // duplicating it) and one that puts the new encoded one; once the iteration is done, // we submit the batch to leveldb and it applies it atomically auto it = std::unique_ptr<leveldb::Iterator>(_db->NewIterator(leveldb::ReadOptions())); leveldb::WriteBatch batch; for (it->SeekToFirst(); it->Valid(); it->Next()) { // decrypt with the old cipher auto value = it->value().ToString(); auto ciphertext = std::vector<uint8_t>(value.cbegin(), value.cend()); auto plaindata = decrypt_preferences_change(ciphertext, *_cipher); // the key is not encrypted auto keyStr = it->key().ToString(); auto key = std::vector<uint8_t>(keyStr.cbegin(), keyStr.cend()); // remove the key and its associated value to prevent duplication putPreferencesChange(batch, _cipher, PreferencesChange(PreferencesChangeType::DELETE_TYPE, key, {})); // encrypt with the new cipher; in order to do that, we need a PreferencesChange // to add with the new cipher auto change = PreferencesChange(PreferencesChangeType::PUT_TYPE, key, plaindata); putPreferencesChange(batch, newCipher, change); } // we also need to update the salt auto saltKey = std::vector<uint8_t>(ENCRYPTION_SALT_KEY.cbegin(), ENCRYPTION_SALT_KEY.cend()); auto noCipher = Option<AESCipher>::NONE; putPreferencesChange(batch, _cipher, PreferencesChange(PreferencesChangeType::DELETE_TYPE, saltKey, {})); putPreferencesChange(batch, noCipher, PreferencesChange( PreferencesChangeType::PUT_TYPE, saltKey, newSaltBytes )); // atomic update leveldb::WriteOptions writeOpts; writeOpts.sync = true; _db->Write(writeOpts, &batch); } void PreferencesBackend::clear() { // unset encryption because it’s disabled by default unsetEncryption(); // drop and recreate the DB; we need to scope that because the lock must be released // in order for obtainInstance to work correctly { std::lock_guard<std::mutex> lock(LEVELDB_INSTANCE_POOL_MUTEX); auto it = LEVELDB_INSTANCE_POOL.find(_dbName); if (it != LEVELDB_INSTANCE_POOL.end()) { // drop the cached DB first LEVELDB_INSTANCE_POOL.erase(it); } _db.reset(); // this should completely drop leveldb::Options options; leveldb::DestroyDB(_dbName, options); } _db = obtainInstance(_dbName); } std::vector<uint8_t> PreferencesBackend::encrypt_preferences_change( const PreferencesChange& change, AESCipher& cipher ) { auto input = BytesReader(change.value); auto output = BytesWriter(); cipher.encrypt(input, output); return output.toByteArray(); } std::vector<uint8_t> PreferencesBackend::decrypt_preferences_change( const std::vector<uint8_t>& data, AESCipher& cipher ) { auto input = BytesReader(data); auto output = BytesWriter(); cipher.decrypt(input, output); return output.toByteArray(); } } } <commit_msg>Update a forgotten std::end -> .end.<commit_after>/* * * PreferencesBackend * ledger-core * * Created by Pierre Pollastri on 10/01/2017. * * The MIT License (MIT) * * Copyright (c) 2016 Ledger * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #include "PreferencesBackend.hpp" #include "../utils/Exception.hpp" #include "../utils/LambdaRunnable.hpp" #include <leveldb/write_batch.h> #include <cstring> #include <leveldb/env.h> #include <iterator> namespace ledger { namespace core { namespace { // number of iteration to perform for PBKDF2 const uint32_t PBKDF2_ITERS = 10000; // see https://pages.nist.gov/800-63-3/sp800-63b.html#sec5 // key at which the encryption salt is found const std::string ENCRYPTION_SALT_KEY = "preferences.backend.salt"; } PreferencesChange::PreferencesChange(PreferencesChangeType t, std::vector<uint8_t> k, std::vector<uint8_t> v) : type(t), key(k), value(v) { } std::unordered_map<std::string, std::weak_ptr<leveldb::DB>> PreferencesBackend::LEVELDB_INSTANCE_POOL; std::mutex PreferencesBackend::LEVELDB_INSTANCE_POOL_MUTEX; PreferencesBackend::PreferencesBackend(const std::string &path, const std::shared_ptr<api::ExecutionContext>& writingContext, const std::shared_ptr<api::PathResolver> &resolver) { _context = writingContext; _dbName = resolver->resolvePreferencesPath(path); _db = obtainInstance(_dbName); } std::shared_ptr<leveldb::DB> PreferencesBackend::obtainInstance(const std::string &path) { std::lock_guard<std::mutex> lock(LEVELDB_INSTANCE_POOL_MUTEX); auto it = LEVELDB_INSTANCE_POOL.find(path); if (it != LEVELDB_INSTANCE_POOL.end()) { auto db = it->second.lock(); if (db != nullptr) return db; } leveldb::DB *db; leveldb::Options options; options.create_if_missing = true; auto status = leveldb::DB::Open(options, path, &db); if (!status.ok()) { throw Exception(api::ErrorCode::UNABLE_TO_OPEN_LEVELDB, status.ToString()); } auto instance = std::shared_ptr<leveldb::DB>(db); std::weak_ptr<leveldb::DB> weakInstance = instance; LEVELDB_INSTANCE_POOL[path] = weakInstance; return instance; } void PreferencesBackend::commit(const std::vector<PreferencesChange> &changes) { auto db = _db; leveldb::WriteBatch batch; leveldb::WriteOptions options; options.sync = true; for (auto& item : changes) { putPreferencesChange(batch, _cipher, item); } db->Write(options, &batch); } // Put a single PreferencesChange. void PreferencesBackend::putPreferencesChange( leveldb::WriteBatch& batch, Option<AESCipher>& cipher, const PreferencesChange& change ) { leveldb::Slice k((const char *)change.key.data(), change.key.size()); if (change.type == PreferencesChangeType::PUT_TYPE) { if (cipher.hasValue()) { auto encrypted = encrypt_preferences_change(change, *_cipher); leveldb::Slice v((const char *)encrypted.data(), encrypted.size()); batch.Put(k, v); } else { leveldb::Slice v((const char *)change.value.data(), change.value.size()); batch.Put(k, v); } } else { batch.Delete(k); } } optional<std::string> PreferencesBackend::get(const std::vector<uint8_t>& key) { leveldb::Slice k((const char *)key.data(), key.size()); std::string value; auto status = _db->Get(leveldb::ReadOptions(), k, &value); if (status.ok()) { if (_cipher.hasValue()) { auto ciphertext = std::vector<uint8_t>(value.cbegin(), value.cend()); auto plaindata = decrypt_preferences_change(ciphertext, *_cipher); auto plaintext = std::string(plaindata.cbegin(), plaindata.cend()); return optional<std::string>(plaintext); } else { return optional<std::string>(value); } } else { return optional<std::string>(); } } void PreferencesBackend::iterate(const std::vector<uint8_t> &keyPrefix, std::function<bool (leveldb::Slice &&, leveldb::Slice &&)> f) { std::unique_ptr<leveldb::Iterator> it(_db->NewIterator(leveldb::ReadOptions())); leveldb::Slice start((const char *) keyPrefix.data(), keyPrefix.size()); std::vector<uint8_t> limitRaw(keyPrefix.begin(), keyPrefix.end()); limitRaw[limitRaw.size() - 1] += 1; leveldb::Slice limit((const char *) limitRaw.data(), limitRaw.size()); for (it->Seek(start); it->Valid(); it->Next()) { if (it->key().compare(limit) > 0) { break; } if (_cipher.hasValue()) { // decrypt the value on the fly auto value = it->value().ToString(); auto ciphertext = std::vector<uint8_t>(value.cbegin(), value.cend()); auto plaindata = decrypt_preferences_change(ciphertext, *_cipher); auto plaintext = std::string(plaindata.cbegin(), plaindata.cbegin()); leveldb::Slice slice(plaintext); if (!f(it->key(), std::move(slice))) { break; } } else { if (!f(it->key(), it->value())) { break; } } } } std::shared_ptr<Preferences> PreferencesBackend::getPreferences(const std::string &name) { return std::make_shared<Preferences>(*this, std::vector<uint8_t>(name.data(), name.data() + name.size())); } std::string PreferencesBackend::createNewSalt(const std::shared_ptr<api::RandomNumberGenerator>& rng) { auto bytes = rng->getRandomBytes(128); return std::string(bytes.begin(), bytes.end()); } void PreferencesBackend::setEncryption( const std::shared_ptr<api::RandomNumberGenerator>& rng, const std::string& password ) { // disable encryption to check whether we have a salt already persisted unsetEncryption(); auto emptySalt = std::string(""); auto saltKey = std::vector<uint8_t>(ENCRYPTION_SALT_KEY.cbegin(), ENCRYPTION_SALT_KEY.cend()); auto salt = get(saltKey).value_or(emptySalt); if (salt == emptySalt) { leveldb::WriteBatch batch; // we don’t have a proper salt; create one salt = createNewSalt(rng); // create the AES cipher _cipher = AESCipher(rng, password, salt, PBKDF2_ITERS); // add the salt to the batch to be written auto saltData = std::vector<uint8_t>(salt.cbegin(), salt.cend()); auto noCipher = Option<AESCipher>::NONE; putPreferencesChange(batch, noCipher, PreferencesChange(PreferencesChangeType::PUT_TYPE, saltKey, saltData)); // iterate through all records already present and update them auto it = std::unique_ptr<leveldb::Iterator>(_db->NewIterator(leveldb::ReadOptions())); for (it->SeekToFirst(); it->Valid(); it->Next()) { // read the clear value auto value = it->value().ToString(); auto plain = std::vector<uint8_t>(value.cbegin(), value.cend()); auto keyStr = it->key().ToString(); auto key = std::vector<uint8_t>(keyStr.cbegin(), keyStr.cend()); // remove the key and its associated value to prevent duplication putPreferencesChange(batch, _cipher, PreferencesChange(PreferencesChangeType::DELETE_TYPE, key, {})); // encrypt putPreferencesChange(batch, _cipher, PreferencesChange(PreferencesChangeType::PUT_TYPE, key, plain)); } // atomic update leveldb::WriteOptions writeOpts; writeOpts.sync = true; _db->Write(writeOpts, &batch); } else { // the salt is already there, just create the AES cipher _cipher = AESCipher(rng, password, salt, PBKDF2_ITERS); } } void PreferencesBackend::unsetEncryption() { _cipher = Option<AESCipher>::NONE; } void PreferencesBackend::resetEncryption( const std::shared_ptr<api::RandomNumberGenerator>& rng, const std::string& oldPassword, const std::string& newPassword ) { // turn on encryption with the old password first setEncryption(rng, oldPassword); // from now on, reading data will use the old password, but we want to persist with a // brand new cipher; create it here auto newSalt = createNewSalt(rng); auto newSaltBytes = std::vector<uint8_t>(newSalt.cbegin(), newSalt.cend()); auto newCipher = Option<AESCipher>(AESCipher(rng, newPassword, newSalt, PBKDF2_ITERS)); // now we can iterate over all data, decrypt with the “old” cipher, encrypt with the // “new” cipher and generate two changes per entry: one that deletes it (to prevent to // duplicating it) and one that puts the new encoded one; once the iteration is done, // we submit the batch to leveldb and it applies it atomically auto it = std::unique_ptr<leveldb::Iterator>(_db->NewIterator(leveldb::ReadOptions())); leveldb::WriteBatch batch; for (it->SeekToFirst(); it->Valid(); it->Next()) { // decrypt with the old cipher auto value = it->value().ToString(); auto ciphertext = std::vector<uint8_t>(value.cbegin(), value.cend()); auto plaindata = decrypt_preferences_change(ciphertext, *_cipher); // the key is not encrypted auto keyStr = it->key().ToString(); auto key = std::vector<uint8_t>(keyStr.cbegin(), keyStr.cend()); // remove the key and its associated value to prevent duplication putPreferencesChange(batch, _cipher, PreferencesChange(PreferencesChangeType::DELETE_TYPE, key, {})); // encrypt with the new cipher; in order to do that, we need a PreferencesChange // to add with the new cipher auto change = PreferencesChange(PreferencesChangeType::PUT_TYPE, key, plaindata); putPreferencesChange(batch, newCipher, change); } // we also need to update the salt auto saltKey = std::vector<uint8_t>(ENCRYPTION_SALT_KEY.cbegin(), ENCRYPTION_SALT_KEY.cend()); auto noCipher = Option<AESCipher>::NONE; putPreferencesChange(batch, _cipher, PreferencesChange(PreferencesChangeType::DELETE_TYPE, saltKey, {})); putPreferencesChange(batch, noCipher, PreferencesChange( PreferencesChangeType::PUT_TYPE, saltKey, newSaltBytes )); // atomic update leveldb::WriteOptions writeOpts; writeOpts.sync = true; _db->Write(writeOpts, &batch); } void PreferencesBackend::clear() { // unset encryption because it’s disabled by default unsetEncryption(); // drop and recreate the DB; we need to scope that because the lock must be released // in order for obtainInstance to work correctly { std::lock_guard<std::mutex> lock(LEVELDB_INSTANCE_POOL_MUTEX); auto it = LEVELDB_INSTANCE_POOL.find(_dbName); if (it != LEVELDB_INSTANCE_POOL.end()) { // drop the cached DB first LEVELDB_INSTANCE_POOL.erase(it); } _db.reset(); // this should completely drop leveldb::Options options; leveldb::DestroyDB(_dbName, options); } _db = obtainInstance(_dbName); } std::vector<uint8_t> PreferencesBackend::encrypt_preferences_change( const PreferencesChange& change, AESCipher& cipher ) { auto input = BytesReader(change.value); auto output = BytesWriter(); cipher.encrypt(input, output); return output.toByteArray(); } std::vector<uint8_t> PreferencesBackend::decrypt_preferences_change( const std::vector<uint8_t>& data, AESCipher& cipher ) { auto input = BytesReader(data); auto output = BytesWriter(); cipher.decrypt(input, output); return output.toByteArray(); } } } <|endoftext|>
<commit_before>/* * Licensed to Green Energy Corp (www.greenenergycorp.com) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. Green Enery * Corp licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ #include "VtoRouterManager.h" #include "VtoRouter.h" #include "VtoRouterSettings.h" #include <APL/Exception.h> #include <APL/IPhysicalLayerSource.h> #include <APL/IPhysicalLayerAsync.h> #include <boost/bind.hpp> #include <boost/foreach.hpp> #include <boost/bind.hpp> #include <sstream> namespace apl { namespace dnp { VtoRouterManager::RouterRecord::RouterRecord(const std::string& arPortName, VtoRouter* apRouter, IVtoWriter* apWriter, boost::uint8_t aVtoChannelId) : mPortName(arPortName), mpRouter(apRouter), mpWriter(apWriter), mVtoChannelId(aVtoChannelId) { } VtoRouterManager::VtoRouterManager(Logger* apLogger, ITimerSource* apTimerSrc, IPhysicalLayerSource* apPhysSrc) : Loggable(apLogger), mpTimerSrc(apTimerSrc), mpPhysSource(apPhysSrc) { assert(apTimerSrc != NULL); assert(apPhysSrc != NULL); } VtoRouterManager::~VtoRouterManager() { this->StopAllRouters(); } void VtoRouterManager::ClenupAfterRouter(IPhysicalLayerAsync* apPhys, VtoRouter* apRouter) { delete apPhys; delete apRouter; } VtoRouter* VtoRouterManager::StartRouter( const std::string& arPortName, const VtoRouterSettings& arSettings, IVtoWriter* apWriter) { IPhysicalLayerAsync* pPhys = mpPhysSource->AcquireLayer(arPortName, false); //don't autodelete Logger* pLogger = this->GetSubLogger(arPortName, arSettings.CHANNEL_ID); VtoRouter* pRouter = new VtoRouter(arSettings, pLogger, apWriter, pPhys, mpTimerSrc); // when the router is completely stopped, it's physical layer will be deleted, followed by itself pRouter->AddCleanupTask(boost::bind(&VtoRouterManager::ClenupAfterRouter, pPhys, pRouter)); RouterRecord record(arPortName, pRouter, apWriter, arSettings.CHANNEL_ID); // we need the VtoRouters to start themselves //pRouter->Start(); this->mRecords.push_back(record); return pRouter; } std::vector<VtoRouterManager::RouterRecord> VtoRouterManager::GetAllRouters() { std::vector<VtoRouterManager::RouterRecord> ret; for(size_t i=0; i<mRecords.size(); ++i) ret.push_back(mRecords[i]); return ret; } void VtoRouterManager::StopRouters(const std::vector<RouterRecord>& arRouters) { for(size_t i=0; i< arRouters.size(); ++i) this->StopRouter(arRouters[i].mpRouter); } void VtoRouterManager::StopAllRouters() { std::vector<VtoRouterManager::RouterRecord> routers = this->GetAllRouters(); this->StopRouters(routers); } void VtoRouterManager::StopRouter(IVtoWriter* apWriter, boost::uint8_t aVtoChannelId) { this->StopRouter(this->GetRouterOnWriter(apWriter, aVtoChannelId).mpRouter); } void VtoRouterManager::StopAllRoutersOnWriter(IVtoWriter* apWriter) { std::vector<RouterRecord> routers = this->GetAllRoutersOnWriter(apWriter); this->StopRouters(routers); } std::vector<VtoRouterManager::RouterRecord> VtoRouterManager::GetAllRoutersOnWriter(IVtoWriter* apWriter) { std::vector< VtoRouterManager::RouterRecord > ret; for(RouterRecordVector::iterator i = this->mRecords.begin(); i != mRecords.end(); ++i) { if(i->mpWriter == apWriter) ret.push_back(*i); } return ret; } VtoRouterManager::RouterRecord VtoRouterManager::GetRouterOnWriter(IVtoWriter* apWriter, boost::uint8_t aVtoChannelId) { for(RouterRecordVector::iterator i = this->mRecords.begin(); i != mRecords.end(); ++i) { if(i->mpWriter == apWriter && i->mVtoChannelId == aVtoChannelId) return *i; } throw ArgumentException(LOCATION, "Router not found for writer on channel"); } VtoRouterManager::RouterRecordVector::iterator VtoRouterManager::Find(IVtoWriter* apWriter, boost::uint8_t aVtoChannelId) { RouterRecordVector::iterator i = this->mRecords.begin(); for(; i != mRecords.end(); ++i) { if(i->mpWriter == apWriter && i->mVtoChannelId == aVtoChannelId) return i; } return i; } VtoRouterManager::RouterRecordVector::iterator VtoRouterManager::Find(IVtoWriter* apWriter) { RouterRecordVector::iterator i = this->mRecords.begin(); for(; i != mRecords.end(); ++i) { if(i->mpWriter == apWriter) return i; } return i; } void VtoRouterManager::StopRouter(VtoRouter* apRouter) { for(RouterRecordVector::iterator i = mRecords.begin(); i != mRecords.end(); ++i) { if(i->mpRouter == apRouter) { LOG_BLOCK(LEV_INFO, "Releasing layer: " << i->mPortName); mpPhysSource->ReleaseLayer(i->mPortName); mpTimerSrc->Post(boost::bind(&VtoRouter::Stop, i->mpRouter)); mRecords.erase(i); return; } } throw ArgumentException(LOCATION, "Router could not be found in vector"); } Logger* VtoRouterManager::GetSubLogger(const std::string& arId, boost::uint8_t aVtoChannelId) { std::ostringstream oss; <<<<<<< HEAD oss << arId << "-VtoRouterChannel-" << aVtoChannelId; return mpLogger->GetSubLogger(oss.str()); ======= oss << arId << "-VtoRouterChannel-" << ((int)aVtoChannelId); return mpLogger->GetSubLogger(oss.str()); >>>>>>> gec/vto_integration } }} <commit_msg>Fixed missing merge comment.<commit_after>/* * Licensed to Green Energy Corp (www.greenenergycorp.com) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. Green Enery * Corp licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ #include "VtoRouterManager.h" #include "VtoRouter.h" #include "VtoRouterSettings.h" #include <APL/Exception.h> #include <APL/IPhysicalLayerSource.h> #include <APL/IPhysicalLayerAsync.h> #include <boost/bind.hpp> #include <boost/foreach.hpp> #include <boost/bind.hpp> #include <sstream> namespace apl { namespace dnp { VtoRouterManager::RouterRecord::RouterRecord(const std::string& arPortName, VtoRouter* apRouter, IVtoWriter* apWriter, boost::uint8_t aVtoChannelId) : mPortName(arPortName), mpRouter(apRouter), mpWriter(apWriter), mVtoChannelId(aVtoChannelId) { } VtoRouterManager::VtoRouterManager(Logger* apLogger, ITimerSource* apTimerSrc, IPhysicalLayerSource* apPhysSrc) : Loggable(apLogger), mpTimerSrc(apTimerSrc), mpPhysSource(apPhysSrc) { assert(apTimerSrc != NULL); assert(apPhysSrc != NULL); } VtoRouterManager::~VtoRouterManager() { this->StopAllRouters(); } void VtoRouterManager::ClenupAfterRouter(IPhysicalLayerAsync* apPhys, VtoRouter* apRouter) { delete apPhys; delete apRouter; } VtoRouter* VtoRouterManager::StartRouter( const std::string& arPortName, const VtoRouterSettings& arSettings, IVtoWriter* apWriter) { IPhysicalLayerAsync* pPhys = mpPhysSource->AcquireLayer(arPortName, false); //don't autodelete Logger* pLogger = this->GetSubLogger(arPortName, arSettings.CHANNEL_ID); VtoRouter* pRouter = new VtoRouter(arSettings, pLogger, apWriter, pPhys, mpTimerSrc); // when the router is completely stopped, it's physical layer will be deleted, followed by itself pRouter->AddCleanupTask(boost::bind(&VtoRouterManager::ClenupAfterRouter, pPhys, pRouter)); RouterRecord record(arPortName, pRouter, apWriter, arSettings.CHANNEL_ID); // we need the VtoRouters to start themselves //pRouter->Start(); this->mRecords.push_back(record); return pRouter; } std::vector<VtoRouterManager::RouterRecord> VtoRouterManager::GetAllRouters() { std::vector<VtoRouterManager::RouterRecord> ret; for(size_t i=0; i<mRecords.size(); ++i) ret.push_back(mRecords[i]); return ret; } void VtoRouterManager::StopRouters(const std::vector<RouterRecord>& arRouters) { for(size_t i=0; i< arRouters.size(); ++i) this->StopRouter(arRouters[i].mpRouter); } void VtoRouterManager::StopAllRouters() { std::vector<VtoRouterManager::RouterRecord> routers = this->GetAllRouters(); this->StopRouters(routers); } void VtoRouterManager::StopRouter(IVtoWriter* apWriter, boost::uint8_t aVtoChannelId) { this->StopRouter(this->GetRouterOnWriter(apWriter, aVtoChannelId).mpRouter); } void VtoRouterManager::StopAllRoutersOnWriter(IVtoWriter* apWriter) { std::vector<RouterRecord> routers = this->GetAllRoutersOnWriter(apWriter); this->StopRouters(routers); } std::vector<VtoRouterManager::RouterRecord> VtoRouterManager::GetAllRoutersOnWriter(IVtoWriter* apWriter) { std::vector< VtoRouterManager::RouterRecord > ret; for(RouterRecordVector::iterator i = this->mRecords.begin(); i != mRecords.end(); ++i) { if(i->mpWriter == apWriter) ret.push_back(*i); } return ret; } VtoRouterManager::RouterRecord VtoRouterManager::GetRouterOnWriter(IVtoWriter* apWriter, boost::uint8_t aVtoChannelId) { for(RouterRecordVector::iterator i = this->mRecords.begin(); i != mRecords.end(); ++i) { if(i->mpWriter == apWriter && i->mVtoChannelId == aVtoChannelId) return *i; } throw ArgumentException(LOCATION, "Router not found for writer on channel"); } VtoRouterManager::RouterRecordVector::iterator VtoRouterManager::Find(IVtoWriter* apWriter, boost::uint8_t aVtoChannelId) { RouterRecordVector::iterator i = this->mRecords.begin(); for(; i != mRecords.end(); ++i) { if(i->mpWriter == apWriter && i->mVtoChannelId == aVtoChannelId) return i; } return i; } VtoRouterManager::RouterRecordVector::iterator VtoRouterManager::Find(IVtoWriter* apWriter) { RouterRecordVector::iterator i = this->mRecords.begin(); for(; i != mRecords.end(); ++i) { if(i->mpWriter == apWriter) return i; } return i; } void VtoRouterManager::StopRouter(VtoRouter* apRouter) { for(RouterRecordVector::iterator i = mRecords.begin(); i != mRecords.end(); ++i) { if(i->mpRouter == apRouter) { LOG_BLOCK(LEV_INFO, "Releasing layer: " << i->mPortName); mpPhysSource->ReleaseLayer(i->mPortName); mpTimerSrc->Post(boost::bind(&VtoRouter::Stop, i->mpRouter)); mRecords.erase(i); return; } } throw ArgumentException(LOCATION, "Router could not be found in vector"); } Logger* VtoRouterManager::GetSubLogger(const std::string& arId, boost::uint8_t aVtoChannelId) { std::ostringstream oss; oss << arId << "-VtoRouterChannel-" << ((int)aVtoChannelId); return mpLogger->GetSubLogger(oss.str()); } }} <|endoftext|>
<commit_before>template <PetscInt dim> PetscErrorCode NavierStokesSolver<dim>::writeSimulationInfo() { PetscErrorCode ierr; PetscInt rank, maxits; PC pc; PCType pcType; KSPType kspType; PetscReal rtol; ierr = MPI_Comm_rank(PETSC_COMM_WORLD, &rank); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "\n---------------------------------------\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Flow\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "---------------------------------------\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Solver type: "); CHKERRQ(ierr); switch(simParams->solverType) { case NAVIER_STOKES : ierr = PetscPrintf(PETSC_COMM_WORLD, "Navier-Stokes\n"); CHKERRQ(ierr); break; case TAIRA_COLONIUS: ierr = PetscPrintf(PETSC_COMM_WORLD, "Taira & Colonius (2007)\n"); CHKERRQ(ierr); break; default: ierr = PetscPrintf(PETSC_COMM_WORLD, "Unrecognized solver!\n"); CHKERRQ(ierr); break; } ierr = PetscPrintf(PETSC_COMM_WORLD, "nu: %g\n", flowDesc->nu); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "\n---------------------------------------\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Mesh\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "---------------------------------------\n"); CHKERRQ(ierr); if(dim == 3) { ierr = PetscPrintf(PETSC_COMM_WORLD, "Size: %d x %d x %d\n", mesh->nx, mesh->ny, mesh->nz); CHKERRQ(ierr); } else { ierr = PetscPrintf(PETSC_COMM_WORLD, "Size: %d x %d\n", mesh->nx, mesh->ny); CHKERRQ(ierr); } ierr = PetscPrintf(PETSC_COMM_WORLD, "\n---------------------------------------\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Time-stepping schemes\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "---------------------------------------\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Convection: "); CHKERRQ(ierr); switch(simParams->convectionScheme) { case EULER_EXPLICIT : ierr = PetscPrintf(PETSC_COMM_WORLD, "Explicit Euler\n"); CHKERRQ(ierr); break; case ADAMS_BASHFORTH_2: ierr = PetscPrintf(PETSC_COMM_WORLD, "2nd-order Adams-Bashforth\n"); CHKERRQ(ierr); break; default: break; } ierr = PetscPrintf(PETSC_COMM_WORLD, "Diffusion : "); CHKERRQ(ierr); switch(simParams->diffusionScheme) { case EULER_EXPLICIT: ierr = PetscPrintf(PETSC_COMM_WORLD, "Explicit Euler\n"); CHKERRQ(ierr); break; case EULER_IMPLICIT: ierr = PetscPrintf(PETSC_COMM_WORLD, "Implicit Euler\n"); CHKERRQ(ierr); break; case CRANK_NICOLSON: ierr = PetscPrintf(PETSC_COMM_WORLD, "Crank-Nicolson\n"); CHKERRQ(ierr); break; default: break; } ierr = PetscPrintf(PETSC_COMM_WORLD, "startStep : %d\n", simParams->startStep); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "nt : %d\n", simParams->nt); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "nsave : %d\n", simParams->nsave); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "\n---------------------------------------\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Linear system for intermediate velocity\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "---------------------------------------\n"); CHKERRQ(ierr); ierr = KSPGetType(ksp1, &kspType); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Solver: %s\n", kspType); CHKERRQ(ierr); ierr = KSPGetPC(ksp1, &pc); CHKERRQ(ierr); ierr = PCGetType(pc, &pcType); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Preconditioner: %s\n", pcType); CHKERRQ(ierr); ierr = KSPGetTolerances(ksp1, &rtol, NULL, NULL, &maxits); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Relative tolerance: %g\n", rtol); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Maximum iterations: %d\n", maxits); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "\n---------------------------------------\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Linear system for Poisson step\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "---------------------------------------\n"); CHKERRQ(ierr); ierr = KSPGetType(ksp2, &kspType); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Solver: %s\n", kspType); CHKERRQ(ierr); ierr = KSPGetPC(ksp2, &pc); CHKERRQ(ierr); ierr = PCGetType(pc, &pcType); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Preconditioner: %s\n", pcType); CHKERRQ(ierr); ierr = KSPGetTolerances(ksp2, &rtol, NULL, NULL, &maxits); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Relative tolerance: %g\n", rtol); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Maximum iterations: %d\n", maxits); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "\n---------------------------------------\n"); CHKERRQ(ierr); if(rank==0) { std::ofstream f(caseFolder+"/simulationInfo.txt"); f << "-nx\t" << mesh->nx << '\n'; f << "-ny\t" << mesh->ny << '\n'; if(dim == 3) { f << "-nz\t" << mesh->nz << '\n'; } f << "-startStep\t" << simParams->startStep << '\n'; f << "-nt\t" << simParams->nt << '\n'; f << "-nsave\t" << simParams->nsave << '\n'; f << "-dt\t" << simParams->dt << '\n'; (flowDesc->bc[0][XPLUS].type==PERIODIC)? f << "-xperiodic\tTrue\n" : f << "-xperiodic\tFalse\n"; (flowDesc->bc[0][YPLUS].type==PERIODIC)? f << "-yperiodic\tTrue\n" : f << "-yperiodic\tFalse\n"; if(dim == 3) { (flowDesc->bc[0][ZPLUS].type==PERIODIC)? f << "-zperiodic\tTrue\n" : f << "-zperiodic\tFalse\n"; } f.close(); } return 0; } <commit_msg>Remove generation of file simulationInfo.txt<commit_after>template <PetscInt dim> PetscErrorCode NavierStokesSolver<dim>::writeSimulationInfo() { PetscErrorCode ierr; PetscInt rank, maxits; PC pc; PCType pcType; KSPType kspType; PetscReal rtol; ierr = MPI_Comm_rank(PETSC_COMM_WORLD, &rank); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "\n---------------------------------------\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Flow\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "---------------------------------------\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Solver type: "); CHKERRQ(ierr); switch(simParams->solverType) { case NAVIER_STOKES : ierr = PetscPrintf(PETSC_COMM_WORLD, "Navier-Stokes\n"); CHKERRQ(ierr); break; case TAIRA_COLONIUS: ierr = PetscPrintf(PETSC_COMM_WORLD, "Taira & Colonius (2007)\n"); CHKERRQ(ierr); break; default: ierr = PetscPrintf(PETSC_COMM_WORLD, "Unrecognized solver!\n"); CHKERRQ(ierr); break; } ierr = PetscPrintf(PETSC_COMM_WORLD, "nu: %g\n", flowDesc->nu); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "\n---------------------------------------\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Mesh\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "---------------------------------------\n"); CHKERRQ(ierr); if(dim == 3) { ierr = PetscPrintf(PETSC_COMM_WORLD, "Size: %d x %d x %d\n", mesh->nx, mesh->ny, mesh->nz); CHKERRQ(ierr); } else { ierr = PetscPrintf(PETSC_COMM_WORLD, "Size: %d x %d\n", mesh->nx, mesh->ny); CHKERRQ(ierr); } ierr = PetscPrintf(PETSC_COMM_WORLD, "\n---------------------------------------\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Time-stepping schemes\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "---------------------------------------\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Convection: "); CHKERRQ(ierr); switch(simParams->convectionScheme) { case EULER_EXPLICIT : ierr = PetscPrintf(PETSC_COMM_WORLD, "Explicit Euler\n"); CHKERRQ(ierr); break; case ADAMS_BASHFORTH_2: ierr = PetscPrintf(PETSC_COMM_WORLD, "2nd-order Adams-Bashforth\n"); CHKERRQ(ierr); break; default: break; } ierr = PetscPrintf(PETSC_COMM_WORLD, "Diffusion : "); CHKERRQ(ierr); switch(simParams->diffusionScheme) { case EULER_EXPLICIT: ierr = PetscPrintf(PETSC_COMM_WORLD, "Explicit Euler\n"); CHKERRQ(ierr); break; case EULER_IMPLICIT: ierr = PetscPrintf(PETSC_COMM_WORLD, "Implicit Euler\n"); CHKERRQ(ierr); break; case CRANK_NICOLSON: ierr = PetscPrintf(PETSC_COMM_WORLD, "Crank-Nicolson\n"); CHKERRQ(ierr); break; default: break; } ierr = PetscPrintf(PETSC_COMM_WORLD, "startStep : %d\n", simParams->startStep); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "nt : %d\n", simParams->nt); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "nsave : %d\n", simParams->nsave); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "\n---------------------------------------\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Linear system for intermediate velocity\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "---------------------------------------\n"); CHKERRQ(ierr); ierr = KSPGetType(ksp1, &kspType); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Solver: %s\n", kspType); CHKERRQ(ierr); ierr = KSPGetPC(ksp1, &pc); CHKERRQ(ierr); ierr = PCGetType(pc, &pcType); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Preconditioner: %s\n", pcType); CHKERRQ(ierr); ierr = KSPGetTolerances(ksp1, &rtol, NULL, NULL, &maxits); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Relative tolerance: %g\n", rtol); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Maximum iterations: %d\n", maxits); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "\n---------------------------------------\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Linear system for Poisson step\n"); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "---------------------------------------\n"); CHKERRQ(ierr); ierr = KSPGetType(ksp2, &kspType); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Solver: %s\n", kspType); CHKERRQ(ierr); ierr = KSPGetPC(ksp2, &pc); CHKERRQ(ierr); ierr = PCGetType(pc, &pcType); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Preconditioner: %s\n", pcType); CHKERRQ(ierr); ierr = KSPGetTolerances(ksp2, &rtol, NULL, NULL, &maxits); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Relative tolerance: %g\n", rtol); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Maximum iterations: %d\n", maxits); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "\n---------------------------------------\n"); CHKERRQ(ierr); return 0; } <|endoftext|>
<commit_before>#ifndef STAN_SERVICES_UTIL_READ_DIAG_MASS_MATRIX_HPP #define STAN_SERVICES_UTIL_READ_DIAG_MASS_MATRIX_HPP #include <stan/callbacks/writer.hpp> #include <stan/io/var_context.hpp> #include <stan/math/prim/mat.hpp> #include <limits> #include <sstream> #include <string> #include <vector> namespace stan { namespace services { namespace util { /** * Extract diagonal values for a mass matrix from a var_context object. * * @param[in] init_mass_matrix a var_context with initial values * @param[in] num_params expected number of diagonal elements * @param[in,out] error_writer message writer * @throws std::domain_error if the mass matrix is invalid * @return mass_matrix vector of diagonal values */ Eigen::VectorXd read_diag_mass_matrix(stan::io::var_context& init_mass_matrix, size_t num_params, stan::callbacks::writer& error_writer) { Eigen::VectorXd inv_mass_matrix(num_params); try { init_mass_matrix.validate_dims("read diag mass matrix", "mass_matrix", "vector_d", init_mass_matrix.to_vec(num_params)); std::vector<double> diag_vals = init_mass_matrix.vals_r("mass_matrix"); for (size_t i=0; i < num_params; i++) { inv_mass_matrix(i) = diag_vals[i]; } } catch (const std::exception& e) { error_writer("Cannot get mass matrix from input file"); throw std::domain_error("Initialization failure"); } return inv_mass_matrix; } } } } #endif <commit_msg>header fix<commit_after>#ifndef STAN_SERVICES_UTIL_READ_DIAG_MASS_MATRIX_HPP #define STAN_SERVICES_UTIL_READ_DIAG_MASS_MATRIX_HPP #include <stan/callbacks/writer.hpp> #include <stan/io/var_context.hpp> #include <Eigen/Dense> #include <limits> #include <sstream> #include <string> #include <vector> namespace stan { namespace services { namespace util { /** * Extract diagonal values for a mass matrix from a var_context object. * * @param[in] init_mass_matrix a var_context with initial values * @param[in] num_params expected number of diagonal elements * @param[in,out] error_writer message writer * @throws std::domain_error if the mass matrix is invalid * @return mass_matrix vector of diagonal values */ Eigen::VectorXd read_diag_mass_matrix(stan::io::var_context& init_mass_matrix, size_t num_params, stan::callbacks::writer& error_writer) { Eigen::VectorXd inv_mass_matrix(num_params); try { init_mass_matrix.validate_dims("read diag mass matrix", "mass_matrix", "vector_d", init_mass_matrix.to_vec(num_params)); std::vector<double> diag_vals = init_mass_matrix.vals_r("mass_matrix"); for (size_t i=0; i < num_params; i++) { inv_mass_matrix(i) = diag_vals[i]; } } catch (const std::exception& e) { error_writer("Cannot get mass matrix from input file"); throw std::domain_error("Initialization failure"); } return inv_mass_matrix; } } } } #endif <|endoftext|>
<commit_before>/*************************************************** This is a library for the HDC1000 Humidity & Temp Sensor Designed specifically to work with the HDC1008 sensor from Adafruit ----> https://www.adafruit.com/products/2635 These sensors use I2C to communicate, 2 pins are required to interface Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried/Ladyada for Adafruit Industries. BSD license, all text above must be included in any redistribution Modified for Photon needs application.h for types RMB ****************************************************/ #include "application.h" #include "Adafruit_HDC1000/Adafruit_HDC1000.h" Adafruit_HDC1000::Adafruit_HDC1000() { } boolean Adafruit_HDC1000::begin(uint8_t addr) { _i2caddr = addr; Wire.begin(); reset(); if (read16(HDC1000_MANUFID) != 0x5449) return false; if (read16(HDC1000_DEVICEID) != 0x1000) return false; return true; } void Adafruit_HDC1000::reset(void) { // reset,combined temp/humidity measurement,and select 14 bit temp & humidity resolution uint16_t config = HDC1000_CONFIG_RST | HDC1000_CONFIG_MODE | HDC1000_CONFIG_TRES_14 | HDC1000_CONFIG_HRES_14; Wire.beginTransmission(_i2caddr); Wire.write(HDC1000_CONFIG); // set pointer register to configuration register RMB Wire.write(config>>8); // now write out 2 bytes MSB first RMB Wire.write(config&0xFF); Wire.endTransmission(); delay(15); } float Adafruit_HDC1000::readTemperature(void) { float temp = (read32(HDC1000_TEMP, 20) >> 16); temp /= 65536; temp *= 165; temp -= 40; return temp; } float Adafruit_HDC1000::readHumidity(void) { // reads both temp and humidity but masks out temp in highest 16 bits // originally used hum but humidity declared in private section of class float humidity = (read32(HDC1000_TEMP, 20) & 0xFFFF); humidity /= 65536; humidity *= 100; return humidity; } void Adafruit_HDC1000::ReadTempHumidity(void) { // HDC1008 setup to measure both temperature and humidity in one conversion // this is a different way to access data in ONE read // this sets internal private variables that can be accessed by Get() functions uint32_t rt,rh ; // working variables rt = read32(HDC1000_TEMP, 20); // get temp and humidity reading together rh = rt; // save a copy for humidity processing // important to use ( ) around temp so private variable accessed and float cast done float (temp = (rt >> 16)); // convert to temp first temp /= 65536; temp *= 165; temp -= 40; // important to use ( ) around humidity so private variable accessed and float cast done float (humidity = (rh & 0xFFFF)); // now convert to humidity humidity /= 65536; humidity *= 100; } float Adafruit_HDC1000::GetTemperature(void) { // getter function to access private temp variable return temp ; } float Adafruit_HDC1000::GetHumidity(void) { // getter function to access private humidity variable return humidity ; } // Add ability to test battery voltage, useful in remote monitoring, TRUE if <2.8V // usually called after Temp/Humid reading RMB // Thanks to KFricke for micropython-hdc1008 example on GitHub boolean Adafruit_HDC1000::batteryLOW(void) { // access private variable battLOW = (read16(HDC1000_CONFIG_BATT, 20)); battLOW &= HDC1000_CONFIG_BATT; // mask off other bits, bit 11 will be 1 if voltage < 2.8V if (battLOW> 0) return true; return false; } /*********************************************************************/ uint16_t Adafruit_HDC1000::read16(uint8_t a, uint8_t d) { Wire.beginTransmission(_i2caddr); Wire.write(a); Wire.endTransmission(); delay(d); Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)2); uint16_t r = Wire.read(); r <<= 8; r |= Wire.read(); //Serial.println(r, HEX); return r; } uint32_t Adafruit_HDC1000::read32(uint8_t a, uint8_t d) { Wire.beginTransmission(_i2caddr); Wire.write(a); Wire.endTransmission(); // delay was hardcoded as 50, should use d RMB delay(d); Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)4); uint32_t r = Wire.read(); // assembles temp into highest 16 bits, humidity into lowest 16 bits r <<= 8; r |= Wire.read(); r <<= 8; r |= Wire.read(); r <<= 8; r |= Wire.read(); //Serial.println(r, HEX); return r; } <commit_msg>batteryLOW() corrected HDC1000_CONFIG<commit_after>/*************************************************** This is a library for the HDC1000 Humidity & Temp Sensor Designed specifically to work with the HDC1008 sensor from Adafruit ----> https://www.adafruit.com/products/2635 These sensors use I2C to communicate, 2 pins are required to interface Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried/Ladyada for Adafruit Industries. BSD license, all text above must be included in any redistribution Modified for Photon needs application.h for types RMB ****************************************************/ #include "application.h" #include "Adafruit_HDC1000/Adafruit_HDC1000.h" Adafruit_HDC1000::Adafruit_HDC1000() { } boolean Adafruit_HDC1000::begin(uint8_t addr) { _i2caddr = addr; Wire.begin(); reset(); if (read16(HDC1000_MANUFID) != 0x5449) return false; if (read16(HDC1000_DEVICEID) != 0x1000) return false; return true; } void Adafruit_HDC1000::reset(void) { // reset,combined temp/humidity measurement,and select 14 bit temp & humidity resolution uint16_t config = HDC1000_CONFIG_RST | HDC1000_CONFIG_MODE | HDC1000_CONFIG_TRES_14 | HDC1000_CONFIG_HRES_14; Wire.beginTransmission(_i2caddr); Wire.write(HDC1000_CONFIG); // set pointer register to configuration register RMB Wire.write(config>>8); // now write out 2 bytes MSB first RMB Wire.write(config&0xFF); Wire.endTransmission(); delay(15); } float Adafruit_HDC1000::readTemperature(void) { float temp = (read32(HDC1000_TEMP, 20) >> 16); temp /= 65536; temp *= 165; temp -= 40; return temp; } float Adafruit_HDC1000::readHumidity(void) { // reads both temp and humidity but masks out temp in highest 16 bits // originally used hum but humidity declared in private section of class float humidity = (read32(HDC1000_TEMP, 20) & 0xFFFF); humidity /= 65536; humidity *= 100; return humidity; } void Adafruit_HDC1000::ReadTempHumidity(void) { // HDC1008 setup to measure both temperature and humidity in one conversion // this is a different way to access data in ONE read // this sets internal private variables that can be accessed by Get() functions uint32_t rt,rh ; // working variables rt = read32(HDC1000_TEMP, 20); // get temp and humidity reading together rh = rt; // save a copy for humidity processing // important to use ( ) around temp so private variable accessed and float cast done float (temp = (rt >> 16)); // convert to temp first temp /= 65536; temp *= 165; temp -= 40; // important to use ( ) around humidity so private variable accessed and float cast done float (humidity = (rh & 0xFFFF)); // now convert to humidity humidity /= 65536; humidity *= 100; } float Adafruit_HDC1000::GetTemperature(void) { // getter function to access private temp variable return temp ; } float Adafruit_HDC1000::GetHumidity(void) { // getter function to access private humidity variable return humidity ; } // Add ability to test battery voltage, useful in remote monitoring, TRUE if <2.8V // usually called after Temp/Humid reading RMB // Thanks to KFricke for micropython-hdc1008 example on GitHub boolean Adafruit_HDC1000::batteryLOW(void) { // access private variable battLOW = (read16(HDC1000_CONFIG, 20)); battLOW &= HDC1000_CONFIG_BATT; // mask off other bits, bit 11 will be 1 if voltage < 2.8V if (battLOW> 0) return true; return false; } /*********************************************************************/ uint16_t Adafruit_HDC1000::read16(uint8_t a, uint8_t d) { Wire.beginTransmission(_i2caddr); Wire.write(a); Wire.endTransmission(); delay(d); Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)2); uint16_t r = Wire.read(); r <<= 8; r |= Wire.read(); //Serial.println(r, HEX); return r; } uint32_t Adafruit_HDC1000::read32(uint8_t a, uint8_t d) { Wire.beginTransmission(_i2caddr); Wire.write(a); Wire.endTransmission(); // delay was hardcoded as 50, should use d RMB delay(d); Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)4); uint32_t r = Wire.read(); // assembles temp into highest 16 bits, humidity into lowest 16 bits r <<= 8; r |= Wire.read(); r <<= 8; r |= Wire.read(); r <<= 8; r |= Wire.read(); //Serial.println(r, HEX); return r; } <|endoftext|>
<commit_before>// ProgStatusBar.cpp : ʵļ // #include "stdafx.h" #include "DacrsUI.h" #include "ProgStatusBar.h" #include "afxdialogex.h" // CProgStatusBar Ի IMPLEMENT_DYNAMIC(CProgStatusBar, CDialogBar) CProgStatusBar::CProgStatusBar() { m_pBmp = NULL ; m_bProgressType = false; m_prosshiden = false; m_ProgressWnd = NULL ; m_nSigIndex = 0 ; m_walletui = false; memset(m_bmpsig , 0 , sizeof(CRect)); m_progress.ShowPercent(FALSE); m_progress.ShowDefineText(TRUE); } CProgStatusBar::~CProgStatusBar() { if( NULL != m_pBmp ) { DeleteObject(m_pBmp) ; m_pBmp = NULL ; } if ( NULL != m_ProgressWnd ) { delete m_ProgressWnd ; m_ProgressWnd = NULL ; } } void CProgStatusBar::DoDataExchange(CDataExchange* pDX) { CDialogBar::DoDataExchange(pDX); DDX_Control(pDX, IDC_PROGRESS, m_progress); DDX_Control(pDX, IDC_STATIC_NET_TB, m_strNeting); DDX_Control(pDX, IDC_STATIC_HEIGHT, m_strHeight); DDX_Control(pDX, IDC_STATIC_VERSION, m_strVersion); } BEGIN_MESSAGE_MAP(CProgStatusBar, CDialogBar) ON_WM_ERASEBKGND() ON_WM_CREATE() ON_WM_SIZE() ON_MESSAGE(MSG_USER_UP_PROGRESS , &CProgStatusBar::OnShowProgressCtrl ) ON_WM_PAINT() END_MESSAGE_MAP() // CProgStatusBar Ϣ void CProgStatusBar::SetBkBmpNid( UINT nBitmapIn ) { if( NULL != m_pBmp ) { ::DeleteObject( m_pBmp ) ; m_pBmp = NULL ; } m_pBmp = NULL ; HINSTANCE hInstResource = NULL; hInstResource = AfxFindResourceHandle(MAKEINTRESOURCE(nBitmapIn), RT_BITMAP); if( NULL != hInstResource ) { m_pBmp = (HBITMAP)::LoadImage(hInstResource, MAKEINTRESOURCE(nBitmapIn), IMAGE_BITMAP, 0, 0, 0); } } void CProgStatusBar::LoadGifing( BOOL bState ) { if( NULL != m_ProgressWnd ) { if( m_ProgressWnd->GetSafeHwnd() ) { if( TRUE == bState ) { if( TRUE == ((CGIFControl*)m_ProgressWnd)->Load(theApp.m_ProgressGifFile.GetBuffer()) ) { CRect rc ; GetClientRect( rc ) ; Invalidate() ; m_ProgressWnd->SetWindowPos( NULL , rc.Width()- 18 , (rc.Height()/2)-8 , 0 , 0 , \ SWP_SHOWWINDOW|SWP_NOSIZE ) ; ((CGIFControl*)m_ProgressWnd)->Play(); } }else{ ((CGIFControl*)m_ProgressWnd)->Stop() ; } } } } BOOL CProgStatusBar::OnEraseBkgnd(CDC* pDC) { // TODO: ڴϢ/Ĭֵ CRect rect; GetClientRect(&rect); if(m_pBmp != NULL) { BITMAP bm; CDC dcMem; ::GetObject(m_pBmp,sizeof(BITMAP), (LPVOID)&bm); dcMem.CreateCompatibleDC(NULL); HBITMAP pOldBitmap =(HBITMAP ) dcMem.SelectObject(m_pBmp); pDC-> StretchBlt(rect.left,rect.top-1,rect.Width(),rect.Height(), &dcMem, 0, 0,bm.bmWidth-1,bm.bmHeight-1, SRCCOPY); dcMem.SelectObject(pOldBitmap); dcMem.DeleteDC(); } else CWnd::OnEraseBkgnd(pDC); return 1; } int CProgStatusBar::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CDialogBar::OnCreate(lpCreateStruct) == -1) return -1; // TODO: ڴרõĴ SetBkBmpNid( IDB_BITMAP_BAR3 ) ; ModifyStyle(WS_BORDER, 0); ModifyStyleEx(WS_EX_WINDOWEDGE, 0); return 0; } void CProgStatusBar::OnSize(UINT nType, int cx, int cy) { CDialogBar::OnSize(nType, cx, cy); // TODO: ڴ˴Ϣ } BOOL CProgStatusBar::Create(CWnd* pParentWnd, UINT nIDTemplate, UINT nStyle, UINT nID) { // TODO: ڴרô/û BOOL bRes = CDialogBar::Create(pParentWnd, nIDTemplate, nStyle, nID); if ( bRes ) { UpdateData(0); m_strNeting.SetFont(90, _T("")); //ʾʹС m_strNeting.SetTextColor(RGB(255,255,255)); //ɫ // m_strNeting.SetWindowText(_T("ͬ...")); m_strNeting.SetWindowText(_T("ȡ")) ; m_strHeight.SetFont(90, _T("")); //ʾʹС m_strHeight.SetTextColor(RGB(255,255,255)); //ɫ m_strHeight.SetWindowText(_T("߶:")) ; m_strHeight.ShowWindow(SW_HIDE) ; m_strVersion.SetFont(90, _T("")); //ʾʹС m_strVersion.SetTextColor(RGB(255,255,255)); //ɫ m_strVersion.SetWindowText(_T("汾:V1.0.0.6beta")) ; if ( NULL == m_ProgressWnd ) { m_ProgressWnd = new CGIFControl ; m_ProgressWnd->Create(_T("") , WS_CHILD | SS_OWNERDRAW | WS_VISIBLE | SS_NOTIFY , \ CRect(20,20,36,36) , this, 111 ) ; } m_Sigbmp[0].LoadBitmap(IDB_BITMAP_SIG0); m_Sigbmp[1].LoadBitmap(IDB_BITMAP_SIG1); m_Sigbmp[2].LoadBitmap(IDB_BITMAP_SIG2); m_Sigbmp[3].LoadBitmap(IDB_BITMAP_SIG3); theApp.SubscribeMsg( theApp.GetMtHthrdId() , GetSafeHwnd() , MSG_USER_UP_PROGRESS ) ; m_progress.SendMessage(PBM_SETBKCOLOR, 0, RGB(66, 65, 63));//ɫ m_progress.SendMessage(PBM_SETBARCOLOR, 0, RGB(254, 153, 0));//ǰɫ //CPostMsg postmsg(MSG_USER_UP_PROGRESS,0); //theApp.m_MsgQueue.pushFront(postmsg); } return bRes ; } LRESULT CProgStatusBar::OnShowProgressCtrl( WPARAM wParam, LPARAM lParam ) { TRACE("OnShowProgressCtrl:%s\r\n","OnShowProgressCtrl"); CPostMsg postmsg; if (!theApp.m_UimsgQueue.pop(postmsg)) { return 1; } uistruct::BLOCKCHANGED_t pBlockchanged; string strTemp = postmsg.GetData(); pBlockchanged.JsonToStruct(strTemp.c_str()); if (pBlockchanged.tips <= 0) { return 1; } //// blocktip߶ theApp.blocktipheight = pBlockchanged.tips ; if (!m_bProgressType) { m_strNeting.SetWindowText(_T("ͬ...")); m_strNeting.ShowWindow(SW_HIDE); m_strNeting.ShowWindow(SW_SHOW); m_progress.SetRange32( 0 , 100); int setpos = (pBlockchanged.high*1.0/pBlockchanged.tips)*100; setpos = setpos>100?100:setpos; //ýֵ m_progress.SetPos(setpos); CString strText; strText.AppendFormat("ʣ ~%d ûͬ", pBlockchanged.tips-pBlockchanged.high); m_progress.SetDefinedStr(strText); m_bProgressType = TRUE; m_nSigIndex =pBlockchanged.connections>3?3:pBlockchanged.connections; if ((pBlockchanged.tips-pBlockchanged.high)<10 && !m_walletui) { TRACE("ok:%s\r\n","OnShowProgressCtrl"); //// Ǯͬ CPostMsg postblockmsg(MSG_USER_MAIN_UI,WM_UPWALLET); theApp.m_MsgQueue.pushFront(postblockmsg); LoadGifing(false); m_walletui = true; theApp.IsSyncBlock = true; } Invalidate(); //InvalidateRect(m_bmpsig); // return 1; } m_nSigIndex = pBlockchanged.connections>3?3:pBlockchanged.connections; int setpos = (pBlockchanged.high*1.0/pBlockchanged.tips)*100 ; setpos = setpos>100?100:setpos; //ýֵ m_progress.SetPos(setpos); CString strText; strText.AppendFormat("ʣ ~%d ûͬ", pBlockchanged.tips-pBlockchanged.high); m_progress.SetDefinedStr(strText); if ((pBlockchanged.tips-pBlockchanged.high)<10&& !m_walletui) { TRACE("ok:%s\r\n","OnShowProgressCtrl"); //// Ǯͬ CPostMsg postblockmsg(MSG_USER_MAIN_UI,WM_UPWALLET); theApp.m_MsgQueue.pushFront(postblockmsg); LoadGifing(false); m_walletui = true; theApp.IsSyncBlock = true; } if ( m_walletui && !m_prosshiden) { m_strNeting.SetWindowText(_T("ͬ")) ; m_strNeting.ShowWindow(SW_HIDE); m_strNeting.ShowWindow(SW_SHOW); m_progress.ShowWindow(SW_HIDE); if ( NULL != m_ProgressWnd ) { m_ProgressWnd->ShowWindow(SW_HIDE) ; } m_prosshiden = !m_prosshiden ; } if (m_walletui && m_prosshiden) { CString strTips; strTips.Format(_T("ǰ߶:%d") ,pBlockchanged.tips ) ; m_strHeight.SetWindowText(strTips) ; m_strHeight.ShowWindow(SW_HIDE); m_strHeight.ShowWindow(SW_SHOW); } InvalidateRect(m_bmpsig); return 1; } //Invalidate(); void CProgStatusBar::OnPaint() { CPaintDC dc(this); // device context for painting // TODO: ڴ˴Ϣ // ΪͼϢ CDialogBar::OnPaint() CDC memDC; memDC.CreateCompatibleDC(&dc); CRect rc; GetClientRect(&rc); HBITMAP hOldbmp = (HBITMAP)memDC.SelectObject(m_Sigbmp[m_nSigIndex]); dc.BitBlt(900-60, 0, rc.Width(), rc.Height(), &memDC, 0, 0, SRCCOPY); CRect rc1(900-60, 0, rc.Width(), rc.Height()); m_bmpsig = rc1; memDC.SelectObject(hOldbmp); memDC.DeleteDC(); } <commit_msg>修改调整更新动画显示位置<commit_after>// ProgStatusBar.cpp : ʵļ // #include "stdafx.h" #include "DacrsUI.h" #include "ProgStatusBar.h" #include "afxdialogex.h" // CProgStatusBar Ի IMPLEMENT_DYNAMIC(CProgStatusBar, CDialogBar) CProgStatusBar::CProgStatusBar() { m_pBmp = NULL ; m_bProgressType = false; m_prosshiden = false; m_ProgressWnd = NULL ; m_nSigIndex = 0 ; m_walletui = false; memset(m_bmpsig , 0 , sizeof(CRect)); m_progress.ShowPercent(FALSE); m_progress.ShowDefineText(TRUE); } CProgStatusBar::~CProgStatusBar() { if( NULL != m_pBmp ) { DeleteObject(m_pBmp) ; m_pBmp = NULL ; } if ( NULL != m_ProgressWnd ) { delete m_ProgressWnd ; m_ProgressWnd = NULL ; } } void CProgStatusBar::DoDataExchange(CDataExchange* pDX) { CDialogBar::DoDataExchange(pDX); DDX_Control(pDX, IDC_PROGRESS, m_progress); DDX_Control(pDX, IDC_STATIC_NET_TB, m_strNeting); DDX_Control(pDX, IDC_STATIC_HEIGHT, m_strHeight); DDX_Control(pDX, IDC_STATIC_VERSION, m_strVersion); } BEGIN_MESSAGE_MAP(CProgStatusBar, CDialogBar) ON_WM_ERASEBKGND() ON_WM_CREATE() ON_WM_SIZE() ON_MESSAGE(MSG_USER_UP_PROGRESS , &CProgStatusBar::OnShowProgressCtrl ) ON_WM_PAINT() END_MESSAGE_MAP() // CProgStatusBar Ϣ void CProgStatusBar::SetBkBmpNid( UINT nBitmapIn ) { if( NULL != m_pBmp ) { ::DeleteObject( m_pBmp ) ; m_pBmp = NULL ; } m_pBmp = NULL ; HINSTANCE hInstResource = NULL; hInstResource = AfxFindResourceHandle(MAKEINTRESOURCE(nBitmapIn), RT_BITMAP); if( NULL != hInstResource ) { m_pBmp = (HBITMAP)::LoadImage(hInstResource, MAKEINTRESOURCE(nBitmapIn), IMAGE_BITMAP, 0, 0, 0); } } void CProgStatusBar::LoadGifing( BOOL bState ) { if( NULL != m_ProgressWnd ) { if( m_ProgressWnd->GetSafeHwnd() ) { if( TRUE == bState ) { if( TRUE == ((CGIFControl*)m_ProgressWnd)->Load(theApp.m_ProgressGifFile.GetBuffer()) ) { CRect rc ; GetClientRect( rc ) ; Invalidate() ; m_ProgressWnd->SetWindowPos( NULL , rc.Width()+880 , rc.Height()+8 , 0 , 0 , \ SWP_SHOWWINDOW|SWP_NOSIZE ) ; ((CGIFControl*)m_ProgressWnd)->Play(); } }else{ ((CGIFControl*)m_ProgressWnd)->Stop() ; } } } } BOOL CProgStatusBar::OnEraseBkgnd(CDC* pDC) { // TODO: ڴϢ/Ĭֵ CRect rect; GetClientRect(&rect); if(m_pBmp != NULL) { BITMAP bm; CDC dcMem; ::GetObject(m_pBmp,sizeof(BITMAP), (LPVOID)&bm); dcMem.CreateCompatibleDC(NULL); HBITMAP pOldBitmap =(HBITMAP ) dcMem.SelectObject(m_pBmp); pDC-> StretchBlt(rect.left,rect.top-1,rect.Width(),rect.Height(), &dcMem, 0, 0,bm.bmWidth-1,bm.bmHeight-1, SRCCOPY); dcMem.SelectObject(pOldBitmap); dcMem.DeleteDC(); } else CWnd::OnEraseBkgnd(pDC); return 1; } int CProgStatusBar::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CDialogBar::OnCreate(lpCreateStruct) == -1) return -1; // TODO: ڴרõĴ SetBkBmpNid( IDB_BITMAP_BAR3 ) ; ModifyStyle(WS_BORDER, 0); ModifyStyleEx(WS_EX_WINDOWEDGE, 0); return 0; } void CProgStatusBar::OnSize(UINT nType, int cx, int cy) { CDialogBar::OnSize(nType, cx, cy); // TODO: ڴ˴Ϣ } BOOL CProgStatusBar::Create(CWnd* pParentWnd, UINT nIDTemplate, UINT nStyle, UINT nID) { // TODO: ڴרô/û BOOL bRes = CDialogBar::Create(pParentWnd, nIDTemplate, nStyle, nID); if ( bRes ) { UpdateData(0); m_strNeting.SetFont(90, _T("")); //ʾʹС m_strNeting.SetTextColor(RGB(255,255,255)); //ɫ // m_strNeting.SetWindowText(_T("ͬ...")); m_strNeting.SetWindowText(_T("ȡ")) ; m_strHeight.SetFont(90, _T("")); //ʾʹС m_strHeight.SetTextColor(RGB(255,255,255)); //ɫ m_strHeight.SetWindowText(_T("߶:")) ; m_strHeight.ShowWindow(SW_HIDE) ; m_strVersion.SetFont(90, _T("")); //ʾʹС m_strVersion.SetTextColor(RGB(255,255,255)); //ɫ m_strVersion.SetWindowText(_T("汾:V1.0.0.6beta")) ; if ( NULL == m_ProgressWnd ) { m_ProgressWnd = new CGIFControl ; m_ProgressWnd->Create(_T("") , WS_CHILD | SS_OWNERDRAW | WS_VISIBLE | SS_NOTIFY , \ CRect(20,20,36,36) , this, 111 ) ; } m_Sigbmp[0].LoadBitmap(IDB_BITMAP_SIG0); m_Sigbmp[1].LoadBitmap(IDB_BITMAP_SIG1); m_Sigbmp[2].LoadBitmap(IDB_BITMAP_SIG2); m_Sigbmp[3].LoadBitmap(IDB_BITMAP_SIG3); theApp.SubscribeMsg( theApp.GetMtHthrdId() , GetSafeHwnd() , MSG_USER_UP_PROGRESS ) ; m_progress.SendMessage(PBM_SETBKCOLOR, 0, RGB(66, 65, 63));//ɫ m_progress.SendMessage(PBM_SETBARCOLOR, 0, RGB(254, 153, 0));//ǰɫ LoadGifing(TRUE); //CPostMsg postmsg(MSG_USER_UP_PROGRESS,0); //theApp.m_MsgQueue.pushFront(postmsg); } return bRes ; } LRESULT CProgStatusBar::OnShowProgressCtrl( WPARAM wParam, LPARAM lParam ) { TRACE("OnShowProgressCtrl:%s\r\n","OnShowProgressCtrl"); CPostMsg postmsg; if (!theApp.m_UimsgQueue.pop(postmsg)) { return 1; } uistruct::BLOCKCHANGED_t pBlockchanged; string strTemp = postmsg.GetData(); pBlockchanged.JsonToStruct(strTemp.c_str()); if (pBlockchanged.tips <= 0) { return 1; } //// blocktip߶ theApp.blocktipheight = pBlockchanged.tips ; if (!m_bProgressType) { m_strNeting.SetWindowText(_T("ͬ...")); m_strNeting.ShowWindow(SW_HIDE); m_strNeting.ShowWindow(SW_SHOW); m_progress.SetRange32( 0 , 100); int setpos = (pBlockchanged.high*1.0/pBlockchanged.tips)*100; setpos = setpos>100?100:setpos; //ýֵ m_progress.SetPos(setpos); CString strText; strText.AppendFormat("ʣ ~%d ûͬ", pBlockchanged.tips-pBlockchanged.high); m_progress.SetDefinedStr(strText); m_bProgressType = TRUE; m_nSigIndex =pBlockchanged.connections>3?3:pBlockchanged.connections; if ((pBlockchanged.tips-pBlockchanged.high)<10 && !m_walletui) { TRACE("ok:%s\r\n","OnShowProgressCtrl"); //// Ǯͬ CPostMsg postblockmsg(MSG_USER_MAIN_UI,WM_UPWALLET); theApp.m_MsgQueue.pushFront(postblockmsg); LoadGifing(false); m_walletui = true; theApp.IsSyncBlock = true; } Invalidate(); //InvalidateRect(m_bmpsig); // return 1; } m_nSigIndex = pBlockchanged.connections>3?3:pBlockchanged.connections; int setpos = (pBlockchanged.high*1.0/pBlockchanged.tips)*100 ; setpos = setpos>100?100:setpos; //ýֵ m_progress.SetPos(setpos); CString strText; strText.AppendFormat("ʣ ~%d ûͬ", pBlockchanged.tips-pBlockchanged.high); m_progress.SetDefinedStr(strText); if ((pBlockchanged.tips-pBlockchanged.high)<10&& !m_walletui) { TRACE("ok:%s\r\n","OnShowProgressCtrl"); //// Ǯͬ CPostMsg postblockmsg(MSG_USER_MAIN_UI,WM_UPWALLET); theApp.m_MsgQueue.pushFront(postblockmsg); LoadGifing(false); m_walletui = true; theApp.IsSyncBlock = true; } if ( m_walletui && !m_prosshiden) { m_strNeting.SetWindowText(_T("ͬ")) ; m_strNeting.ShowWindow(SW_HIDE); m_strNeting.ShowWindow(SW_SHOW); m_progress.ShowWindow(SW_HIDE); if ( NULL != m_ProgressWnd ) { m_ProgressWnd->ShowWindow(SW_HIDE) ; } m_prosshiden = !m_prosshiden ; } if (m_walletui && m_prosshiden) { CString strTips; strTips.Format(_T("ǰ߶:%d") ,pBlockchanged.tips ) ; m_strHeight.SetWindowText(strTips) ; m_strHeight.ShowWindow(SW_HIDE); m_strHeight.ShowWindow(SW_SHOW); } InvalidateRect(m_bmpsig); return 1; } //Invalidate(); void CProgStatusBar::OnPaint() { CPaintDC dc(this); // device context for painting // TODO: ڴ˴Ϣ // ΪͼϢ CDialogBar::OnPaint() CDC memDC; memDC.CreateCompatibleDC(&dc); CRect rc; GetClientRect(&rc); HBITMAP hOldbmp = (HBITMAP)memDC.SelectObject(m_Sigbmp[m_nSigIndex]); dc.BitBlt(900-60, 0, rc.Width(), rc.Height(), &memDC, 0, 0, SRCCOPY); CRect rc1(900-60, 0, rc.Width(), rc.Height()); m_bmpsig = rc1; memDC.SelectObject(hOldbmp); memDC.DeleteDC(); } <|endoftext|>
<commit_before>#include <algorithm> #include <fmo/assert.hpp> #include <fmo/image.hpp> #include <opencv2/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/imgproc.hpp> namespace fmo { namespace { /// Get the number of bytes of data that an image requires, given its format and dimensions. size_t getNumBytes(Format format, Dims dims) { size_t result = static_cast<size_t>(dims.width) * static_cast<size_t>(dims.height); switch (format) { case Format::BGR: result *= 3; break; case Format::GRAY: break; case Format::YUV420SP: result = (result * 3) / 2; break; default: throw std::runtime_error("getNumBytes: unsupported format"); } return result; } /// Convert the actual dimensions to the size that is used by OpenCV. OpenCV considers YUV /// 4:2:0 SP images 1.5x taller. cv::Size getCvSize(Format format, Dims dims) { cv::Size result{dims.width, dims.height}; switch (format) { case Format::BGR: case Format::GRAY: break; case Format::YUV420SP: result.height = (result.height * 3) / 2; break; default: throw std::runtime_error("getCvSize: unsupported format"); } return result; } /// Convert the size used by OpenCV to the actual dimensions. OpenCV considers YUV 4:2:0 SP /// images 1.5x taller. Dims getDims(Format format, cv::Size size) { Dims result{size.width, size.height}; switch (format) { case Format::BGR: case Format::GRAY: break; case Format::YUV420SP: result.height = (result.height * 2) / 3; break; default: throw std::runtime_error("getImageSize: unsupported format"); } return result; } /// Get the Mat data type used by OpenCV that corresponds to the format. int getCvType(Format format) { switch (format) { case Format::BGR: return CV_8UC3; case Format::GRAY: case Format::YUV420SP: return CV_8UC1; default: throw std::runtime_error("getCvType: unsupported format"); } } } Image::Image(const std::string& filename, Format format) { cv::Mat mat; switch (format) { case Format::BGR: mat = cv::imread(filename, cv::IMREAD_COLOR); break; case Format::GRAY: mat = cv::imread(filename, cv::IMREAD_GRAYSCALE); break; default: throw std::runtime_error("reading image: unsupported format"); break; } if (mat.data == nullptr) { throw std::runtime_error("failed to open image"); } FMO_ASSERT(mat.isContinuous(), "reading image: not continuous") FMO_ASSERT(mat.type() == getCvType(format), "reading image: unexpected mat type"); Dims dims = getDims(format, mat.size()); size_t bytes = mat.elemSize() * mat.total(); FMO_ASSERT(getNumBytes(format, dims) == bytes, "reading image: unexpected size"); mData.resize(bytes); std::copy(mat.data, mat.data + mData.size(), mData.data()); mFormat = format; mDims = dims; } void Image::assign(Format format, Dims dims, const uint8_t* data) { size_t bytes = getNumBytes(format, dims); mData.resize(bytes); mDims = dims; mFormat = format; std::copy(data, data + bytes, mData.data()); } void Image::resize(Format format, Dims dims) { size_t bytes = getNumBytes(format, dims); mData.resize(bytes); mDims = dims; mFormat = format; } cv::Mat Image::wrap() { return cv::Mat{getCvSize(mFormat, mDims), getCvType(mFormat), mData.data()}; } cv::Mat Image::wrap() const { auto* ptr = const_cast<uint8_t*>(mData.data()); return cv::Mat{getCvSize(mFormat, mDims), getCvType(mFormat), ptr}; } void convert(const Mat& src, Mat& dst, Format format) { if (src.format() == format) { // no format change -- just copy throw std::runtime_error("not implemented"); return; } if (&src == &dst) { if (src.format() == format) { // same instance and no format change: no-op return; } if (src.format() == Format::YUV420SP && format == Format::GRAY) { // same instance and converting YUV420SP to GRAY: easy case dst.resize(Format::GRAY, dst.dims()); return; } // same instance: convert into a new, temporary Image, then move into dst Image temp; convert(src, temp, format); dst = std::move(temp); return; } enum { ERROR = -1 }; int code = ERROR; dst.resize(format, src.dims()); cv::Mat srcMat = src.wrap(); cv::Mat dstMat = dst.wrap(); const auto srcFormat = src.format(); const auto dstFormat = format; if (srcFormat == Format::BGR) { if (dstFormat == Format::GRAY) { code = cv::COLOR_BGR2GRAY; } } else if (srcFormat == Format::GRAY) { if (dstFormat == Format::BGR) { code = cv::COLOR_GRAY2BGR; } } else if (srcFormat == Format::YUV420SP) { if (dstFormat == Format::BGR) { code = cv::COLOR_YUV420sp2BGR; } else if (dstFormat == Format::GRAY) { code = cv::COLOR_YUV420sp2GRAY; } } if (code == ERROR) { throw std::runtime_error("convert: failed to perform color conversion"); } cv::cvtColor(srcMat, dstMat, code); FMO_ASSERT(dstMat.data == dst.wrap().data, "convert: dst buffer reallocated"); } } <commit_msg>Use format constants in convert()<commit_after>#include <algorithm> #include <fmo/assert.hpp> #include <fmo/image.hpp> #include <opencv2/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/imgproc.hpp> namespace fmo { namespace { /// Get the number of bytes of data that an image requires, given its format and dimensions. size_t getNumBytes(Format format, Dims dims) { size_t result = static_cast<size_t>(dims.width) * static_cast<size_t>(dims.height); switch (format) { case Format::BGR: result *= 3; break; case Format::GRAY: break; case Format::YUV420SP: result = (result * 3) / 2; break; default: throw std::runtime_error("getNumBytes: unsupported format"); } return result; } /// Convert the actual dimensions to the size that is used by OpenCV. OpenCV considers YUV /// 4:2:0 SP images 1.5x taller. cv::Size getCvSize(Format format, Dims dims) { cv::Size result{dims.width, dims.height}; switch (format) { case Format::BGR: case Format::GRAY: break; case Format::YUV420SP: result.height = (result.height * 3) / 2; break; default: throw std::runtime_error("getCvSize: unsupported format"); } return result; } /// Convert the size used by OpenCV to the actual dimensions. OpenCV considers YUV 4:2:0 SP /// images 1.5x taller. Dims getDims(Format format, cv::Size size) { Dims result{size.width, size.height}; switch (format) { case Format::BGR: case Format::GRAY: break; case Format::YUV420SP: result.height = (result.height * 2) / 3; break; default: throw std::runtime_error("getImageSize: unsupported format"); } return result; } /// Get the Mat data type used by OpenCV that corresponds to the format. int getCvType(Format format) { switch (format) { case Format::BGR: return CV_8UC3; case Format::GRAY: case Format::YUV420SP: return CV_8UC1; default: throw std::runtime_error("getCvType: unsupported format"); } } } Image::Image(const std::string& filename, Format format) { cv::Mat mat; switch (format) { case Format::BGR: mat = cv::imread(filename, cv::IMREAD_COLOR); break; case Format::GRAY: mat = cv::imread(filename, cv::IMREAD_GRAYSCALE); break; default: throw std::runtime_error("reading image: unsupported format"); break; } if (mat.data == nullptr) { throw std::runtime_error("failed to open image"); } FMO_ASSERT(mat.isContinuous(), "reading image: not continuous") FMO_ASSERT(mat.type() == getCvType(format), "reading image: unexpected mat type"); Dims dims = getDims(format, mat.size()); size_t bytes = mat.elemSize() * mat.total(); FMO_ASSERT(getNumBytes(format, dims) == bytes, "reading image: unexpected size"); mData.resize(bytes); std::copy(mat.data, mat.data + mData.size(), mData.data()); mFormat = format; mDims = dims; } void Image::assign(Format format, Dims dims, const uint8_t* data) { size_t bytes = getNumBytes(format, dims); mData.resize(bytes); mDims = dims; mFormat = format; std::copy(data, data + bytes, mData.data()); } void Image::resize(Format format, Dims dims) { size_t bytes = getNumBytes(format, dims); mData.resize(bytes); mDims = dims; mFormat = format; } cv::Mat Image::wrap() { return cv::Mat{getCvSize(mFormat, mDims), getCvType(mFormat), mData.data()}; } cv::Mat Image::wrap() const { auto* ptr = const_cast<uint8_t*>(mData.data()); return cv::Mat{getCvSize(mFormat, mDims), getCvType(mFormat), ptr}; } void convert(const Mat& src, Mat& dst, Format format) { const auto srcFormat = src.format(); const auto dstFormat = format; if (srcFormat == dstFormat) { // no format change -- just copy throw std::runtime_error("not implemented"); return; } if (&src == &dst) { if (srcFormat == dstFormat) { // same instance and no format change: no-op return; } if (srcFormat == Format::YUV420SP && dstFormat == Format::GRAY) { // same instance and converting YUV420SP to GRAY: easy case dst.resize(Format::GRAY, dst.dims()); return; } // same instance: convert into a new, temporary Image, then move into dst Image temp; convert(src, temp, dstFormat); dst = std::move(temp); return; } enum { ERROR = -1 }; int code = ERROR; dst.resize(dstFormat, src.dims()); // this is why we check for same instance cv::Mat srcMat = src.wrap(); cv::Mat dstMat = dst.wrap(); if (srcFormat == Format::BGR) { if (dstFormat == Format::GRAY) { code = cv::COLOR_BGR2GRAY; } } else if (srcFormat == Format::GRAY) { if (dstFormat == Format::BGR) { code = cv::COLOR_GRAY2BGR; } } else if (srcFormat == Format::YUV420SP) { if (dstFormat == Format::BGR) { code = cv::COLOR_YUV420sp2BGR; } else if (dstFormat == Format::GRAY) { code = cv::COLOR_YUV420sp2GRAY; } } if (code == ERROR) { throw std::runtime_error("convert: failed to perform color conversion"); } cv::cvtColor(srcMat, dstMat, code); FMO_ASSERT(dstMat.data == dst.wrap().data, "convert: dst buffer reallocated"); } } <|endoftext|>
<commit_before> /*************************************************************************** jabberregister.cpp - Register dialog for Jabber ------------------- begin : Sun Jul 11 2004 copyright : (C) 2004 by Till Gerken <till@tantalo.net> Kopete (C) 2001-2004 Kopete developers <kopete-devel@kde.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 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "jabberregisteraccount.h" #include <klocale.h> #include <kmessagebox.h> #include <klineedit.h> #include <kpassdlg.h> #include <knuminput.h> #include <kpushbutton.h> #include <qlabel.h> #include <qcheckbox.h> #include <qtimer.h> #include <qregexp.h> #include "qca.h" #include "xmpp.h" #include "xmpp_tasks.h" #include "kopeteuiglobal.h" #include "jabberprotocol.h" #include "jabberaccount.h" #include "jabberconnector.h" #include "jabbereditaccountwidget.h" #include "jabberchooseserver.h" #include "dlgjabberregisteraccount.h" JabberRegisterAccount::JabberRegisterAccount ( JabberEditAccountWidget *parent, const char *name ) : KDialogBase ( parent, name, true, i18n("Register New Jabber Account"), KDialogBase::Ok | KDialogBase::Cancel ) { mParentWidget = parent; // setup main dialog mMainWidget = new DlgJabberRegisterAccount ( this ); setMainWidget ( mMainWidget ); // replace "Ok" button with a "Register" button KGuiItem registerButton = KStdGuiItem::ok(); registerButton.setText ( i18n ( "Register" ) ); setButtonOK ( registerButton ); enableButtonSeparator ( true ); // clear variables jabberTLS = 0L; jabberTLSHandler = 0L; jabberClientConnector = 0L; jabberClientStream = 0L; jabberClient = 0L; jidRegExp.setPattern ( "[\\w\\d.+_-]{1,}@[\\w\\d.-]{1,}" ); // get all settings from the main dialog mMainWidget->leServer->setText ( parent->mServer->text () ); mMainWidget->leJID->setText ( parent->mID->text () ); mMainWidget->lePassword->setText ( parent->mPass->text () ); mMainWidget->lePasswordVerify->setText ( parent->mPass->text () ); mMainWidget->sbPort->setValue ( parent->mPort->value () ); mMainWidget->cbUseSSL->setChecked ( parent->cbUseSSL->isChecked () ); // connect buttons to slots, ok is already connected by default connect ( this, SIGNAL ( cancelClicked () ), this, SLOT ( slotDeleteDialog () ) ); connect ( mMainWidget->btnChooseServer, SIGNAL ( clicked () ), this, SLOT ( slotChooseServer () ) ); connect ( mMainWidget->leServer, SIGNAL ( textChanged ( const QString & ) ), this, SLOT ( slotJIDInformation () ) ); connect ( mMainWidget->leJID, SIGNAL ( textChanged ( const QString & ) ), this, SLOT ( slotJIDInformation () ) ); connect ( mMainWidget->cbUseSSL, SIGNAL ( toggled ( bool ) ), this, SLOT ( slotSSLToggled () ) ); // display JID info now slotJIDInformation (); } JabberRegisterAccount::~JabberRegisterAccount() { } void JabberRegisterAccount::slotDeleteDialog () { deleteLater (); } bool JabberRegisterAccount::validateData () { if ( !jidRegExp.exactMatch ( mMainWidget->leJID->text() ) ) { KMessageBox::sorry(this, i18n("The Jabber ID you have chosen is invalid. " "Please make sure it is in the form user@server.com, like an email address."), i18n("Invalid Jabber ID")); mMainWidget->lblStatusMessage->setText ( i18n ( "Please correct your Jabber ID." ) ); return false; } if ( QString::fromLatin1 ( mMainWidget->lePassword->password () ) != QString::fromLatin1 ( mMainWidget->lePasswordVerify->password () ) ) { KMessageBox::sorry(this, i18n("The passwords do not match. Please enter them again."), i18n("Jabber Passwords do not match")); mMainWidget->lblStatusMessage->setText ( i18n ( "Please enter your password again." ) ); return false; } return true; } void JabberRegisterAccount::slotJIDInformation () { if ( !mMainWidget->leServer->text().isEmpty () && ( !jidRegExp.exactMatch ( mMainWidget->leJID->text () ) || ( mMainWidget->leJID->text().section ( "@", 1 ) != mMainWidget->leServer->text () ) ) ) { mMainWidget->lblJIDInformation->setText ( i18n ( "Unless you know what you are doing, your JID should be of the form " "\"user@server.com\", in your case for example \"user@%1\"." ). arg ( mMainWidget->leServer->text () ) ); } else { mMainWidget->lblJIDInformation->setText ( "" ); } } void JabberRegisterAccount::slotSSLToggled () { if ( mMainWidget->cbUseSSL->isChecked () ) { if ( mMainWidget->sbPort->value () == 5222 ) { mMainWidget->sbPort->setValue ( 5223 ); } } else { if ( mMainWidget->sbPort->value () == 5223 ) { mMainWidget->sbPort->setValue ( 5222 ); } } } void JabberRegisterAccount::slotChooseServer () { (new JabberChooseServer ( this ))->show (); } void JabberRegisterAccount::setServer ( const QString &server ) { mMainWidget->leServer->setText ( server ); } void JabberRegisterAccount::slotOk () { mMainWidget->lblStatusMessage->setText ( "" ); if ( !validateData () ) return; kdDebug ( JABBER_DEBUG_GLOBAL ) << k_funcinfo << "Registering a new Jabber account." << endl; enableButtonOK ( false ); mMainWidget->lblStatusMessage->setText ( i18n ( "Connecting to server..." ) ); /* * Check for SSL availability first */ bool trySSL = false; if ( mMainWidget->cbUseSSL->isChecked () ) { bool sslPossible = QCA::isSupported(QCA::CAP_TLS); if (!sslPossible) { KMessageBox::queuedMessageBox(Kopete::UI::Global::mainWidget (), KMessageBox::Error, i18n ("SSL support could not be initialized for account %1. This is most likely because the QCA TLS plugin is not installed on your system."). arg(mMainWidget->leJID->text()), i18n ("Jabber SSL Error")); return; } else { trySSL = true; } } /* * Instantiate connector, responsible for dealing with the socket. * This class uses KDE's socket code, which in turn makes use of * the global proxy settings. */ jabberClientConnector = new JabberConnector; jabberClientConnector->setOptHostPort ( mMainWidget->leServer->text (), mMainWidget->sbPort->value () ); jabberClientConnector->setOptSSL(trySSL); /* * Setup authentication layer */ if ( trySSL ) { jabberTLS = new QCA::TLS; jabberTLSHandler = new XMPP::QCATLSHandler(jabberTLS); { using namespace XMPP; QObject::connect(jabberTLSHandler, SIGNAL(tlsHandshaken()), this, SLOT(slotTLSHandshaken())); } } /* * Instantiate client stream which handles the network communication by referring * to a connector (proxying etc.) and a TLS handler (security layer) */ jabberClientStream = new XMPP::ClientStream(jabberClientConnector, jabberTLSHandler); { using namespace XMPP; QObject::connect (jabberClientStream, SIGNAL (authenticated()), this, SLOT (slotCSAuthenticated ())); QObject::connect (jabberClientStream, SIGNAL (warning (int)), this, SLOT (slotCSWarning ())); QObject::connect (jabberClientStream, SIGNAL (error (int)), this, SLOT (slotCSError (int))); } /* * FIXME: This is required until we fully support XMPP 1.0 * Upon switching to XMPP 1.0, add full TLS capabilities * with fallback (setOptProbe()) and remove the call below. */ jabberClientStream->setOldOnly(true); /* * Initiate anti-idle timer (will be triggered every 55 seconds). */ jabberClientStream->setNoopTime(55000); jabberClient = new XMPP::Client (this); /* * Start connection, no authentication */ jabberClient->connectToServer (jabberClientStream, XMPP::Jid(mMainWidget->leJID->text ()), false); } void JabberRegisterAccount::cleanup () { delete jabberClient; delete jabberClientStream; delete jabberClientConnector; delete jabberTLSHandler; delete jabberTLS; jabberTLS = 0L; jabberTLSHandler = 0L; jabberClientConnector = 0L; jabberClientStream = 0L; jabberClient = 0L; } void JabberRegisterAccount::disconnect () { if(jabberClient) jabberClient->close(true); cleanup (); enableButtonOK ( true ); } void JabberRegisterAccount::slotTLSHandshaken () { kdDebug(JABBER_DEBUG_GLOBAL) << k_funcinfo << "TLS handshake done, testing certificate validity..." << endl; mMainWidget->lblStatusMessage->setText ( i18n ( "Security handshake..." ) ); int validityResult = jabberTLS->certificateValidityResult (); if(validityResult == QCA::TLS::Valid) { kdDebug(JABBER_DEBUG_GLOBAL) << k_funcinfo << "Certificate is valid, continuing." << endl; // valid certificate, continue jabberTLSHandler->continueAfterHandshake (); } else { kdDebug(JABBER_DEBUG_GLOBAL) << k_funcinfo << "Certificate is not valid, asking user what to do next." << endl; // certificate is not valid, query the user if(JabberAccount::handleTLSWarning (validityResult, mMainWidget->leServer->text (), mMainWidget->leJID->text ()) == KMessageBox::Continue) { jabberTLSHandler->continueAfterHandshake (); } else { mMainWidget->lblStatusMessage->setText ( i18n ( "Security handshake failed." ) ); disconnect (); } } } void JabberRegisterAccount::slotCSWarning () { // FIXME: with the next synch point of Iris, this should // have become a slot, so simply connect it through. jabberClientStream->continueAfterWarning (); } void JabberRegisterAccount::slotCSError (int error) { kdDebug(JABBER_DEBUG_GLOBAL) << k_funcinfo << "Error in stream signalled, disconnecting." << endl; KopeteAccount::DisconnectReason errorClass; mMainWidget->lblStatusMessage->setText ( i18n ( "Protocol error." ) ); // display message to user JabberAccount::handleStreamError (error, jabberClientStream->errorCondition (), jabberClientConnector->errorCode (), mMainWidget->leServer->text (), errorClass); disconnect (); } void JabberRegisterAccount::slotCSAuthenticated () { kdDebug (JABBER_DEBUG_GLOBAL) << k_funcinfo << "Launching registration task..." << endl; mMainWidget->lblStatusMessage->setText ( i18n ( "Authentication successful, registering new account..." ) ); /* start the client operation */ XMPP::Jid jid(mMainWidget->leJID->text ()); jabberClient->start ( jid.domain (), jid.node (), "", "" ); XMPP::JT_Register * task = new XMPP::JT_Register (jabberClient->rootTask ()); QObject::connect (task, SIGNAL (finished ()), this, SLOT (slotRegisterUserDone ())); task->reg (mMainWidget->leJID->text().section("@", 0, 0), mMainWidget->lePassword->password ()); task->go (true); } void JabberRegisterAccount::slotRegisterUserDone () { XMPP::JT_Register * task = (XMPP::JT_Register *) sender (); if (task->success ()) { mMainWidget->lblStatusMessage->setText ( i18n ( "Registration successful." ) ); KMessageBox::information (Kopete::UI::Global::mainWidget (), i18n ("Account successfully registered."), i18n ("Jabber Account Registration")); // save settings to parent mParentWidget->mServer->setText ( mMainWidget->leServer->text () ); mParentWidget->mID->setText ( mMainWidget->leJID->text () ); mParentWidget->mPass->setText ( mMainWidget->lePassword->text () ); mParentWidget->mPort->setValue ( mMainWidget->sbPort->value () ); mParentWidget->cbUseSSL->setChecked ( mMainWidget->cbUseSSL->isChecked () ); // FIXME: this is required because Iris crashes if we try // to disconnect here. Hopefully Justin can fix this. QTimer::singleShot(0, this, SLOT(disconnect ())); slotDeleteDialog (); } else { mMainWidget->lblStatusMessage->setText ( i18n ( "Registration failed." ) ); KMessageBox::information (Kopete::UI::Global::mainWidget (), i18n ("Unable to create account on the server. The Jabber ID probably already exists."), i18n ("Jabber Account Registration")); // FIXME: this is required because Iris crashes if we try // to disconnect here. Hopefully Justin can fix this. QTimer::singleShot(0, this, SLOT(disconnect ())); } } #include "jabberregisteraccount.moc" <commit_msg>It still crashes... Iris doesn't like error handling in a slot.<commit_after> /*************************************************************************** jabberregister.cpp - Register dialog for Jabber ------------------- begin : Sun Jul 11 2004 copyright : (C) 2004 by Till Gerken <till@tantalo.net> Kopete (C) 2001-2004 Kopete developers <kopete-devel@kde.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 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "jabberregisteraccount.h" #include <klocale.h> #include <kmessagebox.h> #include <klineedit.h> #include <kpassdlg.h> #include <knuminput.h> #include <kpushbutton.h> #include <qlabel.h> #include <qcheckbox.h> #include <qtimer.h> #include <qregexp.h> #include "qca.h" #include "xmpp.h" #include "xmpp_tasks.h" #include "kopeteuiglobal.h" #include "jabberprotocol.h" #include "jabberaccount.h" #include "jabberconnector.h" #include "jabbereditaccountwidget.h" #include "jabberchooseserver.h" #include "dlgjabberregisteraccount.h" JabberRegisterAccount::JabberRegisterAccount ( JabberEditAccountWidget *parent, const char *name ) : KDialogBase ( parent, name, true, i18n("Register New Jabber Account"), KDialogBase::Ok | KDialogBase::Cancel ) { mParentWidget = parent; // setup main dialog mMainWidget = new DlgJabberRegisterAccount ( this ); setMainWidget ( mMainWidget ); // replace "Ok" button with a "Register" button KGuiItem registerButton = KStdGuiItem::ok(); registerButton.setText ( i18n ( "Register" ) ); setButtonOK ( registerButton ); enableButtonSeparator ( true ); // clear variables jabberTLS = 0L; jabberTLSHandler = 0L; jabberClientConnector = 0L; jabberClientStream = 0L; jabberClient = 0L; jidRegExp.setPattern ( "[\\w\\d.+_-]{1,}@[\\w\\d.-]{1,}" ); // get all settings from the main dialog mMainWidget->leServer->setText ( parent->mServer->text () ); mMainWidget->leJID->setText ( parent->mID->text () ); mMainWidget->lePassword->setText ( parent->mPass->text () ); mMainWidget->lePasswordVerify->setText ( parent->mPass->text () ); mMainWidget->sbPort->setValue ( parent->mPort->value () ); mMainWidget->cbUseSSL->setChecked ( parent->cbUseSSL->isChecked () ); // connect buttons to slots, ok is already connected by default connect ( this, SIGNAL ( cancelClicked () ), this, SLOT ( slotDeleteDialog () ) ); connect ( mMainWidget->btnChooseServer, SIGNAL ( clicked () ), this, SLOT ( slotChooseServer () ) ); connect ( mMainWidget->leServer, SIGNAL ( textChanged ( const QString & ) ), this, SLOT ( slotJIDInformation () ) ); connect ( mMainWidget->leJID, SIGNAL ( textChanged ( const QString & ) ), this, SLOT ( slotJIDInformation () ) ); connect ( mMainWidget->cbUseSSL, SIGNAL ( toggled ( bool ) ), this, SLOT ( slotSSLToggled () ) ); // display JID info now slotJIDInformation (); } JabberRegisterAccount::~JabberRegisterAccount() { } void JabberRegisterAccount::slotDeleteDialog () { deleteLater (); } bool JabberRegisterAccount::validateData () { if ( !jidRegExp.exactMatch ( mMainWidget->leJID->text() ) ) { KMessageBox::sorry(this, i18n("The Jabber ID you have chosen is invalid. " "Please make sure it is in the form user@server.com, like an email address."), i18n("Invalid Jabber ID")); mMainWidget->lblStatusMessage->setText ( i18n ( "Please correct your Jabber ID." ) ); return false; } if ( QString::fromLatin1 ( mMainWidget->lePassword->password () ) != QString::fromLatin1 ( mMainWidget->lePasswordVerify->password () ) ) { KMessageBox::sorry(this, i18n("The passwords do not match. Please enter them again."), i18n("Jabber Passwords do not match")); mMainWidget->lblStatusMessage->setText ( i18n ( "Please enter your password again." ) ); return false; } return true; } void JabberRegisterAccount::slotJIDInformation () { if ( !mMainWidget->leServer->text().isEmpty () && ( !jidRegExp.exactMatch ( mMainWidget->leJID->text () ) || ( mMainWidget->leJID->text().section ( "@", 1 ) != mMainWidget->leServer->text () ) ) ) { mMainWidget->lblJIDInformation->setText ( i18n ( "Unless you know what you are doing, your JID should be of the form " "\"user@server.com\", in your case for example \"user@%1\"." ). arg ( mMainWidget->leServer->text () ) ); } else { mMainWidget->lblJIDInformation->setText ( "" ); } } void JabberRegisterAccount::slotSSLToggled () { if ( mMainWidget->cbUseSSL->isChecked () ) { if ( mMainWidget->sbPort->value () == 5222 ) { mMainWidget->sbPort->setValue ( 5223 ); } } else { if ( mMainWidget->sbPort->value () == 5223 ) { mMainWidget->sbPort->setValue ( 5222 ); } } } void JabberRegisterAccount::slotChooseServer () { (new JabberChooseServer ( this ))->show (); } void JabberRegisterAccount::setServer ( const QString &server ) { mMainWidget->leServer->setText ( server ); } void JabberRegisterAccount::slotOk () { mMainWidget->lblStatusMessage->setText ( "" ); if ( !validateData () ) return; kdDebug ( JABBER_DEBUG_GLOBAL ) << k_funcinfo << "Registering a new Jabber account." << endl; enableButtonOK ( false ); mMainWidget->lblStatusMessage->setText ( i18n ( "Connecting to server..." ) ); /* * Check for SSL availability first */ bool trySSL = false; if ( mMainWidget->cbUseSSL->isChecked () ) { bool sslPossible = QCA::isSupported(QCA::CAP_TLS); if (!sslPossible) { KMessageBox::queuedMessageBox(Kopete::UI::Global::mainWidget (), KMessageBox::Error, i18n ("SSL support could not be initialized for account %1. This is most likely because the QCA TLS plugin is not installed on your system."). arg(mMainWidget->leJID->text()), i18n ("Jabber SSL Error")); return; } else { trySSL = true; } } /* * Instantiate connector, responsible for dealing with the socket. * This class uses KDE's socket code, which in turn makes use of * the global proxy settings. */ jabberClientConnector = new JabberConnector; jabberClientConnector->setOptHostPort ( mMainWidget->leServer->text (), mMainWidget->sbPort->value () ); jabberClientConnector->setOptSSL(trySSL); /* * Setup authentication layer */ if ( trySSL ) { jabberTLS = new QCA::TLS; jabberTLSHandler = new XMPP::QCATLSHandler(jabberTLS); { using namespace XMPP; QObject::connect(jabberTLSHandler, SIGNAL(tlsHandshaken()), this, SLOT(slotTLSHandshaken())); } } /* * Instantiate client stream which handles the network communication by referring * to a connector (proxying etc.) and a TLS handler (security layer) */ jabberClientStream = new XMPP::ClientStream(jabberClientConnector, jabberTLSHandler); { using namespace XMPP; QObject::connect (jabberClientStream, SIGNAL (authenticated()), this, SLOT (slotCSAuthenticated ())); QObject::connect (jabberClientStream, SIGNAL (warning (int)), this, SLOT (slotCSWarning ())); QObject::connect (jabberClientStream, SIGNAL (error (int)), this, SLOT (slotCSError (int))); } /* * FIXME: This is required until we fully support XMPP 1.0 * Upon switching to XMPP 1.0, add full TLS capabilities * with fallback (setOptProbe()) and remove the call below. */ jabberClientStream->setOldOnly(true); /* * Initiate anti-idle timer (will be triggered every 55 seconds). */ jabberClientStream->setNoopTime(55000); jabberClient = new XMPP::Client (this); /* * Start connection, no authentication */ jabberClient->connectToServer (jabberClientStream, XMPP::Jid(mMainWidget->leJID->text ()), false); } void JabberRegisterAccount::cleanup () { delete jabberClient; delete jabberClientStream; delete jabberClientConnector; delete jabberTLSHandler; delete jabberTLS; jabberTLS = 0L; jabberTLSHandler = 0L; jabberClientConnector = 0L; jabberClientStream = 0L; jabberClient = 0L; } void JabberRegisterAccount::disconnect () { if(jabberClient) jabberClient->close(true); cleanup (); enableButtonOK ( true ); } void JabberRegisterAccount::slotTLSHandshaken () { kdDebug(JABBER_DEBUG_GLOBAL) << k_funcinfo << "TLS handshake done, testing certificate validity..." << endl; mMainWidget->lblStatusMessage->setText ( i18n ( "Security handshake..." ) ); int validityResult = jabberTLS->certificateValidityResult (); if(validityResult == QCA::TLS::Valid) { kdDebug(JABBER_DEBUG_GLOBAL) << k_funcinfo << "Certificate is valid, continuing." << endl; // valid certificate, continue jabberTLSHandler->continueAfterHandshake (); } else { kdDebug(JABBER_DEBUG_GLOBAL) << k_funcinfo << "Certificate is not valid, asking user what to do next." << endl; // certificate is not valid, query the user if(JabberAccount::handleTLSWarning (validityResult, mMainWidget->leServer->text (), mMainWidget->leJID->text ()) == KMessageBox::Continue) { jabberTLSHandler->continueAfterHandshake (); } else { mMainWidget->lblStatusMessage->setText ( i18n ( "Security handshake failed." ) ); disconnect (); } } } void JabberRegisterAccount::slotCSWarning () { // FIXME: with the next synch point of Iris, this should // have become a slot, so simply connect it through. jabberClientStream->continueAfterWarning (); } void JabberRegisterAccount::slotCSError (int error) { kdDebug(JABBER_DEBUG_GLOBAL) << k_funcinfo << "Error in stream signalled, disconnecting." << endl; KopeteAccount::DisconnectReason errorClass; mMainWidget->lblStatusMessage->setText ( i18n ( "Protocol error." ) ); // display message to user JabberAccount::handleStreamError (error, jabberClientStream->errorCondition (), jabberClientConnector->errorCode (), mMainWidget->leServer->text (), errorClass); disconnect (); } void JabberRegisterAccount::slotCSAuthenticated () { kdDebug (JABBER_DEBUG_GLOBAL) << k_funcinfo << "Launching registration task..." << endl; mMainWidget->lblStatusMessage->setText ( i18n ( "Authentication successful, registering new account..." ) ); /* start the client operation */ XMPP::Jid jid(mMainWidget->leJID->text ()); jabberClient->start ( jid.domain (), jid.node (), "", "" ); XMPP::JT_Register * task = new XMPP::JT_Register (jabberClient->rootTask ()); QObject::connect (task, SIGNAL (finished ()), this, SLOT (slotRegisterUserDone ())); task->reg (mMainWidget->leJID->text().section("@", 0, 0), mMainWidget->lePassword->password ()); task->go (true); } void JabberRegisterAccount::slotRegisterUserDone () { XMPP::JT_Register * task = (XMPP::JT_Register *) sender (); if (task->success ()) { mMainWidget->lblStatusMessage->setText ( i18n ( "Registration successful." ) ); KMessageBox::information (Kopete::UI::Global::mainWidget (), i18n ("Account successfully registered."), i18n ("Jabber Account Registration")); // save settings to parent mParentWidget->mServer->setText ( mMainWidget->leServer->text () ); mParentWidget->mID->setText ( mMainWidget->leJID->text () ); mParentWidget->mPass->setText ( mMainWidget->lePassword->text () ); mParentWidget->mPort->setValue ( mMainWidget->sbPort->value () ); mParentWidget->cbUseSSL->setChecked ( mMainWidget->cbUseSSL->isChecked () ); slotDeleteDialog (); } else { mMainWidget->lblStatusMessage->setText ( i18n ( "Registration failed." ) ); KMessageBox::information (Kopete::UI::Global::mainWidget (), i18n ("Unable to create account on the server. The Jabber ID probably already exists."), i18n ("Jabber Account Registration")); // FIXME: this is required because Iris crashes if we try // to disconnect here. Hopefully Justin can fix this. QTimer::singleShot(0, this, SLOT(disconnect ())); } } #include "jabberregisteraccount.moc" <|endoftext|>
<commit_before>#include <core/mat4.h> #include "core/draw.h" #include "core/random.h" #include "core/shufflebag.h" #include "core/filesystem.h" #include "core/mat4.h" #include "core/axisangle.h" #include "core/aabb.h" #include "core/texturetypes.h" #include "core/filesystemimagegenerator.h" #include "core/path.h" #include "core/os.h" #include "core/range.h" #include "core/camera.h" #include "core/stringutils.h" #include <render/init.h> #include <render/debuggl.h> #include <render/materialshader.h> #include <render/compiledmesh.h> #include <render/texturecache.h> #include "render/shaderattribute3d.h" #include "render/texture.h" #include "render/world.h" #include "render/viewport.h" #include "render/materialshadercache.h" #include "render/defaultfiles.h" #include "window/imguilibrary.h" #include "window/timer.h" #include "window/imgui_ext.h" #include "window/fpscontroller.h" #include "window/sdllibrary.h" #include "window/sdlwindow.h" #include "window/sdlglcontext.h" #include "window/filesystem.h" #include "editor/browser.h" #include "editor/scimed.h" #include "imgui/imgui.h" #include <SDL.h> #include <iostream> #include <memory> ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2{lhs.x + rhs.x, lhs.y + rhs.y}; } int main(int argc, char** argv) { SdlLibrary sdl; if(sdl.ok == false) { return -1; } int width = 1280; int height = 720; const auto size = ImVec2{width, height}; SdlWindow window{"Euphoria Demo", width, height}; if(window.window == nullptr) { return -1; } SdlGlContext context{&window}; if(context.context == nullptr) { return -1; } Init init{SDL_GL_GetProcAddress}; if(init.ok == false) { return -4; } SetupOpenglDebug(); const auto current_directory = GetCurrentDirectory(); const auto base_path = GetBasePath(); const auto pref_path = GetPrefPath(); ImguiLibrary imgui{window.window, pref_path}; ImGui::StyleColorsLight(); Viewport viewport{ Recti::FromWidthHeight(width, height).SetBottomLeftToCopy(0, 0)}; viewport.Activate(); FileSystem file_system; auto catalog = FileSystemRootCatalog::AddRoot(&file_system); FileSystemRootFolder::AddRoot(&file_system, current_directory); FileSystemImageGenerator::AddRoot(&file_system, "img-plain"); SetupDefaultFiles(catalog); TextureCache texture_cache{&file_system}; bool running = true; std::string demo_file; FileBrowser browser{&file_system}; Scimed scimed; while(running) { SDL_Event e; while(SDL_PollEvent(&e) != 0) { imgui.ProcessEvents(&e); switch(e.type) { case SDL_QUIT: running = false; break; default: // ignore other events break; } } imgui.StartNewFrame(); if(ImGui::BeginMainMenuBar()) { if(ImGui::BeginMenu("File")) { if(ImGui::MenuItem("Exit", "Ctrl+Q")) { running = false; } ImGui::EndMenu(); } ImGui::EndMainMenuBar(); if(ImGui::Begin("Browser")) { InputText("Folder", &demo_file); ImGui::SameLine(); if(ImGui::Button("...")) { browser.SelectFile(demo_file); ImGui::OpenPopup("browse"); } ImGui::SetNextWindowSize(ImVec2{300, 300}, ImGuiCond_Always); if(ImGui::BeginPopup("browse")) { if(browser.Run()) { demo_file = browser.GetSelectedFile(); scimed.LoadFile(&texture_cache, &file_system, demo_file); ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } } ImGui::End(); if(ImGui::Begin("Scimed")) { scimed.Run(); } ImGui::End(); ImGui::ShowMetricsWindow(); } #if 0 const auto mp = ImGui::GetIO().MousePos; auto* list = ImGui::GetOverlayDrawList(); list->AddLine(ImVec2{mp.x, 0}, ImVec2{mp.x, size.y}, IM_COL32_BLACK); list->AddLine(ImVec2{0, mp.y}, ImVec2{size.x, mp.y}, IM_COL32_BLACK); #endif init.ClearScreen(Color::Wheat); imgui.Render(); SDL_GL_SwapWindow(window.window); } return 0; } <commit_msg>cleanup<commit_after>#include <core/mat4.h> #include "core/draw.h" #include "core/random.h" #include "core/shufflebag.h" #include "core/filesystem.h" #include "core/mat4.h" #include "core/axisangle.h" #include "core/aabb.h" #include "core/texturetypes.h" #include "core/filesystemimagegenerator.h" #include "core/path.h" #include "core/os.h" #include "core/range.h" #include "core/camera.h" #include "core/stringutils.h" #include <render/init.h> #include <render/debuggl.h> #include <render/materialshader.h> #include <render/compiledmesh.h> #include <render/texturecache.h> #include "render/shaderattribute3d.h" #include "render/texture.h" #include "render/world.h" #include "render/viewport.h" #include "render/materialshadercache.h" #include "render/defaultfiles.h" #include "window/imguilibrary.h" #include "window/timer.h" #include "window/imgui_ext.h" #include "window/fpscontroller.h" #include "window/sdllibrary.h" #include "window/sdlwindow.h" #include "window/sdlglcontext.h" #include "window/filesystem.h" #include "editor/browser.h" #include "editor/scimed.h" #include "imgui/imgui.h" #include <SDL.h> #include <iostream> #include <memory> ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2{lhs.x + rhs.x, lhs.y + rhs.y}; } int main(int argc, char** argv) { SdlLibrary sdl; if(sdl.ok == false) { return -1; } int width = 1280; int height = 720; const auto size = ImVec2{width, height}; SdlWindow window{"Euphoria Demo", width, height}; if(window.window == nullptr) { return -1; } SdlGlContext context{&window}; if(context.context == nullptr) { return -1; } Init init{SDL_GL_GetProcAddress}; if(init.ok == false) { return -4; } SetupOpenglDebug(); const auto current_directory = GetCurrentDirectory(); const auto base_path = GetBasePath(); const auto pref_path = GetPrefPath(); ImguiLibrary imgui{window.window, pref_path}; ImGui::StyleColorsLight(); Viewport viewport{ Recti::FromWidthHeight(width, height).SetBottomLeftToCopy(0, 0)}; viewport.Activate(); FileSystem file_system; auto catalog = FileSystemRootCatalog::AddRoot(&file_system); FileSystemRootFolder::AddRoot(&file_system, current_directory); FileSystemImageGenerator::AddRoot(&file_system, "img-plain"); SetupDefaultFiles(catalog); TextureCache texture_cache{&file_system}; bool running = true; std::string demo_file; FileBrowser browser{&file_system}; Scimed scimed; while(running) { SDL_Event e; while(SDL_PollEvent(&e) != 0) { imgui.ProcessEvents(&e); switch(e.type) { case SDL_QUIT: running = false; break; default: // ignore other events break; } } imgui.StartNewFrame(); if(ImGui::BeginMainMenuBar()) { if(ImGui::BeginMenu("File")) { if(ImGui::MenuItem("Exit", "Ctrl+Q")) { running = false; } ImGui::EndMenu(); } ImGui::EndMainMenuBar(); if(ImGui::Begin("Browser")) { InputText("Folder", &demo_file); ImGui::SameLine(); if(ImGui::Button("...")) { browser.SelectFile(demo_file); ImGui::OpenPopup("browse"); } ImGui::SetNextWindowSize(ImVec2{300, 300}, ImGuiCond_Always); if(ImGui::BeginPopup("browse")) { if(browser.Run()) { demo_file = browser.GetSelectedFile(); scimed.LoadFile(&texture_cache, &file_system, demo_file); ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } } ImGui::End(); if(ImGui::Begin("Scimed")) { scimed.Run(); } ImGui::End(); // ImGui::ShowMetricsWindow(); } init.ClearScreen(Color::Wheat); imgui.Render(); SDL_GL_SwapWindow(window.window); } return 0; } <|endoftext|>
<commit_before>#include "Observador.h" NS_LOG_COMPONENT_DEFINE ("Observador"); Observador::Observador() { m_enviados=0; m_recibidos=0; m_perdidos=0; m_QoS=0; m_usuarios=0; } Observador::~Observador() { } void Observador::PktEnviado(Ptr<const Packet>paquete) { /*suponemos que el paquete está en la estructura*/ t_encolado=Simulator::Now(); uint64_t id = paquete->GetUid(); array[id]=t_encolado; m_enviados++; } void Observador::PktRecibido(Ptr<const Packet>paquete, const Address & dir) { std::map<uint64_t,Time>::iterator aux=array.find(paquete->GetUid()); if (array.end() == aux) { NS_LOG_INFO("NO ESTA EN LA ESTRUCTURA"); } else { NS_LOG_INFO("SI ESTA EN LA ESTRUCTURA"); Time Taux =array[paquete->GetUid()]; Time Ahora = Simulator:Now(); Retardo.Update((Ahora-Taux).GetMilliSeconds()); if(t_TiempoPaqueteAnterior != 0) Jitter.Update(((Ahora-Taux)-t_TiempoPaqueteAnterior).GetMilliSeconds()); m_recibidos=m_recibidos+1; t_TiempoPaqueteAnterior=(Ahora-Taux).GetMilliSeconds(); array.erase(aux); } } float Observador::QoSActual() { /* modelo E QoS= (Ro − Is) − Id − Ie-eff + A jitter >= 100ms retardo >= 150ms % >=1 */ m_perdidos=array.size(); /* debe ser menor a un 0.01 o un 1%*/ m_porcentaje=((m_perdidos)/m_enviados)*100; //referente a paquetes perdidos m_QoS=(m_porcentaje/PORCENTAJE + Jitter.Mean()/JITTER + Retardo.Mean()/RETARDO)/3; return m_QoS; } float Observador::ActualizaJitter() { /* el jitter debe se menor de 100 ms */ return Jitter.Mean(); } float Observador::ActualizaRetardo() { /* el retardo debe ser menor de 150ms */ return Retardo.Mean(); } void Observador::Reset() { Jitter.Reset(); Retardo.Reset(); } <commit_msg>Pequeño fallo<commit_after>#include "Observador.h" NS_LOG_COMPONENT_DEFINE ("Observador"); Observador::Observador() { m_enviados=0; m_recibidos=0; m_perdidos=0; m_QoS=0; m_usuarios=0; } Observador::~Observador() { } void Observador::PktEnviado(Ptr<const Packet>paquete) { /*suponemos que el paquete está en la estructura*/ t_encolado=Simulator::Now(); uint64_t id = paquete->GetUid(); array[id]=t_encolado; m_enviados++; } void Observador::PktRecibido(Ptr<const Packet>paquete, const Address & dir) { std::map<uint64_t,Time>::iterator aux=array.find(paquete->GetUid()); if (array.end() == aux) { NS_LOG_INFO("NO ESTA EN LA ESTRUCTURA"); } else { NS_LOG_INFO("SI ESTA EN LA ESTRUCTURA"); Time Taux =array[paquete->GetUid()]; Time Ahora = Simulator::Now(); Retardo.Update((Ahora-Taux).GetMilliSeconds()); if(t_TiempoPaqueteAnterior != 0) Jitter.Update(((Ahora-Taux)-t_TiempoPaqueteAnterior).GetMilliSeconds()); m_recibidos=m_recibidos+1; t_TiempoPaqueteAnterior=(Ahora-Taux); array.erase(aux); } } float Observador::QoSActual() { /* modelo E QoS= (Ro − Is) − Id − Ie-eff + A jitter >= 100ms retardo >= 150ms % >=1 */ m_perdidos=array.size(); /* debe ser menor a un 0.01 o un 1%*/ m_porcentaje=((m_perdidos)/m_enviados)*100; //referente a paquetes perdidos m_QoS=(m_porcentaje/PORCENTAJE + Jitter.Mean()/JITTER + Retardo.Mean()/RETARDO)/3; return m_QoS; } float Observador::ActualizaJitter() { /* el jitter debe se menor de 100 ms */ return Jitter.Mean(); } float Observador::ActualizaRetardo() { /* el retardo debe ser menor de 150ms */ return Retardo.Mean(); } void Observador::Reset() { Jitter.Reset(); Retardo.Reset(); } <|endoftext|>
<commit_before><commit_msg>update<commit_after><|endoftext|>
<commit_before>// // Created by david on 2019-06-24. // #include <config/nmspc_settings.h> #include <math/eig.h> #include <math/eig/arpack_solver/matrix_product_hamiltonian.h> #include <tensors/class_tensors_finite.h> #include <tensors/edges/class_edges_finite.h> #include <tensors/model/class_model_finite.h> #include <tensors/state/class_state_finite.h> #include <tools/common/log.h> #include <tools/common/prof.h> #include <tools/finite/measure.h> #include <tools/finite/opt.h> Eigen::Tensor<class_state_finite::Scalar,3> tools::finite::opt::internal::ground_state_optimization(const class_tensors_finite & tensors, StateRitz ritz){ return ground_state_optimization(tensors,enum2str(ritz)); } Eigen::Tensor<class_state_finite::Scalar,3> tools::finite::opt::internal::ground_state_optimization(const class_tensors_finite & tensors, std::string_view ritzstring){ tools::log->trace("Ground state optimization with ritz {} ...", ritzstring); using namespace internal; using namespace settings::precision; eig::Ritz ritz = eig::stringToRitz(ritzstring); auto shape_mps = tensors.state->active_dimensions(); auto shape_mpo = tensors.model->active_dimensions(); const auto & mpo = tensors.model->get_multisite_tensor(); const auto & env = tensors.edges->get_multisite_ene_blk(); // int nev = std::min(4l,(long)(tensors.state->active_problem_size()/2)); auto nev = static_cast<eig::size_type>(1); auto ncv = static_cast<eig::size_type>(settings::precision::eig_max_ncv); tools::common::profile::t_eig->tic(); tools::log->trace("Defining Hamiltonian matrix-vector product"); MatrixProductHamiltonian<Scalar> matrix ( env.L.data(), env.R.data(), mpo.data(), shape_mps, shape_mpo); tools::log->trace("Defining eigenvalue solver"); eig::solver solver; // Since we use reduced energy mpo's, we set a sigma shift = 1.0 to move the smallest eigenvalue away from 0, which // would otherwise cause trouble for Arpack. This equates to subtracting sigma * identity from the bottom corner of the mpo. // The resulting eigenvalue will be shifted by the same amount, but the eigenvector will be the same, and that's what we keep. tools::log->trace("Finding ground state"); solver.eigs(matrix, nev, ncv, ritz, eig::Form::SYMM, eig::Side::R, 1.0, eig::Shinv::OFF, eig::Vecs::ON, eig::Dephase::OFF); tools::common::profile::t_eig->toc(); return eig::view::get_eigvec<Scalar>(solver.result,shape_mps, 0); } <commit_msg>Better debug logging<commit_after>// // Created by david on 2019-06-24. // #include <config/nmspc_settings.h> #include <math/eig.h> #include <math/eig/arpack_solver/matrix_product_hamiltonian.h> #include <tensors/class_tensors_finite.h> #include <tensors/edges/class_edges_finite.h> #include <tensors/model/class_model_finite.h> #include <tensors/state/class_state_finite.h> #include <tools/common/log.h> #include <tools/common/prof.h> #include <tools/finite/measure.h> #include <tools/finite/opt.h> Eigen::Tensor<class_state_finite::Scalar,3> tools::finite::opt::internal::ground_state_optimization(const class_tensors_finite & tensors, StateRitz ritz){ return ground_state_optimization(tensors,enum2str(ritz)); } Eigen::Tensor<class_state_finite::Scalar,3> tools::finite::opt::internal::ground_state_optimization(const class_tensors_finite & tensors, std::string_view ritzstring){ tools::log->debug("Ground state optimization with ritz {} ...", ritzstring); using namespace internal; using namespace settings::precision; eig::Ritz ritz = eig::stringToRitz(ritzstring); auto shape_mps = tensors.state->active_dimensions(); auto shape_mpo = tensors.model->active_dimensions(); const auto & mpo = tensors.model->get_multisite_tensor(); const auto & env = tensors.edges->get_multisite_ene_blk(); // int nev = std::min(4l,(long)(tensors.state->active_problem_size()/2)); auto nev = static_cast<eig::size_type>(1); auto ncv = static_cast<eig::size_type>(settings::precision::eig_max_ncv); tools::common::profile::t_eig->tic(); tools::log->trace("Defining Hamiltonian matrix-vector product"); MatrixProductHamiltonian<Scalar> matrix ( env.L.data(), env.R.data(), mpo.data(), shape_mps, shape_mpo); tools::log->trace("Defining eigenvalue solver"); eig::solver solver; // Since we use reduced energy mpo's, we set a sigma shift = 1.0 to move the smallest eigenvalue away from 0, which // would otherwise cause trouble for Arpack. This equates to subtracting sigma * identity from the bottom corner of the mpo. // The resulting eigenvalue will be shifted by the same amount, but the eigenvector will be the same, and that's what we keep. tools::log->trace("Finding ground state"); solver.eigs(matrix, nev, ncv, ritz, eig::Form::SYMM, eig::Side::R, 1.0, eig::Shinv::OFF, eig::Vecs::ON, eig::Dephase::OFF); tools::common::profile::t_eig->toc(); return eig::view::get_eigvec<Scalar>(solver.result,shape_mps, 0); } <|endoftext|>
<commit_before>// // RemotePhotoTool - remote camera control software // Copyright (C) 2008-2020 Michael Fink // /// \file UsbDriverSwitcherDlg.cpp USB driver switcher dialog // #include "stdafx.h" #include "resource.h" #include "UsbDriverSwitcherDlg.hpp" /// timer ID for refreshing USB devices list const UINT_PTR c_timerRefreshList = 1; /// refresh cycle time for USB devices list const UINT c_refreshCycleTime = 1000; LRESULT UsbDriverSwitcherDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { DlgResize_Init(); DoDataExchange(DDX_LOAD); CenterWindow(); SetupList(); RefreshList(); SetTimer(c_timerRefreshList, c_refreshCycleTime); return TRUE; } LRESULT UsbDriverSwitcherDlg::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { KillTimer(c_timerRefreshList); return 0; } LRESULT UsbDriverSwitcherDlg::OnTimer(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/) { if (wParam == c_timerRefreshList) { KillTimer(c_timerRefreshList); RefreshList(); SetTimer(c_timerRefreshList, c_refreshCycleTime); } return 0; } LRESULT UsbDriverSwitcherDlg::OnButtonUsbSwitchDriver(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { int selectedIndex = m_listUSBDevices.GetSelectedIndex(); if (selectedIndex != -1) { struct wdi_device_info* selectedDeviceInfo = (struct wdi_device_info*)m_listUSBDevices.GetItemData(selectedIndex); if (selectedDeviceInfo != nullptr) { SwitchDriver(selectedDeviceInfo); } } return 0; } LRESULT UsbDriverSwitcherDlg::OnButtonUsbOpenDeviceManager(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { ShellExecute(m_hWnd, _T("open"), _T("devmgmt.msc"), nullptr, nullptr, SW_SHOWNORMAL); return 0; } void UsbDriverSwitcherDlg::SetupList() { m_listUSBDevices.AddColumn(_T("USB Device"), 0); m_listUSBDevices.AddColumn(_T("Driver status"), 1); m_listUSBDevices.SetColumnWidth(0, 300); m_listUSBDevices.SetColumnWidth(1, LVSCW_AUTOSIZE_USEHEADER); m_listUSBDevices.SetExtendedListViewStyle( LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES, LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES); } void UsbDriverSwitcherDlg::RefreshList() { CString selectedDeviceId; int selectedIndex = m_listUSBDevices.GetSelectedIndex(); if (selectedIndex != -1) { struct wdi_device_info* selectedDeviceInfo = (struct wdi_device_info*)m_listUSBDevices.GetItemData(selectedIndex); if (selectedDeviceInfo != nullptr) { selectedDeviceId = selectedDeviceInfo->device_id; } } m_listUSBDevices.SetRedraw(FALSE); m_listUSBDevices.DeleteAllItems(); struct wdi_options_create_list cl_options = { 0 }; cl_options.list_all = TRUE; cl_options.list_hubs = FALSE; cl_options.trim_whitespaces = TRUE; int newSelectedIndex = -1; struct wdi_device_info* rawDeviceInfo = nullptr; int ret = wdi_create_list(&rawDeviceInfo, &cl_options); if (ret == WDI_SUCCESS && rawDeviceInfo != nullptr) { m_deviceInfoList.reset(rawDeviceInfo, wdi_destroy_list); for (struct wdi_device_info* deviceInfo = m_deviceInfoList.get(); deviceInfo != nullptr; deviceInfo = deviceInfo->next) { if (deviceInfo->desc == nullptr) continue; int itemIndex = m_listUSBDevices.InsertItem( m_listUSBDevices.GetItemCount(), CString(deviceInfo->desc), 0); bool isWinusbDriver = CStringA(deviceInfo->driver) == "WinUSB"; m_listUSBDevices.SetItemText(itemIndex, 1, isWinusbDriver ? _T("gPhoto2 compatible") : _T("other driver")); m_listUSBDevices.SetItemData(itemIndex, (DWORD_PTR)deviceInfo); if (!selectedDeviceId.IsEmpty() && selectedDeviceId == deviceInfo->device_id) { newSelectedIndex = itemIndex; } } } if (newSelectedIndex != -1) m_listUSBDevices.SelectItem(newSelectedIndex); m_listUSBDevices.SetColumnWidth(1, LVSCW_AUTOSIZE_USEHEADER); m_listUSBDevices.SetRedraw(TRUE); } void UsbDriverSwitcherDlg::SwitchDriver(struct wdi_device_info* deviceInfo) { // TODO implement } <commit_msg>implemented USB driver switching using libwdi<commit_after>// // RemotePhotoTool - remote camera control software // Copyright (C) 2008-2020 Michael Fink // /// \file UsbDriverSwitcherDlg.cpp USB driver switcher dialog // #include "stdafx.h" #include "resource.h" #include "UsbDriverSwitcherDlg.hpp" #include <ulib/Path.hpp> /// timer ID for refreshing USB devices list const UINT_PTR c_timerRefreshList = 1; /// refresh cycle time for USB devices list const UINT c_refreshCycleTime = 1000; LRESULT UsbDriverSwitcherDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { DlgResize_Init(); DoDataExchange(DDX_LOAD); CenterWindow(); SetupList(); RefreshList(); SetTimer(c_timerRefreshList, c_refreshCycleTime); return TRUE; } LRESULT UsbDriverSwitcherDlg::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { KillTimer(c_timerRefreshList); return 0; } LRESULT UsbDriverSwitcherDlg::OnTimer(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/) { if (wParam == c_timerRefreshList) { KillTimer(c_timerRefreshList); RefreshList(); SetTimer(c_timerRefreshList, c_refreshCycleTime); } return 0; } LRESULT UsbDriverSwitcherDlg::OnButtonUsbSwitchDriver(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { int selectedIndex = m_listUSBDevices.GetSelectedIndex(); if (selectedIndex != -1) { struct wdi_device_info* selectedDeviceInfo = (struct wdi_device_info*)m_listUSBDevices.GetItemData(selectedIndex); if (selectedDeviceInfo != nullptr) { // stop timer or else it will mess up the wdi_device_info struct KillTimer(c_timerRefreshList); SwitchDriver(selectedDeviceInfo); SetTimer(c_timerRefreshList, c_refreshCycleTime); } } return 0; } LRESULT UsbDriverSwitcherDlg::OnButtonUsbOpenDeviceManager(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { ShellExecute(m_hWnd, _T("open"), _T("devmgmt.msc"), nullptr, nullptr, SW_SHOWNORMAL); return 0; } void UsbDriverSwitcherDlg::SetupList() { m_listUSBDevices.AddColumn(_T("USB Device"), 0); m_listUSBDevices.AddColumn(_T("Driver status"), 1); m_listUSBDevices.SetColumnWidth(0, 300); m_listUSBDevices.SetColumnWidth(1, LVSCW_AUTOSIZE_USEHEADER); m_listUSBDevices.SetExtendedListViewStyle( LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES, LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES); } void UsbDriverSwitcherDlg::RefreshList() { CString selectedDeviceId; int selectedIndex = m_listUSBDevices.GetSelectedIndex(); if (selectedIndex != -1) { struct wdi_device_info* selectedDeviceInfo = (struct wdi_device_info*)m_listUSBDevices.GetItemData(selectedIndex); if (selectedDeviceInfo != nullptr) { selectedDeviceId = selectedDeviceInfo->device_id; } } m_listUSBDevices.SetRedraw(FALSE); m_listUSBDevices.DeleteAllItems(); struct wdi_options_create_list cl_options = { 0 }; cl_options.list_all = TRUE; cl_options.list_hubs = FALSE; cl_options.trim_whitespaces = TRUE; int newSelectedIndex = -1; struct wdi_device_info* rawDeviceInfo = nullptr; int ret = wdi_create_list(&rawDeviceInfo, &cl_options); if (ret == WDI_SUCCESS && rawDeviceInfo != nullptr) { m_deviceInfoList.reset(rawDeviceInfo, wdi_destroy_list); for (struct wdi_device_info* deviceInfo = m_deviceInfoList.get(); deviceInfo != nullptr; deviceInfo = deviceInfo->next) { if (deviceInfo->desc == nullptr) continue; int itemIndex = m_listUSBDevices.InsertItem( m_listUSBDevices.GetItemCount(), CString(deviceInfo->desc), 0); bool isWinusbDriver = CStringA(deviceInfo->driver) == "WinUSB"; m_listUSBDevices.SetItemText(itemIndex, 1, isWinusbDriver ? _T("gPhoto2 compatible") : _T("other driver")); m_listUSBDevices.SetItemData(itemIndex, (DWORD_PTR)deviceInfo); if (!selectedDeviceId.IsEmpty() && selectedDeviceId == deviceInfo->device_id) { newSelectedIndex = itemIndex; } } } if (newSelectedIndex != -1) m_listUSBDevices.SelectItem(newSelectedIndex); m_listUSBDevices.SetColumnWidth(1, LVSCW_AUTOSIZE_USEHEADER); m_listUSBDevices.SetRedraw(TRUE); } void UsbDriverSwitcherDlg::SwitchDriver(struct wdi_device_info* deviceInfo) { CString folderPath = Path::Combine(Path::TempFolder(), _T("usb_driver")); CString infName{ _T("default.inf") }; Path::CreateDirectoryRecursive(folderPath); wdi_options_prepare_driver prepareDriverOptions = { }; prepareDriverOptions.driver_type = WDI_WINUSB; int ret = wdi_prepare_driver(deviceInfo, CStringA(folderPath), CStringA(infName), &prepareDriverOptions); if (ret != WDI_SUCCESS) { CString text; text.Format(_T("Error while preparing USB driver: %hs"), wdi_strerror(ret)); AtlMessageBox(m_hWnd, text.GetString(), IDR_MAINFRAME, MB_OK | MB_ICONERROR); return; } wdi_options_install_driver installDriverOptions = { }; installDriverOptions.hWnd = m_hWnd; installDriverOptions.install_filter_driver = false; ret = wdi_install_driver(deviceInfo, CStringA(folderPath), CStringA(infName), &installDriverOptions); if (ret != WDI_SUCCESS) { CString text; text.Format(_T("Error while installing USB driver: %hs"), wdi_strerror(ret)); AtlMessageBox(m_hWnd, text.GetString(), IDR_MAINFRAME, MB_OK | MB_ICONERROR); return; } RefreshList(); } <|endoftext|>
<commit_before>#include <string> /* public class TennisGame4 implements TennisGame { int serverScore; int receiverScore; String server; String receiver; public TennisGame4(String player1, String player2) { this.server = player1; this.receiver = player2; } @java.lang.Override public void wonPoint(String playerName) { if (server.equals(playerName)) this.serverScore += 1; else this.receiverScore += 1; } @java.lang.Override public String getScore() { TennisResult result = new Deuce( this, new GameServer( this, new GameReceiver( this, new AdvantageServer( this, new AdvantageReceiver( this, new DefaultResult(this)))))).getResult(); return result.format(); } boolean receiverHasAdvantage() { return receiverScore >= 4 && (receiverScore - serverScore) == 1; } boolean serverHasAdvantage() { return serverScore >= 4 && (serverScore - receiverScore) == 1; } boolean receiverHasWon() { return receiverScore >= 4 && (receiverScore - serverScore) >= 2; } boolean serverHasWon() { return serverScore >= 4 && (serverScore - receiverScore) >= 2; } boolean isDeuce() { return serverScore >= 3 && receiverScore >= 3 && (serverScore == receiverScore); } } class TennisResult { String serverScore; String receiverScore; TennisResult(String serverScore, String receiverScore) { this.serverScore = serverScore; this.receiverScore = receiverScore; } String format() { if ("".equals(this.receiverScore)) return this.serverScore; if (serverScore.equals(receiverScore)) return serverScore + "-All"; return this.serverScore + "-" + this.receiverScore; } } interface ResultProvider { TennisResult getResult(); } class Deuce implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public Deuce(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.isDeuce()) return new TennisResult("Deuce", ""); return this.nextResult.getResult(); } } class GameServer implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public GameServer(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.serverHasWon()) return new TennisResult("Win for " + game.server, ""); return this.nextResult.getResult(); } } class GameReceiver implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public GameReceiver(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.receiverHasWon()) return new TennisResult("Win for " + game.receiver, ""); return this.nextResult.getResult(); }t } class AdvantageServer implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public AdvantageServer(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.serverHasAdvantage()) return new TennisResult("Advantage " + game.server, ""); return this.nextResult.getResult(); } } class AdvantageReceiver implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public AdvantageReceiver(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.receiverHasAdvantage()) return new TennisResult("Advantage " + game.receiver, ""); return this.nextResult.getResult(); } } class DefaultResult implements ResultProvider { private static final String[] scores = {"Love", "Fifteen", "Thirty", "Forty"}; private final TennisGame4 game; public DefaultResult(TennisGame4 game) { this.game = game; } @Override public TennisResult getResult() { return new TennisResult(scores[game.serverScore], scores[game.receiverScore]); } } */ class TennisResult { std::string serverScore; std::string receiverScore; TennisResult(std::string serverScore, std::string receiverScore) { this->serverScore = serverScore; this->receiverScore = receiverScore; } std::string format() { if ("" == this->receiverScore) return this->serverScore; if (serverScore == this->receiverScore) return serverScore + "-All"; return this->serverScore + "-" + this->receiverScore; } }; class ResultProvider { virtual ~ResultProvider() {} virtual TennisResult getResult() = 0; }; /* public class TennisGame4 implements TennisGame { ##class TennisResult { ##interface ResultProvider { class Deuce implements ResultProvider { class GameServer implements ResultProvider { class GameReceiver implements ResultProvider { class AdvantageServer implements ResultProvider { class AdvantageReceiver implements ResultProvider { class DefaultResult implements ResultProvider { */ // tennis3 function below (TODO: re-implement using class mess above!) /* relevant inspiration from Java Unit Test public void checkAllScores(TennisGame game) { int highestScore = Math.max(this.player1Score, this.player2Score); for (int i = 0; i < highestScore; i++) { if (i < this.player1Score) game.wonPoint("player1"); if (i < this.player2Score) game.wonPoint("player2"); } assertEquals(this.expectedScore, game.getScore()); } */ const std::string tennis_score(int p1, int p2) { std::string s; std::string p1N = "player1"; std::string p2N = "player2"; if ((p1 < 4 && p2 < 4) && (p1 + p2 < 6)) { std::string p[4] = {"Love", "Fifteen", "Thirty", "Forty"}; s = p[p1]; return (p1 == p2) ? s + "-All" : s + "-" + p[p2]; } else { if (p1 == p2) return "Deuce"; s = p1 > p2 ? p1N : p2N; return ((p1-p2)*(p1-p2) == 1) ? "Advantage " + s : "Win for " + s; } }<commit_msg>Add (non-compiling) stub for DefaultResult<commit_after>#include <string> /* public class TennisGame4 implements TennisGame { int serverScore; int receiverScore; String server; String receiver; public TennisGame4(String player1, String player2) { this.server = player1; this.receiver = player2; } @java.lang.Override public void wonPoint(String playerName) { if (server.equals(playerName)) this.serverScore += 1; else this.receiverScore += 1; } @java.lang.Override public String getScore() { TennisResult result = new Deuce( this, new GameServer( this, new GameReceiver( this, new AdvantageServer( this, new AdvantageReceiver( this, new DefaultResult(this)))))).getResult(); return result.format(); } boolean receiverHasAdvantage() { return receiverScore >= 4 && (receiverScore - serverScore) == 1; } boolean serverHasAdvantage() { return serverScore >= 4 && (serverScore - receiverScore) == 1; } boolean receiverHasWon() { return receiverScore >= 4 && (receiverScore - serverScore) >= 2; } boolean serverHasWon() { return serverScore >= 4 && (serverScore - receiverScore) >= 2; } boolean isDeuce() { return serverScore >= 3 && receiverScore >= 3 && (serverScore == receiverScore); } } class TennisResult { String serverScore; String receiverScore; TennisResult(String serverScore, String receiverScore) { this.serverScore = serverScore; this.receiverScore = receiverScore; } String format() { if ("".equals(this.receiverScore)) return this.serverScore; if (serverScore.equals(receiverScore)) return serverScore + "-All"; return this.serverScore + "-" + this.receiverScore; } } interface ResultProvider { TennisResult getResult(); } class Deuce implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public Deuce(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.isDeuce()) return new TennisResult("Deuce", ""); return this.nextResult.getResult(); } } class GameServer implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public GameServer(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.serverHasWon()) return new TennisResult("Win for " + game.server, ""); return this.nextResult.getResult(); } } class GameReceiver implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public GameReceiver(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.receiverHasWon()) return new TennisResult("Win for " + game.receiver, ""); return this.nextResult.getResult(); }t } class AdvantageServer implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public AdvantageServer(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.serverHasAdvantage()) return new TennisResult("Advantage " + game.server, ""); return this.nextResult.getResult(); } } class AdvantageReceiver implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public AdvantageReceiver(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.receiverHasAdvantage()) return new TennisResult("Advantage " + game.receiver, ""); return this.nextResult.getResult(); } } class DefaultResult implements ResultProvider { private static final String[] scores = {"Love", "Fifteen", "Thirty", "Forty"}; private final TennisGame4 game; public DefaultResult(TennisGame4 game) { this.game = game; } @Override public TennisResult getResult() { return new TennisResult(scores[game.serverScore], scores[game.receiverScore]); } } */ //public class TennisGame4 implements TennisGame { class TennisResult { std::string serverScore; std::string receiverScore; TennisResult(std::string serverScore, std::string receiverScore) { this->serverScore = serverScore; this->receiverScore = receiverScore; } std::string format() { if ("" == this->receiverScore) return this->serverScore; if (serverScore == this->receiverScore) return serverScore + "-All"; return this->serverScore + "-" + this->receiverScore; } }; class ResultProvider { virtual ~ResultProvider() {} virtual TennisResult getResult() = 0; }; //class Deuce implements ResultProvider { //class GameServer implements ResultProvider { //class GameReceiver implements ResultProvider { //class AdvantageServer implements ResultProvider { //class AdvantageReceiver implements ResultProvider { class DefaultResult : ResultProvider { public: DefaultResult(TennisGame4& game) : game(game) { } TennisResult getResult() override { return TennisResult(scores[game->serverScore], scores[game->receiverScore]); } private: static const std::string[] scores; const TennisGame4& game; }; const std::string DefaultResult::scores[] = {"Love", "Fifteen", "Thirty", "Forty"}; // tennis3 function below (TODO: re-implement using class mess above!) /* relevant inspiration from Java Unit Test public void checkAllScores(TennisGame game) { int highestScore = Math.max(this.player1Score, this.player2Score); for (int i = 0; i < highestScore; i++) { if (i < this.player1Score) game.wonPoint("player1"); if (i < this.player2Score) game.wonPoint("player2"); } assertEquals(this.expectedScore, game.getScore()); } */ const std::string tennis_score(int p1, int p2) { std::string s; std::string p1N = "player1"; std::string p2N = "player2"; if ((p1 < 4 && p2 < 4) && (p1 + p2 < 6)) { std::string p[4] = {"Love", "Fifteen", "Thirty", "Forty"}; s = p[p1]; return (p1 == p2) ? s + "-All" : s + "-" + p[p2]; } else { if (p1 == p2) return "Deuce"; s = p1 > p2 ? p1N : p2N; return ((p1-p2)*(p1-p2) == 1) ? "Advantage " + s : "Win for " + s; } }<|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////// // $Id: stack64.cc,v 1.9 2002/11/19 05:47:43 bdenney Exp $ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2001 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library 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 2 of the License, or (at your option) any later version. // // This library 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 for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #define NEED_CPU_REG_SHORTCUTS 1 #include "bochs.h" #define LOG_THIS BX_CPU_THIS_PTR #if BX_SUPPORT_X86_64 #if BX_USE_CPU_SMF #define this (BX_CPU(0)) #endif void BX_CPU_C::POP_Eq(bxInstruction_c *i) { Bit64u val64; pop_64(&val64); if (i->modC0()) { BX_WRITE_64BIT_REG(i->rm(), val64); } else { // Note: there is one little weirdism here. When 64bit addressing // is used, it is possible to use RSP in the modrm addressing. // If used, the value of RSP after the pop is used to calculate // the address. if (i->as64L() && (!i->modC0()) && (i->rm()==4) && (i->sibBase()==4)) { // call method on BX_CPU_C object BX_CPU_CALL_METHOD (i->ResolveModrm, (i)); } write_virtual_qword(i->seg(), RMAddr(i), &val64); } } void BX_CPU_C::PUSH_RRX(bxInstruction_c *i) { push_64(BX_CPU_THIS_PTR gen_reg[i->opcodeReg()].rrx); } void BX_CPU_C::POP_RRX(bxInstruction_c *i) { Bit64u rrx; pop_64(&rrx); BX_CPU_THIS_PTR gen_reg[i->opcodeReg()].rrx = rrx; } void BX_CPU_C::PUSH64_CS(bxInstruction_c *i) { push_64(BX_CPU_THIS_PTR sregs[BX_SEG_REG_CS].selector.value); } void BX_CPU_C::PUSH64_DS(bxInstruction_c *i) { push_64(BX_CPU_THIS_PTR sregs[BX_SEG_REG_DS].selector.value); } void BX_CPU_C::PUSH64_ES(bxInstruction_c *i) { push_64(BX_CPU_THIS_PTR sregs[BX_SEG_REG_ES].selector.value); } void BX_CPU_C::PUSH64_FS(bxInstruction_c *i) { push_64(BX_CPU_THIS_PTR sregs[BX_SEG_REG_FS].selector.value); } void BX_CPU_C::PUSH64_GS(bxInstruction_c *i) { push_64(BX_CPU_THIS_PTR sregs[BX_SEG_REG_GS].selector.value); } void BX_CPU_C::PUSH64_SS(bxInstruction_c *i) { push_64(BX_CPU_THIS_PTR sregs[BX_SEG_REG_SS].selector.value); } void BX_CPU_C::POP64_DS(bxInstruction_c *i) { Bit64u ds; pop_64(&ds); load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_DS], (Bit16u) ds); } void BX_CPU_C::POP64_ES(bxInstruction_c *i) { Bit64u es; pop_64(&es); load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_ES], (Bit16u) es); } void BX_CPU_C::POP64_FS(bxInstruction_c *i) { Bit64u fs; pop_64(&fs); load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_FS], (Bit16u) fs); } void BX_CPU_C::POP64_GS(bxInstruction_c *i) { Bit64u gs; pop_64(&gs); load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_GS], (Bit16u) gs); } void BX_CPU_C::POP64_SS(bxInstruction_c *i) { Bit64u ss; pop_64(&ss); load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_SS], (Bit16u) ss); // POP SS inhibits interrupts, debug exceptions and single-step // trap exceptions until the execution boundary following the // next instruction is reached. // Same code as MOV_SwEw() BX_CPU_THIS_PTR inhibit_mask |= BX_INHIBIT_INTERRUPTS | BX_INHIBIT_DEBUG; BX_CPU_THIS_PTR async_event = 1; } void BX_CPU_C::PUSHAD64(bxInstruction_c *i) { Bit64u temp_RSP; Bit64u rsp; temp_RSP = RSP; if ( !can_push(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_SS].cache, temp_RSP, 64) ) { BX_PANIC(("PUSHAD(): stack doesn't have enough room!")); exception(BX_SS_EXCEPTION, 0, 0); return; } rsp = RSP; /* ??? optimize this by using virtual write, all checks passed */ push_64(RAX); push_64(RCX); push_64(RDX); push_64(RBX); push_64(rsp); push_64(RBP); push_64(RSI); push_64(RDI); } void BX_CPU_C::POPAD64(bxInstruction_c *i) { Bit64u rdi, rsi, rbp, rtmp, rbx, rdx, rcx, rax; if ( !can_pop(64) ) { BX_PANIC(("pop_ad: not enough bytes on stack")); exception(BX_SS_EXCEPTION, 0, 0); return; } /* ??? optimize this */ pop_64(&rdi); pop_64(&rsi); pop_64(&rbp); pop_64(&rtmp); /* value for ESP discarded */ pop_64(&rbx); pop_64(&rdx); pop_64(&rcx); pop_64(&rax); RDI = rdi; RSI = rsi; RBP = rbp; RBX = rbx; RDX = rdx; RCX = rcx; RAX = rax; } void BX_CPU_C::PUSH64_Id(bxInstruction_c *i) { Bit64u imm64; imm64 = (Bit32s) i->Id(); push_64(imm64); } void BX_CPU_C::PUSH_Eq(bxInstruction_c *i) { Bit64u op1_64; /* op1_64 is a register or memory reference */ if (i->modC0()) { op1_64 = BX_READ_64BIT_REG(i->rm()); } else { /* pointer, segment address pair */ read_virtual_qword(i->seg(), RMAddr(i), &op1_64); } push_64(op1_64); } void BX_CPU_C::ENTER64_IwIb(bxInstruction_c *i) { Bit64u frame_ptr64; Bit16u frame_ptr16; Bit8u level; static Bit8u first_time = 1; level = i->Ib2(); invalidate_prefetch_q(); level %= 32; /* ??? */ if (first_time && level>0) { BX_ERROR(("enter() with level > 0. The emulation of this instruction may not be complete. This warning will be printed only once per bochs run.")); first_time = 0; } //if (BX_CPU_THIS_PTR sregs[BX_SEG_REG_SS].cache.u.segment.d_b && i->os64L()==0) { // BX_INFO(("enter(): stacksize!=opsize: I'm unsure of the code for this")); // BX_PANIC((" The Intel manuals are a mess on this one!")); // } { Bit64u bytes_to_push, temp_RSP; if (level == 0) { bytes_to_push = 8 + i->Iw(); } else { /* level > 0 */ bytes_to_push = 8 + (level-1)*8 + 8 + i->Iw(); } temp_RSP = RSP; if ( !can_push(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_SS].cache, temp_RSP, bytes_to_push) ) { BX_PANIC(("ENTER: not enough room on stack!")); exception(BX_SS_EXCEPTION, 0, 0); } } push_64(RBP); frame_ptr64 = RSP; if (level > 0) { /* do level-1 times */ while (--level) { Bit64u temp64; RBP -= 4; read_virtual_qword(BX_SEG_REG_SS, RBP, &temp64); ESP -= 4; write_virtual_qword(BX_SEG_REG_SS, RSP, &temp64); } /* while (--level) */ /* push(frame pointer) */ RSP -= 4; write_virtual_qword(BX_SEG_REG_SS, RSP, &frame_ptr64); } /* if (level > 0) ... */ RBP = frame_ptr64; RSP = RSP - i->Iw(); } void BX_CPU_C::LEAVE64(bxInstruction_c *i) { // delete frame RSP = RBP; // restore frame pointer { Bit64u temp64; pop_64(&temp64); RBP = temp64; } } #endif /* if BX_SUPPORT_X86_64 */ <commit_msg>Fixed wrong increment for enter where level > 0<commit_after>///////////////////////////////////////////////////////////////////////// // $Id: stack64.cc,v 1.10 2003/02/08 05:48:01 ptrumpet Exp $ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2001 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library 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 2 of the License, or (at your option) any later version. // // This library 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 for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #define NEED_CPU_REG_SHORTCUTS 1 #include "bochs.h" #define LOG_THIS BX_CPU_THIS_PTR #if BX_SUPPORT_X86_64 #if BX_USE_CPU_SMF #define this (BX_CPU(0)) #endif void BX_CPU_C::POP_Eq(bxInstruction_c *i) { Bit64u val64; pop_64(&val64); if (i->modC0()) { BX_WRITE_64BIT_REG(i->rm(), val64); } else { // Note: there is one little weirdism here. When 64bit addressing // is used, it is possible to use RSP in the modrm addressing. // If used, the value of RSP after the pop is used to calculate // the address. if (i->as64L() && (!i->modC0()) && (i->rm()==4) && (i->sibBase()==4)) { // call method on BX_CPU_C object BX_CPU_CALL_METHOD (i->ResolveModrm, (i)); } write_virtual_qword(i->seg(), RMAddr(i), &val64); } } void BX_CPU_C::PUSH_RRX(bxInstruction_c *i) { push_64(BX_CPU_THIS_PTR gen_reg[i->opcodeReg()].rrx); } void BX_CPU_C::POP_RRX(bxInstruction_c *i) { Bit64u rrx; pop_64(&rrx); BX_CPU_THIS_PTR gen_reg[i->opcodeReg()].rrx = rrx; } void BX_CPU_C::PUSH64_CS(bxInstruction_c *i) { push_64(BX_CPU_THIS_PTR sregs[BX_SEG_REG_CS].selector.value); } void BX_CPU_C::PUSH64_DS(bxInstruction_c *i) { push_64(BX_CPU_THIS_PTR sregs[BX_SEG_REG_DS].selector.value); } void BX_CPU_C::PUSH64_ES(bxInstruction_c *i) { push_64(BX_CPU_THIS_PTR sregs[BX_SEG_REG_ES].selector.value); } void BX_CPU_C::PUSH64_FS(bxInstruction_c *i) { push_64(BX_CPU_THIS_PTR sregs[BX_SEG_REG_FS].selector.value); } void BX_CPU_C::PUSH64_GS(bxInstruction_c *i) { push_64(BX_CPU_THIS_PTR sregs[BX_SEG_REG_GS].selector.value); } void BX_CPU_C::PUSH64_SS(bxInstruction_c *i) { push_64(BX_CPU_THIS_PTR sregs[BX_SEG_REG_SS].selector.value); } void BX_CPU_C::POP64_DS(bxInstruction_c *i) { Bit64u ds; pop_64(&ds); load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_DS], (Bit16u) ds); } void BX_CPU_C::POP64_ES(bxInstruction_c *i) { Bit64u es; pop_64(&es); load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_ES], (Bit16u) es); } void BX_CPU_C::POP64_FS(bxInstruction_c *i) { Bit64u fs; pop_64(&fs); load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_FS], (Bit16u) fs); } void BX_CPU_C::POP64_GS(bxInstruction_c *i) { Bit64u gs; pop_64(&gs); load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_GS], (Bit16u) gs); } void BX_CPU_C::POP64_SS(bxInstruction_c *i) { Bit64u ss; pop_64(&ss); load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_SS], (Bit16u) ss); // POP SS inhibits interrupts, debug exceptions and single-step // trap exceptions until the execution boundary following the // next instruction is reached. // Same code as MOV_SwEw() BX_CPU_THIS_PTR inhibit_mask |= BX_INHIBIT_INTERRUPTS | BX_INHIBIT_DEBUG; BX_CPU_THIS_PTR async_event = 1; } void BX_CPU_C::PUSHAD64(bxInstruction_c *i) { Bit64u temp_RSP; Bit64u rsp; temp_RSP = RSP; if ( !can_push(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_SS].cache, temp_RSP, 64) ) { BX_PANIC(("PUSHAD(): stack doesn't have enough room!")); exception(BX_SS_EXCEPTION, 0, 0); return; } rsp = RSP; /* ??? optimize this by using virtual write, all checks passed */ push_64(RAX); push_64(RCX); push_64(RDX); push_64(RBX); push_64(rsp); push_64(RBP); push_64(RSI); push_64(RDI); } void BX_CPU_C::POPAD64(bxInstruction_c *i) { Bit64u rdi, rsi, rbp, rtmp, rbx, rdx, rcx, rax; if ( !can_pop(64) ) { BX_PANIC(("pop_ad: not enough bytes on stack")); exception(BX_SS_EXCEPTION, 0, 0); return; } /* ??? optimize this */ pop_64(&rdi); pop_64(&rsi); pop_64(&rbp); pop_64(&rtmp); /* value for ESP discarded */ pop_64(&rbx); pop_64(&rdx); pop_64(&rcx); pop_64(&rax); RDI = rdi; RSI = rsi; RBP = rbp; RBX = rbx; RDX = rdx; RCX = rcx; RAX = rax; } void BX_CPU_C::PUSH64_Id(bxInstruction_c *i) { Bit64u imm64; imm64 = (Bit32s) i->Id(); push_64(imm64); } void BX_CPU_C::PUSH_Eq(bxInstruction_c *i) { Bit64u op1_64; /* op1_64 is a register or memory reference */ if (i->modC0()) { op1_64 = BX_READ_64BIT_REG(i->rm()); } else { /* pointer, segment address pair */ read_virtual_qword(i->seg(), RMAddr(i), &op1_64); } push_64(op1_64); } void BX_CPU_C::ENTER64_IwIb(bxInstruction_c *i) { Bit64u frame_ptr64; Bit16u frame_ptr16; Bit8u level; static Bit8u first_time = 1; level = i->Ib2(); invalidate_prefetch_q(); level %= 32; /* ??? */ if (first_time && level>0) { BX_ERROR(("enter() with level > 0. The emulation of this instruction may not be complete. This warning will be printed only once per bochs run.")); first_time = 0; } //if (BX_CPU_THIS_PTR sregs[BX_SEG_REG_SS].cache.u.segment.d_b && i->os64L()==0) { // BX_INFO(("enter(): stacksize!=opsize: I'm unsure of the code for this")); // BX_PANIC((" The Intel manuals are a mess on this one!")); // } { Bit64u bytes_to_push, temp_RSP; if (level == 0) { bytes_to_push = 8 + i->Iw(); } else { /* level > 0 */ bytes_to_push = 8 + (level-1)*8 + 8 + i->Iw(); } temp_RSP = RSP; if ( !can_push(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_SS].cache, temp_RSP, bytes_to_push) ) { BX_PANIC(("ENTER: not enough room on stack!")); exception(BX_SS_EXCEPTION, 0, 0); } } push_64(RBP); frame_ptr64 = RSP; if (level > 0) { /* do level-1 times */ while (--level) { Bit64u temp64; RBP -= 8; read_virtual_qword(BX_SEG_REG_SS, RBP, &temp64); ESP -= 8; write_virtual_qword(BX_SEG_REG_SS, RSP, &temp64); } /* while (--level) */ /* push(frame pointer) */ RSP -= 8; write_virtual_qword(BX_SEG_REG_SS, RSP, &frame_ptr64); } /* if (level > 0) ... */ RBP = frame_ptr64; RSP = RSP - i->Iw(); } void BX_CPU_C::LEAVE64(bxInstruction_c *i) { // delete frame RSP = RBP; // restore frame pointer { Bit64u temp64; pop_64(&temp64); RBP = temp64; } } #endif /* if BX_SUPPORT_X86_64 */ <|endoftext|>
<commit_before>/**************************************************************************** * * (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ #include "ArduPlaneFirmwarePlugin.h" bool ArduPlaneFirmwarePlugin::_remapParamNameIntialized = false; FirmwarePlugin::remapParamNameMajorVersionMap_t ArduPlaneFirmwarePlugin::_remapParamName; APMPlaneMode::APMPlaneMode(uint32_t mode, bool settable) : APMCustomMode(mode, settable) { setEnumToStringMapping({ {MANUAL, "Manual"}, {CIRCLE, "Circle"}, {STABILIZE, "Stabilize"}, {TRAINING, "Training"}, {ACRO, "Acro"}, {FLY_BY_WIRE_A, "FBW A"}, {FLY_BY_WIRE_B, "FBW B"}, {CRUISE, "Cruise"}, {AUTOTUNE, "Autotune"}, {AUTO, "Auto"}, {RTL, "RTL"}, {LOITER, "Loiter"}, {GUIDED, "Guided"}, {INITIALIZING, "Initializing"}, {QSTABILIZE, "QuadPlane Stabilize"}, {QHOVER, "QuadPlane Hover"}, {QLOITER, "QuadPlane Loiter"}, {QLAND, "QuadPlane Land"}, {QRTL, "QuadPlane RTL"}, }); } ArduPlaneFirmwarePlugin::ArduPlaneFirmwarePlugin(void) { QList<APMCustomMode> supportedFlightModes; supportedFlightModes << APMPlaneMode(APMPlaneMode::MANUAL ,true); supportedFlightModes << APMPlaneMode(APMPlaneMode::CIRCLE ,true); supportedFlightModes << APMPlaneMode(APMPlaneMode::STABILIZE ,true); supportedFlightModes << APMPlaneMode(APMPlaneMode::TRAINING ,true); supportedFlightModes << APMPlaneMode(APMPlaneMode::ACRO ,true); supportedFlightModes << APMPlaneMode(APMPlaneMode::FLY_BY_WIRE_A ,true); supportedFlightModes << APMPlaneMode(APMPlaneMode::FLY_BY_WIRE_B ,true); supportedFlightModes << APMPlaneMode(APMPlaneMode::CRUISE ,true); supportedFlightModes << APMPlaneMode(APMPlaneMode::AUTOTUNE ,true); supportedFlightModes << APMPlaneMode(APMPlaneMode::AUTO ,true); supportedFlightModes << APMPlaneMode(APMPlaneMode::RTL ,true); supportedFlightModes << APMPlaneMode(APMPlaneMode::LOITER ,true); supportedFlightModes << APMPlaneMode(APMPlaneMode::GUIDED ,true); supportedFlightModes << APMPlaneMode(APMPlaneMode::INITIALIZING ,false); supportedFlightModes << APMPlaneMode(APMPlaneMode::QSTABILIZE ,true); supportedFlightModes << APMPlaneMode(APMPlaneMode::QHOVER ,true); supportedFlightModes << APMPlaneMode(APMPlaneMode::QLOITER ,true); supportedFlightModes << APMPlaneMode(APMPlaneMode::QLAND ,true); supportedFlightModes << APMPlaneMode(APMPlaneMode::QRTL ,true); setSupportedModes(supportedFlightModes); if (!_remapParamNameIntialized) { FirmwarePlugin::remapParamNameMap_t& remapV3_10 = _remapParamName[3][10]; remapV3_10["BATT_ARM_VOLT"] = QStringLiteral("ARMING_VOLT_MIN"); remapV3_10["BATT2_ARM_VOLT"] = QStringLiteral("ARMING_VOLT2_MIN"); _remapParamNameIntialized = true; } } int ArduPlaneFirmwarePlugin::remapParamNameHigestMinorVersionNumber(int majorVersionNumber) const { // Remapping supports up to 3.10 return majorVersionNumber == 3 ? 10 : Vehicle::versionNotSetValue; } <commit_msg>List in Supported modes<commit_after>/**************************************************************************** * * (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ #include "ArduPlaneFirmwarePlugin.h" bool ArduPlaneFirmwarePlugin::_remapParamNameIntialized = false; FirmwarePlugin::remapParamNameMajorVersionMap_t ArduPlaneFirmwarePlugin::_remapParamName; APMPlaneMode::APMPlaneMode(uint32_t mode, bool settable) : APMCustomMode(mode, settable) { setEnumToStringMapping({ {MANUAL, "Manual"}, {CIRCLE, "Circle"}, {STABILIZE, "Stabilize"}, {TRAINING, "Training"}, {ACRO, "Acro"}, {FLY_BY_WIRE_A, "FBW A"}, {FLY_BY_WIRE_B, "FBW B"}, {CRUISE, "Cruise"}, {AUTOTUNE, "Autotune"}, {AUTO, "Auto"}, {RTL, "RTL"}, {LOITER, "Loiter"}, {GUIDED, "Guided"}, {INITIALIZING, "Initializing"}, {QSTABILIZE, "QuadPlane Stabilize"}, {QHOVER, "QuadPlane Hover"}, {QLOITER, "QuadPlane Loiter"}, {QLAND, "QuadPlane Land"}, {QRTL, "QuadPlane RTL"}, }); } ArduPlaneFirmwarePlugin::ArduPlaneFirmwarePlugin(void) { setSupportedModes({ APMPlaneMode(APMPlaneMode::MANUAL ,true), APMPlaneMode(APMPlaneMode::CIRCLE ,true), APMPlaneMode(APMPlaneMode::STABILIZE ,true), APMPlaneMode(APMPlaneMode::TRAINING ,true), APMPlaneMode(APMPlaneMode::ACRO ,true), APMPlaneMode(APMPlaneMode::FLY_BY_WIRE_A ,true), APMPlaneMode(APMPlaneMode::FLY_BY_WIRE_B ,true), APMPlaneMode(APMPlaneMode::CRUISE ,true), APMPlaneMode(APMPlaneMode::AUTOTUNE ,true), APMPlaneMode(APMPlaneMode::AUTO ,true), APMPlaneMode(APMPlaneMode::RTL ,true), APMPlaneMode(APMPlaneMode::LOITER ,true), APMPlaneMode(APMPlaneMode::GUIDED ,true), APMPlaneMode(APMPlaneMode::INITIALIZING ,false), APMPlaneMode(APMPlaneMode::QSTABILIZE ,true), APMPlaneMode(APMPlaneMode::QHOVER ,true), APMPlaneMode(APMPlaneMode::QLOITER ,true), APMPlaneMode(APMPlaneMode::QLAND ,true), APMPlaneMode(APMPlaneMode::QRTL ,true), }); if (!_remapParamNameIntialized) { FirmwarePlugin::remapParamNameMap_t& remapV3_10 = _remapParamName[3][10]; remapV3_10["BATT_ARM_VOLT"] = QStringLiteral("ARMING_VOLT_MIN"); remapV3_10["BATT2_ARM_VOLT"] = QStringLiteral("ARMING_VOLT2_MIN"); _remapParamNameIntialized = true; } } int ArduPlaneFirmwarePlugin::remapParamNameHigestMinorVersionNumber(int majorVersionNumber) const { // Remapping supports up to 3.10 return majorVersionNumber == 3 ? 10 : Vehicle::versionNotSetValue; } <|endoftext|>
<commit_before>#ifndef EXECUTORS_H #define EXECUTORS_H /* An Executor is effectively the core of a function. Arc functions are represented by a closure structure, which has an attached Executor object. */ /* Calling convention: The Executor is given a Process which is the process within which it must execute itself. Assume you have: virtual void YourExecutor::operator()(Process& proc, Closure& clos) const{ ... } proc.stack[0] contains the closure (the same as clos). If the Executor represents a "normal" function, proc.stack[1] is the "continuation" function and proc.stack[2..n] are the parameters. proc.stack.size() is the number of parameters including the function itself and the continuation. If the Executor represents a "continuation" function, proc.stack[1] is always the return value. proc.stack.size() will be 2. When the Executor returns normally (i.e. without throwing) proc.stack[0] must contain the "next" closure to call, with the stack set up as described above. (as a hint, you can probably just push the values on the stack and then call proc.stack.restack(n)) proc.stack[0] *must* be a Closure with a valid Executor. */ #define PASTE_SYMBOLS(x,y) x##y /* Not necessary when using GCC. NOTE! We retain this and even add references to an _e_executor_label type so that modders who happen to use *only* GCC will remember to update the declarations for the benefit of non-GCC users. */ #define DECLARE_EXECUTORS enum _e_executor_label { #define EXECUTOR_ENUM(x) PASTE_SYMBOLS(_executor_, x) #define AN_EXECUTOR(x) EXECUTOR_ENUM(x), #define END_DECLARE_EXECUTORS __null_executor }; /*NOTE! no ; or : or {} or other markers*/ DECLARE_EXECUTORS AN_EXECUTOR(arc_executor) AN_EXECUTOR(ccc) AN_EXECUTOR(ccc_helper) AN_EXECUTOR(compile) AN_EXECUTOR(compile_helper) AN_EXECUTOR(compile_intseq_bytecode) AN_EXECUTOR(compile_seq_bytecode) AN_EXECUTOR(to_free_fun) AN_EXECUTOR(halting_continuation) AN_EXECUTOR(bif_dispatch) END_DECLARE_EXECUTORS #define DECLARE_BYTECODES enum _e_bytecode_label{ #define BYTECODE_ENUM(x) PASTE_SYMBOLS(_bytecode_, x) #define A_BYTECODE(x) BYTECODE_ENUM(x), #define END_DECLARE_BYTECODES __null_bytecode }; DECLARE_BYTECODES A_BYTECODE(apply) A_BYTECODE(apply_list) A_BYTECODE(car) A_BYTECODE(car_local_push) A_BYTECODE(car_clos_push) A_BYTECODE(cdr) A_BYTECODE(cdr_local_push) A_BYTECODE(cdr_clos_push) A_BYTECODE(check_vars) A_BYTECODE(closure) A_BYTECODE(cons) A_BYTECODE(b_continue) A_BYTECODE(continue_local) A_BYTECODE(continue_on_clos) A_BYTECODE(global) A_BYTECODE(global_set) A_BYTECODE(halt) A_BYTECODE(halt_local_push) A_BYTECODE(halt_clos_push) A_BYTECODE(b_if) A_BYTECODE(if_local) A_BYTECODE(b_int) A_BYTECODE(local) A_BYTECODE(sym) A_BYTECODE(variadic) END_DECLARE_BYTECODES #ifdef __GNUC__ /*use indirect goto when using GCC*/ typedef void* _executor_label; #define EXECUTOR_GOTO(x) goto *x #define DISPATCH_EXECUTORS enum _e_executor_label pc; NEXT_EXECUTOR; #define EXECUTOR(x) pc = EXECUTOR_ENUM(x); PASTE_SYMBOLS(label_, x) #define THE_EXECUTOR_LABEL(x) &&PASTE_SYMBOLS(label_, x) typedef void* _bytecode_label; #define DISPATCH_BYTECODES \ Closure& clos = *dynamic_cast<Closure*>(proc.stack[0]);\ ArcExecutor const* e =\ dynamic_cast<ArcExecutor const*>(&clos.code());\ Bytecode* current_bytecode = &*e->b->head; \ enum _e_bytecode_label bpc; NEXT_BYTECODE; #define BYTECODE_GOTO(x) goto *x #define BYTECODE(x) bpc = BYTECODE_ENUM(x); PASTE_SYMBOLS(label_b_, x) #define THE_BYTECODE_LABEL(x) &&PASTE_SYMBOLS(label_b_, x) #else //__GNUC__ /*use an enum when using standard C*/ typedef enum _e_executor_label _executor_label; #define EXECUTOR_GOTO(x) {pc = (x); goto executor_switch;} #define DISPATCH_EXECUTORS _executor_label pc; NEXT_EXECUTOR;\ executor_switch: switch(pc) #define EXECUTOR(x) case EXECUTOR_ENUM(x) #define THE_EXECUTOR_LABEL(x) EXECUTOR_ENUM(x) typedef enum _e_bytecode_label _bytecode_label; #define BYTECODE_GOTO(x) {bpc = (x); goto bytecode_switch;} #define DISPATCH_BYTECODES \ Closure& clos = *dynamic_cast<Closure*>(proc.stack[0]);\ ArcExecutor const* e =\ dynamic_cast<ArcExecutor const*>(&clos.code());\ Bytecode* current_bytecode = &*e->b->head; \ enum _e_bytecode_label bpc; NEXT_BYTECODE; \ bytecode_switch: switch(bpc) #define BYTECODE(x) case BYTECODE_ENUM(x) #define THE_BYTECODE_LABEL(x) BYTECODE_ENUM(x) #endif//__GNUC__ #define THE_EXECUTOR(x) new Executor(THE_EXECUTOR_LABEL(x)) #define THE_ARC_EXECUTOR(x,y) new ArcExecutor(THE_EXECUTOR_LABEL(x), y) /*TODO: 'call* / 'defcall support*/ #define NEXT_EXECUTOR if(--reductions != 0){ Closure* c = dynamic_cast<Closure*>(proc.stack[0]);\ if(c->code().l == THE_EXECUTOR_LABEL(arc_executor)) goto arc_executor_top;\ EXECUTOR_GOTO((c->code()).l);} else {return process_running;} #define NEXT_BYTECODE { current_bytecode = &*current_bytecode->next;\ BYTECODE_GOTO(current_bytecode->l);} #define GOTO_BYTECODE(x) { current_bytecode = (x);\ BYTECODE_GOTO(current_bytecode->l);} class Executor{ public: virtual ~Executor(){}; Executor(_executor_label nl) : l(nl) {}; _executor_label l; }; class BytecodeSequence; class ArcExecutor : public Executor{ public: virtual ~ArcExecutor(){}; boost::shared_ptr<BytecodeSequence> b; ArcExecutor(_executor_label nl, boost::shared_ptr<BytecodeSequence> nb) : Executor(nl), b(nb) {}; }; class Bytecode{ public: virtual ~Bytecode(){}; Bytecode(_bytecode_label nl) : l(nl), next() {}; _bytecode_label l; boost::scoped_ptr<Bytecode> next; }; /*bytecode with an int parameter*/ class IntBytecode : public Bytecode { public: virtual ~IntBytecode(){}; IntBytecode(_bytecode_label nl, int nnum) : Bytecode(nl), num(nnum){}; int num; }; /*bytecode with a bytecode sequence parameter (e.g. 'if, 'fn) NOTE! recursive references not allowed! */ class SeqBytecode : public Bytecode { public: virtual ~SeqBytecode(){}; SeqBytecode(_bytecode_label nl, boost::shared_ptr<BytecodeSequence> nseq) : Bytecode(nl), seq(nseq) {}; boost::shared_ptr<BytecodeSequence> seq; }; class IntSeqBytecode : public Bytecode{ public: virtual ~IntSeqBytecode(){ }; IntSeqBytecode(_bytecode_label nl, int nnum, boost::shared_ptr<BytecodeSequence> nseq) : Bytecode(nl), num(nnum), seq(nseq) {}; int num; boost::shared_ptr<BytecodeSequence> seq; }; /*bytecode with an atom parameter (e.g. 'global, 'symbol) */ class AtomBytecode : public Bytecode{ public: virtual ~AtomBytecode (){}; AtomBytecode(_bytecode_label nl, boost::shared_ptr<Atom> natom) : Bytecode(nl), atom(natom) {}; boost::shared_ptr<Atom> atom; }; class BytecodeSequence { private: Bytecode* tail; public: boost::scoped_ptr<Bytecode> head; void append(Bytecode* b){ if(tail != NULL){ tail->next.reset(b); } else { head.reset(b); } tail = b; } BytecodeSequence() : tail(NULL), head(NULL) {} }; /*Bytecode definition helper macros*/ #define INTPARAM(i)\ int& i = (dynamic_cast<IntBytecode*>(current_bytecode))->num #define SEQPARAM(i)\ boost::shared_ptr<BytecodeSequence>& i =\ (dynamic_cast<SeqBytecode*>(current_bytecode))->seq #define INTSEQPARAM(i,s)\ int& i = (dynamic_cast<IntSeqBytecode*>(current_bytecode))->num;\ boost::shared_ptr<BytecodeSequence>& s =\ (dynamic_cast<IntSeqBytecode*>(current_bytecode))->seq #define ATOMPARAM(s)\ boost::shared_ptr<Atom>& s =\ (dynamic_cast<AtomBytecode*>(current_bytecode))->atom; typedef enum _e_ProcessStatus { process_running, process_waiting, process_dead } ProcessStatus; class Process; ProcessStatus execute(Process& proc, size_t reductions, bool init=0); #endif //EXECUTORS_H <commit_msg>Converted a few other dynamic_cast's to static_cast's<commit_after>#ifndef EXECUTORS_H #define EXECUTORS_H /* An Executor is effectively the core of a function. Arc functions are represented by a closure structure, which has an attached Executor object. */ /* Calling convention: The Executor is given a Process which is the process within which it must execute itself. Assume you have: virtual void YourExecutor::operator()(Process& proc, Closure& clos) const{ ... } proc.stack[0] contains the closure (the same as clos). If the Executor represents a "normal" function, proc.stack[1] is the "continuation" function and proc.stack[2..n] are the parameters. proc.stack.size() is the number of parameters including the function itself and the continuation. If the Executor represents a "continuation" function, proc.stack[1] is always the return value. proc.stack.size() will be 2. When the Executor returns normally (i.e. without throwing) proc.stack[0] must contain the "next" closure to call, with the stack set up as described above. (as a hint, you can probably just push the values on the stack and then call proc.stack.restack(n)) proc.stack[0] *must* be a Closure with a valid Executor. */ #define PASTE_SYMBOLS(x,y) x##y /* Not necessary when using GCC. NOTE! We retain this and even add references to an _e_executor_label type so that modders who happen to use *only* GCC will remember to update the declarations for the benefit of non-GCC users. */ #define DECLARE_EXECUTORS enum _e_executor_label { #define EXECUTOR_ENUM(x) PASTE_SYMBOLS(_executor_, x) #define AN_EXECUTOR(x) EXECUTOR_ENUM(x), #define END_DECLARE_EXECUTORS __null_executor }; /*NOTE! no ; or : or {} or other markers*/ DECLARE_EXECUTORS AN_EXECUTOR(arc_executor) AN_EXECUTOR(ccc) AN_EXECUTOR(ccc_helper) AN_EXECUTOR(compile) AN_EXECUTOR(compile_helper) AN_EXECUTOR(compile_intseq_bytecode) AN_EXECUTOR(compile_seq_bytecode) AN_EXECUTOR(to_free_fun) AN_EXECUTOR(halting_continuation) AN_EXECUTOR(bif_dispatch) END_DECLARE_EXECUTORS #define DECLARE_BYTECODES enum _e_bytecode_label{ #define BYTECODE_ENUM(x) PASTE_SYMBOLS(_bytecode_, x) #define A_BYTECODE(x) BYTECODE_ENUM(x), #define END_DECLARE_BYTECODES __null_bytecode }; DECLARE_BYTECODES A_BYTECODE(apply) A_BYTECODE(apply_list) A_BYTECODE(car) A_BYTECODE(car_local_push) A_BYTECODE(car_clos_push) A_BYTECODE(cdr) A_BYTECODE(cdr_local_push) A_BYTECODE(cdr_clos_push) A_BYTECODE(check_vars) A_BYTECODE(closure) A_BYTECODE(cons) A_BYTECODE(b_continue) A_BYTECODE(continue_local) A_BYTECODE(continue_on_clos) A_BYTECODE(global) A_BYTECODE(global_set) A_BYTECODE(halt) A_BYTECODE(halt_local_push) A_BYTECODE(halt_clos_push) A_BYTECODE(b_if) A_BYTECODE(if_local) A_BYTECODE(b_int) A_BYTECODE(local) A_BYTECODE(sym) A_BYTECODE(variadic) END_DECLARE_BYTECODES #ifdef __GNUC__ /*use indirect goto when using GCC*/ typedef void* _executor_label; #define EXECUTOR_GOTO(x) goto *x #define DISPATCH_EXECUTORS enum _e_executor_label pc; NEXT_EXECUTOR; #define EXECUTOR(x) pc = EXECUTOR_ENUM(x); PASTE_SYMBOLS(label_, x) #define THE_EXECUTOR_LABEL(x) &&PASTE_SYMBOLS(label_, x) typedef void* _bytecode_label; #define DISPATCH_BYTECODES \ Closure& clos = *static_cast<Closure*>(proc.stack[0]);\ ArcExecutor const* e =\ static_cast<ArcExecutor const*>(&clos.code());\ Bytecode* current_bytecode = &*e->b->head; \ enum _e_bytecode_label bpc; NEXT_BYTECODE; #define BYTECODE_GOTO(x) goto *x #define BYTECODE(x) bpc = BYTECODE_ENUM(x); PASTE_SYMBOLS(label_b_, x) #define THE_BYTECODE_LABEL(x) &&PASTE_SYMBOLS(label_b_, x) #else //__GNUC__ /*use an enum when using standard C*/ typedef enum _e_executor_label _executor_label; #define EXECUTOR_GOTO(x) {pc = (x); goto executor_switch;} #define DISPATCH_EXECUTORS _executor_label pc; NEXT_EXECUTOR;\ executor_switch: switch(pc) #define EXECUTOR(x) case EXECUTOR_ENUM(x) #define THE_EXECUTOR_LABEL(x) EXECUTOR_ENUM(x) typedef enum _e_bytecode_label _bytecode_label; #define BYTECODE_GOTO(x) {bpc = (x); goto bytecode_switch;} #define DISPATCH_BYTECODES \ Closure& clos = *static_cast<Closure*>(proc.stack[0]);\ ArcExecutor const* e =\ static_cast<ArcExecutor const*>(&clos.code());\ Bytecode* current_bytecode = &*e->b->head; \ enum _e_bytecode_label bpc; NEXT_BYTECODE; \ bytecode_switch: switch(bpc) #define BYTECODE(x) case BYTECODE_ENUM(x) #define THE_BYTECODE_LABEL(x) BYTECODE_ENUM(x) #endif//__GNUC__ #define THE_EXECUTOR(x) new Executor(THE_EXECUTOR_LABEL(x)) #define THE_ARC_EXECUTOR(x,y) new ArcExecutor(THE_EXECUTOR_LABEL(x), y) /*TODO: 'call* / 'defcall support*/ #define NEXT_EXECUTOR if(--reductions != 0){ Closure* c = dynamic_cast<Closure*>(proc.stack[0]);\ /*TODO: insert check that c is not NULL; if NULL, lookup in call* */\ if(c->code().l == THE_EXECUTOR_LABEL(arc_executor)) goto arc_executor_top;\ EXECUTOR_GOTO((c->code()).l);} else {return process_running;} #define NEXT_BYTECODE { current_bytecode = &*current_bytecode->next;\ BYTECODE_GOTO(current_bytecode->l);} #define GOTO_BYTECODE(x) { current_bytecode = (x);\ BYTECODE_GOTO(current_bytecode->l);} class Executor{ public: virtual ~Executor(){}; Executor(_executor_label nl) : l(nl) {}; _executor_label l; }; class BytecodeSequence; class ArcExecutor : public Executor{ public: virtual ~ArcExecutor(){}; boost::shared_ptr<BytecodeSequence> b; ArcExecutor(_executor_label nl, boost::shared_ptr<BytecodeSequence> nb) : Executor(nl), b(nb) {}; }; class Bytecode{ public: virtual ~Bytecode(){}; Bytecode(_bytecode_label nl) : l(nl), next() {}; _bytecode_label l; boost::scoped_ptr<Bytecode> next; }; /*bytecode with an int parameter*/ class IntBytecode : public Bytecode { public: virtual ~IntBytecode(){}; IntBytecode(_bytecode_label nl, int nnum) : Bytecode(nl), num(nnum){}; int num; }; /*bytecode with a bytecode sequence parameter (e.g. 'if, 'fn) NOTE! recursive references not allowed! */ class SeqBytecode : public Bytecode { public: virtual ~SeqBytecode(){}; SeqBytecode(_bytecode_label nl, boost::shared_ptr<BytecodeSequence> nseq) : Bytecode(nl), seq(nseq) {}; boost::shared_ptr<BytecodeSequence> seq; }; class IntSeqBytecode : public Bytecode{ public: virtual ~IntSeqBytecode(){ }; IntSeqBytecode(_bytecode_label nl, int nnum, boost::shared_ptr<BytecodeSequence> nseq) : Bytecode(nl), num(nnum), seq(nseq) {}; int num; boost::shared_ptr<BytecodeSequence> seq; }; /*bytecode with an atom parameter (e.g. 'global, 'symbol) */ class AtomBytecode : public Bytecode{ public: virtual ~AtomBytecode (){}; AtomBytecode(_bytecode_label nl, boost::shared_ptr<Atom> natom) : Bytecode(nl), atom(natom) {}; boost::shared_ptr<Atom> atom; }; class BytecodeSequence { private: Bytecode* tail; public: boost::scoped_ptr<Bytecode> head; void append(Bytecode* b){ if(tail != NULL){ tail->next.reset(b); } else { head.reset(b); } tail = b; } BytecodeSequence() : tail(NULL), head(NULL) {} }; /*Bytecode definition helper macros*/ /*WARNING! Assumes that the bytecodes are correct in the first place!*/ #define INTPARAM(i)\ int& i = (static_cast<IntBytecode*>(current_bytecode))->num #define SEQPARAM(i)\ boost::shared_ptr<BytecodeSequence>& i =\ (static_cast<SeqBytecode*>(current_bytecode))->seq #define INTSEQPARAM(i,s)\ int& i = (static_cast<IntSeqBytecode*>(current_bytecode))->num;\ boost::shared_ptr<BytecodeSequence>& s =\ (static_cast<IntSeqBytecode*>(current_bytecode))->seq #define ATOMPARAM(s)\ boost::shared_ptr<Atom>& s =\ (static_cast<AtomBytecode*>(current_bytecode))->atom; typedef enum _e_ProcessStatus { process_running, process_waiting, process_dead } ProcessStatus; class Process; ProcessStatus execute(Process& proc, size_t reductions, bool init=0); #endif //EXECUTORS_H <|endoftext|>
<commit_before>#ifndef GENERIC_FORWARDER_HPP # define GENERIC_FORWARDER_HPP # pragma once #include <cassert> #include <cstddef> #include <cstdint> #include <type_traits> #include <utility> namespace generic { template<typename F, ::std::size_t N = 4 * sizeof(::std::uintptr_t)> class forwarder; template<typename R, typename ...A, ::std::size_t N> class forwarder<R (A...), N> { template <typename U> static R invoker_stub(void const* const ptr, A&&... args) noexcept(noexcept( (*static_cast<U const*>(ptr))(::std::forward<A>(args)...))) { return (*static_cast<U const*>(ptr))(::std::forward<A>(args)...); } R (*stub_)(void const*, A&&...){}; typename ::std::aligned_storage<N>::type store_; public: forwarder() = default; forwarder(forwarder const&) = default; template<typename T> forwarder(T&& f) { *this = ::std::forward<T>(f); } forwarder& operator=(forwarder const&) = default; forwarder& operator=(forwarder&&) = default; template < typename T, typename = typename ::std::enable_if< !::std::is_same<forwarder, typename ::std::decay<T>::type>{} >::type > forwarder& operator=(T&& f) { using functor_type = typename ::std::decay<T>::type; static_assert(sizeof(functor_type) <= sizeof(store_), "functor too large"); static_assert(::std::is_trivially_destructible<T>::value, "functor not trivially destructible"); //static_assert(::std::is_trivially_copy_assignable<T>::value, // "functor not trivially copy assignable"); //static_assert(::std::is_trivially_copy_constructible<T>::value, // "functor not trivially copy constructible"); new (static_cast<void*>(&store_)) functor_type(::std::forward<T>(f)); stub_ = invoker_stub<functor_type>; return *this; } explicit operator bool() const noexcept { return stub_; } R operator()(A... args) const noexcept(noexcept(stub_(&store_, ::std::forward<A>(args)...))) { //assert(stub_); return stub_(&store_, ::std::forward<A>(args)...); } void reset() noexcept { stub_ = {}; } }; } #endif // GENERIC_FORWARDER_HPP <commit_msg>some fixes<commit_after>#ifndef GENERIC_FORWARDER_HPP # define GENERIC_FORWARDER_HPP # pragma once #include <cassert> #include <cstddef> #include <cstdint> #include <type_traits> #include <utility> namespace generic { template<typename F, ::std::size_t N = 4 * sizeof(::std::uintptr_t)> class forwarder; template<typename R, typename ...A, ::std::size_t N> class forwarder<R (A...), N> { template <typename U> static R invoker_stub(void const* const ptr, A&&... args) noexcept(noexcept( (*static_cast<U const*>(ptr))(::std::forward<A>(args)...))) { return (*static_cast<U const*>(ptr))(::std::forward<A>(args)...); } R (*stub_)(void const*, A&&...){}; typename ::std::aligned_storage<N>::type store_; public: forwarder() = default; forwarder(forwarder const&) = default; template<typename T> forwarder(T&& f) { *this = ::std::forward<T>(f); } forwarder& operator=(forwarder const&) = default; forwarder& operator=(forwarder&&) = default; template < typename T, typename = typename ::std::enable_if< !::std::is_same<forwarder, typename ::std::decay<T>::type>{} >::type > forwarder& operator=(T&& f) { using functor_type = typename ::std::decay<T>::type; static_assert(sizeof(functor_type) <= sizeof(store_), "functor too large"); // static_assert(::std::is_trivially_copyable<T>{}, // "functor not trivially destructible"); new (static_cast<void*>(&store_)) functor_type(::std::forward<T>(f)); stub_ = invoker_stub<functor_type>; return *this; } explicit operator bool() const noexcept { return stub_; } R operator()(A... args) const noexcept(noexcept(stub_(&store_, ::std::forward<A>(args)...))) { //assert(stub_); return stub_(&store_, ::std::forward<A>(args)...); } void reset() noexcept { stub_ = {}; } }; } #endif // GENERIC_FORWARDER_HPP <|endoftext|>
<commit_before>#include <iostream> using namespace std; int main(void) { cout<<"hello, world!"<<endl; return 0; }<commit_msg>rm file<commit_after><|endoftext|>
<commit_before><commit_msg>added usage of the new profiler<commit_after><|endoftext|>
<commit_before>#include "ModifierBlock.h" #include "Character.h" using namespace std; ModifierBlock::ModifierBlock(ModifierBlock& other) : LogicBlock(){ target = other.target; previous_modifier = other.previous_modifier; modifiers = other.modifiers; } void ModifierBlock::set_target(Character* new_target) { target = new_target; } Character* ModifierBlock::get_target() const { return target; } QMap<QString, qint8> ModifierBlock::get_modifiers() const { return modifiers; } qint8 ModifierBlock::get_modifier(const QString& name) const { return modifiers.value(name); } void ModifierBlock::set_modifier(QString name, qint8 value) { modifiers[name] = value; } void ModifierBlock::set_previous_modifier(ModifierBlock* other) { previous_modifier = other; target = other->get_target(); for (QString key : other->modifiers.keys()) { set_modifier(key,other->get_modifier(key)*-1); } } ModifierBlock* ModifierBlock::get_previous_modifer() const { return previous_modifier; } void ModifierBlock::populate_id_fields(QList<LogicBlock*>& blocks, QList<Character*>& chars) { next_id = blocks.indexOf(get_next()); target_id = chars.indexOf(target); //previous_mod_id = blocks.indexOf(previous_modifier); if (get_next() != nullptr) get_next()->populate_id_fields(blocks, chars); } void ModifierBlock::populate_pointer_fields(QList<LogicBlock*>& blocks, QList<Character*>& chars) { set_next(blocks.value(next_id)); set_target(chars.value(target_id)); //previous_modifier = blocks.value(previous_mod_id); if (get_next() != nullptr) { get_next()->populate_pointer_fields(blocks, chars); } } void ModifierBlock::remove_modifier(QString name) { if (modifiers.find(name) != modifiers.end()) modifiers.remove(name); else throw logicblock_error("Can't erase modifier, it dosent exist"); } LogicBlock* ModifierBlock::execute() { for (auto key : modifiers.keys()) { target->add_to_attribute(key,modifiers.value(key)); } return this->get_next(); } QDataStream& ModifierBlock::write_to_stream(QDataStream & ds) { ds << next_id; ds << get_last(); ds << modifiers; ds << target_id; //ds << previous_mod_id; return ds; } QDataStream& ModifierBlock::read_from_stream(QDataStream& ds) { bool temp_last; ds >> next_id; ds >> temp_last; set_last(temp_last); ds >> modifiers; ds >> target_id; //ds >> previous_mod_id; return ds; } <commit_msg>WaitBlock will now save and load previous_modifier<commit_after>#include "ModifierBlock.h" #include "Character.h" using namespace std; ModifierBlock::ModifierBlock(ModifierBlock& other) : LogicBlock(){ target = other.target; previous_modifier = other.previous_modifier; modifiers = other.modifiers; } void ModifierBlock::set_target(Character* new_target) { target = new_target; } Character* ModifierBlock::get_target() const { return target; } QMap<QString, qint8> ModifierBlock::get_modifiers() const { return modifiers; } qint8 ModifierBlock::get_modifier(const QString& name) const { return modifiers.value(name); } void ModifierBlock::set_modifier(QString name, qint8 value) { modifiers[name] = value; } void ModifierBlock::set_previous_modifier(ModifierBlock* other) { previous_modifier = other; target = other->get_target(); for (QString key : other->modifiers.keys()) { set_modifier(key,other->get_modifier(key)*-1); } } ModifierBlock* ModifierBlock::get_previous_modifer() const { return previous_modifier; } void ModifierBlock::populate_id_fields(QList<LogicBlock*>& blocks, QList<Character*>& chars) { next_id = blocks.indexOf(get_next()); target_id = chars.indexOf(target); previous_mod_id = blocks.indexOf(previous_modifier); if (get_next() != nullptr) get_next()->populate_id_fields(blocks, chars); } void ModifierBlock::populate_pointer_fields(QList<LogicBlock*>& blocks, QList<Character*>& chars) { set_next(blocks.value(next_id)); set_target(chars.value(target_id)); previous_modifier = dynamic_cast<ModifierBlock*>(blocks.value(previous_mod_id)); if (get_next() != nullptr) { get_next()->populate_pointer_fields(blocks, chars); } } void ModifierBlock::remove_modifier(QString name) { if (modifiers.find(name) != modifiers.end()) modifiers.remove(name); else throw logicblock_error("Can't erase modifier, it dosent exist"); } LogicBlock* ModifierBlock::execute() { for (auto key : modifiers.keys()) { target->add_to_attribute(key,modifiers.value(key)); } return this->get_next(); } QDataStream& ModifierBlock::write_to_stream(QDataStream & ds) { ds << next_id; ds << get_last(); ds << modifiers; ds << target_id; ds << previous_mod_id; return ds; } QDataStream& ModifierBlock::read_from_stream(QDataStream& ds) { bool temp_last; ds >> next_id; ds >> temp_last; set_last(temp_last); ds >> modifiers; ds >> target_id; ds >> previous_mod_id; return ds; } <|endoftext|>
<commit_before>#pragma once #include "apple_hid_usage_tables.hpp" #include "console_user_client.hpp" #include "constants.hpp" #include "hid_report.hpp" #include "human_interface_device.hpp" #include "iokit_user_client.hpp" #include "iokit_utility.hpp" #include "logger.hpp" #include "manipulator.hpp" #include "userspace_defs.h" #include "virtual_hid_manager_user_client_method.hpp" #include <thread> class device_grabber final { public: device_grabber(void) : iokit_user_client_(logger::get_logger(), "org_pqrs_driver_VirtualHIDManager", kIOHIDServerConnectType), console_user_client_() { logger::get_logger().info(__PRETTY_FUNCTION__); manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); if (!manager_) { logger::get_logger().error("{0}: failed to IOHIDManagerCreate", __PRETTY_FUNCTION__); return; } auto device_matching_dictionaries = iokit_utility::create_device_matching_dictionaries({ std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard), // std::make_pair(kHIDPage_Consumer, kHIDUsage_Csmr_ConsumerControl), // std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Mouse), }); if (device_matching_dictionaries) { IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries); CFRelease(device_matching_dictionaries); IOHIDManagerRegisterDeviceMatchingCallback(manager_, static_device_matching_callback, this); IOHIDManagerRegisterDeviceRemovalCallback(manager_, static_device_removal_callback, this); IOHIDManagerScheduleWithRunLoop(manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode); } } ~device_grabber(void) { logger::get_logger().info(__PRETTY_FUNCTION__); if (manager_) { IOHIDManagerUnscheduleFromRunLoop(manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode); CFRelease(manager_); manager_ = nullptr; } } void set_simple_modifications(const uint32_t* _Nullable data, size_t size) { std::lock_guard<std::mutex> guard(simple_modifications_mutex_); simple_modifications_.clear(); if (size > 0) { for (size_t i = 0; i < size - 1; i += 2) { logger::get_logger().info("simple_modification: 0x{0:x} -> 0x{1:x}", data[i], data[i + 1]); simple_modifications_[manipulator::key_code(data[i])] = manipulator::key_code(data[i + 1]); } } } private: static void static_device_matching_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) { if (result != kIOReturnSuccess) { return; } auto self = static_cast<device_grabber*>(context); if (!self) { return; } self->device_matching_callback(device); } void device_matching_callback(IOHIDDeviceRef _Nonnull device) { if (!device) { return; } uint64_t entry_id; if (!iokit_utility::get_registry_entry_id(device, entry_id)) { logger::get_logger().error("get_registry_entry_id is failed"); return; } hids_[device] = std::make_unique<human_interface_device>(device); auto& dev = hids_[device]; logger::get_logger().info("matching device: " "manufacturer:{1}, " "product:{2}, " "vendor_id:0x{3:x}, " "product_id:0x{4:x}, " "location_id:0x{5:x}, " "serial_number:{6} " "@ {0}", __PRETTY_FUNCTION__, dev->get_manufacturer(), dev->get_product(), dev->get_vendor_id(), dev->get_product_id(), dev->get_location_id(), dev->get_serial_number_string()); if (dev->get_serial_number_string() == "org.pqrs.driver.VirtualHIDKeyboard") { return; } if (dev->get_manufacturer() != "pqrs.org") { dev->grab(boost::bind(&device_grabber::value_callback, this, _1, _2, _3, _4, _5, _6)); } } static void static_device_removal_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) { if (result != kIOReturnSuccess) { return; } auto self = static_cast<device_grabber*>(context); if (!self) { return; } self->device_removal_callback(device); } void device_removal_callback(IOHIDDeviceRef _Nonnull device) { if (!device) { return; } auto it = hids_.find(device); if (it != hids_.end()) { auto& dev = it->second; if (dev) { logger::get_logger().info("removal device: " "vendor_id:0x{1:x}, " "product_id:0x{2:x}, " "location_id:0x{3:x} " "@ {0}", __PRETTY_FUNCTION__, dev->get_vendor_id(), dev->get_product_id(), dev->get_location_id()); hids_.erase(it); } } } void value_callback(human_interface_device& device, IOHIDValueRef _Nonnull value, IOHIDElementRef _Nonnull element, uint32_t usage_page, uint32_t usage, CFIndex integer_value) { #if 0 std::cout << "element" << std::endl << " usage_page:0x" << std::hex << usage_page << std::endl << " usage:0x" << std::hex << usage << std::endl << " type:" << IOHIDElementGetType(element) << std::endl << " length:" << IOHIDValueGetLength(value) << std::endl << " integer_value:" << integer_value << std::endl; #endif switch (usage_page) { case kHIDPage_KeyboardOrKeypad: if (kHIDUsage_KeyboardErrorUndefined < usage && usage < kHIDUsage_Keyboard_Reserved) { bool pressed = integer_value; handle_keyboard_event(device, manipulator::key_code(usage), pressed); } break; case kHIDPage_AppleVendorTopCase: if (usage == kHIDUsage_AV_TopCase_KeyboardFn) { bool pressed = integer_value; handle_keyboard_event(device, manipulator::key_code::vk_fn_modifier, pressed); } break; default: break; } } bool handle_modifier_flag_event(manipulator::key_code key_code, bool pressed) { auto operation = pressed ? manipulator::modifier_flag_manager::operation::increase : manipulator::modifier_flag_manager::operation::decrease; auto modifier_flag = manipulator::get_modifier_flag(key_code); if (modifier_flag != manipulator::modifier_flag::zero) { modifier_flag_manager_.manipulate(modifier_flag, operation); // reset modifier_flags state if all keys are released. if (get_all_devices_pressed_keys_count() == 0) { modifier_flag_manager_.reset(); } if (modifier_flag == manipulator::modifier_flag::fn) { console_user_client_.post_modifier_flags(modifier_flag_manager_.get_io_option_bits()); } else { send_keyboard_input_report(); } return true; } return false; } bool handle_function_key_event(manipulator::key_code key_code, bool pressed) { auto event_type = pressed ? KRBN_EVENT_TYPE_KEY_DOWN : KRBN_EVENT_TYPE_KEY_UP; if (manipulator::key_code::vk_f1 <= key_code && key_code <= manipulator::key_code::vk_f12) { auto i = static_cast<uint32_t>(key_code) - static_cast<uint32_t>(manipulator::key_code::vk_f1); console_user_client_.post_key(static_cast<krbn_key_code>(KRBN_KEY_CODE_F1 + i), event_type, modifier_flag_manager_.get_io_option_bits()); return true; } if (manipulator::key_code::vk_fn_f1 <= key_code && key_code <= manipulator::key_code::vk_fn_f12) { auto i = static_cast<uint32_t>(key_code) - static_cast<uint32_t>(manipulator::key_code::vk_fn_f1); console_user_client_.post_key(static_cast<krbn_key_code>(KRBN_KEY_CODE_FN_F1 + i), event_type, modifier_flag_manager_.get_io_option_bits()); return true; } return false; } void handle_keyboard_event(human_interface_device& device, manipulator::key_code key_code, bool pressed) { // ---------------------------------------- // modify usage if (!pressed) { auto it = device.get_simple_changed_keys().find(key_code); if (it != device.get_simple_changed_keys().end()) { key_code = it->second; device.get_simple_changed_keys().erase(it); } } else { std::lock_guard<std::mutex> guard(simple_modifications_mutex_); auto it = simple_modifications_.find(key_code); if (it != simple_modifications_.end()) { (device.get_simple_changed_keys())[key_code] = it->second; key_code = it->second; } } // modify fn+arrow, function keys if (!pressed) { auto it = device.get_fn_changed_keys().find(key_code); if (it != device.get_fn_changed_keys().end()) { key_code = it->second; device.get_fn_changed_keys().erase(it); } } else { auto k = static_cast<uint32_t>(key_code); auto new_key_code = key_code; if (modifier_flag_manager_.pressed(manipulator::modifier_flag::fn)) { if (k == kHIDUsage_KeyboardReturnOrEnter) { new_key_code = manipulator::key_code(kHIDUsage_KeypadEnter); } else if (k == kHIDUsage_KeyboardDeleteOrBackspace) { new_key_code = manipulator::key_code(kHIDUsage_KeyboardDeleteForward); } else if (k == kHIDUsage_KeyboardRightArrow) { new_key_code = manipulator::key_code(kHIDUsage_KeyboardEnd); } else if (k == kHIDUsage_KeyboardLeftArrow) { new_key_code = manipulator::key_code(kHIDUsage_KeyboardHome); } else if (k == kHIDUsage_KeyboardDownArrow) { new_key_code = manipulator::key_code(kHIDUsage_KeyboardPageDown); } else if (k == kHIDUsage_KeyboardUpArrow) { new_key_code = manipulator::key_code(kHIDUsage_KeyboardPageUp); } else if (kHIDUsage_KeyboardF1 <= k && k <= kHIDUsage_KeyboardF12) { new_key_code = manipulator::key_code(static_cast<uint32_t>(manipulator::key_code::vk_fn_f1) + k - kHIDUsage_KeyboardF1); } } else { if (kHIDUsage_KeyboardF1 <= k && k <= kHIDUsage_KeyboardF12) { new_key_code = manipulator::key_code(static_cast<uint32_t>(manipulator::key_code::vk_f1) + k - kHIDUsage_KeyboardF1); } } if (key_code != new_key_code) { (device.get_fn_changed_keys())[key_code] = new_key_code; key_code = new_key_code; } } // ---------------------------------------- // send input events to virtual devices. if (handle_modifier_flag_event(key_code, pressed)) { console_user_client_.stop_key_repeat(); return; } if (handle_function_key_event(key_code, pressed)) { return; } if (static_cast<uint32_t>(key_code) < kHIDUsage_Keyboard_Reserved) { auto usage = static_cast<uint32_t>(key_code); if (pressed) { pressed_key_usages_.push_back(usage); console_user_client_.stop_key_repeat(); } else { pressed_key_usages_.remove(usage); } send_keyboard_input_report(); } } void send_keyboard_input_report(void) { // make report hid_report::keyboard_input report; report.modifiers = modifier_flag_manager_.get_hid_report_bits(); while (pressed_key_usages_.size() > sizeof(report.keys)) { pressed_key_usages_.pop_front(); } int i = 0; for (const auto& u : pressed_key_usages_) { report.keys[i] = u; ++i; } // send new report only if it is changed from last report. if (last_keyboard_input_report_ != report) { last_keyboard_input_report_ = report; auto kr = iokit_user_client_.call_struct_method(static_cast<uint32_t>(virtual_hid_manager_user_client_method::keyboard_input_report), static_cast<const void*>(&report), sizeof(report), nullptr, 0); if (kr != KERN_SUCCESS) { logger::get_logger().error("failed to sent report: 0x{0:x}", kr); } } } size_t get_all_devices_pressed_keys_count(void) const { size_t total = 0; for (const auto& it : hids_) { if (it.second) { total += (it.second)->get_pressed_keys_count(); } } return total; } iokit_user_client iokit_user_client_; IOHIDManagerRef _Nullable manager_; std::unordered_map<IOHIDDeviceRef, std::unique_ptr<human_interface_device>> hids_; std::list<uint32_t> pressed_key_usages_; manipulator::modifier_flag_manager modifier_flag_manager_; hid_report::keyboard_input last_keyboard_input_report_; std::unordered_map<manipulator::key_code, manipulator::key_code> simple_modifications_; std::mutex simple_modifications_mutex_; console_user_client console_user_client_; }; <commit_msg>suppress log<commit_after>#pragma once #include "apple_hid_usage_tables.hpp" #include "console_user_client.hpp" #include "constants.hpp" #include "hid_report.hpp" #include "human_interface_device.hpp" #include "iokit_user_client.hpp" #include "iokit_utility.hpp" #include "logger.hpp" #include "manipulator.hpp" #include "userspace_defs.h" #include "virtual_hid_manager_user_client_method.hpp" #include <thread> class device_grabber final { public: device_grabber(void) : iokit_user_client_(logger::get_logger(), "org_pqrs_driver_VirtualHIDManager", kIOHIDServerConnectType), console_user_client_() { logger::get_logger().info(__PRETTY_FUNCTION__); manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); if (!manager_) { logger::get_logger().error("{0}: failed to IOHIDManagerCreate", __PRETTY_FUNCTION__); return; } auto device_matching_dictionaries = iokit_utility::create_device_matching_dictionaries({ std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard), // std::make_pair(kHIDPage_Consumer, kHIDUsage_Csmr_ConsumerControl), // std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Mouse), }); if (device_matching_dictionaries) { IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries); CFRelease(device_matching_dictionaries); IOHIDManagerRegisterDeviceMatchingCallback(manager_, static_device_matching_callback, this); IOHIDManagerRegisterDeviceRemovalCallback(manager_, static_device_removal_callback, this); IOHIDManagerScheduleWithRunLoop(manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode); } } ~device_grabber(void) { logger::get_logger().info(__PRETTY_FUNCTION__); if (manager_) { IOHIDManagerUnscheduleFromRunLoop(manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode); CFRelease(manager_); manager_ = nullptr; } } void set_simple_modifications(const uint32_t* _Nullable data, size_t size) { std::lock_guard<std::mutex> guard(simple_modifications_mutex_); simple_modifications_.clear(); if (size > 0) { for (size_t i = 0; i < size - 1; i += 2) { simple_modifications_[manipulator::key_code(data[i])] = manipulator::key_code(data[i + 1]); } } } private: static void static_device_matching_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) { if (result != kIOReturnSuccess) { return; } auto self = static_cast<device_grabber*>(context); if (!self) { return; } self->device_matching_callback(device); } void device_matching_callback(IOHIDDeviceRef _Nonnull device) { if (!device) { return; } uint64_t entry_id; if (!iokit_utility::get_registry_entry_id(device, entry_id)) { logger::get_logger().error("get_registry_entry_id is failed"); return; } hids_[device] = std::make_unique<human_interface_device>(device); auto& dev = hids_[device]; logger::get_logger().info("matching device: " "manufacturer:{1}, " "product:{2}, " "vendor_id:0x{3:x}, " "product_id:0x{4:x}, " "location_id:0x{5:x}, " "serial_number:{6} " "@ {0}", __PRETTY_FUNCTION__, dev->get_manufacturer(), dev->get_product(), dev->get_vendor_id(), dev->get_product_id(), dev->get_location_id(), dev->get_serial_number_string()); if (dev->get_serial_number_string() == "org.pqrs.driver.VirtualHIDKeyboard") { return; } if (dev->get_manufacturer() != "pqrs.org") { dev->grab(boost::bind(&device_grabber::value_callback, this, _1, _2, _3, _4, _5, _6)); } } static void static_device_removal_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) { if (result != kIOReturnSuccess) { return; } auto self = static_cast<device_grabber*>(context); if (!self) { return; } self->device_removal_callback(device); } void device_removal_callback(IOHIDDeviceRef _Nonnull device) { if (!device) { return; } auto it = hids_.find(device); if (it != hids_.end()) { auto& dev = it->second; if (dev) { logger::get_logger().info("removal device: " "vendor_id:0x{1:x}, " "product_id:0x{2:x}, " "location_id:0x{3:x} " "@ {0}", __PRETTY_FUNCTION__, dev->get_vendor_id(), dev->get_product_id(), dev->get_location_id()); hids_.erase(it); } } } void value_callback(human_interface_device& device, IOHIDValueRef _Nonnull value, IOHIDElementRef _Nonnull element, uint32_t usage_page, uint32_t usage, CFIndex integer_value) { #if 0 std::cout << "element" << std::endl << " usage_page:0x" << std::hex << usage_page << std::endl << " usage:0x" << std::hex << usage << std::endl << " type:" << IOHIDElementGetType(element) << std::endl << " length:" << IOHIDValueGetLength(value) << std::endl << " integer_value:" << integer_value << std::endl; #endif switch (usage_page) { case kHIDPage_KeyboardOrKeypad: if (kHIDUsage_KeyboardErrorUndefined < usage && usage < kHIDUsage_Keyboard_Reserved) { bool pressed = integer_value; handle_keyboard_event(device, manipulator::key_code(usage), pressed); } break; case kHIDPage_AppleVendorTopCase: if (usage == kHIDUsage_AV_TopCase_KeyboardFn) { bool pressed = integer_value; handle_keyboard_event(device, manipulator::key_code::vk_fn_modifier, pressed); } break; default: break; } } bool handle_modifier_flag_event(manipulator::key_code key_code, bool pressed) { auto operation = pressed ? manipulator::modifier_flag_manager::operation::increase : manipulator::modifier_flag_manager::operation::decrease; auto modifier_flag = manipulator::get_modifier_flag(key_code); if (modifier_flag != manipulator::modifier_flag::zero) { modifier_flag_manager_.manipulate(modifier_flag, operation); // reset modifier_flags state if all keys are released. if (get_all_devices_pressed_keys_count() == 0) { modifier_flag_manager_.reset(); } if (modifier_flag == manipulator::modifier_flag::fn) { console_user_client_.post_modifier_flags(modifier_flag_manager_.get_io_option_bits()); } else { send_keyboard_input_report(); } return true; } return false; } bool handle_function_key_event(manipulator::key_code key_code, bool pressed) { auto event_type = pressed ? KRBN_EVENT_TYPE_KEY_DOWN : KRBN_EVENT_TYPE_KEY_UP; if (manipulator::key_code::vk_f1 <= key_code && key_code <= manipulator::key_code::vk_f12) { auto i = static_cast<uint32_t>(key_code) - static_cast<uint32_t>(manipulator::key_code::vk_f1); console_user_client_.post_key(static_cast<krbn_key_code>(KRBN_KEY_CODE_F1 + i), event_type, modifier_flag_manager_.get_io_option_bits()); return true; } if (manipulator::key_code::vk_fn_f1 <= key_code && key_code <= manipulator::key_code::vk_fn_f12) { auto i = static_cast<uint32_t>(key_code) - static_cast<uint32_t>(manipulator::key_code::vk_fn_f1); console_user_client_.post_key(static_cast<krbn_key_code>(KRBN_KEY_CODE_FN_F1 + i), event_type, modifier_flag_manager_.get_io_option_bits()); return true; } return false; } void handle_keyboard_event(human_interface_device& device, manipulator::key_code key_code, bool pressed) { // ---------------------------------------- // modify usage if (!pressed) { auto it = device.get_simple_changed_keys().find(key_code); if (it != device.get_simple_changed_keys().end()) { key_code = it->second; device.get_simple_changed_keys().erase(it); } } else { std::lock_guard<std::mutex> guard(simple_modifications_mutex_); auto it = simple_modifications_.find(key_code); if (it != simple_modifications_.end()) { (device.get_simple_changed_keys())[key_code] = it->second; key_code = it->second; } } // modify fn+arrow, function keys if (!pressed) { auto it = device.get_fn_changed_keys().find(key_code); if (it != device.get_fn_changed_keys().end()) { key_code = it->second; device.get_fn_changed_keys().erase(it); } } else { auto k = static_cast<uint32_t>(key_code); auto new_key_code = key_code; if (modifier_flag_manager_.pressed(manipulator::modifier_flag::fn)) { if (k == kHIDUsage_KeyboardReturnOrEnter) { new_key_code = manipulator::key_code(kHIDUsage_KeypadEnter); } else if (k == kHIDUsage_KeyboardDeleteOrBackspace) { new_key_code = manipulator::key_code(kHIDUsage_KeyboardDeleteForward); } else if (k == kHIDUsage_KeyboardRightArrow) { new_key_code = manipulator::key_code(kHIDUsage_KeyboardEnd); } else if (k == kHIDUsage_KeyboardLeftArrow) { new_key_code = manipulator::key_code(kHIDUsage_KeyboardHome); } else if (k == kHIDUsage_KeyboardDownArrow) { new_key_code = manipulator::key_code(kHIDUsage_KeyboardPageDown); } else if (k == kHIDUsage_KeyboardUpArrow) { new_key_code = manipulator::key_code(kHIDUsage_KeyboardPageUp); } else if (kHIDUsage_KeyboardF1 <= k && k <= kHIDUsage_KeyboardF12) { new_key_code = manipulator::key_code(static_cast<uint32_t>(manipulator::key_code::vk_fn_f1) + k - kHIDUsage_KeyboardF1); } } else { if (kHIDUsage_KeyboardF1 <= k && k <= kHIDUsage_KeyboardF12) { new_key_code = manipulator::key_code(static_cast<uint32_t>(manipulator::key_code::vk_f1) + k - kHIDUsage_KeyboardF1); } } if (key_code != new_key_code) { (device.get_fn_changed_keys())[key_code] = new_key_code; key_code = new_key_code; } } // ---------------------------------------- // send input events to virtual devices. if (handle_modifier_flag_event(key_code, pressed)) { console_user_client_.stop_key_repeat(); return; } if (handle_function_key_event(key_code, pressed)) { return; } if (static_cast<uint32_t>(key_code) < kHIDUsage_Keyboard_Reserved) { auto usage = static_cast<uint32_t>(key_code); if (pressed) { pressed_key_usages_.push_back(usage); console_user_client_.stop_key_repeat(); } else { pressed_key_usages_.remove(usage); } send_keyboard_input_report(); } } void send_keyboard_input_report(void) { // make report hid_report::keyboard_input report; report.modifiers = modifier_flag_manager_.get_hid_report_bits(); while (pressed_key_usages_.size() > sizeof(report.keys)) { pressed_key_usages_.pop_front(); } int i = 0; for (const auto& u : pressed_key_usages_) { report.keys[i] = u; ++i; } // send new report only if it is changed from last report. if (last_keyboard_input_report_ != report) { last_keyboard_input_report_ = report; auto kr = iokit_user_client_.call_struct_method(static_cast<uint32_t>(virtual_hid_manager_user_client_method::keyboard_input_report), static_cast<const void*>(&report), sizeof(report), nullptr, 0); if (kr != KERN_SUCCESS) { logger::get_logger().error("failed to sent report: 0x{0:x}", kr); } } } size_t get_all_devices_pressed_keys_count(void) const { size_t total = 0; for (const auto& it : hids_) { if (it.second) { total += (it.second)->get_pressed_keys_count(); } } return total; } iokit_user_client iokit_user_client_; IOHIDManagerRef _Nullable manager_; std::unordered_map<IOHIDDeviceRef, std::unique_ptr<human_interface_device>> hids_; std::list<uint32_t> pressed_key_usages_; manipulator::modifier_flag_manager modifier_flag_manager_; hid_report::keyboard_input last_keyboard_input_report_; std::unordered_map<manipulator::key_code, manipulator::key_code> simple_modifications_; std::mutex simple_modifications_mutex_; console_user_client console_user_client_; }; <|endoftext|>
<commit_before>/* --------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2013, Numenta, Inc. Unless you have an agreement * with Numenta, Inc., for a separate license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * 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. * * http://numenta.org/licenses/ * --------------------------------------------------------------------- */ /** @file * Definitions for the FStream classes * * These classes are versions of ifstream and ofstream that accept platform independent * (i.e. win32 or unix) utf-8 path specifiers for their constructor and open() methods. * * The native ifstream and ofstream classes on unix already accept UTF-8, but on win32, * we must convert the utf-8 path to unicode and then pass it to the 'w' version of * ifstream or ofstream */ #include "nta/utils/Log.hpp" #include "nta/os/Path.hpp" #include "nta/os/FStream.hpp" #include "nta/os/Directory.hpp" #include "nta/os/Env.hpp" #include <fstream> #include <cstdlib> #ifdef WIN32 #include <fcntl.h> #include <sys/stat.h> #endif #include <zlib.h> using namespace nta; ////////////////////////////////////////////////////////////////////////// /// Print out diagnostic information when a file open fails ///////////////////////////////////////////////////////////////////////// void IFStream::diagnostics(const char* filename) { bool forceLog = false; // We occasionally get error 116(ESTALE) "Stale NFS file handle" (TOO-402) when creating // a file using OFStream::open() on a shared drive on unix systems. We found that // if we perform a directory listing after encountering the error, that a retry // immediately after is successful. So.... we log this information if we // get errno==ESTALE OR if NTA_FILE_LOGGING is set. #ifdef ESTALE if (errno == ESTALE) forceLog = true; #endif if (forceLog || ::getenv("NTA_FILE_LOGGING")) { NTA_DEBUG << "FStream::open() failed opening file " << filename << "; errno = " << errno << "; errmsg = " << strerror(errno) << "; cwd = " << Directory::getCWD(); Directory::Iterator di(Directory::getCWD()); Directory::Entry e; while (di.next(e)) { NTA_DEBUG << "FStream::open() ls: " << e.path; } } } ////////////////////////////////////////////////////////////////////////// /// open the given file by name ///////////////////////////////////////////////////////////////////////// void IFStream::open(const char * filename, ios_base::openmode mode) { #ifdef WIN32 std::wstring pathW = Path::utf8ToUnicode(filename); std::ifstream::open(pathW.c_str(), mode); #else std::ifstream::open(filename, mode); #endif // Check for error if (!is_open()) { IFStream::diagnostics(filename); // On unix, running nfs, we occasionally get errors opening a file on an nfs drive // and it seems that simply doing a retry makes it successful #ifndef WIN32 std::ifstream::clear(); std::ifstream::open(filename, mode); #endif } } ////////////////////////////////////////////////////////////////////////// /// open the given file by name ///////////////////////////////////////////////////////////////////////// void OFStream::open(const char * filename, ios_base::openmode mode) { #ifdef WIN32 std::wstring pathW = Path::utf8ToUnicode(filename); std::ofstream::open(pathW.c_str(), mode); #else std::ofstream::open(filename, mode); #endif // Check for error if (!is_open()) { IFStream::diagnostics(filename); // On unix, running nfs, we occasionally get errors opening a file on an nfs drive // and it seems that simply doing a retry makes it successful #ifndef WIN32 std::ofstream::clear(); std::ofstream::open(filename, mode); #endif } } void *ZLib::fopen(const std::string &filename, const std::string &mode, std::string *errorMessage) { if(mode.empty()) throw std::invalid_argument("Mode may not be empty."); #ifdef WIN32 std::wstring wfilename(Path::utf8ToUnicode(filename)); int cflags = _O_BINARY; int pflags = 0; if(mode[0] == 'r') { cflags |= _O_RDONLY; } else if(mode[0] == 'w') { cflags |= _O_TRUNC | _O_CREAT | _O_WRONLY; pflags |= _S_IREAD | _S_IWRITE; } else if(mode[0] == 'a') { cflags |= _O_APPEND | _O_CREAT | _O_WRONLY; pflags |= _S_IREAD | _S_IWRITE; } else { throw std::invalid_argument("Mode must start with 'r', 'w' or 'a'."); } int fd = _wopen(wfilename.c_str(), cflags, pflags); gzFile fs = gzdopen(fd, mode.c_str()); if(fs == 0) { // TODO: Build an error message for Windows. } #else gzFile fs = 0; { // zlib may not be thread-safe in its current compiled state. int attempts = 0; const int maxAttempts = 1; int lastError = 0; while(1) { fs = gzopen(filename.c_str(), mode.c_str()); if(fs) break; int error = errno; if(error != lastError) { std::string message("Unknown error."); // lastError = error; switch(error) { case Z_STREAM_ERROR: message = "Zlib stream error."; break; case Z_DATA_ERROR: message = "Zlib data error."; break; case Z_MEM_ERROR: message = "Zlib memory error."; break; case Z_BUF_ERROR: message = "Zlib buffer error."; break; case Z_VERSION_ERROR: message = "Zlib version error."; break; default: char errbuf[256]; char* retval = (char*)::strerror_r(error, errbuf, 256); if(retval != NULL) { //empty code to silence -Werror=unused-variable warning } message = errbuf; break; } if(errorMessage) { *errorMessage = message; } else if(maxAttempts > 1) { // If we will try again, warn about failure. std::cerr << "Warning: Failed to open file '" << filename << "': " << message << std::endl; } } if((++attempts) >= maxAttempts) break; ::usleep(10000); } } #endif return fs; } <commit_msg>Revert "Revert "use POSIX version of esrerror_r""<commit_after>/* --------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2013, Numenta, Inc. Unless you have an agreement * with Numenta, Inc., for a separate license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * 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. * * http://numenta.org/licenses/ * --------------------------------------------------------------------- */ /** @file * Definitions for the FStream classes * * These classes are versions of ifstream and ofstream that accept platform independent * (i.e. win32 or unix) utf-8 path specifiers for their constructor and open() methods. * * The native ifstream and ofstream classes on unix already accept UTF-8, but on win32, * we must convert the utf-8 path to unicode and then pass it to the 'w' version of * ifstream or ofstream */ #include "nta/utils/Log.hpp" #include "nta/os/Path.hpp" #include "nta/os/FStream.hpp" #include "nta/os/Directory.hpp" #include "nta/os/Env.hpp" #include <fstream> #include <cstdlib> #ifdef WIN32 #include <fcntl.h> #include <sys/stat.h> #endif #include <zlib.h> using namespace nta; ////////////////////////////////////////////////////////////////////////// /// Print out diagnostic information when a file open fails ///////////////////////////////////////////////////////////////////////// void IFStream::diagnostics(const char* filename) { bool forceLog = false; // We occasionally get error 116(ESTALE) "Stale NFS file handle" (TOO-402) when creating // a file using OFStream::open() on a shared drive on unix systems. We found that // if we perform a directory listing after encountering the error, that a retry // immediately after is successful. So.... we log this information if we // get errno==ESTALE OR if NTA_FILE_LOGGING is set. #ifdef ESTALE if (errno == ESTALE) forceLog = true; #endif if (forceLog || ::getenv("NTA_FILE_LOGGING")) { NTA_DEBUG << "FStream::open() failed opening file " << filename << "; errno = " << errno << "; errmsg = " << strerror(errno) << "; cwd = " << Directory::getCWD(); Directory::Iterator di(Directory::getCWD()); Directory::Entry e; while (di.next(e)) { NTA_DEBUG << "FStream::open() ls: " << e.path; } } } ////////////////////////////////////////////////////////////////////////// /// open the given file by name ///////////////////////////////////////////////////////////////////////// void IFStream::open(const char * filename, ios_base::openmode mode) { #ifdef WIN32 std::wstring pathW = Path::utf8ToUnicode(filename); std::ifstream::open(pathW.c_str(), mode); #else std::ifstream::open(filename, mode); #endif // Check for error if (!is_open()) { IFStream::diagnostics(filename); // On unix, running nfs, we occasionally get errors opening a file on an nfs drive // and it seems that simply doing a retry makes it successful #ifndef WIN32 std::ifstream::clear(); std::ifstream::open(filename, mode); #endif } } ////////////////////////////////////////////////////////////////////////// /// open the given file by name ///////////////////////////////////////////////////////////////////////// void OFStream::open(const char * filename, ios_base::openmode mode) { #ifdef WIN32 std::wstring pathW = Path::utf8ToUnicode(filename); std::ofstream::open(pathW.c_str(), mode); #else std::ofstream::open(filename, mode); #endif // Check for error if (!is_open()) { IFStream::diagnostics(filename); // On unix, running nfs, we occasionally get errors opening a file on an nfs drive // and it seems that simply doing a retry makes it successful #ifndef WIN32 std::ofstream::clear(); std::ofstream::open(filename, mode); #endif } } void *ZLib::fopen(const std::string &filename, const std::string &mode, std::string *errorMessage) { if(mode.empty()) throw std::invalid_argument("Mode may not be empty."); #ifdef WIN32 std::wstring wfilename(Path::utf8ToUnicode(filename)); int cflags = _O_BINARY; int pflags = 0; if(mode[0] == 'r') { cflags |= _O_RDONLY; } else if(mode[0] == 'w') { cflags |= _O_TRUNC | _O_CREAT | _O_WRONLY; pflags |= _S_IREAD | _S_IWRITE; } else if(mode[0] == 'a') { cflags |= _O_APPEND | _O_CREAT | _O_WRONLY; pflags |= _S_IREAD | _S_IWRITE; } else { throw std::invalid_argument("Mode must start with 'r', 'w' or 'a'."); } int fd = _wopen(wfilename.c_str(), cflags, pflags); gzFile fs = gzdopen(fd, mode.c_str()); if(fs == 0) { // TODO: Build an error message for Windows. } #else gzFile fs = 0; { // zlib may not be thread-safe in its current compiled state. int attempts = 0; const int maxAttempts = 1; int lastError = 0; while(1) { fs = gzopen(filename.c_str(), mode.c_str()); if(fs) break; int error = errno; if(error != lastError) { std::string message("Unknown error."); // lastError = error; switch(error) { case Z_STREAM_ERROR: message = "Zlib stream error."; break; case Z_DATA_ERROR: message = "Zlib data error."; break; case Z_MEM_ERROR: message = "Zlib memory error."; break; case Z_BUF_ERROR: message = "Zlib buffer error."; break; case Z_VERSION_ERROR: message = "Zlib version error."; break; default: message = ::strerror(error); break; } if(errorMessage) { *errorMessage = message; } else if(maxAttempts > 1) { // If we will try again, warn about failure. std::cerr << "Warning: Failed to open file '" << filename << "': " << message << std::endl; } } if((++attempts) >= maxAttempts) break; ::usleep(10000); } } #endif return fs; } <|endoftext|>
<commit_before> #pragma once /** * Graph.hpp * Purpose: An class for the representation of attributed graphs and digraphs. * * @author Kevin A. Naudé * @version 1.1 */ #include <algorithm> #include <assert.h> #include <string> #include <limits> #include <vector> #include <unordered_map> #include <memory> #include <BitStructures.hpp> #include <AttributeModel.hpp> #include <Matrix.hpp> namespace kn { class Graph { public: typedef std::size_t VertexID; typedef std::size_t EdgeID; typedef std::size_t AttrID; struct Edge { EdgeID id; VertexID u; VertexID v; AttrID attrID; bool undirected; }; struct Vertex { VertexID id; std::size_t outDegree; std::size_t inDegree; AttrID attrID; }; struct Pair { VertexID u; VertexID v; Pair() {} Pair(VertexID u, VertexID v) { this->u = u; this->v = v; } }; class VertexIterator; class EdgeIterator; class Walker; private: struct EdgeInfo : Edge { EdgeInfo* prevToDestination; EdgeInfo* nextToDestination; EdgeInfo* prevFromSource; EdgeInfo* nextFromSource; }; struct VertexInfo : Vertex { EdgeInfo* destinationEdges; EdgeInfo* sourceEdges; }; private: const AttributeModel* vertexAttributes; const AttributeModel* edgeAttributes; std::vector<VertexInfo> vertices; std::unordered_map<VertexID, std::size_t> vertexIDtoIndex; std::unordered_map<EdgeID, VertexID> edgeIDtoSourceID; VertexID nextVertexID; EdgeID nextEdgeID; void deleteEdge(EdgeInfo* e); void removeEdgeHelper(VertexID sourceID, VertexID destinationID); void insertEdge(EdgeID id, VertexID sourceID, VertexID destinationID, AttrID attrID, bool undirected); void vertexAdjacency(VertexID id, IntegerSet& row); public: Graph(); Graph(const AttributeModel* vertexAttributeModel, const AttributeModel* edgeAttributeModel); Graph(const Graph& other) : Graph(other, false) { } Graph(const Graph& other, bool complement); virtual ~Graph(); Graph(Graph&& other); Graph& operator=(Graph&& other); const AttributeModel* getVertexAttributeModel() const { return vertexAttributes; } const AttributeModel* getEdgeAttributeModel() const { return edgeAttributes; } std::unique_ptr<IntegerSet> vertexAdjacency(VertexID id) { std::unique_ptr<IntegerSet> adj(new IntegerSet(vertices.size())); vertexAdjacency(id, *adj); return adj; } std::unique_ptr<std::vector<IntegerSet>> adjacency(); template <typename T> void constructAdjacencyMatrix(Matrix<T>& m) const { m.reshape(vertices.size(), vertices.size()); for (std::size_t u = 0; u < vertices.size(); u++) { for (std::size_t v = 0; v < vertices.size(); v++) { if (hasArc(vertices[u].id, vertices[v].id)) { m.setValue(u, v, 1); } else { m.setValue(u, v, 0); } } } } std::size_t countVertices() const { return vertices.size(); } std::size_t countEdges() const { return edgeIDtoSourceID.size(); } VertexIterator vertexIterator() const { return VertexIterator(this); } EdgeIterator exitingEdgeIterator(VertexID id) const { std::size_t index = vertexIDtoIndex.at(id); const VertexInfo* u = &vertices[index]; return EdgeIterator(u->sourceEdges, true); } EdgeIterator enteringEdgeIterator(VertexID id) const { std::size_t index = vertexIDtoIndex.at(id); const VertexInfo* v = &vertices[index]; return EdgeIterator(v->destinationEdges, false); } bool validVertexID(VertexID id) const { return (vertexIDtoIndex.find(id) != vertexIDtoIndex.end()); } VertexID getVertexID(std::size_t index) const { if (index < vertices.size()) { return vertices[index].id; } else { return 0; } } bool getVertex(VertexID id, Vertex& v) const { if (!validVertexID(id)) { // This line prevents a spurious compiler warning. v.id = v.outDegree = v.inDegree = v.attrID = 0; return false; } v = vertices[vertexIDtoIndex.at(id)]; return true; } bool getVertexByIndex(std::size_t index, Vertex& v) const { if (index >= vertices.size()) { // This line prevents a spurious compiler warning. v.id = v.outDegree = v.inDegree = v.attrID = 0; return false; } v = vertices[index]; return true; } bool getEdge(EdgeID id, Edge& e) const; bool getEdge(VertexID sourceID, VertexID destinationID, Edge& e) const; VertexID addVertex(AttrID attrID) { VertexID id = nextVertexID++; std::size_t index = vertices.size(); VertexInfo v; v.id = id; v.outDegree = 0; v.inDegree = 0; v.sourceEdges = nullptr; v.destinationEdges = nullptr; v.attrID = attrID; vertices.push_back(v); vertexIDtoIndex.insert(std::make_pair(id, index)); return id; } bool removeVertex(VertexID id); bool removeEdge(EdgeID id) { Edge e; if (getEdge(id, e)) return removeEdge(e.u, e.v); else return false; } bool removeEdge(VertexID sourceID, VertexID destinationID); bool hasArc(VertexID sourceID, VertexID destinationID) const; bool hasEdge(VertexID sourceID, VertexID destinationID) const; EdgeID addArc(VertexID sourceID, VertexID destinationID, AttrID attrID) { if (!validVertexID(sourceID) || !validVertexID(destinationID)) return 0; else { EdgeID id = nextEdgeID++; insertEdge(id, sourceID, destinationID, attrID, false); edgeIDtoSourceID.insert(std::make_pair(id, sourceID)); return id; } } EdgeID addEdge(VertexID sourceID, VertexID destinationID, AttrID attrID) { if (!validVertexID(sourceID) || !validVertexID(destinationID)) return 0; else { EdgeID id = nextEdgeID++; if (sourceID > destinationID) { // reordering the end points is not strictly required. std::swap(sourceID, destinationID); } insertEdge(id, sourceID, destinationID, attrID, true); if (sourceID != destinationID) { insertEdge(id, destinationID, sourceID, attrID, true); } edgeIDtoSourceID.insert(std::make_pair(id, sourceID)); return id; } } std::vector<VertexID> listOfVertices() { std::vector<VertexID> result(vertices.size()); for (auto it = vertices.begin(); it != vertices.end(); ++it) { result.push_back(it->id); } return result; } std::vector<Pair> listOfEdges() { std::vector<Pair> result(countEdges()); for (std::size_t ui = 0; ui < vertices.size(); ui++) { VertexID u = vertices[ui].id; for (std::size_t vi = 0; vi < vertices.size(); vi++) { VertexID v = vertices[vi].id; if ((u <= v) && hasEdge(u, v)) { result.push_back(Pair(u, v)); } } } return result; } std::vector<Pair> listOfArcs() { std::vector<Pair> result(countEdges()); for (std::size_t ui = 0; ui < vertices.size(); ui++) { VertexID u = vertices[ui].id; for (std::size_t vi = 0; vi < vertices.size(); vi++) { VertexID v = vertices[vi].id; if (hasArc(u, v)) { result.push_back(Pair(u, v)); } } } return result; } std::vector<Pair> listOfAbsentEdges() { std::vector<Pair> result(countEdges()); for (std::size_t ui = 0; ui < vertices.size(); ui++) { VertexID u = vertices[ui].id; for (std::size_t vi = 0; vi < vertices.size(); vi++) { VertexID v = vertices[vi].id; if ((u < v) && !hasArc(u, v) && !hasArc(v, u)) { result.push_back(Pair(u, v)); } } } return result; } std::vector<Pair> listOfAbsentArcs() { std::vector<Pair> result(countEdges()); for (std::size_t ui = 0; ui < vertices.size(); ui++) { VertexID u = vertices[ui].id; for (std::size_t vi = 0; vi < vertices.size(); vi++) { VertexID v = vertices[vi].id; if ((u != v) && !hasArc(u, v)) { result.push_back(Pair(u, v)); } } } return result; } public: class VertexIterator { private: friend class Graph; const Graph* graph; std::size_t index; std::size_t count; VertexIterator(const Graph* graph) { this->graph = graph; index = 0; count = graph->countVertices(); } public: bool hasNext() { return index < count; } bool next(Vertex& v) { if (index < count) { graph->getVertex(graph->getVertexID(index), v); index++; return true; } else return false; } bool current(Vertex& v) const { return graph->getVertex(graph->getVertexID(index), v); } }; class EdgeIterator { private: friend class Graph; friend class Walker; const EdgeInfo* ei; bool exitingEdges; EdgeIterator(const EdgeInfo* ei, bool exitingEdges) { this->ei = ei; this->exitingEdges = exitingEdges; } public: bool hasNext() { return (ei != nullptr); } bool next(Edge& e) { if (ei) { e = *ei; if (exitingEdges) ei = ei->nextFromSource; else ei = ei->nextToDestination; return true; } else return false; } bool current(Edge& e) const { if (ei) { e = *ei; return true; } else return false; } }; class Walker { private: friend class Graph; const Graph* graph; VertexID position; Walker(const Graph* graph, VertexID position) { this->graph = graph; this->position = position; } public: bool teleport(VertexID id) { if (graph->validVertexID(id)) { position = id; return true; } else return false; } EdgeIterator exitingEdges() const { return graph->exitingEdgeIterator(position); } EdgeIterator enteringEdges() const { return graph->enteringEdgeIterator(position); } VertexID moveForwardAlong(const EdgeIterator& it) { Edge e; if (it.current(e)) { position = e.v; return position; } else return 0; } VertexID moveBackwardAlong(const EdgeIterator& it) { Edge e; if (it.current(e)) { position = e.u; return position; } else return 0; } VertexID moveForwardAlong(EdgeID id) { auto it = exitingEdges(); Edge e; while (it.next(e)) { if (e.id == id) { position = e.v; return position; } } return 0; } VertexID moveBackwardAlong(EdgeID id) { auto it = enteringEdges(); Edge e; while (it.next(e)) { if (e.id == id) { position = e.u; return position; } } return 0; } EdgeID moveForwardTo(VertexID id) { auto it = exitingEdges(); Edge e; while (it.next(e)) { if (e.v == id) { position = id; return e.id; } } return 0; } EdgeID moveBackwardTo(VertexID id) { auto it = enteringEdges(); Edge e; while (it.next(e)) { if (e.u == id) { position = id; return e.id; } } return 0; } }; }; } <commit_msg>Graph.hpp: added clear()<commit_after> #pragma once /** * Graph.hpp * Purpose: An class for the representation of attributed graphs and digraphs. * * @author Kevin A. Naudé * @version 1.1 */ #include <algorithm> #include <assert.h> #include <string> #include <limits> #include <vector> #include <unordered_map> #include <memory> #include <BitStructures.hpp> #include <AttributeModel.hpp> #include <Matrix.hpp> namespace kn { class Graph { public: typedef std::size_t VertexID; typedef std::size_t EdgeID; typedef std::size_t AttrID; struct Edge { EdgeID id; VertexID u; VertexID v; AttrID attrID; bool undirected; }; struct Vertex { VertexID id; std::size_t outDegree; std::size_t inDegree; AttrID attrID; }; struct Pair { VertexID u; VertexID v; Pair() {} Pair(VertexID u, VertexID v) { this->u = u; this->v = v; } }; class VertexIterator; class EdgeIterator; class Walker; private: struct EdgeInfo : Edge { EdgeInfo* prevToDestination; EdgeInfo* nextToDestination; EdgeInfo* prevFromSource; EdgeInfo* nextFromSource; }; struct VertexInfo : Vertex { EdgeInfo* destinationEdges; EdgeInfo* sourceEdges; }; private: const AttributeModel* vertexAttributes; const AttributeModel* edgeAttributes; std::vector<VertexInfo> vertices; std::unordered_map<VertexID, std::size_t> vertexIDtoIndex; std::unordered_map<EdgeID, VertexID> edgeIDtoSourceID; VertexID nextVertexID; EdgeID nextEdgeID; void deleteEdge(EdgeInfo* e); void removeEdgeHelper(VertexID sourceID, VertexID destinationID); void insertEdge(EdgeID id, VertexID sourceID, VertexID destinationID, AttrID attrID, bool undirected); void vertexAdjacency(VertexID id, IntegerSet& row); public: Graph(); Graph(const AttributeModel* vertexAttributeModel, const AttributeModel* edgeAttributeModel); Graph(const Graph& other) : Graph(other, false) { } Graph(const Graph& other, bool complement); virtual ~Graph(); Graph(Graph&& other); Graph& operator=(Graph&& other); void clear() { vertices.clear(); vertexIDtoIndex.clear(); edgeIDtoSourceID.clear(); nextVertexID = 0; nextEdgeID = 0; } const AttributeModel* getVertexAttributeModel() const { return vertexAttributes; } const AttributeModel* getEdgeAttributeModel() const { return edgeAttributes; } std::unique_ptr<IntegerSet> vertexAdjacency(VertexID id) { std::unique_ptr<IntegerSet> adj(new IntegerSet(vertices.size())); vertexAdjacency(id, *adj); return adj; } std::unique_ptr<std::vector<IntegerSet>> adjacency(); template <typename T> void constructAdjacencyMatrix(Matrix<T>& m) const { m.reshape(vertices.size(), vertices.size()); for (std::size_t u = 0; u < vertices.size(); u++) { for (std::size_t v = 0; v < vertices.size(); v++) { if (hasArc(vertices[u].id, vertices[v].id)) { m.setValue(u, v, 1); } else { m.setValue(u, v, 0); } } } } std::size_t countVertices() const { return vertices.size(); } std::size_t countEdges() const { return edgeIDtoSourceID.size(); } VertexIterator vertexIterator() const { return VertexIterator(this); } EdgeIterator exitingEdgeIterator(VertexID id) const { std::size_t index = vertexIDtoIndex.at(id); const VertexInfo* u = &vertices[index]; return EdgeIterator(u->sourceEdges, true); } EdgeIterator enteringEdgeIterator(VertexID id) const { std::size_t index = vertexIDtoIndex.at(id); const VertexInfo* v = &vertices[index]; return EdgeIterator(v->destinationEdges, false); } bool validVertexID(VertexID id) const { return (vertexIDtoIndex.find(id) != vertexIDtoIndex.end()); } VertexID getVertexID(std::size_t index) const { if (index < vertices.size()) { return vertices[index].id; } else { return 0; } } bool getVertex(VertexID id, Vertex& v) const { if (!validVertexID(id)) { // This line prevents a spurious compiler warning. v.id = v.outDegree = v.inDegree = v.attrID = 0; return false; } v = vertices[vertexIDtoIndex.at(id)]; return true; } bool getVertexByIndex(std::size_t index, Vertex& v) const { if (index >= vertices.size()) { // This line prevents a spurious compiler warning. v.id = v.outDegree = v.inDegree = v.attrID = 0; return false; } v = vertices[index]; return true; } bool getEdge(EdgeID id, Edge& e) const; bool getEdge(VertexID sourceID, VertexID destinationID, Edge& e) const; VertexID addVertex(AttrID attrID) { VertexID id = nextVertexID++; std::size_t index = vertices.size(); VertexInfo v; v.id = id; v.outDegree = 0; v.inDegree = 0; v.sourceEdges = nullptr; v.destinationEdges = nullptr; v.attrID = attrID; vertices.push_back(v); vertexIDtoIndex.insert(std::make_pair(id, index)); return id; } bool removeVertex(VertexID id); bool removeEdge(EdgeID id) { Edge e; if (getEdge(id, e)) return removeEdge(e.u, e.v); else return false; } bool removeEdge(VertexID sourceID, VertexID destinationID); bool hasArc(VertexID sourceID, VertexID destinationID) const; bool hasEdge(VertexID sourceID, VertexID destinationID) const; EdgeID addArc(VertexID sourceID, VertexID destinationID, AttrID attrID) { if (!validVertexID(sourceID) || !validVertexID(destinationID)) return 0; else { EdgeID id = nextEdgeID++; insertEdge(id, sourceID, destinationID, attrID, false); edgeIDtoSourceID.insert(std::make_pair(id, sourceID)); return id; } } EdgeID addEdge(VertexID sourceID, VertexID destinationID, AttrID attrID) { if (!validVertexID(sourceID) || !validVertexID(destinationID)) return 0; else { EdgeID id = nextEdgeID++; if (sourceID > destinationID) { // reordering the end points is not strictly required. std::swap(sourceID, destinationID); } insertEdge(id, sourceID, destinationID, attrID, true); if (sourceID != destinationID) { insertEdge(id, destinationID, sourceID, attrID, true); } edgeIDtoSourceID.insert(std::make_pair(id, sourceID)); return id; } } std::vector<VertexID> listOfVertices() { std::vector<VertexID> result(vertices.size()); for (auto it = vertices.begin(); it != vertices.end(); ++it) { result.push_back(it->id); } return result; } std::vector<Pair> listOfEdges() { std::vector<Pair> result(countEdges()); for (std::size_t ui = 0; ui < vertices.size(); ui++) { VertexID u = vertices[ui].id; for (std::size_t vi = 0; vi < vertices.size(); vi++) { VertexID v = vertices[vi].id; if ((u <= v) && hasEdge(u, v)) { result.push_back(Pair(u, v)); } } } return result; } std::vector<Pair> listOfArcs() { std::vector<Pair> result(countEdges()); for (std::size_t ui = 0; ui < vertices.size(); ui++) { VertexID u = vertices[ui].id; for (std::size_t vi = 0; vi < vertices.size(); vi++) { VertexID v = vertices[vi].id; if (hasArc(u, v)) { result.push_back(Pair(u, v)); } } } return result; } std::vector<Pair> listOfAbsentEdges() { std::vector<Pair> result(countEdges()); for (std::size_t ui = 0; ui < vertices.size(); ui++) { VertexID u = vertices[ui].id; for (std::size_t vi = 0; vi < vertices.size(); vi++) { VertexID v = vertices[vi].id; if ((u < v) && !hasArc(u, v) && !hasArc(v, u)) { result.push_back(Pair(u, v)); } } } return result; } std::vector<Pair> listOfAbsentArcs() { std::vector<Pair> result(countEdges()); for (std::size_t ui = 0; ui < vertices.size(); ui++) { VertexID u = vertices[ui].id; for (std::size_t vi = 0; vi < vertices.size(); vi++) { VertexID v = vertices[vi].id; if ((u != v) && !hasArc(u, v)) { result.push_back(Pair(u, v)); } } } return result; } public: class VertexIterator { private: friend class Graph; const Graph* graph; std::size_t index; std::size_t count; VertexIterator(const Graph* graph) { this->graph = graph; index = 0; count = graph->countVertices(); } public: bool hasNext() { return index < count; } bool next(Vertex& v) { if (index < count) { graph->getVertex(graph->getVertexID(index), v); index++; return true; } else return false; } bool current(Vertex& v) const { return graph->getVertex(graph->getVertexID(index), v); } }; class EdgeIterator { private: friend class Graph; friend class Walker; const EdgeInfo* ei; bool exitingEdges; EdgeIterator(const EdgeInfo* ei, bool exitingEdges) { this->ei = ei; this->exitingEdges = exitingEdges; } public: bool hasNext() { return (ei != nullptr); } bool next(Edge& e) { if (ei) { e = *ei; if (exitingEdges) ei = ei->nextFromSource; else ei = ei->nextToDestination; return true; } else return false; } bool current(Edge& e) const { if (ei) { e = *ei; return true; } else return false; } }; class Walker { private: friend class Graph; const Graph* graph; VertexID position; Walker(const Graph* graph, VertexID position) { this->graph = graph; this->position = position; } public: bool teleport(VertexID id) { if (graph->validVertexID(id)) { position = id; return true; } else return false; } EdgeIterator exitingEdges() const { return graph->exitingEdgeIterator(position); } EdgeIterator enteringEdges() const { return graph->enteringEdgeIterator(position); } VertexID moveForwardAlong(const EdgeIterator& it) { Edge e; if (it.current(e)) { position = e.v; return position; } else return 0; } VertexID moveBackwardAlong(const EdgeIterator& it) { Edge e; if (it.current(e)) { position = e.u; return position; } else return 0; } VertexID moveForwardAlong(EdgeID id) { auto it = exitingEdges(); Edge e; while (it.next(e)) { if (e.id == id) { position = e.v; return position; } } return 0; } VertexID moveBackwardAlong(EdgeID id) { auto it = enteringEdges(); Edge e; while (it.next(e)) { if (e.id == id) { position = e.u; return position; } } return 0; } EdgeID moveForwardTo(VertexID id) { auto it = exitingEdges(); Edge e; while (it.next(e)) { if (e.v == id) { position = id; return e.id; } } return 0; } EdgeID moveBackwardTo(VertexID id) { auto it = enteringEdges(); Edge e; while (it.next(e)) { if (e.u == id) { position = id; return e.id; } } return 0; } }; }; } <|endoftext|>
<commit_before>// Copyright (c) 2019-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <consensus/merkle.h> #include <consensus/validation.h> #include <core_io.h> #include <core_memusage.h> #include <primitives/block.h> #include <pubkey.h> #include <streams.h> #include <test/fuzz/fuzz.h> #include <validation.h> #include <version.h> #include <cassert> #include <string> void initialize() { static const ECCVerifyHandle verify_handle; SelectParams(CBaseChainParams::REGTEST); } void test_one_input(const std::vector<uint8_t>& buffer) { CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION); CBlock block; try { int nVersion; ds >> nVersion; ds.SetVersion(nVersion); ds >> block; } catch (const std::ios_base::failure&) { return; } const Consensus::Params& consensus_params = Params().GetConsensus(); BlockValidationState validation_state_pow_and_merkle; const bool valid_incl_pow_and_merkle = CheckBlock(block, validation_state_pow_and_merkle, consensus_params, /* fCheckPOW= */ true, /* fCheckMerkleRoot= */ true); BlockValidationState validation_state_pow; const bool valid_incl_pow = CheckBlock(block, validation_state_pow, consensus_params, /* fCheckPOW= */ true, /* fCheckMerkleRoot= */ false); BlockValidationState validation_state_merkle; const bool valid_incl_merkle = CheckBlock(block, validation_state_merkle, consensus_params, /* fCheckPOW= */ false, /* fCheckMerkleRoot= */ true); BlockValidationState validation_state_none; const bool valid_incl_none = CheckBlock(block, validation_state_none, consensus_params, /* fCheckPOW= */ false, /* fCheckMerkleRoot= */ false); if (valid_incl_pow_and_merkle) { assert(valid_incl_pow && valid_incl_merkle && valid_incl_none); } else if (valid_incl_merkle || valid_incl_pow) { assert(valid_incl_none); } (void)block.GetHash(); (void)block.ToString(); (void)BlockMerkleRoot(block); if (!block.vtx.empty()) { // TODO: Avoid array index out of bounds error in BlockWitnessMerkleRoot // when block.vtx.empty(). (void)BlockWitnessMerkleRoot(block); } (void)GetBlockWeight(block); (void)GetWitnessCommitmentIndex(block); const size_t raw_memory_size = RecursiveDynamicUsage(block); const size_t raw_memory_size_as_shared_ptr = RecursiveDynamicUsage(std::make_shared<CBlock>(block)); assert(raw_memory_size_as_shared_ptr > raw_memory_size); CBlock block_copy = block; block_copy.SetNull(); const bool is_null = block_copy.IsNull(); assert(is_null); } <commit_msg>tests: Fill fuzzing coverage gaps for functions in consensus/validation.h<commit_after>// Copyright (c) 2019-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <consensus/merkle.h> #include <consensus/validation.h> #include <core_io.h> #include <core_memusage.h> #include <primitives/block.h> #include <pubkey.h> #include <streams.h> #include <test/fuzz/fuzz.h> #include <validation.h> #include <version.h> #include <cassert> #include <string> void initialize() { static const ECCVerifyHandle verify_handle; SelectParams(CBaseChainParams::REGTEST); } void test_one_input(const std::vector<uint8_t>& buffer) { CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION); CBlock block; try { int nVersion; ds >> nVersion; ds.SetVersion(nVersion); ds >> block; } catch (const std::ios_base::failure&) { return; } const Consensus::Params& consensus_params = Params().GetConsensus(); BlockValidationState validation_state_pow_and_merkle; const bool valid_incl_pow_and_merkle = CheckBlock(block, validation_state_pow_and_merkle, consensus_params, /* fCheckPOW= */ true, /* fCheckMerkleRoot= */ true); assert(validation_state_pow_and_merkle.IsValid() || validation_state_pow_and_merkle.IsInvalid() || validation_state_pow_and_merkle.IsError()); (void)validation_state_pow_and_merkle.Error(""); BlockValidationState validation_state_pow; const bool valid_incl_pow = CheckBlock(block, validation_state_pow, consensus_params, /* fCheckPOW= */ true, /* fCheckMerkleRoot= */ false); assert(validation_state_pow.IsValid() || validation_state_pow.IsInvalid() || validation_state_pow.IsError()); BlockValidationState validation_state_merkle; const bool valid_incl_merkle = CheckBlock(block, validation_state_merkle, consensus_params, /* fCheckPOW= */ false, /* fCheckMerkleRoot= */ true); assert(validation_state_merkle.IsValid() || validation_state_merkle.IsInvalid() || validation_state_merkle.IsError()); BlockValidationState validation_state_none; const bool valid_incl_none = CheckBlock(block, validation_state_none, consensus_params, /* fCheckPOW= */ false, /* fCheckMerkleRoot= */ false); assert(validation_state_none.IsValid() || validation_state_none.IsInvalid() || validation_state_none.IsError()); if (valid_incl_pow_and_merkle) { assert(valid_incl_pow && valid_incl_merkle && valid_incl_none); } else if (valid_incl_merkle || valid_incl_pow) { assert(valid_incl_none); } (void)block.GetHash(); (void)block.ToString(); (void)BlockMerkleRoot(block); if (!block.vtx.empty()) { // TODO: Avoid array index out of bounds error in BlockWitnessMerkleRoot // when block.vtx.empty(). (void)BlockWitnessMerkleRoot(block); } (void)GetBlockWeight(block); (void)GetWitnessCommitmentIndex(block); const size_t raw_memory_size = RecursiveDynamicUsage(block); const size_t raw_memory_size_as_shared_ptr = RecursiveDynamicUsage(std::make_shared<CBlock>(block)); assert(raw_memory_size_as_shared_ptr > raw_memory_size); CBlock block_copy = block; block_copy.SetNull(); const bool is_null = block_copy.IsNull(); assert(is_null); } <|endoftext|>
<commit_before>#include <string> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include "Joystick.h" namespace RhIO { bool Joystick::JoystickEvent::isPressed() { return value; } float Joystick::JoystickEvent::getValue() { return value/(float(1<<15)); } Joystick::Joystick() : fd(-1) { } bool Joystick::open() { char *pad = getenv("JOYSTICK"); if (pad == NULL) { pad = JOYSTICK_DEVNAME; } fd = ::open(pad, O_RDONLY | O_NONBLOCK); /* read write for force feedback? */ return fd > 0; } bool Joystick::getEvent(JoystickEvent *evt) { int bytes = read(fd, evt, sizeof(evt)); return (bytes == sizeof(*evt)); } void Joystick::close() { if (fd > 0) { ::close(fd); fd = -1; } } } <commit_msg>Adding sleep in joystick read<commit_after>#include <string> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include "Joystick.h" namespace RhIO { bool Joystick::JoystickEvent::isPressed() { return value; } float Joystick::JoystickEvent::getValue() { return value/(float(1<<15)); } Joystick::Joystick() : fd(-1) { } bool Joystick::open() { char *pad = getenv("JOYSTICK"); if (pad == NULL) { pad = JOYSTICK_DEVNAME; } fd = ::open(pad, O_RDONLY | O_NONBLOCK); /* read write for force feedback? */ return fd > 0; } bool Joystick::getEvent(JoystickEvent *evt) { usleep(10000); int bytes = read(fd, evt, sizeof(evt)); return (bytes == sizeof(*evt)); } void Joystick::close() { if (fd > 0) { ::close(fd); fd = -1; } } } <|endoftext|>
<commit_before>// Copyright (c) 2014-2015 The Dash developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "masternode-sync.h" #include "masternode-payments.h" #include "masternode-budget.h" #include "masternode.h" #include "masternodeman.h" #include "util.h" #include "addrman.h" class CMasternodeSync; CMasternodeSync masternodeSync; CMasternodeSync::CMasternodeSync() { lastMasternodeList = 0; lastMasternodeWinner = 0; lastBudgetItem = 0; RequestedMasternodeAssets = MASTERNODE_SYNC_INITIAL; RequestedMasternodeAttempt = 0; } bool CMasternodeSync::IsSynced() { return RequestedMasternodeAssets == MASTERNODE_SYNC_FINISHED; } bool CMasternodeSync::IsBlockchainSynced() { CBlockIndex* pindexPrev = chainActive.Tip(); if(pindexPrev == NULL) return false; if(pindexPrev->nHeight + 4 < pindexBestHeader->nHeight || pindexPrev->nTime + 600 < GetTime()) return false; return true; } void CMasternodeSync::AddedMasternodeList() { lastMasternodeList = GetTime(); } void CMasternodeSync::AddedMasternodeWinner() { lastMasternodeWinner = GetTime(); } void CMasternodeSync::AddedBudgetItem() { lastBudgetItem = GetTime(); } void CMasternodeSync::GetNextAsset() { switch(RequestedMasternodeAssets) { case(MASTERNODE_SYNC_INITIAL): case(MASTERNODE_SYNC_FAILED): lastMasternodeList = 0; lastMasternodeWinner = 0; lastBudgetItem = 0; RequestedMasternodeAssets = MASTERNODE_SYNC_SPORKS; break; case(MASTERNODE_SYNC_SPORKS): RequestedMasternodeAssets = MASTERNODE_SYNC_LIST; break; case(MASTERNODE_SYNC_LIST): RequestedMasternodeAssets = MASTERNODE_SYNC_MNW; break; case(MASTERNODE_SYNC_MNW): RequestedMasternodeAssets = MASTERNODE_SYNC_BUDGET; break; case(MASTERNODE_SYNC_BUDGET): LogPrintf("CMasternodeSync::GetNextAsset - Sync has finished\n"); RequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED; break; } RequestedMasternodeAttempt = 0; } void CMasternodeSync::Process() { static int tick = 0; if(tick++ % MASTERNODE_SYNC_TIMEOUT != 0) return; CBlockIndex* pindexPrev = chainActive.Tip(); if(pindexPrev == NULL) return; if(IsSynced()) { /* Resync if we lose all masternodes from sleep/wake or failure to sync originally */ if(mnodeman.CountEnabled() == 0) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { pnode->ClearFulfilledRequest("getspork"); pnode->ClearFulfilledRequest("mnsync"); pnode->ClearFulfilledRequest("mnwsync"); pnode->ClearFulfilledRequest("busync"); } RequestedMasternodeAssets = MASTERNODE_SYNC_INITIAL; } else return; } //try syncing again in an hour if(RequestedMasternodeAssets == MASTERNODE_SYNC_FAILED && lastFailure + (60*60) < GetTime()) { GetNextAsset(); } else if (RequestedMasternodeAssets == MASTERNODE_SYNC_FAILED) { return; } if(fDebug) LogPrintf("CMasternodeSync::Process() - tick %d RequestedMasternodeAssets %d\n", tick, RequestedMasternodeAssets); if(RequestedMasternodeAssets == MASTERNODE_SYNC_INITIAL) GetNextAsset(); LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if(Params().NetworkID() == CBaseChainParams::REGTEST){ if(RequestedMasternodeAttempt <= 2) { pnode->PushMessage("getsporks"); //get current network sporks } else if(RequestedMasternodeAttempt < 4) { mnodeman.DsegUpdate(pnode); } else if(RequestedMasternodeAttempt < 6) { int nMnCount = mnodeman.CountEnabled()*2; pnode->PushMessage("mnget", nMnCount); //sync payees uint256 n = 0; pnode->PushMessage("mnvs", n); //sync masternode votes } else { RequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED; } RequestedMasternodeAttempt++; return; } //set to synced if(RequestedMasternodeAssets == MASTERNODE_SYNC_SPORKS){ if(pnode->HasFulfilledRequest("getspork")) continue; pnode->FulfilledRequest("getspork"); pnode->PushMessage("getsporks"); //get current network sporks if(RequestedMasternodeAttempt >= 2) GetNextAsset(); RequestedMasternodeAttempt++; return; } if(IsInitialBlockDownload()) return; //don't begin syncing until we're almost at a recent block if(pindexPrev->nHeight + 4 < pindexBestHeader->nHeight || pindexPrev->nTime + 600 < GetTime()) return; if (pnode->nVersion >= masternodePayments.GetMinMasternodePaymentsProto()) { if(RequestedMasternodeAssets == MASTERNODE_SYNC_LIST) { if(fDebug) LogPrintf("CMasternodeSync::Process() - lastMasternodeList %lld (GetTime() - MASTERNODE_SYNC_TIMEOUT) %lld\n", lastMasternodeList, GetTime() - MASTERNODE_SYNC_TIMEOUT); if(lastMasternodeList > 0 && lastMasternodeList < GetTime() - MASTERNODE_SYNC_TIMEOUT && RequestedMasternodeAttempt >= 4){ //hasn't received a new item in the last five seconds, so we'll move to the GetNextAsset(); return; } if(pnode->HasFulfilledRequest("mnsync")) continue; pnode->FulfilledRequest("mnsync"); mnodeman.DsegUpdate(pnode); RequestedMasternodeAttempt++; return; } if(RequestedMasternodeAssets == MASTERNODE_SYNC_MNW) { if(lastMasternodeWinner > 0 && lastMasternodeWinner < GetTime() - MASTERNODE_SYNC_TIMEOUT && RequestedMasternodeAttempt >= 4){ //hasn't received a new item in the last five seconds, so we'll move to the GetNextAsset(); return; } if(pnode->HasFulfilledRequest("mnwsync")) continue; pnode->FulfilledRequest("mnwsync"); CBlockIndex* pindexPrev = chainActive.Tip(); if(pindexPrev == NULL) return; int nMnCount = mnodeman.CountEnabled()*2; pnode->PushMessage("mnget", nMnCount); //sync payees RequestedMasternodeAttempt++; return; } } if (pnode->nVersion >= MIN_BUDGET_PEER_PROTO_VERSION) { if(RequestedMasternodeAssets == MASTERNODE_SYNC_BUDGET){ //we'll start rejecting votes if we accidentally get set as synced too soon if(lastBudgetItem > 0 && lastBudgetItem < GetTime() - MASTERNODE_SYNC_TIMEOUT*3 && RequestedMasternodeAttempt >= 4){ //hasn't received a new item in the last five seconds, so we'll move to the if(budget.HasNextFinalizedBudget()) { GetNextAsset(); } else { //we've failed to sync, this state will reject the next budget block LogPrintf("CMasternodeSync::Process - ERROR - Sync has failed, will retry later\n"); RequestedMasternodeAssets = MASTERNODE_SYNC_FAILED; RequestedMasternodeAttempt = 0; lastFailure = GetTime(); } return; } if(pnode->HasFulfilledRequest("busync")) continue; pnode->FulfilledRequest("busync"); uint256 n = 0; pnode->PushMessage("mnvs", n); //sync masternode votes RequestedMasternodeAttempt++; return; } } } } <commit_msg>Update isBlockchainSynced requirements<commit_after>// Copyright (c) 2014-2015 The Dash developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "masternode-sync.h" #include "masternode-payments.h" #include "masternode-budget.h" #include "masternode.h" #include "masternodeman.h" #include "util.h" #include "addrman.h" class CMasternodeSync; CMasternodeSync masternodeSync; CMasternodeSync::CMasternodeSync() { lastMasternodeList = 0; lastMasternodeWinner = 0; lastBudgetItem = 0; RequestedMasternodeAssets = MASTERNODE_SYNC_INITIAL; RequestedMasternodeAttempt = 0; } bool CMasternodeSync::IsSynced() { return RequestedMasternodeAssets == MASTERNODE_SYNC_FINISHED; } bool CMasternodeSync::IsBlockchainSynced() { CBlockIndex* pindexPrev = chainActive.Tip(); if(pindexPrev == NULL) return false; if(pindexPrev->nTime + 600 < GetTime()) return false; return true; } void CMasternodeSync::AddedMasternodeList() { lastMasternodeList = GetTime(); } void CMasternodeSync::AddedMasternodeWinner() { lastMasternodeWinner = GetTime(); } void CMasternodeSync::AddedBudgetItem() { lastBudgetItem = GetTime(); } void CMasternodeSync::GetNextAsset() { switch(RequestedMasternodeAssets) { case(MASTERNODE_SYNC_INITIAL): case(MASTERNODE_SYNC_FAILED): lastMasternodeList = 0; lastMasternodeWinner = 0; lastBudgetItem = 0; RequestedMasternodeAssets = MASTERNODE_SYNC_SPORKS; break; case(MASTERNODE_SYNC_SPORKS): RequestedMasternodeAssets = MASTERNODE_SYNC_LIST; break; case(MASTERNODE_SYNC_LIST): RequestedMasternodeAssets = MASTERNODE_SYNC_MNW; break; case(MASTERNODE_SYNC_MNW): RequestedMasternodeAssets = MASTERNODE_SYNC_BUDGET; break; case(MASTERNODE_SYNC_BUDGET): LogPrintf("CMasternodeSync::GetNextAsset - Sync has finished\n"); RequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED; break; } RequestedMasternodeAttempt = 0; } void CMasternodeSync::Process() { static int tick = 0; if(tick++ % MASTERNODE_SYNC_TIMEOUT != 0) return; CBlockIndex* pindexPrev = chainActive.Tip(); if(pindexPrev == NULL) return; if(IsSynced()) { /* Resync if we lose all masternodes from sleep/wake or failure to sync originally */ if(mnodeman.CountEnabled() == 0) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { pnode->ClearFulfilledRequest("getspork"); pnode->ClearFulfilledRequest("mnsync"); pnode->ClearFulfilledRequest("mnwsync"); pnode->ClearFulfilledRequest("busync"); } RequestedMasternodeAssets = MASTERNODE_SYNC_INITIAL; } else return; } //try syncing again in an hour if(RequestedMasternodeAssets == MASTERNODE_SYNC_FAILED && lastFailure + (60*60) < GetTime()) { GetNextAsset(); } else if (RequestedMasternodeAssets == MASTERNODE_SYNC_FAILED) { return; } if(fDebug) LogPrintf("CMasternodeSync::Process() - tick %d RequestedMasternodeAssets %d\n", tick, RequestedMasternodeAssets); if(RequestedMasternodeAssets == MASTERNODE_SYNC_INITIAL) GetNextAsset(); LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if(Params().NetworkID() == CBaseChainParams::REGTEST){ if(RequestedMasternodeAttempt <= 2) { pnode->PushMessage("getsporks"); //get current network sporks } else if(RequestedMasternodeAttempt < 4) { mnodeman.DsegUpdate(pnode); } else if(RequestedMasternodeAttempt < 6) { int nMnCount = mnodeman.CountEnabled()*2; pnode->PushMessage("mnget", nMnCount); //sync payees uint256 n = 0; pnode->PushMessage("mnvs", n); //sync masternode votes } else { RequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED; } RequestedMasternodeAttempt++; return; } //set to synced if(RequestedMasternodeAssets == MASTERNODE_SYNC_SPORKS){ if(pnode->HasFulfilledRequest("getspork")) continue; pnode->FulfilledRequest("getspork"); pnode->PushMessage("getsporks"); //get current network sporks if(RequestedMasternodeAttempt >= 2) GetNextAsset(); RequestedMasternodeAttempt++; return; } if(IsInitialBlockDownload()) return; //don't begin syncing until we're almost at a recent block if(pindexPrev->nTime + 600 < GetTime()) return; if (pnode->nVersion >= masternodePayments.GetMinMasternodePaymentsProto()) { if(RequestedMasternodeAssets == MASTERNODE_SYNC_LIST) { if(fDebug) LogPrintf("CMasternodeSync::Process() - lastMasternodeList %lld (GetTime() - MASTERNODE_SYNC_TIMEOUT) %lld\n", lastMasternodeList, GetTime() - MASTERNODE_SYNC_TIMEOUT); if(lastMasternodeList > 0 && lastMasternodeList < GetTime() - MASTERNODE_SYNC_TIMEOUT && RequestedMasternodeAttempt >= 4){ //hasn't received a new item in the last five seconds, so we'll move to the GetNextAsset(); return; } if(pnode->HasFulfilledRequest("mnsync")) continue; pnode->FulfilledRequest("mnsync"); mnodeman.DsegUpdate(pnode); RequestedMasternodeAttempt++; return; } if(RequestedMasternodeAssets == MASTERNODE_SYNC_MNW) { if(lastMasternodeWinner > 0 && lastMasternodeWinner < GetTime() - MASTERNODE_SYNC_TIMEOUT && RequestedMasternodeAttempt >= 4){ //hasn't received a new item in the last five seconds, so we'll move to the GetNextAsset(); return; } if(pnode->HasFulfilledRequest("mnwsync")) continue; pnode->FulfilledRequest("mnwsync"); CBlockIndex* pindexPrev = chainActive.Tip(); if(pindexPrev == NULL) return; int nMnCount = mnodeman.CountEnabled()*2; pnode->PushMessage("mnget", nMnCount); //sync payees RequestedMasternodeAttempt++; return; } } if (pnode->nVersion >= MIN_BUDGET_PEER_PROTO_VERSION) { if(RequestedMasternodeAssets == MASTERNODE_SYNC_BUDGET){ //we'll start rejecting votes if we accidentally get set as synced too soon if(lastBudgetItem > 0 && lastBudgetItem < GetTime() - MASTERNODE_SYNC_TIMEOUT*3 && RequestedMasternodeAttempt >= 4){ //hasn't received a new item in the last five seconds, so we'll move to the if(budget.HasNextFinalizedBudget()) { GetNextAsset(); } else { //we've failed to sync, this state will reject the next budget block LogPrintf("CMasternodeSync::Process - ERROR - Sync has failed, will retry later\n"); RequestedMasternodeAssets = MASTERNODE_SYNC_FAILED; RequestedMasternodeAttempt = 0; lastFailure = GetTime(); } return; } if(pnode->HasFulfilledRequest("busync")) continue; pnode->FulfilledRequest("busync"); uint256 n = 0; pnode->PushMessage("mnvs", n); //sync masternode votes RequestedMasternodeAttempt++; return; } } } } <|endoftext|>
<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Module: FGLocation.cpp Author: Jon S. Berndt Date started: 04/04/2004 Purpose: Store an arbitrary location on the globe ------- Copyright (C) 1999 Jon S. Berndt (jsb@hal-pc.org) ------------------ ------- (C) 2004 Mathias Froehlich (Mathias.Froehlich@web.de) ---- This program 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 2 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser 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. Further information about the GNU Lesser General Public License can also be found on the world wide web at http://www.gnu.org. FUNCTIONAL DESCRIPTION ------------------------------------------------------------------------------ This class encapsulates an arbitrary position in the globe with its accessors. It has vector properties, so you can add multiply .... HISTORY ------------------------------------------------------------------------------ 04/04/2004 MF Created %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #ifdef FGFS # include <simgear/compiler.h> # ifdef SG_HAVE_STD_INCLUDES # include <cmath> # else # include <math.h> # endif #else # if defined(sgi) && !defined(__GNUC__) # include <math.h> # else # include <cmath> # endif #endif #include "FGLocation.h" #include <input_output/FGPropertyManager.h> namespace JSBSim { static const char *IdSrc = "$Id: FGLocation.cpp,v 1.9 2008/03/01 01:25:12 jberndt Exp $"; static const char *IdHdr = ID_LOCATION; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CLASS IMPLEMENTATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ FGLocation::FGLocation(void) { mCacheValid = false; initial_longitude = 0.0; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGLocation::FGLocation(double lon, double lat, double radius) { mCacheValid = false; double sinLat = sin(lat); double cosLat = cos(lat); double sinLon = sin(lon); double cosLon = cos(lon); initial_longitude = lon; mECLoc = FGColumnVector3( radius*cosLat*cosLon, radius*cosLat*sinLon, radius*sinLat ); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::SetLongitude(double longitude) { double rtmp = mECLoc.Magnitude(eX, eY); // Check if we have zero radius. // If so set it to 1, so that we can set a position if (0.0 == mECLoc.Magnitude()) rtmp = 1.0; // Fast return if we are on the north or south pole ... if (rtmp == 0.0) return; mCacheValid = false; // Need to figure out how to set the initial_longitude here mECLoc(eX) = rtmp*cos(longitude); mECLoc(eY) = rtmp*sin(longitude); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::SetLatitude(double latitude) { mCacheValid = false; double r = mECLoc.Magnitude(); if (r == 0.0) { mECLoc(eX) = 1.0; r = 1.0; } double rtmp = mECLoc.Magnitude(eX, eY); if (rtmp != 0.0) { double fac = r/rtmp*cos(latitude); mECLoc(eX) *= fac; mECLoc(eY) *= fac; } else { mECLoc(eX) = r*cos(latitude); mECLoc(eY) = 0.0; } mECLoc(eZ) = r*sin(latitude); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::SetRadius(double radius) { mCacheValid = false; double rold = mECLoc.Magnitude(); if (rold == 0.0) mECLoc(eX) = radius; else mECLoc *= radius/rold; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::SetEllipse(double semimajor, double semiminor) { mCacheValid = false; a = semimajor; b = semiminor; a2 = a*a; b2 = b*b; e2 = 1.0 - b2/a2; e = sqrt(e2); eps2 = a2/b2 - 1.0; f = 1.0 - b/a; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Compute the ECEF to ECI transformation matrix using Stevens and Lewis "Aircraft // Control and Simulation", second edition, eqn. 1.4-12, pg. 39 const FGMatrix33& FGLocation::GetTec2i(double epa) { double mu = epa - initial_longitude; mTec2i = FGMatrix33( cos(mu), -sin(mu), 0.0, sin(mu), cos(mu), 0.0, 0.0, 0.0, 1.0 ); return mTec2i; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% const FGMatrix33& FGLocation::GetTi2ec(double epa) { double mu = epa - initial_longitude; mTi2ec = FGMatrix33( cos(mu), sin(mu), 0.0, -sin(mu), cos(mu), 0.0, 0.0, 0.0, 1.0 ); return mTi2ec; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::ComputeDerivedUnconditional(void) const { // The radius is just the Euclidean norm of the vector. mRadius = mECLoc.Magnitude(); // The distance of the location to the Z-axis, which is the axis // through the poles. double rxy = sqrt(mECLoc(eX)*mECLoc(eX) + mECLoc(eY)*mECLoc(eY)); // Compute the sin/cos values of the longitude double sinLon, cosLon; if (rxy == 0.0) { sinLon = 0.0; cosLon = 1.0; } else { sinLon = mECLoc(eY)/rxy; cosLon = mECLoc(eX)/rxy; } // Compute the sin/cos values of the latitude double sinLat, cosLat; if (mRadius == 0.0) { sinLat = 0.0; cosLat = 1.0; } else { sinLat = mECLoc(eZ)/mRadius; cosLat = rxy/mRadius; } // Compute the longitude and latitude itself if ( mECLoc( eX ) == 0.0 && mECLoc( eY ) == 0.0 ) mLon = 0.0; else mLon = atan2( mECLoc( eY ), mECLoc( eX ) ); if ( rxy == 0.0 && mECLoc( eZ ) == 0.0 ) mLat = 0.0; else mLat = atan2( mECLoc(eZ), rxy ); // Compute the transform matrices from and to the earth centered frame. // See Stevens and Lewis, "Aircraft Control and Simulation", Second Edition, // Eqn. 1.4-13, page 40. mTec2l = FGMatrix33( -cosLon*sinLat, -sinLon*sinLat, cosLat, -sinLon , cosLon , 0.0 , -cosLon*cosLat, -sinLon*cosLat, -sinLat ); mTl2ec = mTec2l.Transposed(); // Calculate the geodetic latitude base on AIAA Journal of Guidance and Control paper, // "Improved Method for Calculating Exact Geodetic Latitude and Altitude", and // "Improved Method for Calculating Exact Geodetic Latitude and Altitude, Revisited", // author: I. Sofair double c, p, q, s, t, u, v, w, z, p2, u2; double Ne, P, Q0, Q, signz0, sqrt_q; p = fabs(mECLoc(eZ))/eps2; s = (mRadius*mRadius)/(e2*eps2); p2 = p*p; q = p2 - b2 + s; sqrt_q = sqrt(q); if (q>0) { u = p/sqrt_q; u2 = p2/q; v = b2*u2/q; P = 27.0*v*s/q; Q0 = sqrt(P+1) + sqrt(P); Q = pow(Q0, 0.66666666667); t = (1.0 + Q + 1.0/Q)/6.0; c = sqrt(u2 - 1 + 2.0*t); w = (c - u)/2.0; signz0 = mECLoc(eZ)>=0?1.0:-1.0; z = signz0*sqrt_q*(w+sqrt(sqrt(t*t+v)-u*w-0.5*t-0.25)); Ne = a*sqrt(1+eps2*z*z/b2); mGeodLat = asin((eps2+1.0)*(z/Ne)); GeodeticAltitude = mRadius*cos(mGeodLat) + mECLoc(eZ)*sin(mGeodLat) - a2/Ne; } // Mark the cached values as valid mCacheValid = true; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% } // namespace JSBSim <commit_msg>Made a fix of sorts to the uninitialized b2 variable bug in FGLocation<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Module: FGLocation.cpp Author: Jon S. Berndt Date started: 04/04/2004 Purpose: Store an arbitrary location on the globe ------- Copyright (C) 1999 Jon S. Berndt (jsb@hal-pc.org) ------------------ ------- (C) 2004 Mathias Froehlich (Mathias.Froehlich@web.de) ---- This program 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 2 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser 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. Further information about the GNU Lesser General Public License can also be found on the world wide web at http://www.gnu.org. FUNCTIONAL DESCRIPTION ------------------------------------------------------------------------------ This class encapsulates an arbitrary position in the globe with its accessors. It has vector properties, so you can add multiply .... HISTORY ------------------------------------------------------------------------------ 04/04/2004 MF Created %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #ifdef FGFS # include <simgear/compiler.h> # ifdef SG_HAVE_STD_INCLUDES # include <cmath> # else # include <math.h> # endif #else # if defined(sgi) && !defined(__GNUC__) # include <math.h> # else # include <cmath> # endif #endif #include "FGLocation.h" #include <input_output/FGPropertyManager.h> namespace JSBSim { static const char *IdSrc = "$Id: FGLocation.cpp,v 1.10 2008/04/16 13:18:59 jberndt Exp $"; static const char *IdHdr = ID_LOCATION; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CLASS IMPLEMENTATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ FGLocation::FGLocation(void) { mCacheValid = false; initial_longitude = 0.0; a = 0.0; b = 0.0; a2 = 0.0; b2 = 0.0; e2 = 1.0; e = 1.0; eps2 = -1.0; f = 1.0; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGLocation::FGLocation(double lon, double lat, double radius) { mCacheValid = false; double sinLat = sin(lat); double cosLat = cos(lat); double sinLon = sin(lon); double cosLon = cos(lon); initial_longitude = lon; a = 0.0; b = 0.0; a2 = 0.0; b2 = 0.0; e2 = 1.0; e = 1.0; eps2 = -1.0; f = 1.0; mECLoc = FGColumnVector3( radius*cosLat*cosLon, radius*cosLat*sinLon, radius*sinLat ); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::SetLongitude(double longitude) { double rtmp = mECLoc.Magnitude(eX, eY); // Check if we have zero radius. // If so set it to 1, so that we can set a position if (0.0 == mECLoc.Magnitude()) rtmp = 1.0; // Fast return if we are on the north or south pole ... if (rtmp == 0.0) return; mCacheValid = false; // Need to figure out how to set the initial_longitude here mECLoc(eX) = rtmp*cos(longitude); mECLoc(eY) = rtmp*sin(longitude); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::SetLatitude(double latitude) { mCacheValid = false; double r = mECLoc.Magnitude(); if (r == 0.0) { mECLoc(eX) = 1.0; r = 1.0; } double rtmp = mECLoc.Magnitude(eX, eY); if (rtmp != 0.0) { double fac = r/rtmp*cos(latitude); mECLoc(eX) *= fac; mECLoc(eY) *= fac; } else { mECLoc(eX) = r*cos(latitude); mECLoc(eY) = 0.0; } mECLoc(eZ) = r*sin(latitude); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::SetRadius(double radius) { mCacheValid = false; double rold = mECLoc.Magnitude(); if (rold == 0.0) mECLoc(eX) = radius; else mECLoc *= radius/rold; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::SetEllipse(double semimajor, double semiminor) { mCacheValid = false; a = semimajor; b = semiminor; a2 = a*a; b2 = b*b; e2 = 1.0 - b2/a2; e = sqrt(e2); eps2 = a2/b2 - 1.0; f = 1.0 - b/a; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Compute the ECEF to ECI transformation matrix using Stevens and Lewis "Aircraft // Control and Simulation", second edition, eqn. 1.4-12, pg. 39 const FGMatrix33& FGLocation::GetTec2i(double epa) { double mu = epa - initial_longitude; mTec2i = FGMatrix33( cos(mu), -sin(mu), 0.0, sin(mu), cos(mu), 0.0, 0.0, 0.0, 1.0 ); return mTec2i; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% const FGMatrix33& FGLocation::GetTi2ec(double epa) { double mu = epa - initial_longitude; mTi2ec = FGMatrix33( cos(mu), sin(mu), 0.0, -sin(mu), cos(mu), 0.0, 0.0, 0.0, 1.0 ); return mTi2ec; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLocation::ComputeDerivedUnconditional(void) const { // The radius is just the Euclidean norm of the vector. mRadius = mECLoc.Magnitude(); // The distance of the location to the Z-axis, which is the axis // through the poles. double rxy = sqrt(mECLoc(eX)*mECLoc(eX) + mECLoc(eY)*mECLoc(eY)); // Compute the sin/cos values of the longitude double sinLon, cosLon; if (rxy == 0.0) { sinLon = 0.0; cosLon = 1.0; } else { sinLon = mECLoc(eY)/rxy; cosLon = mECLoc(eX)/rxy; } // Compute the sin/cos values of the latitude double sinLat, cosLat; if (mRadius == 0.0) { sinLat = 0.0; cosLat = 1.0; } else { sinLat = mECLoc(eZ)/mRadius; cosLat = rxy/mRadius; } // Compute the longitude and latitude itself if ( mECLoc( eX ) == 0.0 && mECLoc( eY ) == 0.0 ) mLon = 0.0; else mLon = atan2( mECLoc( eY ), mECLoc( eX ) ); if ( rxy == 0.0 && mECLoc( eZ ) == 0.0 ) mLat = 0.0; else mLat = atan2( mECLoc(eZ), rxy ); // Compute the transform matrices from and to the earth centered frame. // See Stevens and Lewis, "Aircraft Control and Simulation", Second Edition, // Eqn. 1.4-13, page 40. mTec2l = FGMatrix33( -cosLon*sinLat, -sinLon*sinLat, cosLat, -sinLon , cosLon , 0.0 , -cosLon*cosLat, -sinLon*cosLat, -sinLat ); mTl2ec = mTec2l.Transposed(); // Calculate the geodetic latitude base on AIAA Journal of Guidance and Control paper, // "Improved Method for Calculating Exact Geodetic Latitude and Altitude", and // "Improved Method for Calculating Exact Geodetic Latitude and Altitude, Revisited", // author: I. Sofair if (a != 0.0 && b != 0.0) { double c, p, q, s, t, u, v, w, z, p2, u2; double Ne, P, Q0, Q, signz0, sqrt_q; p = fabs(mECLoc(eZ))/eps2; s = (mRadius*mRadius)/(e2*eps2); p2 = p*p; q = p2 - b2 + s; sqrt_q = sqrt(q); if (q>0) { u = p/sqrt_q; u2 = p2/q; v = b2*u2/q; P = 27.0*v*s/q; Q0 = sqrt(P+1) + sqrt(P); Q = pow(Q0, 0.66666666667); t = (1.0 + Q + 1.0/Q)/6.0; c = sqrt(u2 - 1 + 2.0*t); w = (c - u)/2.0; signz0 = mECLoc(eZ)>=0?1.0:-1.0; z = signz0*sqrt_q*(w+sqrt(sqrt(t*t+v)-u*w-0.5*t-0.25)); Ne = a*sqrt(1+eps2*z*z/b2); mGeodLat = asin((eps2+1.0)*(z/Ne)); GeodeticAltitude = mRadius*cos(mGeodLat) + mECLoc(eZ)*sin(mGeodLat) - a2/Ne; } } // Mark the cached values as valid mCacheValid = true; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% } // namespace JSBSim <|endoftext|>
<commit_before>// Copyright (c) 2014-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "main.h" #include "test/test_bitcoin.h" #include <boost/signals2/signal.hpp> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(main_tests, TestingSetup) static void TestBlockSubsidyHalvings(const Consensus::Params& consensusParams) { int maxHalvings = 64; CAmount nInitialSubsidy = 50 * COIN; CAmount nPreviousSubsidy = nInitialSubsidy * 2; // for height == 0 BOOST_CHECK_EQUAL(nPreviousSubsidy, nInitialSubsidy * 2); for (int nHalvings = 0; nHalvings < maxHalvings; nHalvings++) { int nHeight = nHalvings * consensusParams.nSubsidyHalvingInterval; CAmount nSubsidy = GetBlockSubsidy(nHeight, consensusParams, 1475020800); BOOST_CHECK(nSubsidy <= nInitialSubsidy); if(nHeight > 0) BOOST_CHECK_EQUAL(nSubsidy, nPreviousSubsidy / 2); nPreviousSubsidy = nPreviousSubsidy / 2; } BOOST_CHECK_EQUAL(GetBlockSubsidy(maxHalvings * consensusParams.nSubsidyHalvingInterval, consensusParams), 0); } static void TestBlockSubsidyHalvings(int nSubsidyHalvingInterval) { Consensus::Params consensusParams; consensusParams.nMTPSwitchTime = INT_MAX; consensusParams.nSubsidyHalvingInterval = nSubsidyHalvingInterval; TestBlockSubsidyHalvings(consensusParams); } BOOST_AUTO_TEST_CASE(block_subsidy_test) { TestBlockSubsidyHalvings(Params(CBaseChainParams::MAIN).GetConsensus()); // As in main TestBlockSubsidyHalvings(305000); // As in regtest //TestBlockSubsidyHalvings(1000); // Just another interval } BOOST_AUTO_TEST_CASE(subsidy_limit_test) { const Consensus::Params& consensusParams = Params(CBaseChainParams::MAIN).GetConsensus(); CAmount nSum = 0; for (int nHeight = 0; nHeight < 14000000; nHeight += 1000) { CAmount nSubsidy = GetBlockSubsidy(nHeight, consensusParams); if(nHeight == 0) nSubsidy = 50 * COIN; BOOST_CHECK(nSubsidy <= 50 * COIN); nSum += nSubsidy * 1000; BOOST_CHECK(MoneyRange(nSum)); } //TODO: re-calculate correct sum here (halving block has changed from 210000 to 305000) //BOOST_CHECK_EQUAL(nSum, 2099999997690000ULL); } bool ReturnFalse() { return false; } bool ReturnTrue() { return true; } BOOST_AUTO_TEST_CASE(test_combiner_all) { boost::signals2::signal<bool (), CombinerAll> Test; BOOST_CHECK(Test()); Test.connect(&ReturnFalse); BOOST_CHECK(!Test()); Test.connect(&ReturnTrue); BOOST_CHECK(!Test()); Test.disconnect(&ReturnFalse); BOOST_CHECK(Test()); Test.disconnect(&ReturnTrue); BOOST_CHECK(Test()); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Fix for the subsidy unit test<commit_after>// Copyright (c) 2014-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "main.h" #include "test/test_bitcoin.h" #include <boost/signals2/signal.hpp> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(main_tests, TestingSetup) static void TestBlockSubsidyHalvings(const Consensus::Params& consensusParams) { int maxHalvings = 64; CAmount nInitialSubsidy = 50 * COIN; CAmount nPreviousSubsidy = nInitialSubsidy * 2; // for height == 0 BOOST_CHECK_EQUAL(nPreviousSubsidy, nInitialSubsidy * 2); for (int nHalvings = 0; nHalvings < maxHalvings; nHalvings++) { int nHeight = nHalvings * consensusParams.nSubsidyHalvingInterval; CAmount nSubsidy = GetBlockSubsidy(nHeight, consensusParams, 1475020800); BOOST_CHECK(nSubsidy <= nInitialSubsidy); if(nHeight > 0) BOOST_CHECK_EQUAL(nSubsidy, nPreviousSubsidy / 2); nPreviousSubsidy = nPreviousSubsidy / 2; } BOOST_CHECK_EQUAL(GetBlockSubsidy(maxHalvings * consensusParams.nSubsidyHalvingInterval, consensusParams), 0); } static void TestBlockSubsidyHalvings(int nSubsidyHalvingInterval) { Consensus::Params consensusParams; consensusParams.nMTPSwitchTime = INT_MAX; consensusParams.nSubsidyHalvingInterval = nSubsidyHalvingInterval; TestBlockSubsidyHalvings(consensusParams); } BOOST_AUTO_TEST_CASE(block_subsidy_test) { TestBlockSubsidyHalvings(Params(CBaseChainParams::MAIN).GetConsensus()); // As in main TestBlockSubsidyHalvings(305000); // As in regtest //TestBlockSubsidyHalvings(1000); // Just another interval } BOOST_AUTO_TEST_CASE(subsidy_limit_test) { Consensus::Params consensusParams = Params(CBaseChainParams::MAIN).GetConsensus(); CAmount nSum = 0; int const t5m = 300 , t10m = 600 , mtpActivationHeight = (consensusParams.nMTPSwitchTime - consensusParams.nChainStartTime) / t10m , mtpReleaseHeight = 110725 ; int nHeight = 0; int const step = 1000; consensusParams.nSubsidyHalvingInterval = 210000; for(; nHeight < mtpReleaseHeight; nHeight += step) { CAmount nSubsidy = GetBlockSubsidy(nHeight, consensusParams); if(nHeight == 0) nSubsidy = 50 * COIN; BOOST_CHECK(nSubsidy <= 50 * COIN); nSum += nSubsidy * 1000; BOOST_CHECK(MoneyRange(nSum)); } BOOST_CHECK_EQUAL(nSum, 555000000000000ULL); consensusParams.nSubsidyHalvingInterval = 305000; for(; nHeight < 14000000 + mtpReleaseHeight; nHeight += step) { int blockTime = nHeight * t10m; if(nHeight > mtpActivationHeight) blockTime -= (nHeight - mtpActivationHeight) * t5m; CAmount nSubsidy = GetBlockSubsidy(nHeight, consensusParams, blockTime + consensusParams.nChainStartTime); if(nHeight == 0) nSubsidy = 50 * COIN; BOOST_CHECK(nSubsidy <= 50 * COIN); nSum += nSubsidy * 1000; BOOST_CHECK(MoneyRange(nSum)); } BOOST_CHECK_EQUAL(nSum, 2003203125000000ULL); } bool ReturnFalse() { return false; } bool ReturnTrue() { return true; } BOOST_AUTO_TEST_CASE(test_combiner_all) { boost::signals2::signal<bool (), CombinerAll> Test; BOOST_CHECK(Test()); Test.connect(&ReturnFalse); BOOST_CHECK(!Test()); Test.connect(&ReturnTrue); BOOST_CHECK(!Test()); Test.disconnect(&ReturnFalse); BOOST_CHECK(Test()); Test.disconnect(&ReturnTrue); BOOST_CHECK(Test()); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include <allegro.h> #include <iostream> #include "util/file-system.h" #include "mugen/character.h" #include "mugen/mugen_exception.h" using namespace std; int main(){ install_allegro(SYSTEM_NONE, &errno, atexit); set_color_depth(16); set_color_conversion(COLORCONV_NONE); // for (int i = 0; i < 3; i++){ try{ Mugen::Character kfm(Filesystem::find("mugen/chars/kfm/kfm.def")); kfm.load(); Global::debug(0, "test") << "Success" << endl; } catch (const MugenException & e){ Global::debug(0, "test") << "Test failure!: " << e.getReason() << endl; } // } } <commit_msg>fix test<commit_after>#include <allegro.h> #include <iostream> #include "util/file-system.h" #include "mugen/character.h" #include "mugen/mugen_exception.h" using namespace std; int main(int argc, char ** argv){ install_allegro(SYSTEM_NONE, &errno, atexit); set_color_depth(16); set_color_conversion(COLORCONV_NONE); // for (int i = 0; i < 3; i++){ try{ Mugen::Character kfm(Filesystem::find("mugen/chars/kfm/kfm.def")); kfm.load(); Global::debug(0, "test") << "Success" << endl; } catch (const MugenException & e){ Global::debug(0, "test") << "Test failure!: " << e.getReason() << endl; } // } } <|endoftext|>
<commit_before>#ifndef SHAPE_HPP_ #define SHAPE_HPP_ #include <iostream> #include <vector> #include <opencv2/opencv.hpp> #include "PointXY.hpp" class Shape { public: Shape() { } cv::Point getCentroid() { std::pair<int,int> centroid; for(unsigned short i = 0; i < m_point_list.size(); ++i) { centroid.first += m_point_list[i].x; centroid.second += m_point_list[i].y; } centroid.first /= m_point_list.size(); centroid.second /= m_point_list.size(); return cv::Point(centroid.second, centroid.first); } std::string get_semantic_shape() { std::string shape_name_ = "unk"; unsigned int v_ = m_vertices.size(); if (v_ == 3) shape_name_ = "triangle"; else if (v_ == 4) shape_name_ = "square"; else if (v_ == 5) shape_name_ = "pentagon"; else if (v_ == 6) shape_name_ = "hexagon"; else if (v_ == 12) shape_name_ = "star"; else if (v_ > 6) shape_name_ = "circle"; return shape_name_; } std::string getSemanticAverageColorHSV() { PointXY point_ = getAverageColor(); return point_.getSemanticColorHSV(); } std::string getSemanticAverageColorLAB() { PointXY point_ = getAverageColor(); return point_.getSemanticColorLAB(); } PointXY getAverageColor() { PointXY color_avg_; for(unsigned short i = 0; i < m_point_list.size(); ++i) { color_avg_.values[0] += m_point_list[i].values[0]; color_avg_.values[1] += m_point_list[i].values[1]; color_avg_.values[2] += m_point_list[i].values[2]; } color_avg_.values[0] /= m_point_list.size(); color_avg_.values[1] /= m_point_list.size(); color_avg_.values[2] /= m_point_list.size(); return color_avg_; } void add_point(PointXY point) { m_point_list.push_back(point); } void add_vertex (const cv::Point & crVertex) { m_vertices.push_back(crVertex); } void draw_contour (cv::Mat & rImage, const cv::Scalar & crColor) { for (unsigned int i = 0; i < m_vertices.size()-1; ++i) { cv::line(rImage, m_vertices[i], m_vertices[i+1], crColor, 10); } if (m_vertices.size() > 2) cv::line(rImage, m_vertices[m_vertices.size()-1], m_vertices[0], crColor, 10); } void draw_name (cv::Mat & rImage, const cv::Scalar & crColor) { cv::putText(rImage, get_semantic_shape(), m_vertices[0], cv::FONT_HERSHEY_SIMPLEX, 5, crColor, 5); } private: std::vector<PointXY> m_point_list; std::vector<cv::Point> m_vertices; }; #endif <commit_msg>add circle properties to shape<commit_after>#ifndef SHAPE_HPP_ #define SHAPE_HPP_ #include <iostream> #include <vector> #include <opencv2/opencv.hpp> #include "PointXY.hpp" class Shape { public: Shape() { m_radius = -1; } cv::Point getCentroid() { std::pair<int,int> centroid; for(unsigned short i = 0; i < m_point_list.size(); ++i) { centroid.first += m_point_list[i].x; centroid.second += m_point_list[i].y; } centroid.first /= m_point_list.size(); centroid.second /= m_point_list.size(); return cv::Point(centroid.second, centroid.first); } std::string get_semantic_shape() { std::string shape_name_ = "unk"; unsigned int v_ = m_vertices.size(); if (m_radius > 0) shape_name_ = "circle"; if (v_ == 3) shape_name_ = "triangle"; else if (v_ == 4) shape_name_ = "square"; else if (v_ == 5) shape_name_ = "pentagon"; else if (v_ == 6) shape_name_ = "hexagon"; else if (v_ == 12) shape_name_ = "star"; return shape_name_; } std::string getSemanticAverageColorHSV() { PointXY point_ = getAverageColor(); return point_.getSemanticColorHSV(); } std::string getSemanticAverageColorLAB() { PointXY point_ = getAverageColor(); return point_.getSemanticColorLAB(); } PointXY getAverageColor() { PointXY color_avg_; for(unsigned short i = 0; i < m_point_list.size(); ++i) { color_avg_.values[0] += m_point_list[i].values[0]; color_avg_.values[1] += m_point_list[i].values[1]; color_avg_.values[2] += m_point_list[i].values[2]; } color_avg_.values[0] /= m_point_list.size(); color_avg_.values[1] /= m_point_list.size(); color_avg_.values[2] /= m_point_list.size(); return color_avg_; } void set_radius(const int & crRadius) { m_radius = crRadius; } void add_point(PointXY point) { m_point_list.push_back(point); } void add_vertex (const cv::Point & crVertex) { m_vertices.push_back(crVertex); } void draw_contour (cv::Mat & rImage, const cv::Scalar & crColor) { if (m_radius > 0.0) { cv::circle(rImage, m_vertices[0], 3, crColor, -1, 8, 0 ); cv::circle(rImage, m_vertices[0], m_radius, crColor, 3, 8, 0); } else { for (unsigned int i = 0; i < m_vertices.size()-1; ++i) { cv::line(rImage, m_vertices[i], m_vertices[i+1], crColor, 10); } if (m_vertices.size() > 2) cv::line(rImage, m_vertices[m_vertices.size()-1], m_vertices[0], crColor, 10); } } void draw_name (cv::Mat & rImage, const cv::Scalar & crColor) { cv::putText(rImage, get_semantic_shape(), m_vertices[0], cv::FONT_HERSHEY_SIMPLEX, 5, crColor, 5); } private: std::vector<PointXY> m_point_list; std::vector<cv::Point> m_vertices; int m_radius; }; #endif <|endoftext|>
<commit_before>/* created by Ghabriel Nunes <ghabriel.nunes@gmail.com> [2017] */ #ifndef UTILS_DEBUG_HPP #define UTILS_DEBUG_HPP #include <csignal> #include <functional> #include <iostream> #include <sstream> #include <tuple> #include <unordered_map> #include <utility> #ifndef ALLOW_DEBUG_USAGE #define ALLOW_DEBUG_USAGE 1 #endif #ifndef DEBUG_ENABLED #define DEBUG_ENABLED 1 #endif #ifndef FUNCTION_NAME #define FUNCTION_NAME __func__ #endif #if ALLOW_DEBUG_USAGE == 1 namespace dbg { template<typename... Args> void echo(Args&&...); namespace detail { std::tuple<size_t, std::string, std::string> debugBuffer; const std::unordered_map<int, std::string> debugLabels = { {SIGABRT, "Aborted"}, {SIGFPE, "Division by zero"}, {SIGILL, "SIGILL"}, {SIGINT, "Interruption"}, {SIGSEGV, "Segmentation fault"}, {SIGTERM, "SIGTERM"} }; inline void printer(int type) { auto line = std::get<0>(debugBuffer); auto& filename = std::get<1>(debugBuffer); auto& functionName = std::get<2>(debugBuffer); std::stringstream ss; ss << debugLabels.at(type) << ".\n Location: " << filename << ":" << line << "\n Function: " << functionName; echo(ss.str()); std::signal(type, SIG_DFL); std::raise(type); } using Redirector = std::function<void(const std::string&)>; using StreamType = decltype(std::cout); struct StreamContainer { static StreamContainer& instance() { static StreamContainer inst; return inst; } StreamContainer& operator<<(const std::string& message) { redirector(message); return *this; } Redirector redirector = [](const std::string& message) { StreamContainer::instance().stream.get() << message; }; std::reference_wrapper<StreamType> stream = std::cout; private: StreamContainer() = default; }; const auto defaultRedirector = StreamContainer::instance().redirector; inline StreamContainer& stream() { return StreamContainer::instance(); } template<bool = DEBUG_ENABLED> struct DebugContainer; template<> struct DebugContainer<true> { static void echo() {} template<typename T, typename... Args> static void echo(const T& value, Args&&... args) { std::stringstream ss; ss << value << '\n'; stream() << ss.str(); echo(std::forward<Args>(args)...); } template<typename... Args> static void echo(const std::string& value, Args&&... args) { stream() << (value + '\n'); echo(std::forward<Args>(args)...); } static void echoIndented(size_t) {} template<typename T, typename... Args> static void echoIndented(size_t numTabs, const T& value, Args&&... args) { std::stringstream ss; for (size_t i = 0; i < numTabs; i++) { ss << "\t"; } ss << value; echo(ss.str()); echoIndented(numTabs, std::forward<Args>(args)...); } template<typename T> static void trace(const std::string& name, const T& value) { std::stringstream ss; ss << name << " = " << value; echo(ss.str()); } static void trace(const std::string& name, const std::string& value) { echo(name + " = " + value); } template<typename T, typename F> static void trace(const std::string& name, const T& value, const F& formatter) { trace(name, formatter(value)); } template<typename T> static void traceIterable(const std::string& name, const T& value) { unsigned long long counter = 0; for (auto& elem : value) { stream() << name << "[" << std::to_string(counter++) << "] = "; echo(elem); } } static void debug(size_t line, const std::string& filename, const std::string& fn) { debugBuffer = std::make_tuple(line, filename, fn); static bool ready = false; if (!ready) { for (auto& pair : debugLabels) { std::signal(pair.first, printer); } ready = true; } } static void redirect(StreamType& stream) { static auto& streamContainer = StreamContainer::instance(); streamContainer.redirector = defaultRedirector; streamContainer.stream = stream; } static void redirect(const Redirector& redirector) { StreamContainer::instance().redirector = redirector; } }; template<> struct DebugContainer<false> { template<typename... Args> static void echo(Args&&...) {} template<typename... Args> static void echoIndented(Args&&...) {} template<typename... Args> static void trace(Args&&...) {} template<typename T> static void traceIterable(const std::string&, const T&) {} static void debug(size_t, const std::string&, const std::string&) {} template<typename T> static void redirect(const T&) {} }; } template<typename... Args> inline void echo(Args&&... args) { detail::DebugContainer<>::echo(std::forward<Args>(args)...); } template<typename... Args> inline void echoIndented(size_t numTabs, Args&&... args) { detail::DebugContainer<>::echoIndented(numTabs, std::forward<Args>(args)...); } template<typename... Args> inline void trace(Args&&... args) { detail::DebugContainer<>::trace(std::forward<Args>(args)...); } template<typename T> inline void traceIterable(const std::string& name, const T& value) { detail::DebugContainer<>::traceIterable(name, value); } inline void debug(size_t line, const std::string& filename, const std::string& fn) { detail::DebugContainer<>::debug(line, filename, fn); } template<typename T> inline void redirect(T& stream) { detail::DebugContainer<>::redirect(stream); } template<typename T> inline void redirect(const T& stream) { detail::DebugContainer<>::redirect(stream); } } #define FIRST_NAME(v, ...) (#v) #define ECHO(...) dbg::echo(__VA_ARGS__) #define ECHOI(numTabs,...) dbg::echoIndented((numTabs), __VA_ARGS__) #define TRACE(...) dbg::trace(FIRST_NAME(__VA_ARGS__), __VA_ARGS__) #define TRACE_L(x,...) dbg::trace((x), __VA_ARGS__) #define TRACE_IT(x) dbg::traceIterable((#x), (x)) #define TRACE_ITL(x) dbg::traceIterable((l), (x)) #define BLANK ECHO(""); #define DEBUG dbg::debug(__LINE__, __FILE__, FUNCTION_NAME); #define DEBUG_REDIRECT(stream) dbg::redirect(stream) #if DEBUG_ENABLED == 1 #define DEBUG_EXEC(...) __VA_ARGS__ #else #define DEBUG_EXEC(...) ; #endif #else #define ECHO(...) {int debug_usage;} #define ECHOI(numTabs,...) {int debug_usage;} #define TRACE(...) {int debug_usage;} #define TRACE_L(x,...) {int debug_usage;} #define TRACE_IT(x) {int debug_usage;} #define TRACE_ITL(x) {int debug_usage;} #define BLANK {int debug_usage;} #define DEBUG {int debug_usage;} #define DEBUG_EXEC(...) {int debug_usage;} #endif #endif <commit_msg>Improved the organization of debug.hpp<commit_after>/* created by Ghabriel Nunes <ghabriel.nunes@gmail.com> [2017] */ #ifndef UTILS_DEBUG_HPP #define UTILS_DEBUG_HPP #include <csignal> #include <functional> #include <iostream> #include <sstream> #include <tuple> #include <unordered_map> #include <utility> #ifndef ALLOW_DEBUG_USAGE #define ALLOW_DEBUG_USAGE 1 #endif #ifndef DEBUG_ENABLED #define DEBUG_ENABLED 1 #endif #ifndef FUNCTION_NAME #define FUNCTION_NAME __func__ #endif #if ALLOW_DEBUG_USAGE == 0 #define FN_SUFFIX __attribute__ ((deprecated("debug usage"))) #else #define FN_SUFFIX #endif namespace dbg { template<typename... Args> void echo(Args&&...) FN_SUFFIX; template<typename... Args> inline void echoIndented(size_t numTabs, Args&&... args) FN_SUFFIX; template<typename... Args> inline void trace(Args&&... args) FN_SUFFIX; template<typename T> inline void traceIterable(const std::string& name, const T& value) FN_SUFFIX; inline void debug(size_t line, const std::string& filename, const std::string& fn) FN_SUFFIX; template<typename T> inline void redirect(T& stream) FN_SUFFIX; template<typename T> inline void redirect(const T& stream) FN_SUFFIX; namespace detail { std::tuple<size_t, std::string, std::string> debugBuffer; const std::unordered_map<int, std::string> debugLabels = { {SIGABRT, "Aborted"}, {SIGFPE, "Division by zero"}, {SIGILL, "SIGILL"}, {SIGINT, "Interruption"}, {SIGSEGV, "Segmentation fault"}, {SIGTERM, "SIGTERM"} }; inline void printer(int type) { #if ALLOW_DEBUG_USAGE == 1 auto& line = std::get<0>(debugBuffer); auto& filename = std::get<1>(debugBuffer); auto& functionName = std::get<2>(debugBuffer); std::stringstream ss; ss << debugLabels.at(type) << ".\n Location: " << filename << ":" << line << "\n Function: " << functionName; echo(ss.str()); std::signal(type, SIG_DFL); std::raise(type); #endif } using Redirector = std::function<void(const std::string&)>; using StreamType = decltype(std::cout); struct StreamContainer { static StreamContainer& instance() { static StreamContainer inst; return inst; } StreamContainer& operator<<(const std::string& message) { redirector(message); return *this; } Redirector redirector = [](const std::string& message) { StreamContainer::instance().stream.get() << message; }; std::reference_wrapper<StreamType> stream = std::cout; private: StreamContainer() = default; }; const auto defaultRedirector = StreamContainer::instance().redirector; inline StreamContainer& stream() { return StreamContainer::instance(); } template<bool = DEBUG_ENABLED, bool = ALLOW_DEBUG_USAGE> struct DebugContainer { template<typename... Args> static void echo(Args&&...) {} template<typename... Args> static void echoIndented(Args&&...) {} template<typename... Args> static void trace(Args&&...) {} template<typename T> static void traceIterable(const std::string&, const T&) {} static void debug(size_t, const std::string&, const std::string&) {} template<typename T> static void redirect(const T&) {} }; template<> struct DebugContainer<true, true> { static void echo() {} template<typename T, typename... Args> static void echo(const T& value, Args&&... args) { std::stringstream ss; ss << value << '\n'; stream() << ss.str(); echo(std::forward<Args>(args)...); } template<typename... Args> static void echo(const std::string& value, Args&&... args) { stream() << (value + '\n'); echo(std::forward<Args>(args)...); } static void echoIndented(size_t) {} template<typename T, typename... Args> static void echoIndented(size_t numTabs, const T& value, Args&&... args) { std::stringstream ss; for (size_t i = 0; i < numTabs; i++) { ss << "\t"; } ss << value; echo(ss.str()); echoIndented(numTabs, std::forward<Args>(args)...); } template<typename T> static void trace(const std::string& name, const T& value) { std::stringstream ss; ss << name << " = " << value; echo(ss.str()); } static void trace(const std::string& name, const std::string& value) { echo(name + " = " + value); } template<typename T, typename F> static void trace(const std::string& name, const T& value, const F& formatter) { trace(name, formatter(value)); } template<typename T> static void traceIterable(const std::string& name, const T& value) { unsigned long long counter = 0; for (auto& elem : value) { stream() << name << "[" << std::to_string(counter++) << "] = "; echo(elem); } } static void debug(size_t line, const std::string& filename, const std::string& fn) { debugBuffer = std::make_tuple(line, filename, fn); static bool ready = false; if (!ready) { for (auto& pair : debugLabels) { std::signal(pair.first, printer); } ready = true; } } static void redirect(StreamType& stream) { static auto& streamContainer = StreamContainer::instance(); streamContainer.redirector = defaultRedirector; streamContainer.stream = stream; } static void redirect(const Redirector& redirector) { StreamContainer::instance().redirector = redirector; } }; } template<typename... Args> inline void echo(Args&&... args) { detail::DebugContainer<>::echo(std::forward<Args>(args)...); } template<typename... Args> inline void echoIndented(size_t numTabs, Args&&... args) { detail::DebugContainer<>::echoIndented(numTabs, std::forward<Args>(args)...); } template<typename... Args> inline void trace(Args&&... args) { detail::DebugContainer<>::trace(std::forward<Args>(args)...); } template<typename T> inline void traceIterable(const std::string& name, const T& value) { detail::DebugContainer<>::traceIterable(name, value); } inline void debug(size_t line, const std::string& filename, const std::string& fn) { detail::DebugContainer<>::debug(line, filename, fn); } template<typename T> inline void redirect(T& stream) { detail::DebugContainer<>::redirect(stream); } template<typename T> inline void redirect(const T& stream) { detail::DebugContainer<>::redirect(stream); } } #define FIRST_NAME(v, ...) (#v) #define ECHO(...) dbg::echo(__VA_ARGS__) #define ECHOI(numTabs,...) dbg::echoIndented((numTabs), __VA_ARGS__) #define TRACE(...) dbg::trace(FIRST_NAME(__VA_ARGS__), __VA_ARGS__) #define TRACE_L(x,...) dbg::trace((x), __VA_ARGS__) #define TRACE_IT(x) dbg::traceIterable((#x), (x)) #define TRACE_ITL(x) dbg::traceIterable((l), (x)) #define BLANK ECHO(""); #define DEBUG dbg::debug(__LINE__, __FILE__, FUNCTION_NAME); #define DEBUG_REDIRECT(stream) dbg::redirect(stream) #if DEBUG_ENABLED == 1 #define DEBUG_EXEC(...) __VA_ARGS__ #else #define DEBUG_EXEC(...) ; #endif #endif <|endoftext|>
<commit_before>#ifndef FRAME_HPP #define FRAME_HPP #include <stdint.h> /*! One L2 Frame. * This datastructure represents one ethernet frame. */ struct frame { uint8_t* buf_ptr; //!< pointer to the buffer which holds the frame (must be at least MTU+14 sized) uint16_t len; //!< length of the L2-PDU uint16_t iface; //!< interface responsible for this frame }; #endif /* FRAME_HPP */ <commit_msg>add flags + special IFACE numbers to frame<commit_after>#ifndef FRAME_HPP #define FRAME_HPP #include <stdint.h> /*! One L2 Frame. * This datastructure represents one ethernet frame. */ struct frame { uint8_t* buf_ptr; //!< pointer to the buffer which holds the frame (must be at least MTU+14 sized) uint16_t len; //!< length of the L2-PDU uint16_t iface; //!< interface responsible for this frame #define IFACE_HOST std::numeric_limits<uint16_t>::max() -1; #define IFACE_DISCARD std::numeric_limits<uint16_t>::max() -2; #define IFACE_ARP std::numeric_limits<uint16_t>::max() -3; uint16_t vlan; //!< VLAN tag (unused as of now) }; #endif /* FRAME_HPP */ <|endoftext|>
<commit_before>#pragma once #include "common.hpp" #include "debug.hpp" #include <cassert> #include <climits> #include <omp.h> template<typename SizeType, typename WordType> void copy_bits(WordType* const dst, WordType const* const src, SizeType& dst_off_ref, SizeType& src_off_ref, SizeType const block_size, SizeType const words_size, SizeType const full_words_size ) { if (block_size == 0) return; WordType constexpr BITS = (sizeof(WordType) * CHAR_BIT); WordType constexpr MOD_MASK = BITS - 1; WordType constexpr SHIFT = log2(MOD_MASK); SizeType dst_off = dst_off_ref; SizeType src_off = src_off_ref; auto const dst_off_end = dst_off + block_size; // NB: Check if source and target block are aligned the same way // This is needed because the non-aligned code path would // trigger undefined behavior in the aligned case. if ((dst_off & MOD_MASK) == (src_off & MOD_MASK)) { // Copy unaligned leading bits { auto& word = dst[dst_off >> SHIFT]; while ((dst_off & MOD_MASK) != 0 && dst_off != dst_off_end) { bool const bit = bit_at<WordType>(src, src_off++); word |= (WordType(bit) << (MOD_MASK - (dst_off++ & MOD_MASK))); } } // Copy the the bulk in-between word-wise { auto const words = (dst_off_end - dst_off) >> SHIFT; WordType* ds = dst + (dst_off >> SHIFT); WordType const* sr = src + (src_off >> SHIFT); WordType const* const ds_end = ds + words; while (ds != ds_end) { *ds++ = *sr++; } dst_off += words * BITS; src_off += words * BITS; } // Copy unaligned trailing bits { auto& word = dst[dst_off >> SHIFT]; while (dst_off != dst_off_end) { bool const bit = bit_at<WordType>(src, src_off++); word |= (WordType(bit) << (MOD_MASK - (dst_off++ & MOD_MASK))); } } } else { // Copy unaligned leading bits { auto& word = dst[dst_off >> SHIFT]; while ((dst_off & MOD_MASK) != 0 && dst_off != dst_off_end) { bool const bit = bit_at<WordType>(src, src_off++); word |= (WordType(bit) << (MOD_MASK - (dst_off++ & MOD_MASK))); } } // Copy the the bulk in-between word-wise { auto const words = (dst_off_end - dst_off) >> SHIFT; WordType const src_shift_a = src_off & MOD_MASK; WordType const src_shift_b = BITS - src_shift_a; WordType* ds = dst + (dst_off >> SHIFT); WordType const* sr = src + (src_off >> SHIFT); WordType const* const ds_end = ds + words; std::cout << "[start]\n"; auto chk = [ full_words_size, src_shift_a, src_shift_b, dst_off, src_off ](auto ds, auto dst, auto sr, auto src) { std::cout << "dst ptr: " << (ds - dst) << ", src ptr: " << (sr - src) << ", len: " << full_words_size << ", shifts: " << size_t(src_shift_a) << ", " << size_t(src_shift_b) << "\n"; std::cout << "sr: " << size_t(sr) << "\n"; std::cout << "src: " << size_t(src) << "\n"; std::cout << "dst_off: " << dst_off << "\n"; std::cout << "src_off: " << src_off << "\n"; assert((ds - dst) < full_words_size); assert((sr - src) < full_words_size); assert(((sr - src) + 1) < full_words_size); std::cout << "---\n"; }; while (ds != ds_end) { chk(ds, dst, sr, src); WordType const vala = *sr; std::cout << "sp pre: " << size_t(sr) << "\n"; sr++; std::cout << "sp post: " << size_t(sr) << "\n"; WordType const valb = *sr; *ds++ = (vala << src_shift_a) | (valb >> src_shift_b); } std::cout << "[end]\n"; dst_off += words * BITS; src_off += words * BITS; } // Copy unaligned trailing bits { auto& word = dst[dst_off >> SHIFT]; while (dst_off != dst_off_end) { bool const bit = bit_at<WordType>(src, src_off++); word |= (WordType(bit) << (MOD_MASK - (dst_off++ & MOD_MASK))); } } } dst_off_ref += block_size; src_off_ref += block_size; } template<typename SizeType, typename Rho> inline auto merge_bvs(SizeType size, SizeType levels, SizeType shards, const std::vector<std::vector<std::vector<SizeType>>>& glob_hist, const std::vector<Bvs<SizeType>>& glob_bv, const Rho& rho) -> Bvs<SizeType> { assert(shards == glob_bv.size()); assert(shards == glob_hist.size()); auto offsets = std::vector<SizeType>(shards); auto local_offsets = std::vector<std::vector<std::vector<SizeType>>>( levels, std::vector<std::vector<SizeType>>( shards, std::vector<SizeType>(shards + 1))); auto word_offsets = std::vector<std::vector<SizeType>>( levels, std::vector<SizeType>(shards + 1)); auto block_seq_offsets = std::vector<std::vector<SizeType>>( levels, std::vector<SizeType>(shards + 1)); auto glob_cursors = std::vector<std::vector<std::vector<size_t>>>( shards, std::vector<std::vector<size_t>>( levels, std::vector<size_t>(shards) )); for (size_t rank = 1; rank < shards; rank++) { const size_t omp_rank = rank; const size_t omp_size = shards; const SizeType offset = (omp_rank * (word_size(size) / omp_size)) + std::min<SizeType>(omp_rank, word_size(size) % omp_size); offsets[rank - 1] = offset * 64ull; } offsets[shards - 1] = word_size(size) * 64ull; // TODO: fix for(size_t level = 0; level < levels; level++) { const size_t br_size = 1ull << level; size_t j = 0; size_t oi = 0; for(size_t i = 0; i < br_size * shards; i++) { const auto bit_i = i / shards; const auto shard = i % shards; const auto h = glob_hist[shard][level]; const auto block_size = h[rho(level, bit_i)]; j += block_size; local_offsets[level][shard][oi + 1] += block_size; if (j <= offsets[oi]) { // ... } else { size_t right = j - offsets[oi]; size_t left = block_size - right; j -= block_size; local_offsets[level][shard][oi + 1] -= block_size; j += left; local_offsets[level][shard][oi + 1] += left; // TODO: rename word_offset to something like // "offset in block" word_offsets[level][oi + 1] = left; block_seq_offsets[level][oi + 1] = i; if (oi + 2 < shards + 1) { for(size_t s = 0; s < shards; s++) { local_offsets[level][s][oi + 2] = local_offsets[level][s][oi + 1]; } } oi++; j += right; local_offsets[level][shard][oi + 1] += right; } } } auto r = Bvs<SizeType>(size, levels); auto& _bv = r.vec(); //#pragma omp parallel for(size_t omp_rank = 0; omp_rank < shards; omp_rank++) { //assert(size_t(omp_get_num_threads()) == shards); //const size_t omp_rank = omp_get_thread_num(); const size_t merge_shard = omp_rank; const auto target_right = std::min(offsets[merge_shard], size); const auto target_left = std::min((merge_shard > 0 ? offsets[merge_shard - 1] : 0), target_right); auto& cursors = glob_cursors[merge_shard]; for (size_t level = 0; level < levels; level++) { for(size_t read_shard = 0; read_shard < shards; read_shard++) { cursors[level][read_shard] = local_offsets[level][read_shard][merge_shard]; } } for (size_t level = 0; level < levels; level++) { auto seq_i = block_seq_offsets[level][merge_shard]; size_t j = target_left; size_t init_offset = word_offsets[level][merge_shard]; while (j < target_right) { const auto i = seq_i / shards; const auto shard = seq_i % shards; seq_i++; const auto& h = glob_hist[shard][level]; const auto& local_bv = glob_bv[shard].vec()[level]; auto const block_size = std::min( target_right - j, h[rho(level, i)] - init_offset ); init_offset = 0; // TODO: remove this by doing a initial pass auto& local_cursor = cursors[level][shard]; copy_bits( _bv[level], local_bv, j, local_cursor, block_size, word_size(target_right - target_left), word_size(size) ); } } } return r; } <commit_msg>debug more 8<commit_after>#pragma once #include "common.hpp" #include "debug.hpp" #include <cassert> #include <climits> #include <omp.h> template<typename SizeType, typename WordType> void copy_bits(WordType* const dst, WordType const* const src, SizeType& dst_off_ref, SizeType& src_off_ref, SizeType const block_size, SizeType const words_size, SizeType const full_words_size ) { if (block_size == 0) return; WordType constexpr BITS = (sizeof(WordType) * CHAR_BIT); WordType constexpr MOD_MASK = BITS - 1; WordType constexpr SHIFT = log2(MOD_MASK); SizeType dst_off = dst_off_ref; SizeType src_off = src_off_ref; auto const dst_off_end = dst_off + block_size; // NB: Check if source and target block are aligned the same way // This is needed because the non-aligned code path would // trigger undefined behavior in the aligned case. if ((dst_off & MOD_MASK) == (src_off & MOD_MASK)) { // Copy unaligned leading bits { auto& word = dst[dst_off >> SHIFT]; while ((dst_off & MOD_MASK) != 0 && dst_off != dst_off_end) { bool const bit = bit_at<WordType>(src, src_off++); word |= (WordType(bit) << (MOD_MASK - (dst_off++ & MOD_MASK))); } } // Copy the the bulk in-between word-wise { auto const words = (dst_off_end - dst_off) >> SHIFT; WordType* ds = dst + (dst_off >> SHIFT); WordType const* sr = src + (src_off >> SHIFT); WordType const* const ds_end = ds + words; while (ds != ds_end) { *ds++ = *sr++; } dst_off += words * BITS; src_off += words * BITS; } // Copy unaligned trailing bits { auto& word = dst[dst_off >> SHIFT]; while (dst_off != dst_off_end) { bool const bit = bit_at<WordType>(src, src_off++); word |= (WordType(bit) << (MOD_MASK - (dst_off++ & MOD_MASK))); } } } else { std::cout << "[start]\n"; // Copy unaligned leading bits { auto& word = dst[dst_off >> SHIFT]; std::cout << "src_off: " << src_off << "\n"; while ((dst_off & MOD_MASK) != 0 && dst_off != dst_off_end) { bool const bit = bit_at<WordType>(src, src_off++); word |= (WordType(bit) << (MOD_MASK - (dst_off++ & MOD_MASK))); std::cout << "src_off: " << src_off << "\n"; } } // Copy the the bulk in-between word-wise { auto const words = (dst_off_end - dst_off) >> SHIFT; WordType const src_shift_a = src_off & MOD_MASK; WordType const src_shift_b = BITS - src_shift_a; WordType* ds = dst + (dst_off >> SHIFT); WordType const* sr = src + (src_off >> SHIFT); WordType const* const ds_end = ds + words; auto chk = [ full_words_size, src_shift_a, src_shift_b, dst_off, src_off ](auto ds, auto dst, auto sr, auto src) { std::cout << "dst ptr: " << (ds - dst) << ", src ptr: " << (sr - src) << ", len: " << full_words_size << ", shifts: " << size_t(src_shift_a) << ", " << size_t(src_shift_b) << "\n"; std::cout << "sr: " << size_t(sr) << "\n"; std::cout << "src: " << size_t(src) << "\n"; std::cout << "dst_off: " << dst_off << "\n"; std::cout << "src_off: " << src_off << "\n"; assert((ds - dst) < full_words_size); assert((sr - src) < full_words_size); assert(((sr - src) + 1) < full_words_size); std::cout << "---\n"; }; while (ds != ds_end) { chk(ds, dst, sr, src); WordType const vala = *sr; std::cout << "sp pre: " << size_t(sr) << "\n"; sr++; std::cout << "sp post: " << size_t(sr) << "\n"; WordType const valb = *sr; *ds++ = (vala << src_shift_a) | (valb >> src_shift_b); } std::cout << "[end]\n"; dst_off += words * BITS; src_off += words * BITS; } // Copy unaligned trailing bits { auto& word = dst[dst_off >> SHIFT]; while (dst_off != dst_off_end) { bool const bit = bit_at<WordType>(src, src_off++); word |= (WordType(bit) << (MOD_MASK - (dst_off++ & MOD_MASK))); } } } dst_off_ref += block_size; src_off_ref += block_size; } template<typename SizeType, typename Rho> inline auto merge_bvs(SizeType size, SizeType levels, SizeType shards, const std::vector<std::vector<std::vector<SizeType>>>& glob_hist, const std::vector<Bvs<SizeType>>& glob_bv, const Rho& rho) -> Bvs<SizeType> { assert(shards == glob_bv.size()); assert(shards == glob_hist.size()); auto offsets = std::vector<SizeType>(shards); auto local_offsets = std::vector<std::vector<std::vector<SizeType>>>( levels, std::vector<std::vector<SizeType>>( shards, std::vector<SizeType>(shards + 1))); auto word_offsets = std::vector<std::vector<SizeType>>( levels, std::vector<SizeType>(shards + 1)); auto block_seq_offsets = std::vector<std::vector<SizeType>>( levels, std::vector<SizeType>(shards + 1)); auto glob_cursors = std::vector<std::vector<std::vector<size_t>>>( shards, std::vector<std::vector<size_t>>( levels, std::vector<size_t>(shards) )); for (size_t rank = 1; rank < shards; rank++) { const size_t omp_rank = rank; const size_t omp_size = shards; const SizeType offset = (omp_rank * (word_size(size) / omp_size)) + std::min<SizeType>(omp_rank, word_size(size) % omp_size); offsets[rank - 1] = offset * 64ull; } offsets[shards - 1] = word_size(size) * 64ull; // TODO: fix for(size_t level = 0; level < levels; level++) { const size_t br_size = 1ull << level; size_t j = 0; size_t oi = 0; for(size_t i = 0; i < br_size * shards; i++) { const auto bit_i = i / shards; const auto shard = i % shards; const auto h = glob_hist[shard][level]; const auto block_size = h[rho(level, bit_i)]; j += block_size; local_offsets[level][shard][oi + 1] += block_size; if (j <= offsets[oi]) { // ... } else { size_t right = j - offsets[oi]; size_t left = block_size - right; j -= block_size; local_offsets[level][shard][oi + 1] -= block_size; j += left; local_offsets[level][shard][oi + 1] += left; // TODO: rename word_offset to something like // "offset in block" word_offsets[level][oi + 1] = left; block_seq_offsets[level][oi + 1] = i; if (oi + 2 < shards + 1) { for(size_t s = 0; s < shards; s++) { local_offsets[level][s][oi + 2] = local_offsets[level][s][oi + 1]; } } oi++; j += right; local_offsets[level][shard][oi + 1] += right; } } } auto r = Bvs<SizeType>(size, levels); auto& _bv = r.vec(); //#pragma omp parallel for(size_t omp_rank = 0; omp_rank < shards; omp_rank++) { //assert(size_t(omp_get_num_threads()) == shards); //const size_t omp_rank = omp_get_thread_num(); const size_t merge_shard = omp_rank; const auto target_right = std::min(offsets[merge_shard], size); const auto target_left = std::min((merge_shard > 0 ? offsets[merge_shard - 1] : 0), target_right); auto& cursors = glob_cursors[merge_shard]; for (size_t level = 0; level < levels; level++) { for(size_t read_shard = 0; read_shard < shards; read_shard++) { cursors[level][read_shard] = local_offsets[level][read_shard][merge_shard]; } } for (size_t level = 0; level < levels; level++) { auto seq_i = block_seq_offsets[level][merge_shard]; size_t j = target_left; size_t init_offset = word_offsets[level][merge_shard]; while (j < target_right) { const auto i = seq_i / shards; const auto shard = seq_i % shards; seq_i++; const auto& h = glob_hist[shard][level]; const auto& local_bv = glob_bv[shard].vec()[level]; auto const block_size = std::min( target_right - j, h[rho(level, i)] - init_offset ); init_offset = 0; // TODO: remove this by doing a initial pass auto& local_cursor = cursors[level][shard]; copy_bits( _bv[level], local_bv, j, local_cursor, block_size, word_size(target_right - target_left), word_size(size) ); } } } return r; } <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_SCAL_PROB_NEG_BINOMIAL_2_LPMF_HPP #define STAN_MATH_PRIM_SCAL_PROB_NEG_BINOMIAL_2_LPMF_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/scal/err/check_consistent_sizes.hpp> #include <stan/math/prim/scal/err/check_positive_finite.hpp> #include <stan/math/prim/scal/err/check_nonnegative.hpp> #include <stan/math/prim/scal/fun/size_zero.hpp> #include <stan/math/prim/scal/fun/multiply_log.hpp> #include <stan/math/prim/scal/fun/digamma.hpp> #include <stan/math/prim/scal/fun/lgamma.hpp> #include <stan/math/prim/scal/fun/binomial_coefficient_log.hpp> #include <stan/math/prim/scal/fun/value_of.hpp> #include <stan/math/prim/scal/prob/poisson_lpmf.hpp> #include <cmath> namespace stan { namespace math { namespace internal { // Exposing to let me us this in tests // The current tests fail when the cutoff is 1e8 and pass with 1e9, // setting 1e10 to be safe constexpr double neg_binomial_2_phi_cutoff = 1e10; } // namespace internal // NegBinomial(n|mu, phi) [mu >= 0; phi > 0; n >= 0] template <bool propto, typename T_n, typename T_location, typename T_precision> return_type_t<T_location, T_precision> neg_binomial_2_lpmf( const T_n& n, const T_location& mu, const T_precision& phi) { using T_partials_return = partials_return_t<T_n, T_location, T_precision>; static const char* function = "neg_binomial_2_lpmf"; if (size_zero(n, mu, phi)) { return 0.0; } T_partials_return logp(0.0); check_nonnegative(function, "Failures variable", n); check_positive_finite(function, "Location parameter", mu); check_positive_finite(function, "Precision parameter", phi); check_consistent_sizes(function, "Failures variable", n, "Location parameter", mu, "Precision parameter", phi); if (!include_summand<propto, T_location, T_precision>::value) { return 0.0; } using std::log; scalar_seq_view<T_n> n_vec(n); scalar_seq_view<T_location> mu_vec(mu); scalar_seq_view<T_precision> phi_vec(phi); size_t size = max_size(n, mu, phi); operands_and_partials<T_location, T_precision> ops_partials(mu, phi); size_t len_ep = max_size(mu, phi); size_t len_np = max_size(n, phi); VectorBuilder<true, T_partials_return, T_location> mu__(length(mu)); for (size_t i = 0, size = length(mu); i < size; ++i) { mu__[i] = value_of(mu_vec[i]); } VectorBuilder<true, T_partials_return, T_precision> phi__(length(phi)); for (size_t i = 0, size = length(phi); i < size; ++i) { phi__[i] = value_of(phi_vec[i]); } VectorBuilder<true, T_partials_return, T_precision> log_phi(length(phi)); for (size_t i = 0, size = length(phi); i < size; ++i) { log_phi[i] = log(phi__[i]); } VectorBuilder<true, T_partials_return, T_location, T_precision> log_mu_plus_phi(len_ep); for (size_t i = 0; i < len_ep; ++i) { log_mu_plus_phi[i] = log(mu__[i] + phi__[i]); } VectorBuilder<true, T_partials_return, T_n, T_precision> n_plus_phi(len_np); for (size_t i = 0; i < len_np; ++i) { n_plus_phi[i] = n_vec[i] + phi__[i]; } for (size_t i = 0; i < size; i++) { if (phi__[i] > internal::neg_binomial_2_phi_cutoff) { // Phi is large, deferring to Poisson. // Copying the code here as just calling // poisson_lpmf does not preserve propto logic correctly if (include_summand<propto>::value) { logp -= lgamma(n_vec[i] + 1.0); } if (include_summand<propto, T_location>::value) { logp += multiply_log(n_vec[i], mu__[i]) - mu__[i]; } // if (include_summand<propto, T_location, T_precision>::value) { // logp += (mu__[i] * (mu__[i] - 2 * n_vec[i]) + // n_vec[i] * (n_vec[i] - 1)) / ( 2 * phi__[i] ); // // logp += (mu__[i] * mu__[i] - n_vec[i] - // // 2 * mu__[i] * n_vec[i] + n_vec[i] * n_vec[i])/phi // } if (!is_constant_all<T_location>::value) { // This is the Taylor series of the full derivative for phi -> Inf // Obtained in Mathematica via // Series[n/mu - (n + phi)/(mu+phi),{phi,Infinity, 1}] ops_partials.edge1_.partials_[i] += n_vec[i] / mu__[i] + (mu__[i] - n_vec[i]) / phi__[i] - 1; } // The derivative wrt. phi = 0 + O(1/neg_binomial_2_phi_cutoff^2) // So ignoring here // Obtained in Mathematica via // Series[1 - (n + phi) / (mu + phi) + Log[phi] - Log[mu + phi] - // PolyGamma[phi] + PolyGamma[n + phi],{phi,Infinity, 1}] } else { if (include_summand<propto, T_precision>::value) { logp += binomial_coefficient_log(n_plus_phi[i] - 1, n_vec[i]); } if (include_summand<propto, T_location, T_precision>::value) { logp += phi__[i] * (log(phi__[i]) - log(mu__[i] + phi__[i])) - (n_vec[i]) * log_mu_plus_phi[i]; } if (include_summand<propto, T_location>::value) { logp += multiply_log(n_vec[i], mu__[i]); } if (!is_constant_all<T_location>::value) { ops_partials.edge1_.partials_[i] += n_vec[i] / mu__[i] - (n_vec[i] + phi__[i]) / (mu__[i] + phi__[i]); } if (!is_constant_all<T_precision>::value) { ops_partials.edge2_.partials_[i] += 1.0 - n_plus_phi[i] / (mu__[i] + phi__[i]) + log_phi[i] - log_mu_plus_phi[i] - digamma(phi__[i]) + digamma(n_plus_phi[i]); } } } return ops_partials.build(logp); } template <typename T_n, typename T_location, typename T_precision> inline return_type_t<T_location, T_precision> neg_binomial_2_lpmf( const T_n& n, const T_location& mu, const T_precision& phi) { return neg_binomial_2_lpmf<false>(n, mu, phi); } } // namespace math } // namespace stan #endif <commit_msg>Use precomputed values<commit_after>#ifndef STAN_MATH_PRIM_SCAL_PROB_NEG_BINOMIAL_2_LPMF_HPP #define STAN_MATH_PRIM_SCAL_PROB_NEG_BINOMIAL_2_LPMF_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/scal/err/check_consistent_sizes.hpp> #include <stan/math/prim/scal/err/check_positive_finite.hpp> #include <stan/math/prim/scal/err/check_nonnegative.hpp> #include <stan/math/prim/scal/fun/size_zero.hpp> #include <stan/math/prim/scal/fun/multiply_log.hpp> #include <stan/math/prim/scal/fun/digamma.hpp> #include <stan/math/prim/scal/fun/lgamma.hpp> #include <stan/math/prim/scal/fun/binomial_coefficient_log.hpp> #include <stan/math/prim/scal/fun/value_of.hpp> #include <stan/math/prim/scal/prob/poisson_lpmf.hpp> #include <cmath> namespace stan { namespace math { namespace internal { // Exposing to let me us this in tests // The current tests fail when the cutoff is 1e8 and pass with 1e9, // setting 1e10 to be safe constexpr double neg_binomial_2_phi_cutoff = 1e10; } // namespace internal // NegBinomial(n|mu, phi) [mu >= 0; phi > 0; n >= 0] template <bool propto, typename T_n, typename T_location, typename T_precision> return_type_t<T_location, T_precision> neg_binomial_2_lpmf( const T_n& n, const T_location& mu, const T_precision& phi) { using T_partials_return = partials_return_t<T_n, T_location, T_precision>; static const char* function = "neg_binomial_2_lpmf"; if (size_zero(n, mu, phi)) { return 0.0; } T_partials_return logp(0.0); check_nonnegative(function, "Failures variable", n); check_positive_finite(function, "Location parameter", mu); check_positive_finite(function, "Precision parameter", phi); check_consistent_sizes(function, "Failures variable", n, "Location parameter", mu, "Precision parameter", phi); if (!include_summand<propto, T_location, T_precision>::value) { return 0.0; } using std::log; scalar_seq_view<T_n> n_vec(n); scalar_seq_view<T_location> mu_vec(mu); scalar_seq_view<T_precision> phi_vec(phi); size_t size = max_size(n, mu, phi); operands_and_partials<T_location, T_precision> ops_partials(mu, phi); size_t len_ep = max_size(mu, phi); size_t len_np = max_size(n, phi); VectorBuilder<true, T_partials_return, T_location> mu__(length(mu)); for (size_t i = 0, size = length(mu); i < size; ++i) { mu__[i] = value_of(mu_vec[i]); } VectorBuilder<true, T_partials_return, T_precision> phi__(length(phi)); for (size_t i = 0, size = length(phi); i < size; ++i) { phi__[i] = value_of(phi_vec[i]); } VectorBuilder<true, T_partials_return, T_precision> log_phi(length(phi)); for (size_t i = 0, size = length(phi); i < size; ++i) { log_phi[i] = log(phi__[i]); } VectorBuilder<true, T_partials_return, T_location, T_precision> log_mu_plus_phi(len_ep); for (size_t i = 0; i < len_ep; ++i) { log_mu_plus_phi[i] = log(mu__[i] + phi__[i]); } VectorBuilder<true, T_partials_return, T_n, T_precision> n_plus_phi(len_np); for (size_t i = 0; i < len_np; ++i) { n_plus_phi[i] = n_vec[i] + phi__[i]; } for (size_t i = 0; i < size; i++) { if (phi__[i] > internal::neg_binomial_2_phi_cutoff) { // Phi is large, deferring to Poisson. // Copying the code here as just calling // poisson_lpmf does not preserve propto logic correctly if (include_summand<propto>::value) { logp -= lgamma(n_vec[i] + 1.0); } if (include_summand<propto, T_location>::value) { logp += multiply_log(n_vec[i], mu__[i]) - mu__[i]; } // if (include_summand<propto, T_location, T_precision>::value) { // logp += (mu__[i] * (mu__[i] - 2 * n_vec[i]) + // n_vec[i] * (n_vec[i] - 1)) / ( 2 * phi__[i] ); // // logp += (mu__[i] * mu__[i] - n_vec[i] - // // 2 * mu__[i] * n_vec[i] + n_vec[i] * n_vec[i])/phi // } if (!is_constant_all<T_location>::value) { // This is the Taylor series of the full derivative for phi -> Inf // Obtained in Mathematica via // Series[n/mu - (n + phi)/(mu+phi),{phi,Infinity, 1}] ops_partials.edge1_.partials_[i] += n_vec[i] / mu__[i] + (mu__[i] - n_vec[i]) / phi__[i] - 1; } // The derivative wrt. phi = 0 + O(1/neg_binomial_2_phi_cutoff^2) // So ignoring here // Obtained in Mathematica via // Series[1 - (n + phi) / (mu + phi) + Log[phi] - Log[mu + phi] - // PolyGamma[phi] + PolyGamma[n + phi],{phi,Infinity, 1}] } else { if (include_summand<propto, T_precision>::value) { logp += binomial_coefficient_log(n_plus_phi[i] - 1, n_vec[i]); } if (include_summand<propto, T_location, T_precision>::value) { logp += phi__[i] * (log_phi[i] - log_mu_plus_phi[i]) - (n_vec[i]) * log_mu_plus_phi[i]; } if (include_summand<propto, T_location>::value) { logp += multiply_log(n_vec[i], mu__[i]); } if (!is_constant_all<T_location>::value) { ops_partials.edge1_.partials_[i] += n_vec[i] / mu__[i] - (n_vec[i] + phi__[i]) / (mu__[i] + phi__[i]); } if (!is_constant_all<T_precision>::value) { ops_partials.edge2_.partials_[i] += 1.0 - n_plus_phi[i] / (mu__[i] + phi__[i]) + log_phi[i] - log_mu_plus_phi[i] - digamma(phi__[i]) + digamma(n_plus_phi[i]); } } } return ops_partials.build(logp); } template <typename T_n, typename T_location, typename T_precision> inline return_type_t<T_location, T_precision> neg_binomial_2_lpmf( const T_n& n, const T_location& mu, const T_precision& phi) { return neg_binomial_2_lpmf<false>(n, mu, phi); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>/// /// @file pmath.hpp /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef PMATH_HPP #define PMATH_HPP #include <int128.hpp> #include <stdint.h> #include <algorithm> #include <limits> #include <cassert> #include <cmath> #include <vector> namespace primecount { inline int64_t isquare(int32_t x) { return x * (int64_t) x; } template <typename A, typename B> inline A ceil_div(A a, B b) { assert(b > 0); return (A) ((a + b - 1) / b); } template <typename T> inline T number_of_bits(T) { return (T) (sizeof(T) * 8); } /// @brief Check if an integer is a power of 2. /// @see Book "Hacker's Delight". /// template <typename T> inline bool is_power_of_2(T x) { return (x != 0 && (x & (x - 1)) == 0); } /// @brief Round up to the next power of 2. /// @see Book "Hacker's Delight". /// template <typename T> inline T next_power_of_2(T x) { if (x == 0) return 1; x--; for (T i = 1; i < number_of_bits(x); i += i) x |= (x >> i); return ++x; } template <typename T> inline int ilog(T x) { return (int) std::log((double) x); } /// Raise to power template <typename T> inline T ipow(T x, int n) { T r = 1; for (int i = 0; i < n; i++) r *= x; return r; } /// Integer suare root template <typename T> inline T isqrt(T x) { T r = (T) std::sqrt((double) x); while (r * r > x) r--; while (x - r * r > r * 2) r++; return r; } /// Check if ipow(x, n) <= limit template <typename T> inline bool ipow_less_equal(T x, int n, T limit) { if (limit <= 0) return false; for (T r = 1; n > 0; n--, r *= x) if (r > limit / x) return false; return true; } /// Integer nth root template <int N, typename T> inline T iroot(T x) { T r = (T) std::pow((double) x, 1.0 / N); while (ipow(r, N) > x) r--; while (ipow_less_equal(r + 1, N, x)) r++; return r; } /// Calculate the number of primes below x using binary search. /// @pre primes[1] = 2, primes[3] = 3, ... /// @pre x <= primes.back() /// template <typename T1, typename T2> inline T2 pi_bsearch(const std::vector<T1>& primes, T2 x) { // primecount uses 1-indexing assert(primes[0] == 0); return (T2) (std::upper_bound(primes.begin() + 1, primes.end(), x) - (primes.begin() + 1)); } /// Calculate the number of primes below x using binary search. /// @pre primes[1] = 2, primes[3] = 3, ... /// @pre x <= primes.back() /// template <typename T1, typename T2, typename T3> inline T3 pi_bsearch(const std::vector<T1>& primes, T2 len, T3 x) { // primecount uses 1-indexing assert(primes[0] == 0); return (T3) (std::upper_bound(primes.begin() + 1, primes.begin() + len + 1, x) - (primes.begin() + 1)); } template <typename T1, typename T2, typename T3> inline T2 in_between(T1 min, T2 x, T3 max) { if (x < min) return (T2) min; if (x > max) return (T2) max; return x; } } // namespace #endif <commit_msg>Improved error correction for isqrt(x)<commit_after>/// /// @file pmath.hpp /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef PMATH_HPP #define PMATH_HPP #include <int128.hpp> #include <stdint.h> #include <algorithm> #include <limits> #include <cassert> #include <cmath> #include <vector> namespace primecount { inline int64_t isquare(int32_t x) { return x * (int64_t) x; } template <typename A, typename B> inline A ceil_div(A a, B b) { assert(b > 0); return (A) ((a + b - 1) / b); } template <typename T> inline T number_of_bits(T) { return (T) (sizeof(T) * 8); } /// @brief Check if an integer is a power of 2. /// @see Book "Hacker's Delight". /// template <typename T> inline bool is_power_of_2(T x) { return (x != 0 && (x & (x - 1)) == 0); } /// @brief Round up to the next power of 2. /// @see Book "Hacker's Delight". /// template <typename T> inline T next_power_of_2(T x) { if (x == 0) return 1; x--; for (T i = 1; i < number_of_bits(x); i += i) x |= (x >> i); return ++x; } template <typename T> inline int ilog(T x) { return (int) std::log((double) x); } /// Raise to power template <typename T> inline T ipow(T x, int n) { T r = 1; for (int i = 0; i < n; i++) r *= x; return r; } #if __cplusplus >= 201103L #define MID ((lo + hi + 1) / 2) template <typename T> constexpr T sqrt_helper(T x, T lo, T hi) { return lo == hi ? lo : ((x / MID < MID) ? sqrt_helper<T>(x, lo, MID - 1) : sqrt_helper<T>(x, MID, hi)); } #undef MID /// C++11 compile time square root template <typename T> constexpr T ct_sqrt(T x) { return sqrt_helper<T>(x, 0, (x < 9) ? x : x - 1); } #endif /// Integer square root template <typename T> inline T isqrt(T x) { T r = (T) std::sqrt((double) x); #if __cplusplus >= 201103L r = std::min(r , ct_sqrt(prt::numeric_limits<T>::max())); #endif while (r * r > x) r--; while (x - r * r > r * 2) r++; return r; } /// Check if ipow(x, n) <= limit template <typename T> inline bool ipow_less_equal(T x, int n, T limit) { if (limit <= 0) return false; for (T r = 1; n > 0; n--, r *= x) if (r > limit / x) return false; return true; } /// Integer nth root template <int N, typename T> inline T iroot(T x) { T r = (T) std::pow((double) x, 1.0 / N); while (ipow(r, N) > x) r--; while (ipow_less_equal(r + 1, N, x)) r++; return r; } /// Calculate the number of primes below x using binary search. /// @pre primes[1] = 2, primes[3] = 3, ... /// @pre x <= primes.back() /// template <typename T1, typename T2> inline T2 pi_bsearch(const std::vector<T1>& primes, T2 x) { // primecount uses 1-indexing assert(primes[0] == 0); return (T2) (std::upper_bound(primes.begin() + 1, primes.end(), x) - (primes.begin() + 1)); } /// Calculate the number of primes below x using binary search. /// @pre primes[1] = 2, primes[3] = 3, ... /// @pre x <= primes.back() /// template <typename T1, typename T2, typename T3> inline T3 pi_bsearch(const std::vector<T1>& primes, T2 len, T3 x) { // primecount uses 1-indexing assert(primes[0] == 0); return (T3) (std::upper_bound(primes.begin() + 1, primes.begin() + len + 1, x) - (primes.begin() + 1)); } template <typename T1, typename T2, typename T3> inline T2 in_between(T1 min, T2 x, T3 max) { if (x < min) return (T2) min; if (x > max) return (T2) max; return x; } } // namespace #endif <|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) <2016> <Stephan Gatzka> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <stdbool.h> #include "authenticate.h" extern "C" { bool credentials_ok(const char *user, const char *passwd) { (void)user; (void)passwd; return true; } } <commit_msg>Correct function prototype.<commit_after>/* * The MIT License (MIT) * * Copyright (c) <2016> <Stephan Gatzka> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <stdbool.h> #include "authenticate.h" extern "C" { bool credentials_ok(const char *user, char *passwd) { (void)user; (void)passwd; return true; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Mikhail Baranov * Copyright (c) 2015 Victor Gaydov * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <CppUTest/CommandLineArguments.h> #include <CppUTest/CommandLineTestRunner.h> #include "roc_core/log.h" int main(int argc, const char** argv) { CommandLineArguments args(argc, argv); if (args.parse(NULL) && args.isVerbose()) { roc::core::set_log_level(roc::LogDebug); } MemoryLeakWarningPlugin::turnOffNewDeleteOverloads(); return CommandLineTestRunner::RunAllTests(argc, argv); } <commit_msg>Fix log level in test_main<commit_after>/* * Copyright (c) 2015 Mikhail Baranov * Copyright (c) 2015 Victor Gaydov * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <CppUTest/CommandLineArguments.h> #include <CppUTest/CommandLineTestRunner.h> #include "roc_core/log.h" int main(int argc, const char** argv) { CommandLineArguments args(argc, argv); if (args.parse(NULL) && args.isVerbose()) { roc::core::set_log_level(roc::LogDebug); } else { roc::core::set_log_level(roc::LogNone); } MemoryLeakWarningPlugin::turnOffNewDeleteOverloads(); return CommandLineTestRunner::RunAllTests(argc, argv); } <|endoftext|>
<commit_before>void testJetFinderHits(Int_t evNumber1=0, Int_t evNumber2=0) { //*-- Author: Andreas Morsch (CERN) // Dynamically link some shared libs if (gClassTable->GetID("AliRun") < 0) { gROOT->LoadMacro("../macros/loadlibs.C"); loadlibs(); } // Connect the Root Galice file containing Geometry, Kine and Hits TFile *file = (TFile*)gROOT->GetListOfFiles()->FindObject("galice.root"); if (!file) { printf("\n Creating galice.root \n"); file = new TFile("galice.root", "update"); } else { printf("\n galice.root found in file list"); } // Get AliRun object from file or create it if not on file if (!gAlice) { gAlice = (AliRun*)(file->Get("gAlice")); if (gAlice) printf("AliRun object found on file\n"); if (!gAlice) { printf("\n create new gAlice object"); gAlice = new AliRun("gAlice","Alice test program"); } } AliEMCALJetFinder* jetFinder = new AliEMCALJetFinder("UA1 Jet Finder", "Test"); jetFinder->SetConeRadius(0.7); jetFinder->SetEtSeed(3.); jetFinder->SetMinJetEt(10.); jetFinder->SetMinCellEt(1.); // // Loop over events // // TCanvas *c1 = new TCanvas("c1","Canvas 1",400,10,600,700); // c1->Divide(2,2); Int_t nhit=0; for (Int_t nev=0; nev<= evNumber2; nev++) { Int_t nparticles = gAlice->GetEvent(nev); if (nev < evNumber1) continue; if (nparticles <= 0) return; // ECAL information jetFinder->FillFromHits(); // TPC information jetFinder->FillFromTracks(1, 0); // ^ preserves info from hit jetFinder->Find(); printf("\n Test Jets: %d\n", jetFinder->Njets()); Int_t njet = jetFinder->Njets(); for (Int_t nj=0; nj<njet; nj++) { printf("\n Jet Energy %5d %8.2f \n", nj, jetFinder->JetEnergy(nj)); printf("\n Jet Phi %5d %8.2f %8.2f \n", nj, jetFinder->JetPhiL(nj), jetFinder->JetPhiW(nj)); printf("\n Jet Eta %5d %8.2f %8.2f \n", nj, jetFinder->JetEtaL(nj), jetFinder->JetEtaW(nj)); } // c1->cd(2); // (jetFinder->GetLego())->Draw(); } // event loop } <commit_msg>Discontinued. Use testJetFinder.C !<commit_after><|endoftext|>
<commit_before>#pragma once #include <algorithm> #include <cassert> namespace { template <typename T> void swapEndian (T* p) { uint8_t* q = reinterpret_cast<uint8_t*>(p); std::reverse(q, q + sizeof(T)); } } template <typename T> struct TypedFixedSlice { T* begin; T* end; TypedFixedSlice () : begin(nullptr), end(nullptr) {} TypedFixedSlice (T* begin, T* end) : begin(begin), end(end) { assert(this->begin); assert(this->end); } auto drop (size_t n) const; auto take (size_t n) const; size_t length () const { return static_cast<size_t>(this->end - this->begin) / sizeof(T); } template <typename Y = T> auto peek (size_t offset = 0) const { assert(offset + sizeof(Y) <= this->length()); return *(reinterpret_cast<Y*>(this->begin + offset)); } template <typename Y, bool swap = false> void put (Y value, size_t offset = 0) { assert(offset + sizeof(Y) <= this->length()); auto ptr = reinterpret_cast<Y*>(this->begin + offset); *ptr = value; if (swap) swapEndian(ptr); } auto& operator[] (const size_t i) { assert(i < this->length()); return this->begin[i]; } const auto operator[] (const size_t i) const { assert(i < this->length()); return this->begin[i]; } }; template <typename T> struct TypedSlice : public TypedFixedSlice<T> { TypedSlice () : TypedFixedSlice<T>() {} TypedSlice (T* begin, T* end) : TypedFixedSlice<T>(begin, end) {} void popFrontN (size_t n) { assert(n <= this->length()); this->begin += n; } void popFront () { this->popFrontN(1); } template <typename Y> auto read () { const auto value = this->template peek<Y>(); this->popFrontN(sizeof(T) / sizeof(Y)); return value; } template <typename Y, bool swap = false> void write (Y value) { this->template put<Y, swap>(value); this->popFrontN(sizeof(T) / sizeof(Y)); } }; template <typename T> auto TypedFixedSlice<T>::drop (size_t n) const { assert(n <= this->length()); return TypedSlice<T>(this->begin + n, this->end); } template <typename T> auto TypedFixedSlice<T>::take (size_t n) const { assert(n <= this->length()); return TypedSlice<T>(this->begin, this->begin + n); } template <size_t N, typename T> struct TypedStackSlice : TypedFixedSlice<T> { T data[N]; TypedStackSlice (size_t n) : TypedFixedSlice<T>(data, data + N) {} }; template <typename T> struct TypedHeapSlice : TypedFixedSlice<T> { TypedHeapSlice (size_t n) : TypedFixedSlice<T>() { this->begin = new T[n]; this->end = this->begin + n; } ~TypedHeapSlice () { delete[] this->begin; } }; typedef TypedHeapSlice<uint8_t> HeapSlice; template <size_t N> using StackSlice = TypedStackSlice<N, uint8_t>; typedef TypedSlice<uint8_t> Slice; <commit_msg>slice: more const and add copy<commit_after>#pragma once #include <algorithm> #include <cassert> namespace { template <typename T> void swapEndian (T* p) { uint8_t* q = reinterpret_cast<uint8_t*>(p); std::reverse(q, q + sizeof(T)); } } template <typename T> struct TypedFixedSlice { T* begin; T* end; TypedFixedSlice () : begin(nullptr), end(nullptr) {} TypedFixedSlice (T* begin, T* end) : begin(begin), end(end) { assert(this->begin); assert(this->end); } auto drop (size_t n) const; auto take (size_t n) const; size_t length () const { return static_cast<size_t>(this->end - this->begin) / sizeof(T); } template <typename Y = T> auto peek (const size_t offset = 0) const { assert(offset + sizeof(Y) <= this->length()); return *(reinterpret_cast<Y*>(this->begin + offset)); } template <typename Y, bool swap = false> void put (const Y value, size_t offset = 0) { assert(offset + sizeof(Y) <= this->length()); auto ptr = reinterpret_cast<Y*>(this->begin + offset); *ptr = value; if (swap) swapEndian(ptr); } auto& operator[] (const size_t i) { assert(i < this->length()); return this->begin[i]; } const auto operator[] (const size_t i) const { assert(i < this->length()); return this->begin[i]; } }; template <typename T> struct TypedSlice : public TypedFixedSlice<T> { TypedSlice () : TypedFixedSlice<T>() {} TypedSlice (T* begin, T* end) : TypedFixedSlice<T>(begin, end) {} void popFrontN (size_t n) { assert(n <= this->length()); this->begin += n; } void popFront () { this->popFrontN(1); } template <typename Y> auto read () { const auto value = this->template peek<Y>(); this->popFrontN(sizeof(T) / sizeof(Y)); return value; } template <typename Y, bool swap = false> void write (const Y value) { this->template put<Y, swap>(value); this->popFrontN(sizeof(T) / sizeof(Y)); } template <typename S> void copy (const S& other) { assert(other.length() >= this->length()); memcpy(other.begin, this->begin, other.length()); } }; template <typename T> auto TypedFixedSlice<T>::drop (const size_t n) const { assert(n <= this->length()); return TypedSlice<T>(this->begin + n, this->end); } template <typename T> auto TypedFixedSlice<T>::take (const size_t n) const { assert(n <= this->length()); return TypedSlice<T>(this->begin, this->begin + n); } template <size_t N, typename T> struct TypedStackSlice : TypedFixedSlice<T> { T data[N]; TypedStackSlice (const size_t n) : TypedFixedSlice<T>(data, data + N) {} }; template <typename T> struct TypedHeapSlice : TypedFixedSlice<T> { TypedHeapSlice (const size_t n) : TypedFixedSlice<T>() { this->begin = new T[n]; this->end = this->begin + n; } ~TypedHeapSlice () { delete[] this->begin; } }; typedef TypedHeapSlice<uint8_t> HeapSlice; template <size_t N> using StackSlice = TypedStackSlice<N, uint8_t>; typedef TypedSlice<uint8_t> Slice; <|endoftext|>
<commit_before>#ifndef STACK_HPP #define STACK_HPP #include <cstdlib> #include <iostream> #include <memory> using namespace std; template <typename T> class stack { public: stack(); size_t count() const; void push(T const &); T pop(); ~stack(); stack(const stack &b); stack & operator=(const stack &b); bool operator==(stack const & _s); private: T * array_; size_t array_size_; size_t count_; }; #include "stack.cpp" #endif <commit_msg>Update stack.hpp<commit_after>#ifndef STACK_HPP #define STACK_HPP #include <cstdlib> #include <iostream> #include <memory> using namespace std; template <typename T> class stack { public: stack(); size_t count() const; void push(T const &); T pop(); ~stack(); T top(); stack(const stack &b); stack & operator=(const stack &b); bool operator==(stack const & _s); private: T * array_; size_t array_size_; size_t count_; }; #include "stack.cpp" #endif <|endoftext|>
<commit_before>#ifndef KLMR_LISP_CPP_VALUE_HPP #define KLMR_LISP_CPP_VALUE_HPP #include <iosfwd> #include <string> #include <vector> #include <unordered_map> #include <boost/variant.hpp> #include <boost/range/sub_range.hpp> namespace klmr { namespace lisp { struct symbol { std::string repr; }; inline auto operator ==(symbol const& lhs, symbol const& rhs) -> bool { return lhs.repr == rhs.repr; } inline auto operator !=(symbol const& lhs, symbol const& rhs) -> bool { return not (lhs == rhs); } struct literal { double value; }; enum class call_type { as_macro, as_call }; template <call_type C> struct callable; using macro = callable<call_type::as_macro>; using call = callable<call_type::as_call>; struct list; using value = boost::variant< symbol, literal, boost::recursive_wrapper<macro>, boost::recursive_wrapper<call>, boost::recursive_wrapper<list> >; struct list { using range = boost::sub_range<std::vector<value>>; using const_range = boost::sub_range<std::vector<value> const>; std::vector<value> values; template <typename... Ts> list(Ts&&... values) : values{std::forward<Ts>(values)...} {} }; inline auto head(list const& list) -> value const& { return list.values[0]; } inline auto tail(list const& list) -> list::const_range { return {begin(list.values) + 1, end(list.values)}; } inline auto values(list const& list) -> decltype(list.values) { return list.values; } template <call_type C> struct callable { using iterator = list::const_range::iterator; using function_type = std::function<symbol(iterator, iterator)>; callable(callable const&) = default; template <typename F> callable(F lambda) : lambda{lambda} {} function_type lambda; auto operator ()(iterator begin, iterator end) const -> value { return lambda(begin, end); } }; auto operator <<(std::ostream& out, symbol const& sym) -> std::ostream&; auto operator <<(std::ostream& out, literal const& lit) -> std::ostream&; auto operator <<(std::ostream& out, macro const& macro) -> std::ostream&; auto operator <<(std::ostream& out, call const& call) -> std::ostream&; auto operator <<(std::ostream& out, list const& list) -> std::ostream&; } } // namespace klmr::lisp namespace std { template <> struct hash<::klmr::lisp::symbol> { auto operator ()(::klmr::lisp::symbol const& value) const -> size_t { return std::hash<decltype(value.repr)>{}(value.repr); } }; } // namespace std #endif // ndef KLMR_LISP_CPP_VALUE_HPP <commit_msg>Make callable names shorter<commit_after>#ifndef KLMR_LISP_CPP_VALUE_HPP #define KLMR_LISP_CPP_VALUE_HPP #include <iosfwd> #include <string> #include <vector> #include <unordered_map> #include <boost/variant.hpp> #include <boost/range/sub_range.hpp> namespace klmr { namespace lisp { struct symbol { std::string repr; }; inline auto operator ==(symbol const& lhs, symbol const& rhs) -> bool { return lhs.repr == rhs.repr; } inline auto operator !=(symbol const& lhs, symbol const& rhs) -> bool { return not (lhs == rhs); } struct literal { double value; }; enum class call_type { macro, call }; template <call_type C> struct callable; using macro = callable<call_type::macro>; using call = callable<call_type::call>; struct list; using value = boost::variant< symbol, literal, boost::recursive_wrapper<macro>, boost::recursive_wrapper<call>, boost::recursive_wrapper<list> >; struct list { using range = boost::sub_range<std::vector<value>>; using const_range = boost::sub_range<std::vector<value> const>; std::vector<value> values; template <typename... Ts> list(Ts&&... values) : values{std::forward<Ts>(values)...} {} }; inline auto head(list const& list) -> value const& { return list.values[0]; } inline auto tail(list const& list) -> list::const_range { return {begin(list.values) + 1, end(list.values)}; } inline auto values(list const& list) -> decltype(list.values) { return list.values; } template <call_type C> struct callable { using iterator = list::const_range::iterator; using function_type = std::function<symbol(iterator, iterator)>; callable(callable const&) = default; template <typename F> callable(F lambda) : lambda{lambda} {} function_type lambda; auto operator ()(iterator begin, iterator end) const -> value { return lambda(begin, end); } }; auto operator <<(std::ostream& out, symbol const& sym) -> std::ostream&; auto operator <<(std::ostream& out, literal const& lit) -> std::ostream&; auto operator <<(std::ostream& out, macro const& macro) -> std::ostream&; auto operator <<(std::ostream& out, call const& call) -> std::ostream&; auto operator <<(std::ostream& out, list const& list) -> std::ostream&; } } // namespace klmr::lisp namespace std { template <> struct hash<::klmr::lisp::symbol> { auto operator ()(::klmr::lisp::symbol const& value) const -> size_t { return std::hash<decltype(value.repr)>{}(value.repr); } }; } // namespace std #endif // ndef KLMR_LISP_CPP_VALUE_HPP <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: mailmodelapi.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-03-27 09:29:51 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library 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 for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef INCLUDED_SFX_MAILMODEL_HXX #define INCLUDED_SFX_MAILMODEL_HXX #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif #ifndef INCLUDED_SFX2_DLLAPI_H #include "sfx2/dllapi.h" #endif // class SfxMailModel_Impl ----------------------------------------------- class AddressList_Impl; class SFX2_DLLPUBLIC SfxMailModel { public: enum MailPriority { PRIO_HIGHEST, PRIO_HIGH, PRIO_NORMAL, PRIO_LOW, PRIO_LOWEST }; enum AddressRole { ROLE_TO, ROLE_CC, ROLE_BCC }; enum MailDocType { TYPE_SELF, TYPE_ASPDF }; private: enum SaveResult { SAVE_SUCCESSFULL, SAVE_CANCELLED, SAVE_ERROR }; ::std::vector< ::rtl::OUString > maAttachedDocuments; AddressList_Impl* mpToList; AddressList_Impl* mpCcList; AddressList_Impl* mpBccList; String maFromAddress; String maSubject; MailPriority mePriority; sal_Bool mbLoadDone; void ClearList( AddressList_Impl* pList ); void MakeValueList( AddressList_Impl* pList, String& rValueList ); SaveResult SaveDocumentAsFormat( const rtl::OUString& aSaveFileName, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xFrameOrModel, const rtl::OUString& rType, rtl::OUString& rFileNamePath ); DECL_LINK( DoneHdl, void* ); public: enum SendMailResult { SEND_MAIL_OK, SEND_MAIL_CANCELLED, SEND_MAIL_ERROR }; SfxMailModel(); ~SfxMailModel(); void AddAddress( const String& rAddress, AddressRole eRole ); void SetFromAddress( const String& rAddress ) { maFromAddress = rAddress; } void SetSubject( const String& rSubject ) { maSubject = rSubject; } void SetPriority( MailPriority ePrio ) { mePriority = ePrio; } /** attaches a document to the current attachment list, can be called more than once. * at the moment there will be a dialog for export executed for every model which is going to be attached. * * \param sDocumentType The doc type to export. PDF will be at the moment only a direct export (no dialog). * \param xModel The current model to attach * \param sAttachmentTitle The title which will be used as attachment title * \return @see error code */ SendMailResult AttachDocument( const ::rtl::OUString& sDocumentType, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xFrameOrModel, const ::rtl::OUString& sAttachmentTitle ); SendMailResult SaveAndSend( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame, const rtl::OUString& rType ); SendMailResult Send( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame ); sal_Int32 GetCount() const; sal_Bool IsEmpty() const; }; BOOL CreateFromAddress_Impl( String& rFrom ); #endif // INCLUDED_SFX_MAILMODEL_HXX <commit_msg>INTEGRATION: CWS warnings01 (1.3.66); FILE MERGED 2006/04/07 19:23:16 sb 1.3.66.2: RESYNC: (1.3-1.4); FILE MERGED 2006/01/31 12:44:33 sb 1.3.66.1: #i53898# Made code warning-free.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: mailmodelapi.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2006-06-19 22:01:29 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library 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 for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef INCLUDED_SFX_MAILMODEL_HXX #define INCLUDED_SFX_MAILMODEL_HXX #include <vector> #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif #ifndef _LINK_HXX #include "tools/link.hxx" #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef INCLUDED_SFX2_DLLAPI_H #include "sfx2/dllapi.h" #endif // class SfxMailModel_Impl ----------------------------------------------- class AddressList_Impl; class SFX2_DLLPUBLIC SfxMailModel { public: enum MailPriority { PRIO_HIGHEST, PRIO_HIGH, PRIO_NORMAL, PRIO_LOW, PRIO_LOWEST }; enum AddressRole { ROLE_TO, ROLE_CC, ROLE_BCC }; enum MailDocType { TYPE_SELF, TYPE_ASPDF }; private: enum SaveResult { SAVE_SUCCESSFULL, SAVE_CANCELLED, SAVE_ERROR }; ::std::vector< ::rtl::OUString > maAttachedDocuments; AddressList_Impl* mpToList; AddressList_Impl* mpCcList; AddressList_Impl* mpBccList; String maFromAddress; String maSubject; MailPriority mePriority; sal_Bool mbLoadDone; void ClearList( AddressList_Impl* pList ); void MakeValueList( AddressList_Impl* pList, String& rValueList ); SaveResult SaveDocumentAsFormat( const rtl::OUString& aSaveFileName, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xFrameOrModel, const rtl::OUString& rType, rtl::OUString& rFileNamePath ); DECL_LINK( DoneHdl, void* ); public: enum SendMailResult { SEND_MAIL_OK, SEND_MAIL_CANCELLED, SEND_MAIL_ERROR }; SfxMailModel(); ~SfxMailModel(); void AddAddress( const String& rAddress, AddressRole eRole ); void SetFromAddress( const String& rAddress ) { maFromAddress = rAddress; } void SetSubject( const String& rSubject ) { maSubject = rSubject; } void SetPriority( MailPriority ePrio ) { mePriority = ePrio; } /** attaches a document to the current attachment list, can be called more than once. * at the moment there will be a dialog for export executed for every model which is going to be attached. * * \param sDocumentType The doc type to export. PDF will be at the moment only a direct export (no dialog). * \param xModel The current model to attach * \param sAttachmentTitle The title which will be used as attachment title * \return @see error code */ SendMailResult AttachDocument( const ::rtl::OUString& sDocumentType, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xFrameOrModel, const ::rtl::OUString& sAttachmentTitle ); SendMailResult SaveAndSend( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame, const rtl::OUString& rType ); SendMailResult Send( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame ); sal_Int32 GetCount() const; sal_Bool IsEmpty() const; }; BOOL CreateFromAddress_Impl( String& rFrom ); #endif // INCLUDED_SFX_MAILMODEL_HXX <|endoftext|>
<commit_before>#include "filesystem_test.h" #include <boost/filesystem.hpp> #include <fstream> void mu::core_test::filesystem_test::run () { run_1 (); run_2 (); } void mu::core_test::filesystem_test::run_1 () { auto path (::boost::filesystem::initial_path ()); path /= L"test"; path /= L"test"; } void mu::core_test::filesystem_test::run_2 () { auto path (boost::filesystem::initial_path ()); path /= L"examples"; path /= L"test.lp"; std::ifstream stream; std::string str (path.string ()); stream.open (str); assert (stream.is_open ()); } <commit_msg>Added info.<commit_after>#include "filesystem_test.h" #include <boost/filesystem.hpp> #include <fstream> void mu::core_test::filesystem_test::run () { run_1 (); run_2 (); } void mu::core_test::filesystem_test::run_1 () { auto path (::boost::filesystem::initial_path ()); path /= L"test"; path /= L"test"; } void mu::core_test::filesystem_test::run_2 () { auto path (boost::filesystem::initial_path ()); path /= L"examples"; path /= L"test.lp"; std::ifstream stream; std::string str (path.string ()); stream.open (str); assert (stream.is_open () && "Set project working directory to $(SolutionDir)"); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <characterclassificationImpl.hxx> #include <rtl/ustrbuf.hxx> using namespace com::sun::star::uno; using namespace com::sun::star::lang; namespace com { namespace sun { namespace star { namespace i18n { CharacterClassificationImpl::CharacterClassificationImpl( const Reference < uno::XComponentContext >& rxContext ) : m_xContext( rxContext ) { if (createLocaleSpecificCharacterClassification(OUString("Unicode"), Locale())) xUCI = cachedItem->xCI; } CharacterClassificationImpl::~CharacterClassificationImpl() { // Clear lookuptable for (size_t l = 0; l < lookupTable.size(); l++) delete lookupTable[l]; lookupTable.clear(); } OUString SAL_CALL CharacterClassificationImpl::toUpper( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { return getLocaleSpecificCharacterClassification(rLocale)->toUpper(Text, nPos, nCount, rLocale); } OUString SAL_CALL CharacterClassificationImpl::toLower( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { return getLocaleSpecificCharacterClassification(rLocale)->toLower(Text, nPos, nCount, rLocale); } OUString SAL_CALL CharacterClassificationImpl::toTitle( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { return getLocaleSpecificCharacterClassification(rLocale)->toTitle(Text, nPos, nCount, rLocale); } sal_Int16 SAL_CALL CharacterClassificationImpl::getType( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) { if (xUCI.is()) return xUCI->getType(Text, nPos); throw RuntimeException(); } sal_Int16 SAL_CALL CharacterClassificationImpl::getCharacterDirection( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) { if (xUCI.is()) return xUCI->getCharacterDirection(Text, nPos); throw RuntimeException(); } sal_Int16 SAL_CALL CharacterClassificationImpl::getScript( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) { if (xUCI.is()) return xUCI->getScript(Text, nPos); throw RuntimeException(); } sal_Int32 SAL_CALL CharacterClassificationImpl::getCharacterType( const OUString& Text, sal_Int32 nPos, const Locale& rLocale ) throw(RuntimeException) { return getLocaleSpecificCharacterClassification(rLocale)->getCharacterType(Text, nPos, rLocale); } sal_Int32 SAL_CALL CharacterClassificationImpl::getStringType( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { return getLocaleSpecificCharacterClassification(rLocale)->getStringType(Text, nPos, nCount, rLocale); } ParseResult SAL_CALL CharacterClassificationImpl::parseAnyToken( const OUString& Text, sal_Int32 nPos, const Locale& rLocale, sal_Int32 startCharTokenType, const OUString& userDefinedCharactersStart, sal_Int32 contCharTokenType, const OUString& userDefinedCharactersCont ) throw(RuntimeException) { return getLocaleSpecificCharacterClassification(rLocale)->parseAnyToken(Text, nPos, rLocale, startCharTokenType,userDefinedCharactersStart, contCharTokenType, userDefinedCharactersCont); } ParseResult SAL_CALL CharacterClassificationImpl::parsePredefinedToken( sal_Int32 nTokenType, const OUString& Text, sal_Int32 nPos, const Locale& rLocale, sal_Int32 startCharTokenType, const OUString& userDefinedCharactersStart, sal_Int32 contCharTokenType, const OUString& userDefinedCharactersCont ) throw(RuntimeException) { return getLocaleSpecificCharacterClassification(rLocale)->parsePredefinedToken( nTokenType, Text, nPos, rLocale, startCharTokenType, userDefinedCharactersStart, contCharTokenType, userDefinedCharactersCont); } sal_Bool SAL_CALL CharacterClassificationImpl::createLocaleSpecificCharacterClassification(const OUString& serviceName, const Locale& rLocale) { // to share service between same Language but different Country code, like zh_CN and zh_SG for (size_t l = 0; l < lookupTable.size(); l++) { cachedItem = lookupTable[l]; if (serviceName == cachedItem->aName) { lookupTable.push_back( cachedItem = new lookupTableItem(rLocale, serviceName, cachedItem->xCI) ); return sal_True; } } Reference < XInterface > xI = m_xContext->getServiceManager()->createInstanceWithContext( OUString("com.sun.star.i18n.CharacterClassification_") + serviceName, m_xContext); Reference < XCharacterClassification > xCI; if ( xI.is() ) { xCI.set( xI, UNO_QUERY ); if (xCI.is()) { lookupTable.push_back( cachedItem = new lookupTableItem(rLocale, serviceName, xCI) ); return sal_True; } } return sal_False; } Reference < XCharacterClassification > SAL_CALL CharacterClassificationImpl::getLocaleSpecificCharacterClassification(const Locale& rLocale) throw(RuntimeException) { // reuse instance if locale didn't change if (cachedItem && cachedItem->equals(rLocale)) return cachedItem->xCI; else { for (size_t i = 0; i < lookupTable.size(); i++) { cachedItem = lookupTable[i]; if (cachedItem->equals(rLocale)) return cachedItem->xCI; } static sal_Unicode under = (sal_Unicode)'_'; sal_Int32 l = rLocale.Language.getLength(); sal_Int32 c = rLocale.Country.getLength(); sal_Int32 v = rLocale.Variant.getLength(); OUStringBuffer aBuf(l+c+v+3); // load service with name <base>_<lang>_<country>_<varian> if ((l > 0 && c > 0 && v > 0 && createLocaleSpecificCharacterClassification(aBuf.append(rLocale.Language).append(under).append( rLocale.Country).append(under).append(rLocale.Variant).makeStringAndClear(), rLocale)) || // load service with name <base>_<lang>_<country> (l > 0 && c > 0 && createLocaleSpecificCharacterClassification(aBuf.append(rLocale.Language).append(under).append( rLocale.Country).makeStringAndClear(), rLocale)) || (l > 0 && c > 0 && rLocale.Language.compareToAscii("zh") == 0 && (rLocale.Country.compareToAscii("HK") == 0 || rLocale.Country.compareToAscii("MO") == 0) && // if the country code is HK or MO, one more step to try TW. createLocaleSpecificCharacterClassification(aBuf.append(rLocale.Language).append(under).append( "TW").makeStringAndClear(), rLocale)) || (l > 0 && // load service with name <base>_<lang> createLocaleSpecificCharacterClassification(rLocale.Language, rLocale))) { return cachedItem->xCI; } else if (xUCI.is()) { lookupTable.push_back( cachedItem = new lookupTableItem(rLocale, OUString("Unicode"), xUCI) ); return cachedItem->xCI; } } throw RuntimeException(); } const sal_Char cClass[] = "com.sun.star.i18n.CharacterClassification"; OUString SAL_CALL CharacterClassificationImpl::getImplementationName(void) throw( RuntimeException ) { return OUString::createFromAscii(cClass); } sal_Bool SAL_CALL CharacterClassificationImpl::supportsService(const OUString& rServiceName) throw( RuntimeException ) { return !rServiceName.compareToAscii(cClass); } Sequence< OUString > SAL_CALL CharacterClassificationImpl::getSupportedServiceNames(void) throw( RuntimeException ) { Sequence< OUString > aRet(1); aRet[0] = OUString::createFromAscii(cClass); return aRet; } } } } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>use get*LocaleServiceName<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <characterclassificationImpl.hxx> #include <localedata.hxx> #include <rtl/ustrbuf.hxx> using namespace com::sun::star::uno; using namespace com::sun::star::lang; namespace com { namespace sun { namespace star { namespace i18n { CharacterClassificationImpl::CharacterClassificationImpl( const Reference < uno::XComponentContext >& rxContext ) : m_xContext( rxContext ) { if (createLocaleSpecificCharacterClassification(OUString("Unicode"), Locale())) xUCI = cachedItem->xCI; } CharacterClassificationImpl::~CharacterClassificationImpl() { // Clear lookuptable for (size_t l = 0; l < lookupTable.size(); l++) delete lookupTable[l]; lookupTable.clear(); } OUString SAL_CALL CharacterClassificationImpl::toUpper( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { return getLocaleSpecificCharacterClassification(rLocale)->toUpper(Text, nPos, nCount, rLocale); } OUString SAL_CALL CharacterClassificationImpl::toLower( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { return getLocaleSpecificCharacterClassification(rLocale)->toLower(Text, nPos, nCount, rLocale); } OUString SAL_CALL CharacterClassificationImpl::toTitle( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { return getLocaleSpecificCharacterClassification(rLocale)->toTitle(Text, nPos, nCount, rLocale); } sal_Int16 SAL_CALL CharacterClassificationImpl::getType( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) { if (xUCI.is()) return xUCI->getType(Text, nPos); throw RuntimeException(); } sal_Int16 SAL_CALL CharacterClassificationImpl::getCharacterDirection( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) { if (xUCI.is()) return xUCI->getCharacterDirection(Text, nPos); throw RuntimeException(); } sal_Int16 SAL_CALL CharacterClassificationImpl::getScript( const OUString& Text, sal_Int32 nPos ) throw(RuntimeException) { if (xUCI.is()) return xUCI->getScript(Text, nPos); throw RuntimeException(); } sal_Int32 SAL_CALL CharacterClassificationImpl::getCharacterType( const OUString& Text, sal_Int32 nPos, const Locale& rLocale ) throw(RuntimeException) { return getLocaleSpecificCharacterClassification(rLocale)->getCharacterType(Text, nPos, rLocale); } sal_Int32 SAL_CALL CharacterClassificationImpl::getStringType( const OUString& Text, sal_Int32 nPos, sal_Int32 nCount, const Locale& rLocale ) throw(RuntimeException) { return getLocaleSpecificCharacterClassification(rLocale)->getStringType(Text, nPos, nCount, rLocale); } ParseResult SAL_CALL CharacterClassificationImpl::parseAnyToken( const OUString& Text, sal_Int32 nPos, const Locale& rLocale, sal_Int32 startCharTokenType, const OUString& userDefinedCharactersStart, sal_Int32 contCharTokenType, const OUString& userDefinedCharactersCont ) throw(RuntimeException) { return getLocaleSpecificCharacterClassification(rLocale)->parseAnyToken(Text, nPos, rLocale, startCharTokenType,userDefinedCharactersStart, contCharTokenType, userDefinedCharactersCont); } ParseResult SAL_CALL CharacterClassificationImpl::parsePredefinedToken( sal_Int32 nTokenType, const OUString& Text, sal_Int32 nPos, const Locale& rLocale, sal_Int32 startCharTokenType, const OUString& userDefinedCharactersStart, sal_Int32 contCharTokenType, const OUString& userDefinedCharactersCont ) throw(RuntimeException) { return getLocaleSpecificCharacterClassification(rLocale)->parsePredefinedToken( nTokenType, Text, nPos, rLocale, startCharTokenType, userDefinedCharactersStart, contCharTokenType, userDefinedCharactersCont); } sal_Bool SAL_CALL CharacterClassificationImpl::createLocaleSpecificCharacterClassification(const OUString& serviceName, const Locale& rLocale) { // to share service between same Language but different Country code, like zh_CN and zh_SG for (size_t l = 0; l < lookupTable.size(); l++) { cachedItem = lookupTable[l]; if (serviceName == cachedItem->aName) { lookupTable.push_back( cachedItem = new lookupTableItem(rLocale, serviceName, cachedItem->xCI) ); return sal_True; } } Reference < XInterface > xI = m_xContext->getServiceManager()->createInstanceWithContext( OUString("com.sun.star.i18n.CharacterClassification_") + serviceName, m_xContext); Reference < XCharacterClassification > xCI; if ( xI.is() ) { xCI.set( xI, UNO_QUERY ); if (xCI.is()) { lookupTable.push_back( cachedItem = new lookupTableItem(rLocale, serviceName, xCI) ); return sal_True; } } return sal_False; } Reference < XCharacterClassification > SAL_CALL CharacterClassificationImpl::getLocaleSpecificCharacterClassification(const Locale& rLocale) throw(RuntimeException) { // reuse instance if locale didn't change if (cachedItem && cachedItem->equals(rLocale)) return cachedItem->xCI; else { for (size_t i = 0; i < lookupTable.size(); i++) { cachedItem = lookupTable[i]; if (cachedItem->equals(rLocale)) return cachedItem->xCI; } // Load service with name <base>_<lang>_<country> or // <base>_<bcp47> and fallbacks. bool bLoaded = createLocaleSpecificCharacterClassification( LocaleData::getFirstLocaleServiceName( rLocale), rLocale); if (!bLoaded) { ::std::vector< OUString > aFallbacks( LocaleData::getFallbackLocaleServiceNames( rLocale)); for (::std::vector< OUString >::const_iterator it( aFallbacks.begin()); it != aFallbacks.end(); ++it) { bLoaded = createLocaleSpecificCharacterClassification( *it, rLocale); if (bLoaded) break; } } if (bLoaded) return cachedItem->xCI; else if (xUCI.is()) { lookupTable.push_back( cachedItem = new lookupTableItem( rLocale, OUString("Unicode"), xUCI)); return cachedItem->xCI; } } throw RuntimeException(); } const sal_Char cClass[] = "com.sun.star.i18n.CharacterClassification"; OUString SAL_CALL CharacterClassificationImpl::getImplementationName(void) throw( RuntimeException ) { return OUString::createFromAscii(cClass); } sal_Bool SAL_CALL CharacterClassificationImpl::supportsService(const OUString& rServiceName) throw( RuntimeException ) { return !rServiceName.compareToAscii(cClass); } Sequence< OUString > SAL_CALL CharacterClassificationImpl::getSupportedServiceNames(void) throw( RuntimeException ) { Sequence< OUString > aRet(1); aRet[0] = OUString::createFromAscii(cClass); return aRet; } } } } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/**************************************************************************** This file is part of the GLC-lib library. Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net) Version 1.2.0, packaged on September 2009. http://glc-lib.sourceforge.net GLC-lib 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 2 of the License, or (at your option) any later version. GLC-lib 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 GLC-lib; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************/ //! \file glc_texture.cpp implementation of the GLC_Texture class. #include "glc_texture.h" #include "../glc_exception.h" #include <QtDebug> // The default maximum texture size QSize GLC_Texture::m_MaxTextureSize(676, 676); // The Minimum texture size const QSize GLC_Texture::m_MinTextureSize(10, 10); ////////////////////////////////////////////////////////////////////// // Constructor Destructor ////////////////////////////////////////////////////////////////////// //! Default constructor GLC_Texture::GLC_Texture(const QGLContext *pContext) : m_pQGLContext(const_cast<QGLContext*>(pContext)) , m_FileName() , m_GlTextureID(0) , m_textureImage() , m_TextureSize() , m_HasAlphaChannel(false) { } // Constructor with fileName GLC_Texture::GLC_Texture(const QGLContext *pContext, const QString &Filename) : m_pQGLContext(const_cast<QGLContext*>(pContext)) , m_FileName(Filename) , m_GlTextureID(0) , m_textureImage(m_FileName) , m_TextureSize() , m_HasAlphaChannel(m_textureImage.hasAlphaChannel()) { if (m_textureImage.isNull()) { QString ErrorMess("GLC_Texture::GLC_Texture open image : "); ErrorMess.append(m_FileName).append(" Failed"); qDebug() << ErrorMess; GLC_Exception e(ErrorMess); throw(e); } } // Constructor with QFile GLC_Texture::GLC_Texture(const QGLContext *pContext, const QFile &file) : m_pQGLContext(const_cast<QGLContext*>(pContext)) , m_FileName(file.fileName()) , m_GlTextureID(0) , m_textureImage(m_FileName) , m_TextureSize() , m_HasAlphaChannel(m_textureImage.hasAlphaChannel()) { if (m_textureImage.isNull()) { QString ErrorMess("GLC_Texture::GLC_Texture open image : "); ErrorMess.append(m_FileName).append(" Failed"); qDebug() << ErrorMess; GLC_Exception e(ErrorMess); throw(e); } } // Constructor with QImage GLC_Texture::GLC_Texture(const QGLContext* pContext, const QImage& image, const QString& fileName) : m_pQGLContext(const_cast<QGLContext*>(pContext)) , m_FileName(fileName) , m_GlTextureID(0) , m_textureImage(image) , m_TextureSize() , m_HasAlphaChannel(m_textureImage.hasAlphaChannel()) { Q_ASSERT(!m_textureImage.isNull()); } GLC_Texture::GLC_Texture(const GLC_Texture &TextureToCopy) : m_pQGLContext(TextureToCopy.m_pQGLContext) , m_FileName(TextureToCopy.m_FileName) , m_GlTextureID(0) , m_textureImage(TextureToCopy.m_textureImage) , m_TextureSize(TextureToCopy.m_TextureSize) , m_HasAlphaChannel(m_textureImage.hasAlphaChannel()) { if (m_textureImage.isNull()) { QString ErrorMess("GLC_Texture::GLC_Texture open image : "); ErrorMess.append(m_FileName).append(" Failed"); qDebug() << ErrorMess; GLC_Exception e(ErrorMess); throw(e); } } // Overload "=" operator GLC_Texture& GLC_Texture::operator=(const GLC_Texture& texture) { if (!(*this == texture)) { if (m_GlTextureID != 0) { m_pQGLContext->deleteTexture(m_GlTextureID); m_GlTextureID= 0; } m_pQGLContext= texture.m_pQGLContext; m_FileName= texture.m_FileName; m_GlTextureID= 0; m_textureImage= texture.m_textureImage; m_TextureSize= texture.m_TextureSize; m_HasAlphaChannel= m_textureImage.hasAlphaChannel(); } return *this; } GLC_Texture::~GLC_Texture() { //qDebug() << "GLC_Texture::~GLC_Texture Texture ID : " << m_GlTextureID; if (m_GlTextureID != 0) { m_pQGLContext->deleteTexture(m_GlTextureID); m_GlTextureID= 0; } } ////////////////////////////////////////////////////////////////////// // Get Functions ////////////////////////////////////////////////////////////////////// // Return true if texture are the same bool GLC_Texture::operator==(const GLC_Texture& texture) const { bool result; if (this == &texture) { result= true; } else { result= (m_FileName == texture.m_FileName) && (m_textureImage == texture.m_textureImage); } return result; } ////////////////////////////////////////////////////////////////////// // Set Functions ////////////////////////////////////////////////////////////////////// // Set the maximum texture size void GLC_Texture::setMaxTextureSize(const QSize& size) { if ((size.height() > m_MinTextureSize.height()) && (size.width() > m_MinTextureSize.width())) { m_MaxTextureSize= size; } else { qDebug() << "GLC_Texture::setMaxTextureSize m_MaxTextureSize set to m_MinTextureSize"; m_MaxTextureSize= m_MinTextureSize; } } ////////////////////////////////////////////////////////////////////// // Private OpenGL functions ////////////////////////////////////////////////////////////////////// // Load the texture void GLC_Texture::glLoadTexture(void) { if (m_GlTextureID == 0) { if (NULL == m_pQGLContext) { m_pQGLContext= const_cast<QGLContext*>(QGLContext::currentContext()); } // Test image size if ((m_textureImage.height() > m_MaxTextureSize.height()) || (m_textureImage.width() > m_MaxTextureSize.width())) { QImage rescaledImage; if(m_textureImage.height() > m_textureImage.width()) { rescaledImage= m_textureImage.scaledToHeight(m_MaxTextureSize.height(), Qt::SmoothTransformation); } else { rescaledImage= m_textureImage.scaledToWidth(m_MaxTextureSize.width(), Qt::SmoothTransformation); } m_TextureSize= rescaledImage.size(); m_GlTextureID= m_pQGLContext->bindTexture(rescaledImage); } else { m_TextureSize= m_textureImage.size(); m_GlTextureID= m_pQGLContext->bindTexture(m_textureImage); } //qDebug() << "GLC_Texture::glcBindTexture Texture ID = " << m_GlTextureID; } } // Bind texture in 2D mode void GLC_Texture::glcBindTexture(void) { if (m_GlTextureID == 0) { glLoadTexture(); } glBindTexture(GL_TEXTURE_2D, m_GlTextureID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } // Non-member stream operator QDataStream &operator<<(QDataStream &stream, const GLC_Texture &texture) { stream << texture.fileName(); stream << texture.imageOfTexture(); return stream; } QDataStream &operator>>(QDataStream &stream, GLC_Texture &texture) { QString fileName; QImage image; stream >> fileName >> image; texture= GLC_Texture(texture.context(), image, fileName); return stream; } <commit_msg>Bug Fix : rescale texture Qimage if needed.<commit_after>/**************************************************************************** This file is part of the GLC-lib library. Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net) Version 1.2.0, packaged on September 2009. http://glc-lib.sourceforge.net GLC-lib 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 2 of the License, or (at your option) any later version. GLC-lib 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 GLC-lib; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************/ //! \file glc_texture.cpp implementation of the GLC_Texture class. #include "glc_texture.h" #include "../glc_exception.h" #include <QtDebug> // The default maximum texture size QSize GLC_Texture::m_MaxTextureSize(676, 676); // The Minimum texture size const QSize GLC_Texture::m_MinTextureSize(10, 10); ////////////////////////////////////////////////////////////////////// // Constructor Destructor ////////////////////////////////////////////////////////////////////// //! Default constructor GLC_Texture::GLC_Texture(const QGLContext *pContext) : m_pQGLContext(const_cast<QGLContext*>(pContext)) , m_FileName() , m_GlTextureID(0) , m_textureImage() , m_TextureSize() , m_HasAlphaChannel(false) { } // Constructor with fileName GLC_Texture::GLC_Texture(const QGLContext *pContext, const QString &Filename) : m_pQGLContext(const_cast<QGLContext*>(pContext)) , m_FileName(Filename) , m_GlTextureID(0) , m_textureImage(m_FileName) , m_TextureSize() , m_HasAlphaChannel(m_textureImage.hasAlphaChannel()) { if (m_textureImage.isNull()) { QString ErrorMess("GLC_Texture::GLC_Texture open image : "); ErrorMess.append(m_FileName).append(" Failed"); qDebug() << ErrorMess; GLC_Exception e(ErrorMess); throw(e); } } // Constructor with QFile GLC_Texture::GLC_Texture(const QGLContext *pContext, const QFile &file) : m_pQGLContext(const_cast<QGLContext*>(pContext)) , m_FileName(file.fileName()) , m_GlTextureID(0) , m_textureImage(m_FileName) , m_TextureSize() , m_HasAlphaChannel(m_textureImage.hasAlphaChannel()) { if (m_textureImage.isNull()) { QString ErrorMess("GLC_Texture::GLC_Texture open image : "); ErrorMess.append(m_FileName).append(" Failed"); qDebug() << ErrorMess; GLC_Exception e(ErrorMess); throw(e); } } // Constructor with QImage GLC_Texture::GLC_Texture(const QGLContext* pContext, const QImage& image, const QString& fileName) : m_pQGLContext(const_cast<QGLContext*>(pContext)) , m_FileName(fileName) , m_GlTextureID(0) , m_textureImage(image) , m_TextureSize() , m_HasAlphaChannel(m_textureImage.hasAlphaChannel()) { Q_ASSERT(!m_textureImage.isNull()); } GLC_Texture::GLC_Texture(const GLC_Texture &TextureToCopy) : m_pQGLContext(TextureToCopy.m_pQGLContext) , m_FileName(TextureToCopy.m_FileName) , m_GlTextureID(0) , m_textureImage(TextureToCopy.m_textureImage) , m_TextureSize(TextureToCopy.m_TextureSize) , m_HasAlphaChannel(m_textureImage.hasAlphaChannel()) { if (m_textureImage.isNull()) { QString ErrorMess("GLC_Texture::GLC_Texture open image : "); ErrorMess.append(m_FileName).append(" Failed"); qDebug() << ErrorMess; GLC_Exception e(ErrorMess); throw(e); } } // Overload "=" operator GLC_Texture& GLC_Texture::operator=(const GLC_Texture& texture) { if (!(*this == texture)) { if (m_GlTextureID != 0) { m_pQGLContext->deleteTexture(m_GlTextureID); m_GlTextureID= 0; } m_pQGLContext= texture.m_pQGLContext; m_FileName= texture.m_FileName; m_GlTextureID= 0; m_textureImage= texture.m_textureImage; m_TextureSize= texture.m_TextureSize; m_HasAlphaChannel= m_textureImage.hasAlphaChannel(); } return *this; } GLC_Texture::~GLC_Texture() { //qDebug() << "GLC_Texture::~GLC_Texture Texture ID : " << m_GlTextureID; if (m_GlTextureID != 0) { m_pQGLContext->deleteTexture(m_GlTextureID); m_GlTextureID= 0; } } ////////////////////////////////////////////////////////////////////// // Get Functions ////////////////////////////////////////////////////////////////////// // Return true if texture are the same bool GLC_Texture::operator==(const GLC_Texture& texture) const { bool result; if (this == &texture) { result= true; } else { result= (m_FileName == texture.m_FileName) && (m_textureImage == texture.m_textureImage); } return result; } ////////////////////////////////////////////////////////////////////// // Set Functions ////////////////////////////////////////////////////////////////////// // Set the maximum texture size void GLC_Texture::setMaxTextureSize(const QSize& size) { if ((size.height() > m_MinTextureSize.height()) && (size.width() > m_MinTextureSize.width())) { m_MaxTextureSize= size; } else { qDebug() << "GLC_Texture::setMaxTextureSize m_MaxTextureSize set to m_MinTextureSize"; m_MaxTextureSize= m_MinTextureSize; } } ////////////////////////////////////////////////////////////////////// // Private OpenGL functions ////////////////////////////////////////////////////////////////////// // Load the texture void GLC_Texture::glLoadTexture(void) { if (m_GlTextureID == 0) { if (NULL == m_pQGLContext) { m_pQGLContext= const_cast<QGLContext*>(QGLContext::currentContext()); } // Test image size if ((m_textureImage.height() > m_MaxTextureSize.height()) || (m_textureImage.width() > m_MaxTextureSize.width())) { QImage rescaledImage; if(m_textureImage.height() > m_textureImage.width()) { rescaledImage= m_textureImage.scaledToHeight(m_MaxTextureSize.height(), Qt::SmoothTransformation); } else { rescaledImage= m_textureImage.scaledToWidth(m_MaxTextureSize.width(), Qt::SmoothTransformation); } m_textureImage= rescaledImage; m_TextureSize= m_textureImage.size(); m_GlTextureID= m_pQGLContext->bindTexture(m_textureImage); } else { m_TextureSize= m_textureImage.size(); m_GlTextureID= m_pQGLContext->bindTexture(m_textureImage); } //qDebug() << "GLC_Texture::glcBindTexture Texture ID = " << m_GlTextureID; } } // Bind texture in 2D mode void GLC_Texture::glcBindTexture(void) { if (m_GlTextureID == 0) { glLoadTexture(); } glBindTexture(GL_TEXTURE_2D, m_GlTextureID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } // Non-member stream operator QDataStream &operator<<(QDataStream &stream, const GLC_Texture &texture) { stream << texture.fileName(); stream << texture.imageOfTexture(); return stream; } QDataStream &operator>>(QDataStream &stream, GLC_Texture &texture) { QString fileName; QImage image; stream >> fileName >> image; texture= GLC_Texture(texture.context(), image, fileName); return stream; } <|endoftext|>
<commit_before> /* This file is part of indexlib. * Copyright (C) 2005 Luís Pedro Coelho <luis@luispedro.org> * * Indexlib is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License, version 2, as * published by the Free Software Foundation and available as file * GPL_V2 which is distributed along with indexlib. * * Indexlib 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., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA * * In addition, as a special exception, the copyright holders give * permission to link the code of this program with any edition of * the Qt library by Trolltech AS, Norway (or with modified versions * of Qt that use the same license as Qt), and distribute linked * combinations including the two. You must obey the GNU General * Public License in all respects for all of the code used other than * Qt. If you modify this file, you may extend this exception to * your version of the file, but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from * your version. */ #include "stringarray.h" #include "leafdata.h" #include "manager.h" #include "mmap_manager.h" #include "mempool.h" #include "index_slow.h" #include "ifile.h" #include "quotes.h" #include "compressed.h" #include "create.h" #include <map> #include <iostream> #include <cstdlib> #include <string> #include <fstream> #include <memory> #include <string.h> #include "format.h" typedef std::auto_ptr<indexlib::index> index_smart; index_smart get_index( std::string name ) { return indexlib::open( name.c_str(), indexlib::open_flags::create_quotes ); } std::string read_stream( std::istream& in ) { std::string res; char c; while ( in.get( c ) ) res.push_back( c ); return res; } std::string read_string( std::string file ) { if ( file == "-" ) return read_stream( std::cin ); std::ifstream in( file.c_str() ); return read_stream( in ); } void usage( int argc, char* argv[] ) { std::cout << argv[ 0 ] << " cmd [index]\n"; } int debug( int argc, char* argv[] ) { std::string type = argv[ 2 ]; std::string argument = argv[ 3 ]; if ( type == "sa" ) { //nolog(); std::cout << "stringarray:\n"; stringarray sa( argument ); sa.print( std::cout ); } else if ( type == "compressed" ) { compressed_file file( argument ); nolog(); std::cout << "compressed_file:\n"; file.print( std::cout ); } else { std::cerr << "Unknown function\n"; return 1; } return 0; } int remove( int argc, char* argv[] ) { if ( argc < 4 ) { usage( argc, argv ); return 1; } index_smart t = get_index( argv[ 2 ] ); t->remove_doc( argv[ 3 ] ); return 0; } int maintenance( int argc, char* argv[] ) { index_smart t = get_index( argv[ 2 ] ); t->maintenance(); return 0; } int add( int argc, char* argv[] ) { if ( argc < 4 ) { usage( argc, argv ) ; return 1; } index_smart t = get_index( argv[ 2 ] ); std::string input; if ( argv[ 4 ] ) input = argv[ 4 ]; else input = argv[ 3 ]; t->add( read_string( input ), argv[ 3 ] ); //std::cout << format( "%s indexed as %s\n" ) % argv[ 3 ] % -1; //FIXME return 0; } int search( int argc, char* argv[] ) { if ( argc < 4 ) { usage( argc, argv ); return 1; } index_smart t = get_index( argv[ 2 ] ); std::vector<unsigned> files = t->search( argv[ 3 ] )->list(); if ( files.empty() ) std::cout << "Empty results\n"; else { for ( std::vector<unsigned>::const_iterator first = files.begin(), past = files.end(); first != past; ++first ) { std::cout << format( "%s\n" ) % t->lookup_docname( *first ); } } return 0; } int list( int argc, char* argv[] ) { index_smart t = get_index( argv[ 2 ] ); unsigned ndocs = t->ndocs(); for ( unsigned i = 0; i != ndocs; ++i ) { std::cout << format( "%s\n" ) % t->lookup_docname( i ); } return 0; } int main( int argc, char* argv[]) try { //nolog(); if ( argc < 3 ) { usage( argc, argv ); return 0; } std::map<std::string, int (*)( int, char* [] )> handlers; handlers[ "debug" ] = &debug; handlers[ "remove" ] = &remove; handlers[ "maintenance" ] = &maintenance; handlers[ "add" ] = &add; handlers[ "search" ] = &search; handlers[ "list" ] = &list; int ( *handle )( int, char*[] ) = handlers[ argv[ 1 ] ]; if ( handle ) return handle( argc, argv ); else { std::cerr << format( "Unkown command: %s\n" ) % argv[ 1 ]; return 1; } } catch ( const char* msg ) { std::cerr << "Error: " << msg << std::endl; return 1; } catch ( std::exception& e ) { std::cerr << "Std Error: " << e.what() << std::endl; return 1; } catch ( ... ) { std::cerr << "Some Unspecified error\n"; return 1; } <commit_msg>forward port: SVN commit 489209 by luis_pedro:<commit_after> /* This file is part of indexlib. * Copyright (C) 2005 Luís Pedro Coelho <luis@luispedro.org> * * Indexlib is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License, version 2, as * published by the Free Software Foundation and available as file * GPL_V2 which is distributed along with indexlib. * * Indexlib 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., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA * * In addition, as a special exception, the copyright holders give * permission to link the code of this program with any edition of * the Qt library by Trolltech AS, Norway (or with modified versions * of Qt that use the same license as Qt), and distribute linked * combinations including the two. You must obey the GNU General * Public License in all respects for all of the code used other than * Qt. If you modify this file, you may extend this exception to * your version of the file, but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from * your version. */ #include "stringarray.h" #include "leafdata.h" #include "manager.h" #include "mmap_manager.h" #include "mempool.h" #include "compressed.h" #include "create.h" #include "tokenizer.h" #include <sstream> #include <map> #include <iostream> #include <cstdlib> #include <string> #include <fstream> #include <memory> #include <string.h> typedef std::auto_ptr<indexlib::index> index_smart; index_smart get_index( std::string name ) { return indexlib::open( name.c_str(), indexlib::open_flags::create_quotes ); } std::string read_stream( std::istream& in ) { std::string res; char c; while ( in.get( c ) ) res.push_back( c ); return res; } std::string read_string( std::string file ) { if ( file == "-" ) return read_stream( std::cin ); std::ifstream in( file.c_str() ); return read_stream( in ); } void usage( int argc, char* argv[], const std::map<std::string, int (*)( int, char** )>& commands ) { std::cout << argv[ 0 ] << " cmd [index]\n" << "Possible Commands:\n\n"; for ( std::map<std::string, int (*)( int, char** )>::const_iterator first = commands.begin(), past = commands.end(); first != past; ++first ) { std::cout << '\t' << first->first << '\n'; } std::cout << std::endl; } int debug( int argc, char* argv[] ) { using namespace indexlib; using namespace indexlib::detail; std::string type = argv[ 2 ]; std::string argument = argv[ 3 ]; if ( type == "print.sa" ) { //nolog(); std::cout << "stringarray:\n"; stringarray sa( argument ); sa.print( std::cout ); } else if ( type == "print.compressed" ) { compressed_file file( argument ); nolog(); std::cout << "compressed_file:\n"; file.print( std::cout ); } else if ( type == "break_up" ) { std::auto_ptr<tokenizer> tok = get_tokenizer( "latin-1:european" ); if ( !tok.get() ) { std::cerr << "Could not get tokenizer\n"; return 1; } nolog(); std::ostringstream whole_str; whole_str << std::ifstream( argument.c_str() ).rdbuf(); std::vector<std::string> words = tok->string_to_words( whole_str.str().c_str() ); for ( std::vector<std::string>::const_iterator cur = words.begin(), past = words.end(); cur != past; ++cur ) { std::cout << *cur << '\n'; } } else { std::cerr << "Unknown function\n"; return 1; } return 0; } int remove_doc( int argc, char* argv[] ) { if ( argc < 4 ) { std::cerr << "Filename argument for remove_doc is required\n"; return 1; } index_smart t = get_index( argv[ 2 ] ); t->remove_doc( argv[ 3 ] ); return 0; } int maintenance( int argc, char* argv[] ) { index_smart t = get_index( argv[ 2 ] ); t->maintenance(); return 0; } int add( int argc, char* argv[] ) { if ( argc < 4 ) { std::cerr << "Input file argument is required\n" "Name is optional (defaults to filename)\n"; return 1; } index_smart t = get_index( argv[ 2 ] ); std::string input; if ( argv[ 4 ] ) input = argv[ 4 ]; else input = argv[ 3 ]; t->add( read_string( input ), argv[ 3 ] ); return 0; } int search( int argc, char* argv[] ) { if ( argc < 4 ) { std::cerr << "Search string is required\n"; return 1; } index_smart t = get_index( argv[ 2 ] ); std::vector<unsigned> files = t->search( argv[ 3 ] )->list(); for ( std::vector<unsigned>::const_iterator first = files.begin(), past = files.end(); first != past; ++first ) { std::cout << t->lookup_docname( *first ) << std::endl; } return 0; } int list( int argc, char* argv[] ) { index_smart t = get_index( argv[ 2 ] ); unsigned ndocs = t->ndocs(); for ( unsigned i = 0; i != ndocs; ++i ) { std::cout << t->lookup_docname( i ) << std::endl; } return 0; } int remove( int argc, char* argv[] ) { indexlib::remove( argv[ 2 ] ); } int main( int argc, char* argv[]) try { //nolog(); std::map<std::string, int (*)( int, char* [] )> handlers; handlers[ "debug" ] = &debug; handlers[ "remove" ] = &remove; handlers[ "remove_doc" ] = &remove_doc; handlers[ "maintenance" ] = &maintenance; handlers[ "add" ] = &add; handlers[ "search" ] = &search; handlers[ "list" ] = &list; if ( argc < 3 ) { usage( argc, argv, handlers ); return 0; } int ( *handle )( int, char*[] ) = handlers[ argv[ 1 ] ]; if ( handle ) return handle( argc, argv ); else { std::cerr << "Unkown command: " << argv[ 1 ] << std::endl; return 1; } } catch ( const char* msg ) { std::cerr << "Error: " << msg << std::endl; return 1; } catch ( std::exception& e ) { std::cerr << "Std Error: " << e.what() << std::endl; return 1; } catch ( ... ) { std::cerr << "Some Unspecified error\n"; return 1; } <|endoftext|>
<commit_before>//===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // FIXME: Document. // //===----------------------------------------------------------------------===// #include "CodeEmitterGen.h" #include "Record.h" #include "Support/Debug.h" using namespace llvm; void CodeEmitterGen::run(std::ostream &o) { std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction"); EmitSourceFileHeader("Machine Code Emitter", o); std::string Namespace = "V9::"; std::string ClassName = "SparcV9CodeEmitter::"; //const std::string &Namespace = Inst->getValue("Namespace")->getName(); o << "unsigned " << ClassName << "getBinaryCodeForInstr(MachineInstr &MI) {\n" << " unsigned Value = 0;\n" << " DEBUG(std::cerr << MI);\n" << " switch (MI.getOpcode()) {\n"; for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end(); I != E; ++I) { Record *R = *I; o << " case " << Namespace << R->getName() << ": {\n" << " DEBUG(std::cerr << \"Emitting " << R->getName() << "\\n\");\n"; BitsInit *BI = R->getValueAsBitsInit("Inst"); unsigned Value = 0; const std::vector<RecordVal> &Vals = R->getValues(); DEBUG(o << " // prefilling: "); // Start by filling in fixed values... for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) { if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1))) { Value |= B->getValue() << (e-i-1); DEBUG(o << B->getValue()); } else { DEBUG(o << "0"); } } DEBUG(o << "\n"); DEBUG(o << " // " << *R->getValue("Inst") << "\n"); o << " Value = " << Value << "U;\n\n"; // Loop over all of the fields in the instruction determining which are the // operands to the instruction. // unsigned op = 0; std::map<std::string, unsigned> OpOrder; std::map<std::string, bool> OpContinuous; for (unsigned i = 0, e = Vals.size(); i != e; ++i) { if (!Vals[i].getPrefix() && !Vals[i].getValue()->isComplete()) { // Is the operand continuous? If so, we can just mask and OR it in // instead of doing it bit-by-bit, saving a lot in runtime cost. const BitsInit *InstInit = BI; int beginBitInVar = -1, endBitInVar = -1; int beginBitInInst = -1, endBitInInst = -1; bool continuous = true; for (int bit = InstInit->getNumBits()-1; bit >= 0; --bit) { if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(InstInit->getBit(bit))) { TypedInit *TI = VBI->getVariable(); if (VarInit *VI = dynamic_cast<VarInit*>(TI)) { // only process the current variable if (VI->getName() != Vals[i].getName()) continue; if (beginBitInVar == -1) beginBitInVar = VBI->getBitNum(); if (endBitInVar == -1) endBitInVar = VBI->getBitNum(); else { if (endBitInVar == (int)VBI->getBitNum() + 1) endBitInVar = VBI->getBitNum(); else { continuous = false; break; } } if (beginBitInInst == -1) beginBitInInst = bit; if (endBitInInst == -1) endBitInInst = bit; else { if (endBitInInst == bit + 1) endBitInInst = bit; else { continuous = false; break; } } // maintain same distance between bits in field and bits in // instruction. if the relative distances stay the same // throughout, if (beginBitInVar - (int)VBI->getBitNum() != beginBitInInst - bit) { continuous = false; break; } } } } // If we have found no bit in "Inst" which comes from this field, then // this is not an operand!! if (beginBitInInst != -1) { o << " // op" << op << ": " << Vals[i].getName() << "\n" << " int64_t op" << op <<" = getMachineOpValue(MI, MI.getOperand("<<op<<"));\n"; //<< " MachineOperand &op" << op <<" = MI.getOperand("<<op<<");\n"; OpOrder[Vals[i].getName()] = op++; DEBUG(o << " // Var: begin = " << beginBitInVar << ", end = " << endBitInVar << "; Inst: begin = " << beginBitInInst << ", end = " << endBitInInst << "\n"); if (continuous) { DEBUG(o << " // continuous: op" << OpOrder[Vals[i].getName()] << "\n"); // Mask off the right bits // Low mask (ie. shift, if necessary) assert(endBitInVar >= 0 && "Negative shift amount in masking!"); if (endBitInVar != 0) { o << " op" << OpOrder[Vals[i].getName()] << " >>= " << endBitInVar << ";\n"; beginBitInVar -= endBitInVar; endBitInVar = 0; } // High mask o << " op" << OpOrder[Vals[i].getName()] << " &= (1<<" << beginBitInVar+1 << ") - 1;\n"; // Shift the value to the correct place (according to place in inst) assert(endBitInInst >= 0 && "Negative shift amount in inst position!"); if (endBitInInst != 0) o << " op" << OpOrder[Vals[i].getName()] << " <<= " << endBitInInst << ";\n"; // Just OR in the result o << " Value |= op" << OpOrder[Vals[i].getName()] << ";\n"; } // otherwise, will be taken care of in the loop below using this // value: OpContinuous[Vals[i].getName()] = continuous; } } } for (unsigned f = 0, e = Vals.size(); f != e; ++f) { if (Vals[f].getPrefix()) { BitsInit *FieldInitializer = (BitsInit*)Vals[f].getValue(); // Scan through the field looking for bit initializers of the current // variable... for (int i = FieldInitializer->getNumBits()-1; i >= 0; --i) { if (BitInit *BI = dynamic_cast<BitInit*>(FieldInitializer->getBit(i))) { DEBUG(o << " // bit init: f: " << f << ", i: " << i << "\n"); } else if (UnsetInit *UI = dynamic_cast<UnsetInit*>(FieldInitializer->getBit(i))) { DEBUG(o << " // unset init: f: " << f << ", i: " << i << "\n"); } else if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(FieldInitializer->getBit(i))) { TypedInit *TI = VBI->getVariable(); if (VarInit *VI = dynamic_cast<VarInit*>(TI)) { // If the bits of the field are laid out consecutively in the // instruction, then instead of separately ORing in bits, just // mask and shift the entire field for efficiency. if (OpContinuous[VI->getName()]) { // already taken care of in the loop above, thus there is no // need to individually OR in the bits // for debugging, output the regular version anyway, commented DEBUG(o << " // Value |= getValueBit(op" << OpOrder[VI->getName()] << ", " << VBI->getBitNum() << ")" << " << " << i << ";\n"); } else { o << " Value |= getValueBit(op" << OpOrder[VI->getName()] << ", " << VBI->getBitNum() << ")" << " << " << i << ";\n"; } } else if (FieldInit *FI = dynamic_cast<FieldInit*>(TI)) { // FIXME: implement this! o << "FIELD INIT not implemented yet!\n"; } else { o << "Error: UNIMPLEMENTED\n"; } } } } } o << " break;\n" << " }\n"; } o << " default:\n" << " std::cerr << \"Not supported instr: \" << MI << \"\\n\";\n" << " abort();\n" << " }\n" << " return Value;\n" << "}\n"; EmitSourceFileTail(o); } <commit_msg>* Added documentation in the file header * Shorten assert() text to make it fit within 80 cols<commit_after>//===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // CodeEmitterGen uses the descriptions of instructions and their fields to // construct an automated code emitter: a function that, given a MachineInstr, // returns the (currently, 32-bit unsigned) value of the instruction. // //===----------------------------------------------------------------------===// #include "CodeEmitterGen.h" #include "Record.h" #include "Support/Debug.h" using namespace llvm; void CodeEmitterGen::run(std::ostream &o) { std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction"); EmitSourceFileHeader("Machine Code Emitter", o); std::string Namespace = "V9::"; std::string ClassName = "SparcV9CodeEmitter::"; //const std::string &Namespace = Inst->getValue("Namespace")->getName(); o << "unsigned " << ClassName << "getBinaryCodeForInstr(MachineInstr &MI) {\n" << " unsigned Value = 0;\n" << " DEBUG(std::cerr << MI);\n" << " switch (MI.getOpcode()) {\n"; for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end(); I != E; ++I) { Record *R = *I; o << " case " << Namespace << R->getName() << ": {\n" << " DEBUG(std::cerr << \"Emitting " << R->getName() << "\\n\");\n"; BitsInit *BI = R->getValueAsBitsInit("Inst"); unsigned Value = 0; const std::vector<RecordVal> &Vals = R->getValues(); DEBUG(o << " // prefilling: "); // Start by filling in fixed values... for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) { if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1))) { Value |= B->getValue() << (e-i-1); DEBUG(o << B->getValue()); } else { DEBUG(o << "0"); } } DEBUG(o << "\n"); DEBUG(o << " // " << *R->getValue("Inst") << "\n"); o << " Value = " << Value << "U;\n\n"; // Loop over all of the fields in the instruction determining which are the // operands to the instruction. // unsigned op = 0; std::map<std::string, unsigned> OpOrder; std::map<std::string, bool> OpContinuous; for (unsigned i = 0, e = Vals.size(); i != e; ++i) { if (!Vals[i].getPrefix() && !Vals[i].getValue()->isComplete()) { // Is the operand continuous? If so, we can just mask and OR it in // instead of doing it bit-by-bit, saving a lot in runtime cost. const BitsInit *InstInit = BI; int beginBitInVar = -1, endBitInVar = -1; int beginBitInInst = -1, endBitInInst = -1; bool continuous = true; for (int bit = InstInit->getNumBits()-1; bit >= 0; --bit) { if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(InstInit->getBit(bit))) { TypedInit *TI = VBI->getVariable(); if (VarInit *VI = dynamic_cast<VarInit*>(TI)) { // only process the current variable if (VI->getName() != Vals[i].getName()) continue; if (beginBitInVar == -1) beginBitInVar = VBI->getBitNum(); if (endBitInVar == -1) endBitInVar = VBI->getBitNum(); else { if (endBitInVar == (int)VBI->getBitNum() + 1) endBitInVar = VBI->getBitNum(); else { continuous = false; break; } } if (beginBitInInst == -1) beginBitInInst = bit; if (endBitInInst == -1) endBitInInst = bit; else { if (endBitInInst == bit + 1) endBitInInst = bit; else { continuous = false; break; } } // maintain same distance between bits in field and bits in // instruction. if the relative distances stay the same // throughout, if (beginBitInVar - (int)VBI->getBitNum() != beginBitInInst - bit) { continuous = false; break; } } } } // If we have found no bit in "Inst" which comes from this field, then // this is not an operand!! if (beginBitInInst != -1) { o << " // op" << op << ": " << Vals[i].getName() << "\n" << " int64_t op" << op <<" = getMachineOpValue(MI, MI.getOperand("<<op<<"));\n"; //<< " MachineOperand &op" << op <<" = MI.getOperand("<<op<<");\n"; OpOrder[Vals[i].getName()] = op++; DEBUG(o << " // Var: begin = " << beginBitInVar << ", end = " << endBitInVar << "; Inst: begin = " << beginBitInInst << ", end = " << endBitInInst << "\n"); if (continuous) { DEBUG(o << " // continuous: op" << OpOrder[Vals[i].getName()] << "\n"); // Mask off the right bits // Low mask (ie. shift, if necessary) assert(endBitInVar >= 0 && "Negative shift amount in masking!"); if (endBitInVar != 0) { o << " op" << OpOrder[Vals[i].getName()] << " >>= " << endBitInVar << ";\n"; beginBitInVar -= endBitInVar; endBitInVar = 0; } // High mask o << " op" << OpOrder[Vals[i].getName()] << " &= (1<<" << beginBitInVar+1 << ") - 1;\n"; // Shift the value to the correct place (according to place in inst) assert(endBitInInst >= 0 && "Negative shift amount!"); if (endBitInInst != 0) o << " op" << OpOrder[Vals[i].getName()] << " <<= " << endBitInInst << ";\n"; // Just OR in the result o << " Value |= op" << OpOrder[Vals[i].getName()] << ";\n"; } // otherwise, will be taken care of in the loop below using this // value: OpContinuous[Vals[i].getName()] = continuous; } } } for (unsigned f = 0, e = Vals.size(); f != e; ++f) { if (Vals[f].getPrefix()) { BitsInit *FieldInitializer = (BitsInit*)Vals[f].getValue(); // Scan through the field looking for bit initializers of the current // variable... for (int i = FieldInitializer->getNumBits()-1; i >= 0; --i) { if (BitInit *BI = dynamic_cast<BitInit*>(FieldInitializer->getBit(i))) { DEBUG(o << " // bit init: f: " << f << ", i: " << i << "\n"); } else if (UnsetInit *UI = dynamic_cast<UnsetInit*>(FieldInitializer->getBit(i))) { DEBUG(o << " // unset init: f: " << f << ", i: " << i << "\n"); } else if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(FieldInitializer->getBit(i))) { TypedInit *TI = VBI->getVariable(); if (VarInit *VI = dynamic_cast<VarInit*>(TI)) { // If the bits of the field are laid out consecutively in the // instruction, then instead of separately ORing in bits, just // mask and shift the entire field for efficiency. if (OpContinuous[VI->getName()]) { // already taken care of in the loop above, thus there is no // need to individually OR in the bits // for debugging, output the regular version anyway, commented DEBUG(o << " // Value |= getValueBit(op" << OpOrder[VI->getName()] << ", " << VBI->getBitNum() << ")" << " << " << i << ";\n"); } else { o << " Value |= getValueBit(op" << OpOrder[VI->getName()] << ", " << VBI->getBitNum() << ")" << " << " << i << ";\n"; } } else if (FieldInit *FI = dynamic_cast<FieldInit*>(TI)) { // FIXME: implement this! o << "FIELD INIT not implemented yet!\n"; } else { o << "Error: UNIMPLEMENTED\n"; } } } } } o << " break;\n" << " }\n"; } o << " default:\n" << " std::cerr << \"Not supported instr: \" << MI << \"\\n\";\n" << " abort();\n" << " }\n" << " return Value;\n" << "}\n"; EmitSourceFileTail(o); } <|endoftext|>
<commit_before>//===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===// // // FIXME: Document. // //===----------------------------------------------------------------------===// #include "CodeEmitterGen.h" #include "Record.h" #include "Support/Debug.h" void CodeEmitterGen::run(std::ostream &o) { std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction"); EmitSourceFileHeader("Machine Code Emitter", o); std::string Namespace = "V9::"; std::string ClassName = "SparcV9CodeEmitter::"; //const std::string &Namespace = Inst->getValue("Namespace")->getName(); o << "unsigned " << ClassName << "getBinaryCodeForInstr(MachineInstr &MI) {\n" << " unsigned Value = 0;\n" << " DEBUG(std::cerr << MI);\n" << " switch (MI.getOpcode()) {\n"; for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end(); I != E; ++I) { Record *R = *I; o << " case " << Namespace << R->getName() << ": {\n" << " DEBUG(std::cerr << \"Emitting " << R->getName() << "\\n\");\n"; BitsInit *BI = R->getValueAsBitsInit("Inst"); unsigned Value = 0; const std::vector<RecordVal> &Vals = R->getValues(); DEBUG(o << " // prefilling: "); // Start by filling in fixed values... for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) { if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1))) { Value |= B->getValue() << (e-i-1); DEBUG(o << B->getValue()); } else { DEBUG(o << "0"); } } DEBUG(o << "\n"); DEBUG(o << " // " << *R->getValue("Inst") << "\n"); o << " Value = " << Value << "U;\n\n"; // Loop over all of the fields in the instruction determining which are the // operands to the instruction. // unsigned op = 0; std::map<std::string, unsigned> OpOrder; std::map<std::string, bool> OpContinuous; for (unsigned i = 0, e = Vals.size(); i != e; ++i) { if (!Vals[i].getPrefix() && !Vals[i].getValue()->isComplete()) { // Is the operand continuous? If so, we can just mask and OR it in // instead of doing it bit-by-bit, saving a lot in runtime cost. const BitsInit *InstInit = BI; int beginBitInVar = -1, endBitInVar = -1; int beginBitInInst = -1, endBitInInst = -1; bool continuous = true; for (int bit = InstInit->getNumBits()-1; bit >= 0; --bit) { if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(InstInit->getBit(bit))) { TypedInit *TI = VBI->getVariable(); if (VarInit *VI = dynamic_cast<VarInit*>(TI)) { // only process the current variable if (VI->getName() != Vals[i].getName()) continue; if (beginBitInVar == -1) beginBitInVar = VBI->getBitNum(); if (endBitInVar == -1) endBitInVar = VBI->getBitNum(); else { if (endBitInVar == (int)VBI->getBitNum() + 1) endBitInVar = VBI->getBitNum(); else { continuous = false; break; } } if (beginBitInInst == -1) beginBitInInst = bit; if (endBitInInst == -1) endBitInInst = bit; else { if (endBitInInst == bit + 1) endBitInInst = bit; else { continuous = false; break; } } // maintain same distance between bits in field and bits in // instruction. if the relative distances stay the same // throughout, if (beginBitInVar - (int)VBI->getBitNum() != beginBitInInst - bit) { continuous = false; break; } } } } // If we have found no bit in "Inst" which comes from this field, then // this is not an operand!! if (beginBitInInst != -1) { o << " // op" << op << ": " << Vals[i].getName() << "\n" << " int64_t op" << op <<" = getMachineOpValue(MI, MI.getOperand("<<op<<"));\n"; //<< " MachineOperand &op" << op <<" = MI.getOperand("<<op<<");\n"; OpOrder[Vals[i].getName()] = op++; DEBUG(o << " // Var: begin = " << beginBitInVar << ", end = " << endBitInVar << "; Inst: begin = " << beginBitInInst << ", end = " << endBitInInst << "\n"); if (continuous) { DEBUG(o << " // continuous: op" << OpOrder[Vals[i].getName()] << "\n"); // Mask off the right bits // Low mask (ie. shift, if necessary) assert(endBitInVar >= 0 && "Negative shift amount in masking!"); if (endBitInVar != 0) { o << " op" << OpOrder[Vals[i].getName()] << " >>= " << endBitInVar << ";\n"; beginBitInVar -= endBitInVar; endBitInVar = 0; } // High mask o << " op" << OpOrder[Vals[i].getName()] << " &= (1<<" << beginBitInVar+1 << ") - 1;\n"; // Shift the value to the correct place (according to place in inst) assert(endBitInInst >= 0 && "Negative shift amount in inst position!"); if (endBitInInst != 0) o << " op" << OpOrder[Vals[i].getName()] << " <<= " << endBitInInst << ";\n"; // Just OR in the result o << " Value |= op" << OpOrder[Vals[i].getName()] << ";\n"; } // otherwise, will be taken care of in the loop below using this // value: OpContinuous[Vals[i].getName()] = continuous; } } } for (unsigned f = 0, e = Vals.size(); f != e; ++f) { if (Vals[f].getPrefix()) { BitsInit *FieldInitializer = (BitsInit*)Vals[f].getValue(); // Scan through the field looking for bit initializers of the current // variable... for (int i = FieldInitializer->getNumBits()-1; i >= 0; --i) { if (BitInit *BI = dynamic_cast<BitInit*>(FieldInitializer->getBit(i))) { DEBUG(o << " // bit init: f: " << f << ", i: " << i << "\n"); } else if (UnsetInit *UI = dynamic_cast<UnsetInit*>(FieldInitializer->getBit(i))) { DEBUG(o << " // unset init: f: " << f << ", i: " << i << "\n"); } else if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(FieldInitializer->getBit(i))) { TypedInit *TI = VBI->getVariable(); if (VarInit *VI = dynamic_cast<VarInit*>(TI)) { // If the bits of the field are laid out consecutively in the // instruction, then instead of separately ORing in bits, just // mask and shift the entire field for efficiency. if (OpContinuous[VI->getName()]) { // already taken care of in the loop above, thus there is no // need to individually OR in the bits // for debugging, output the regular version anyway, commented DEBUG(o << " // Value |= getValueBit(op" << OpOrder[VI->getName()] << ", " << VBI->getBitNum() << ")" << " << " << i << ";\n"); } else { o << " Value |= getValueBit(op" << OpOrder[VI->getName()] << ", " << VBI->getBitNum() << ")" << " << " << i << ";\n"; } } else if (FieldInit *FI = dynamic_cast<FieldInit*>(TI)) { // FIXME: implement this! o << "FIELD INIT not implemented yet!\n"; } else { o << "Error: UNIMPLEMENTED\n"; } } } } } o << " break;\n" << " }\n"; } o << " default:\n" << " DEBUG(std::cerr << \"Not supported instr: \" << MI << \"\\n\");\n" << " abort();\n" << " }\n" << " return Value;\n" << "}\n"; } <commit_msg>Do not put DEBUG() guard around error condition; this must *always* be printed.<commit_after>//===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===// // // FIXME: Document. // //===----------------------------------------------------------------------===// #include "CodeEmitterGen.h" #include "Record.h" #include "Support/Debug.h" void CodeEmitterGen::run(std::ostream &o) { std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction"); EmitSourceFileHeader("Machine Code Emitter", o); std::string Namespace = "V9::"; std::string ClassName = "SparcV9CodeEmitter::"; //const std::string &Namespace = Inst->getValue("Namespace")->getName(); o << "unsigned " << ClassName << "getBinaryCodeForInstr(MachineInstr &MI) {\n" << " unsigned Value = 0;\n" << " DEBUG(std::cerr << MI);\n" << " switch (MI.getOpcode()) {\n"; for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end(); I != E; ++I) { Record *R = *I; o << " case " << Namespace << R->getName() << ": {\n" << " DEBUG(std::cerr << \"Emitting " << R->getName() << "\\n\");\n"; BitsInit *BI = R->getValueAsBitsInit("Inst"); unsigned Value = 0; const std::vector<RecordVal> &Vals = R->getValues(); DEBUG(o << " // prefilling: "); // Start by filling in fixed values... for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) { if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1))) { Value |= B->getValue() << (e-i-1); DEBUG(o << B->getValue()); } else { DEBUG(o << "0"); } } DEBUG(o << "\n"); DEBUG(o << " // " << *R->getValue("Inst") << "\n"); o << " Value = " << Value << "U;\n\n"; // Loop over all of the fields in the instruction determining which are the // operands to the instruction. // unsigned op = 0; std::map<std::string, unsigned> OpOrder; std::map<std::string, bool> OpContinuous; for (unsigned i = 0, e = Vals.size(); i != e; ++i) { if (!Vals[i].getPrefix() && !Vals[i].getValue()->isComplete()) { // Is the operand continuous? If so, we can just mask and OR it in // instead of doing it bit-by-bit, saving a lot in runtime cost. const BitsInit *InstInit = BI; int beginBitInVar = -1, endBitInVar = -1; int beginBitInInst = -1, endBitInInst = -1; bool continuous = true; for (int bit = InstInit->getNumBits()-1; bit >= 0; --bit) { if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(InstInit->getBit(bit))) { TypedInit *TI = VBI->getVariable(); if (VarInit *VI = dynamic_cast<VarInit*>(TI)) { // only process the current variable if (VI->getName() != Vals[i].getName()) continue; if (beginBitInVar == -1) beginBitInVar = VBI->getBitNum(); if (endBitInVar == -1) endBitInVar = VBI->getBitNum(); else { if (endBitInVar == (int)VBI->getBitNum() + 1) endBitInVar = VBI->getBitNum(); else { continuous = false; break; } } if (beginBitInInst == -1) beginBitInInst = bit; if (endBitInInst == -1) endBitInInst = bit; else { if (endBitInInst == bit + 1) endBitInInst = bit; else { continuous = false; break; } } // maintain same distance between bits in field and bits in // instruction. if the relative distances stay the same // throughout, if (beginBitInVar - (int)VBI->getBitNum() != beginBitInInst - bit) { continuous = false; break; } } } } // If we have found no bit in "Inst" which comes from this field, then // this is not an operand!! if (beginBitInInst != -1) { o << " // op" << op << ": " << Vals[i].getName() << "\n" << " int64_t op" << op <<" = getMachineOpValue(MI, MI.getOperand("<<op<<"));\n"; //<< " MachineOperand &op" << op <<" = MI.getOperand("<<op<<");\n"; OpOrder[Vals[i].getName()] = op++; DEBUG(o << " // Var: begin = " << beginBitInVar << ", end = " << endBitInVar << "; Inst: begin = " << beginBitInInst << ", end = " << endBitInInst << "\n"); if (continuous) { DEBUG(o << " // continuous: op" << OpOrder[Vals[i].getName()] << "\n"); // Mask off the right bits // Low mask (ie. shift, if necessary) assert(endBitInVar >= 0 && "Negative shift amount in masking!"); if (endBitInVar != 0) { o << " op" << OpOrder[Vals[i].getName()] << " >>= " << endBitInVar << ";\n"; beginBitInVar -= endBitInVar; endBitInVar = 0; } // High mask o << " op" << OpOrder[Vals[i].getName()] << " &= (1<<" << beginBitInVar+1 << ") - 1;\n"; // Shift the value to the correct place (according to place in inst) assert(endBitInInst >= 0 && "Negative shift amount in inst position!"); if (endBitInInst != 0) o << " op" << OpOrder[Vals[i].getName()] << " <<= " << endBitInInst << ";\n"; // Just OR in the result o << " Value |= op" << OpOrder[Vals[i].getName()] << ";\n"; } // otherwise, will be taken care of in the loop below using this // value: OpContinuous[Vals[i].getName()] = continuous; } } } for (unsigned f = 0, e = Vals.size(); f != e; ++f) { if (Vals[f].getPrefix()) { BitsInit *FieldInitializer = (BitsInit*)Vals[f].getValue(); // Scan through the field looking for bit initializers of the current // variable... for (int i = FieldInitializer->getNumBits()-1; i >= 0; --i) { if (BitInit *BI = dynamic_cast<BitInit*>(FieldInitializer->getBit(i))) { DEBUG(o << " // bit init: f: " << f << ", i: " << i << "\n"); } else if (UnsetInit *UI = dynamic_cast<UnsetInit*>(FieldInitializer->getBit(i))) { DEBUG(o << " // unset init: f: " << f << ", i: " << i << "\n"); } else if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(FieldInitializer->getBit(i))) { TypedInit *TI = VBI->getVariable(); if (VarInit *VI = dynamic_cast<VarInit*>(TI)) { // If the bits of the field are laid out consecutively in the // instruction, then instead of separately ORing in bits, just // mask and shift the entire field for efficiency. if (OpContinuous[VI->getName()]) { // already taken care of in the loop above, thus there is no // need to individually OR in the bits // for debugging, output the regular version anyway, commented DEBUG(o << " // Value |= getValueBit(op" << OpOrder[VI->getName()] << ", " << VBI->getBitNum() << ")" << " << " << i << ";\n"); } else { o << " Value |= getValueBit(op" << OpOrder[VI->getName()] << ", " << VBI->getBitNum() << ")" << " << " << i << ";\n"; } } else if (FieldInit *FI = dynamic_cast<FieldInit*>(TI)) { // FIXME: implement this! o << "FIELD INIT not implemented yet!\n"; } else { o << "Error: UNIMPLEMENTED\n"; } } } } } o << " break;\n" << " }\n"; } o << " default:\n" << " std::cerr << \"Not supported instr: \" << MI << \"\\n\";\n" << " abort();\n" << " }\n" << " return Value;\n" << "}\n"; } <|endoftext|>
<commit_before>// // Created by michael on 10.08.15. // #include <Template/TemplateEngine.h> using namespace std; using namespace weave; shared_ptr<QuestTemplate> TemplateEngine::GetTemplateForNewQuest() { if (factories.size() == 0) { throw ContractFailedException("No factory defined to create template.\n"); } auto factoryIndex = randomStream->GetRandomIndex(factories.size()); shared_ptr<QuestTemplateFactory> factory = factories.at(factoryIndex); auto factoryKeys = factory->GetTemplateKeys(); if (factoryKeys.size() == 0) { throw ContractFailedException("No templates defined in template factory.\n"); } auto templateIndex = randomStream->GetRandomIndex(factoryKeys.size()); auto key = factoryKeys.at(templateIndex); cout << "Creating template with key: " << key << endl; return factory->CreateTemplate(key); } void TemplateEngine::RegisterTemplateFactory(std::shared_ptr<QuestTemplateFactory> factory) { for (auto f : factories) { if (f.get() == factory.get()) { return; } } factory->randomStream = randomStream; factory->dirs = dirs; factory->formatterType = format; factories.push_back(factory); } TemplateEngine::TemplateEngine(std::shared_ptr<RandomStream> randomStream, Directories dirs, FormatterType format) : randomStream(randomStream), dirs(dirs), format(format) { } void weave::TemplateEngine::ChangeDirectories(Directories newDirs) { dirs = newDirs; for (auto factory : factories) { factory->dirs = dirs; } } FormatterType TemplateEngine::GetFormat() const { return format; } <commit_msg>Removed debug output<commit_after>// // Created by michael on 10.08.15. // #include <Template/TemplateEngine.h> using namespace std; using namespace weave; shared_ptr<QuestTemplate> TemplateEngine::GetTemplateForNewQuest() { if (factories.size() == 0) { throw ContractFailedException("No factory defined to create template.\n"); } auto factoryIndex = randomStream->GetRandomIndex(factories.size()); shared_ptr<QuestTemplateFactory> factory = factories.at(factoryIndex); auto factoryKeys = factory->GetTemplateKeys(); if (factoryKeys.size() == 0) { throw ContractFailedException("No templates defined in template factory.\n"); } auto templateIndex = randomStream->GetRandomIndex(factoryKeys.size()); auto key = factoryKeys.at(templateIndex); return factory->CreateTemplate(key); } void TemplateEngine::RegisterTemplateFactory(std::shared_ptr<QuestTemplateFactory> factory) { for (auto f : factories) { if (f.get() == factory.get()) { return; } } factory->randomStream = randomStream; factory->dirs = dirs; factory->formatterType = format; factories.push_back(factory); } TemplateEngine::TemplateEngine(std::shared_ptr<RandomStream> randomStream, Directories dirs, FormatterType format) : randomStream(randomStream), dirs(dirs), format(format) { } void weave::TemplateEngine::ChangeDirectories(Directories newDirs) { dirs = newDirs; for (auto factory : factories) { factory->dirs = dirs; } } FormatterType TemplateEngine::GetFormat() const { return format; } <|endoftext|>
<commit_before>/* * This file is part of meego-im-framework * * * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * Contact: Nokia Corporation (directui@nokia.com) * * If you have questions regarding the use of this file, please contact * Nokia at directui@nokia.com. * * 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 * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "mimgraphicsview_p.h" #include "mimgraphicsview.h" #if defined(Q_WS_X11) #include "mimxapplication.h" #endif #include <QDebug> MImGraphicsViewPrivate::MImGraphicsViewPrivate() : q_ptr(0) {} MImGraphicsViewPrivate::~MImGraphicsViewPrivate() {} MImGraphicsView::MImGraphicsView(QWidget *parent) : QGraphicsView(parent) , d_ptr(new MImGraphicsViewPrivate) { init(); } MImGraphicsView::MImGraphicsView(QGraphicsScene *scene, QWidget *parent) : QGraphicsView(scene, parent) , d_ptr(new MImGraphicsViewPrivate) { init(); } MImGraphicsView::MImGraphicsView(MImGraphicsViewPrivate *dd, QGraphicsScene *scene, QWidget *parent) : QGraphicsView(scene, parent) , d_ptr(dd) { init(); } MImGraphicsView::~MImGraphicsView() { delete d_ptr; } void MImGraphicsView::init() { Q_D(MImGraphicsView); d->q_ptr = this; setAttribute(Qt::WA_OpaquePaintEvent); setAttribute(Qt::WA_NoSystemBackground); if (viewport()) { viewport()->setAttribute(Qt::WA_OpaquePaintEvent); viewport()->setAttribute(Qt::WA_NoSystemBackground); } else { qWarning() << __PRETTY_FUNCTION__ << "Could not find viewport - unable to set window attributes!"; } } void MImGraphicsView::drawBackground(QPainter *painter, const QRectF &rect) { if (rect.isEmpty()) { return; } #if defined(Q_WS_X11) const QPixmap &bg(MImXApplication::instance()->remoteWindowPixmap()); if (not bg.isNull()) { painter->drawPixmap(rect.toRect(), bg, rect.toRect()); } #else return; #endif } <commit_msg>Fix unused argument error<commit_after>/* * This file is part of meego-im-framework * * * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * Contact: Nokia Corporation (directui@nokia.com) * * If you have questions regarding the use of this file, please contact * Nokia at directui@nokia.com. * * 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 * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "mimgraphicsview_p.h" #include "mimgraphicsview.h" #if defined(Q_WS_X11) #include "mimxapplication.h" #endif #include <QDebug> MImGraphicsViewPrivate::MImGraphicsViewPrivate() : q_ptr(0) {} MImGraphicsViewPrivate::~MImGraphicsViewPrivate() {} MImGraphicsView::MImGraphicsView(QWidget *parent) : QGraphicsView(parent) , d_ptr(new MImGraphicsViewPrivate) { init(); } MImGraphicsView::MImGraphicsView(QGraphicsScene *scene, QWidget *parent) : QGraphicsView(scene, parent) , d_ptr(new MImGraphicsViewPrivate) { init(); } MImGraphicsView::MImGraphicsView(MImGraphicsViewPrivate *dd, QGraphicsScene *scene, QWidget *parent) : QGraphicsView(scene, parent) , d_ptr(dd) { init(); } MImGraphicsView::~MImGraphicsView() { delete d_ptr; } void MImGraphicsView::init() { Q_D(MImGraphicsView); d->q_ptr = this; setAttribute(Qt::WA_OpaquePaintEvent); setAttribute(Qt::WA_NoSystemBackground); if (viewport()) { viewport()->setAttribute(Qt::WA_OpaquePaintEvent); viewport()->setAttribute(Qt::WA_NoSystemBackground); } else { qWarning() << __PRETTY_FUNCTION__ << "Could not find viewport - unable to set window attributes!"; } } void MImGraphicsView::drawBackground(QPainter *painter, const QRectF &rect) { if (rect.isEmpty()) { return; } #if defined(Q_WS_X11) const QPixmap &bg(MImXApplication::instance()->remoteWindowPixmap()); if (not bg.isNull()) { painter->drawPixmap(rect.toRect(), bg, rect.toRect()); } #else Q_UNUSED(painter); return; #endif } <|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2011 \file main.cpp \author Урусов Андрей (rdo@rk9.bmstu.ru) \authors Пройдаков Евгений (lord.tiran@gmail.com) \date 10.05.2009 \brief Тест common-библиотеки \indent 4T */ // ----------------------------------------------------------------------- PLATFORM #include "utils/src/common/platform.h" // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- INCLUDES #define BOOST_TEST_MODULE RDOCommon_Test #include <boost/test/included/unit_test.hpp> #include <boost/format.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "utils/src/common/rdocommon.h" #include "utils/src/file/rdofile.h" #include "utils/src/time/rdotime.h" #include "utils/src/locale/rdolocale.h" // -------------------------------------------------------------------------------- const tstring s_testFileName("test_file"); const ruint64 s_createTestLocalTime = 129557633912040000; BOOST_AUTO_TEST_SUITE(RDOCommon_Test) BOOST_AUTO_TEST_CASE(RDOCommon_FileCreate) { rdo::locale::init(); BOOST_CHECK(rdo::File::create(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileExist) { BOOST_CHECK(rdo::File::exist(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileReadOnly) { BOOST_CHECK(!rdo::File::read_only(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileRemove) { BOOST_CHECK(rdo::File::unlink(s_testFileName)); } #ifdef OST_LINUX BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInLinux) { boost::filesystem::path file(rdo::locale::convertToWStr("/rdo/русский пробел/files/проект.smr")); boost::filesystem::path dir; boost::filesystem::path name; boost::filesystem::path ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == rdo::locale::convertToWStr("/rdo/русский пробел/files/")); BOOST_CHECK(name == rdo::locale::convertToWStr("проект")); BOOST_CHECK(ext == rdo::locale::convertToWStr(".smr")); BOOST_CHECK(rdo::locale::convertFromWStr(dir.wstring()) == "/rdo/русский пробел/files/"); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInLinux) { boost::filesystem::path file(rdo::locale::convertToWStr("/проект.smr")); boost::filesystem::path dir; boost::filesystem::path name; boost::filesystem::path ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == rdo::locale::convertToWStr("/")); BOOST_CHECK(name == rdo::locale::convertToWStr("проект")); BOOST_CHECK(ext == rdo::locale::convertToWStr(".smr")); } #endif #ifdef OST_WINDOWS BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInWindows) { boost::filesystem::path file(rdo::locale::convertToWStr("C:/rdo/русский пробел/files/проект.smr")); boost::filesystem::path dir; boost::filesystem::path name; boost::filesystem::path ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == rdo::locale::convertToWStr("C:\\rdo\\русский пробел\\files\\")); BOOST_CHECK(name == rdo::locale::convertToWStr("проект")); BOOST_CHECK(ext == rdo::locale::convertToWStr(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInWindows) { boost::filesystem::path file(rdo::locale::convertToWStr("C:/проект.smr")); boost::filesystem::path dir; boost::filesystem::path name; boost::filesystem::path ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == rdo::locale::convertToWStr("C:\\")); BOOST_CHECK(name == rdo::locale::convertToWStr("проект")); BOOST_CHECK(ext == rdo::locale::convertToWStr(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInWindows_BackSlash) { boost::filesystem::path file(rdo::locale::convertToWStr("C:\\rdo\\русский пробел\\files\\проект.smr")); boost::filesystem::path dir; boost::filesystem::path name; boost::filesystem::path ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == rdo::locale::convertToWStr("C:\\rdo\\русский пробел\\files\\")); BOOST_CHECK(name == rdo::locale::convertToWStr("проект")); BOOST_CHECK(ext == rdo::locale::convertToWStr(".smr")); BOOST_CHECK(rdo::locale::convertFromWStr(dir.wstring()) == "C:\\rdo\\русский пробел\\files\\"); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInWindows_BackSlash) { boost::filesystem::path file(rdo::locale::convertToWStr("C:\\проект.smr")); boost::filesystem::path dir; boost::filesystem::path name; boost::filesystem::path ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == rdo::locale::convertToWStr("C:\\")); BOOST_CHECK(name == rdo::locale::convertToWStr("проект")); BOOST_CHECK(ext == rdo::locale::convertToWStr(".smr")); } #endif // #endif BOOST_AUTO_TEST_CASE(RDOCommon_GetTempFile) { std::set<boost::filesystem::path> nameSet; for (int i = 0; i < 15; ++i) { boost::filesystem::path fileName = rdo::File::getTempFileName(); rdo::File::unlink(fileName); BOOST_CHECK(nameSet.find(fileName) == nameSet.end()); nameSet.insert(fileName); } } BOOST_AUTO_TEST_CASE(RDOCommon_Time) { rdo::Time timeValue = rdo::Time::local(); BOOST_CHECK(timeValue > s_createTestLocalTime); std::wcout << rdo::locale::convertToWStr(boost::str( boost::format("Today: %1%, is not it?") % timeValue.asString())) << std::endl; } BOOST_AUTO_TEST_SUITE_END() // RDOCommon_Test <commit_msg> - remove output<commit_after>/*! \copyright (c) RDO-Team, 2011 \file main.cpp \author Урусов Андрей (rdo@rk9.bmstu.ru) \authors Пройдаков Евгений (lord.tiran@gmail.com) \date 10.05.2009 \brief Тест common-библиотеки \indent 4T */ // ----------------------------------------------------------------------- PLATFORM #include "utils/src/common/platform.h" // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- INCLUDES #define BOOST_TEST_MODULE RDOCommon_Test #include <boost/test/included/unit_test.hpp> #include <boost/format.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "utils/src/common/rdocommon.h" #include "utils/src/file/rdofile.h" #include "utils/src/time/rdotime.h" #include "utils/src/locale/rdolocale.h" // -------------------------------------------------------------------------------- const tstring s_testFileName("test_file"); const ruint64 s_createTestLocalTime = 129557633912040000; BOOST_AUTO_TEST_SUITE(RDOCommon_Test) BOOST_AUTO_TEST_CASE(RDOCommon_FileCreate) { rdo::locale::init(); BOOST_CHECK(rdo::File::create(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileExist) { BOOST_CHECK(rdo::File::exist(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileReadOnly) { BOOST_CHECK(!rdo::File::read_only(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileRemove) { BOOST_CHECK(rdo::File::unlink(s_testFileName)); } #ifdef OST_LINUX BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInLinux) { boost::filesystem::path file(rdo::locale::convertToWStr("/rdo/русский пробел/files/проект.smr")); boost::filesystem::path dir; boost::filesystem::path name; boost::filesystem::path ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == rdo::locale::convertToWStr("/rdo/русский пробел/files/")); BOOST_CHECK(name == rdo::locale::convertToWStr("проект")); BOOST_CHECK(ext == rdo::locale::convertToWStr(".smr")); BOOST_CHECK(rdo::locale::convertFromWStr(dir.wstring()) == "/rdo/русский пробел/files/"); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInLinux) { boost::filesystem::path file(rdo::locale::convertToWStr("/проект.smr")); boost::filesystem::path dir; boost::filesystem::path name; boost::filesystem::path ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == rdo::locale::convertToWStr("/")); BOOST_CHECK(name == rdo::locale::convertToWStr("проект")); BOOST_CHECK(ext == rdo::locale::convertToWStr(".smr")); } #endif #ifdef OST_WINDOWS BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInWindows) { boost::filesystem::path file(rdo::locale::convertToWStr("C:/rdo/русский пробел/files/проект.smr")); boost::filesystem::path dir; boost::filesystem::path name; boost::filesystem::path ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == rdo::locale::convertToWStr("C:\\rdo\\русский пробел\\files\\")); BOOST_CHECK(name == rdo::locale::convertToWStr("проект")); BOOST_CHECK(ext == rdo::locale::convertToWStr(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInWindows) { boost::filesystem::path file(rdo::locale::convertToWStr("C:/проект.smr")); boost::filesystem::path dir; boost::filesystem::path name; boost::filesystem::path ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == rdo::locale::convertToWStr("C:\\")); BOOST_CHECK(name == rdo::locale::convertToWStr("проект")); BOOST_CHECK(ext == rdo::locale::convertToWStr(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInWindows_BackSlash) { boost::filesystem::path file(rdo::locale::convertToWStr("C:\\rdo\\русский пробел\\files\\проект.smr")); boost::filesystem::path dir; boost::filesystem::path name; boost::filesystem::path ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == rdo::locale::convertToWStr("C:\\rdo\\русский пробел\\files\\")); BOOST_CHECK(name == rdo::locale::convertToWStr("проект")); BOOST_CHECK(ext == rdo::locale::convertToWStr(".smr")); BOOST_CHECK(rdo::locale::convertFromWStr(dir.wstring()) == "C:\\rdo\\русский пробел\\files\\"); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInWindows_BackSlash) { boost::filesystem::path file(rdo::locale::convertToWStr("C:\\проект.smr")); boost::filesystem::path dir; boost::filesystem::path name; boost::filesystem::path ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == rdo::locale::convertToWStr("C:\\")); BOOST_CHECK(name == rdo::locale::convertToWStr("проект")); BOOST_CHECK(ext == rdo::locale::convertToWStr(".smr")); } #endif // #endif BOOST_AUTO_TEST_CASE(RDOCommon_GetTempFile) { std::set<boost::filesystem::path> nameSet; for (int i = 0; i < 15; ++i) { boost::filesystem::path fileName = rdo::File::getTempFileName(); rdo::File::unlink(fileName); BOOST_CHECK(nameSet.find(fileName) == nameSet.end()); nameSet.insert(fileName); } } BOOST_AUTO_TEST_CASE(RDOCommon_Time) { rdo::Time timeValue = rdo::Time::local(); BOOST_CHECK(timeValue > s_createTestLocalTime); } BOOST_AUTO_TEST_SUITE_END() // RDOCommon_Test <|endoftext|>
<commit_before>/* QSyncable Project Author: Ben Lau License: Apache-2.0 Web: https://github.com/benlau/qsyncable */ #include "qspatch.h" class QSPatchPriv : public QSharedData { public: QSPatchPriv() { from = 0; to = 0; type = QSPatch::Null; count = 0; } QSPatch::Type type; QVariantList data; int from; int to; int count; }; QSPatch::QSPatch() : d(new QSPatchPriv) { } QSPatch::QSPatch(QSPatch::Type type, int from, int to, int count) : d(new QSPatchPriv) { d->type = type; d->from = from; d->to = to; d->count = count; } QSPatch::QSPatch(QSPatch::Type type, int from, int to, int count, const QVariantMap& data) : d(new QSPatchPriv) { d->type = type; d->from = from; d->to = to; d->count = count; d->data.append(data); } QSPatch::QSPatch(Type type,int from, int to, int count, const QVariantList& data) : d(new QSPatchPriv) { d->type = type; d->from = from; d->to = to; d->count = count; d->data = data; } QSPatch::QSPatch(const QSPatch &rhs) : d(rhs.d) { } QSPatch &QSPatch::operator=(const QSPatch &rhs) { if (this != &rhs) d.operator=(rhs.d); return *this; } QSPatch::~QSPatch() { } QSPatch::Type QSPatch::type() const { return d->type; } void QSPatch::setType(const QSPatch::Type &type) { d->type = type; } QVariantList QSPatch::data() const { return d->data; } void QSPatch::setData(const QVariantList &data) { d->data = data; } void QSPatch::setData(const QVariantMap &data) { d->data.clear(); d->data.append(data); } bool QSPatch::operator==(const QSPatch &rhs) const { if (d->type != rhs.d->type || d->data != rhs.data() || d->from != rhs.from() || d->to != rhs.to() || d->count != rhs.count()) { return false; } return true; } int QSPatch::from() const { return d->from; } void QSPatch::setFrom(int from) { d->from = from; } int QSPatch::to() const { return d->to; } void QSPatch::setTo(int to) { d->to = to; } bool QSPatch::isNull() const { return d->type == QSPatch::Null; } int QSPatch::count() const { return d->count; } void QSPatch::setCount(int count) { d->count = count; } bool QSPatch::canMerge(const QSPatch &other) const { bool res = false; if (d->type != other.type()) { return false; } if (d->type == QSPatch::Remove) { if (d->from == other.to() + 1 || d->to == other.from() - 1) { res = true; } } else if (d->type == QSPatch::Move) { if (d->from + d->count == other.from() && d->to + d->count == other.to() ) { res = true; } } else if (d->type == QSPatch::Insert) { if (d->from == other.from() || d->to == other.from() - 1) { res = true; } } return res; } QSPatch QSPatch::merged(const QSPatch &other) const { if (!canMerge(other)) { return QSPatch(); } QSPatch res = *this; res.merge(other); return res; } QSPatch &QSPatch::merge(const QSPatch &other) { if (!canMerge(other)) return (*this); if (d->type == QSPatch::Remove) { d->from = qMin(d->from, other.from()); d->to = qMax(d->to, other.to()); d->count = d->to - d->from + 1; } else if (d->type == QSPatch::Move) { d->count = d->count + other.count(); } else if (d->type == QSPatch::Insert) { d->data.append(other.data()); d->to = d->from + d->data.count() - 1; d->count = d->data.count(); } return *this; } QSPatch QSPatch::createUpdate(int index, const QVariantMap &diff) { return QSPatch(QSPatch::Update, index, index, 1, diff); } QDebug operator<<(QDebug dbg, const QSPatch& change){ switch (change.type()) { case QSPatch::Remove: dbg << QString("Remove from %1 to %2").arg(change.from()).arg(change.to()); break; case QSPatch::Move: dbg << QString("Move from %1 to %2 with %3").arg(change.from()).arg(change.to()).arg(change.count()); break; case QSPatch::Insert: dbg << QString("Insert from %1 to %2 with %3").arg(change.from()).arg(change.to()).arg(change.count()); dbg << change.data(); break; case QSPatch::Update: dbg << QString("Update %12").arg(change.from()); dbg << change.data(); break; default: dbg << "Null"; break; } return dbg; } <commit_msg>QSPatch : Change "data" storage type from QVariantList to QVariant<commit_after>/* QSyncable Project Author: Ben Lau License: Apache-2.0 Web: https://github.com/benlau/qsyncable */ #include "qspatch.h" class QSPatchPriv : public QSharedData { public: QSPatchPriv() { from = 0; to = 0; type = QSPatch::Null; count = 0; } QSPatch::Type type; QVariant data; int from; int to; int count; }; QSPatch::QSPatch() : d(new QSPatchPriv) { } QSPatch::QSPatch(QSPatch::Type type, int from, int to, int count) : d(new QSPatchPriv) { d->type = type; d->from = from; d->to = to; d->count = count; } QSPatch::QSPatch(QSPatch::Type type, int from, int to, int count, const QVariantMap& data) : d(new QSPatchPriv) { d->type = type; d->from = from; d->to = to; d->count = count; QVariantList list; list.append(data); d->data = list; } QSPatch::QSPatch(Type type,int from, int to, int count, const QVariantList& data) : d(new QSPatchPriv) { d->type = type; d->from = from; d->to = to; d->count = count; d->data = data; } QSPatch::QSPatch(const QSPatch &rhs) : d(rhs.d) { } QSPatch &QSPatch::operator=(const QSPatch &rhs) { if (this != &rhs) d.operator=(rhs.d); return *this; } QSPatch::~QSPatch() { } QSPatch::Type QSPatch::type() const { return d->type; } void QSPatch::setType(const QSPatch::Type &type) { d->type = type; } QVariantList QSPatch::data() const { return d->data.toList(); } void QSPatch::setData(const QVariantList &data) { d->data = data; } void QSPatch::setData(const QVariantMap &data) { QVariantList list; list << data; d->data = list; } bool QSPatch::operator==(const QSPatch &rhs) const { if (d->type != rhs.d->type || d->data.toList() != rhs.data() || d->from != rhs.from() || d->to != rhs.to() || d->count != rhs.count()) { return false; } return true; } int QSPatch::from() const { return d->from; } void QSPatch::setFrom(int from) { d->from = from; } int QSPatch::to() const { return d->to; } void QSPatch::setTo(int to) { d->to = to; } bool QSPatch::isNull() const { return d->type == QSPatch::Null; } int QSPatch::count() const { return d->count; } void QSPatch::setCount(int count) { d->count = count; } bool QSPatch::canMerge(const QSPatch &other) const { bool res = false; if (d->type != other.type()) { return false; } if (d->type == QSPatch::Remove) { if (d->from == other.to() + 1 || d->to == other.from() - 1) { res = true; } } else if (d->type == QSPatch::Move) { if (d->from + d->count == other.from() && d->to + d->count == other.to() ) { res = true; } } else if (d->type == QSPatch::Insert) { if (d->from == other.from() || d->to == other.from() - 1) { res = true; } } return res; } QSPatch QSPatch::merged(const QSPatch &other) const { if (!canMerge(other)) { return QSPatch(); } QSPatch res = *this; res.merge(other); return res; } QSPatch &QSPatch::merge(const QSPatch &other) { if (!canMerge(other)) return (*this); if (d->type == QSPatch::Remove) { d->from = qMin(d->from, other.from()); d->to = qMax(d->to, other.to()); d->count = d->to - d->from + 1; } else if (d->type == QSPatch::Move) { d->count = d->count + other.count(); } else if (d->type == QSPatch::Insert) { QVariantList list = d->data.toList(); list.append(other.data()); d->data = list; d->to = d->from + list.count() - 1; d->count = list.count(); } return *this; } QSPatch QSPatch::createUpdate(int index, const QVariantMap &diff) { return QSPatch(QSPatch::Update, index, index, 1, diff); } QDebug operator<<(QDebug dbg, const QSPatch& change){ switch (change.type()) { case QSPatch::Remove: dbg << QString("Remove from %1 to %2").arg(change.from()).arg(change.to()); break; case QSPatch::Move: dbg << QString("Move from %1 to %2 with %3").arg(change.from()).arg(change.to()).arg(change.count()); break; case QSPatch::Insert: dbg << QString("Insert from %1 to %2 with %3").arg(change.from()).arg(change.to()).arg(change.count()); dbg << change.data(); break; case QSPatch::Update: dbg << QString("Update %12").arg(change.from()); dbg << change.data(); break; default: dbg << "Null"; break; } return dbg; } <|endoftext|>
<commit_before>#ifndef __SIMFQT_SVC_SIMFQT_SERVICE_HPP #define __SIMFQT_SVC_SIMFQT_SERVICE_HPP // ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // StdAir #include <stdair/stdair_basic_types.hpp> #include <stdair/stdair_service_types.hpp> #include <stdair/bom/TravelSolutionTypes.hpp> // SimFQT #include <simfqt/SIMFQT_Types.hpp> #include <stdair/bom/TravelSolutionTypes.hpp> // Forward declarations. namespace stdair { class STDAIR_Service; struct BasLogParams; struct BasDBParams; struct BookingRequestStruct; } namespace SIMFQT { // Forward declaration class SIMFQT_ServiceContext; /** Interface for the SIMFQT Services. */ class SIMFQT_Service { public: // /////////// Business Methods ///////////// /** Calculate the fares corresponding to a given list of travel solutions. <br>The stdair::Fare_T attribute of each travel solution of the list is calculated. @param stdair::BookingRequestStruct& Booking request. @param stdair::TravelSolutionList_T& List of travel solution. */ void getFares (const stdair::BookingRequestStruct&, stdair::TravelSolutionList_T&); public: // ////////////////// Constructors and Destructors ////////////////// /** Constructor. <br>The init() method is called; see the corresponding documentation for more details. <br>A reference on an output stream is given, so that log outputs can be directed onto that stream. <br>Moreover, database connection parameters are given, so that a session can be created on the corresponding database. @param const stdair::BasLogParams& Parameters for the output log stream. @param const stdair::BasDBParams& Parameters for the database access. @param const stdair::Filename_T& Filename of the input fare file. */ SIMFQT_Service (const stdair::BasLogParams&, const stdair::BasDBParams&, const stdair::Filename_T& iFareInputFilename); /** Constructor. <br>The init() method is called; see the corresponding documentation for more details. <br>Moreover, a reference on an output stream is given, so that log outputs can be directed onto that stream. @param const stdair::BasLogParams& Parameters for the output log stream. @param const stdair::Date_T& Date for the beginning of analysis. @param const stdair::Filename_T& Filename of the input fare file. */ SIMFQT_Service (const stdair::BasLogParams&, const stdair::Filename_T& iFareInputFilename); /** Constructor. <br>The init() method is called; see the corresponding documentation for more details. <br>Moreover, as no reference on any output stream is given, it is assumed that the StdAir log service has already been initialised with the proper log output stream by some other methods in the calling chain (for instance, when the SIMFQT_Service is itself being initialised by another library service such as SIMCRS_Service). @param const stdair::Date_T& Date for the beginning of analysis. @param const stdair::Filename_T& Filename of the input fare file. */ SIMFQT_Service (stdair::STDAIR_ServicePtr_T ioSTDAIR_ServicePtr, const stdair::Filename_T& iFareInputFilename); /** Destructor. */ ~SIMFQT_Service(); private: // /////// Construction and Destruction helper methods /////// /** Default constructor. */ SIMFQT_Service (); /** Default copy constructor. */ SIMFQT_Service (const SIMFQT_Service&); /** Initialise the (SIMFQT) service context (i.e., the SIMFQT_ServiceContext object). */ void initServiceContext (); /** Initialise the STDAIR service (including the log service). <br>A reference on the root of the BOM tree, namely the BomRoot object, is stored within the service context for later use. @param const stdair::BasLogParams& Parameters for the output log stream. @param const stdair::BasDBParams& Parameters for the database access. */ void initStdAirService (const stdair::BasLogParams&, const stdair::BasDBParams&); /** Initialise the STDAIR service (including the log service). <br>A reference on the root of the BOM tree, namely the BomRoot object, is stored within the service context for later use. @param const stdair::BasLogParams& Parameters for the output log stream. */ void initStdAirService (const stdair::BasLogParams&); /** Initialise. <br>The CSV file, describing the airline fares for the simulator, is parsed and the inventories are generated accordingly. @param const stdair::Filename_T& Filename of the input fare file. */ void init (const stdair::Filename_T& iFareInputFilename); /** Finalise. */ void finalise (); private: // ///////// Service Context ///////// /** Simfqt context. */ SIMFQT_ServiceContext* _simfqtServiceContext; }; } #endif // __SIMFQT_SVC_SIMFQT_SERVICE_HPP <commit_msg>[SimFQT][Dev] Added a missing forward declaration in SIMFQT_Service.<commit_after>#ifndef __SIMFQT_SVC_SIMFQT_SERVICE_HPP #define __SIMFQT_SVC_SIMFQT_SERVICE_HPP // ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // StdAir #include <stdair/stdair_basic_types.hpp> #include <stdair/stdair_service_types.hpp> #include <stdair/bom/TravelSolutionTypes.hpp> // SimFQT #include <simfqt/SIMFQT_Types.hpp> #include <stdair/bom/TravelSolutionTypes.hpp> // Forward declarations. namespace stdair { class STDAIR_Service; struct BookingRequestStruct; struct BasLogParams; struct BasDBParams; struct BookingRequestStruct; } namespace SIMFQT { // Forward declaration class SIMFQT_ServiceContext; /** Interface for the SIMFQT Services. */ class SIMFQT_Service { public: // /////////// Business Methods ///////////// /** Calculate the fares corresponding to a given list of travel solutions. <br>The stdair::Fare_T attribute of each travel solution of the list is calculated. @param stdair::BookingRequestStruct& Booking request. @param stdair::TravelSolutionList_T& List of travel solution. */ void getFares (const stdair::BookingRequestStruct&, stdair::TravelSolutionList_T&); public: // ////////////////// Constructors and Destructors ////////////////// /** Constructor. <br>The init() method is called; see the corresponding documentation for more details. <br>A reference on an output stream is given, so that log outputs can be directed onto that stream. <br>Moreover, database connection parameters are given, so that a session can be created on the corresponding database. @param const stdair::BasLogParams& Parameters for the output log stream. @param const stdair::BasDBParams& Parameters for the database access. @param const stdair::Filename_T& Filename of the input fare file. */ SIMFQT_Service (const stdair::BasLogParams&, const stdair::BasDBParams&, const stdair::Filename_T& iFareInputFilename); /** Constructor. <br>The init() method is called; see the corresponding documentation for more details. <br>Moreover, a reference on an output stream is given, so that log outputs can be directed onto that stream. @param const stdair::BasLogParams& Parameters for the output log stream. @param const stdair::Date_T& Date for the beginning of analysis. @param const stdair::Filename_T& Filename of the input fare file. */ SIMFQT_Service (const stdair::BasLogParams&, const stdair::Filename_T& iFareInputFilename); /** Constructor. <br>The init() method is called; see the corresponding documentation for more details. <br>Moreover, as no reference on any output stream is given, it is assumed that the StdAir log service has already been initialised with the proper log output stream by some other methods in the calling chain (for instance, when the SIMFQT_Service is itself being initialised by another library service such as SIMCRS_Service). @param const stdair::Date_T& Date for the beginning of analysis. @param const stdair::Filename_T& Filename of the input fare file. */ SIMFQT_Service (stdair::STDAIR_ServicePtr_T ioSTDAIR_ServicePtr, const stdair::Filename_T& iFareInputFilename); /** Destructor. */ ~SIMFQT_Service(); private: // /////// Construction and Destruction helper methods /////// /** Default constructor. */ SIMFQT_Service (); /** Default copy constructor. */ SIMFQT_Service (const SIMFQT_Service&); /** Initialise the (SIMFQT) service context (i.e., the SIMFQT_ServiceContext object). */ void initServiceContext (); /** Initialise the STDAIR service (including the log service). <br>A reference on the root of the BOM tree, namely the BomRoot object, is stored within the service context for later use. @param const stdair::BasLogParams& Parameters for the output log stream. @param const stdair::BasDBParams& Parameters for the database access. */ void initStdAirService (const stdair::BasLogParams&, const stdair::BasDBParams&); /** Initialise the STDAIR service (including the log service). <br>A reference on the root of the BOM tree, namely the BomRoot object, is stored within the service context for later use. @param const stdair::BasLogParams& Parameters for the output log stream. */ void initStdAirService (const stdair::BasLogParams&); /** Initialise. <br>The CSV file, describing the airline fares for the simulator, is parsed and the inventories are generated accordingly. @param const stdair::Filename_T& Filename of the input fare file. */ void init (const stdair::Filename_T& iFareInputFilename); /** Finalise. */ void finalise (); private: // ///////// Service Context ///////// /** Simfqt context. */ SIMFQT_ServiceContext* _simfqtServiceContext; }; } #endif // __SIMFQT_SVC_SIMFQT_SERVICE_HPP <|endoftext|>
<commit_before>// commands.cxx - encapsulated commands. // Started Spring 2001 by David Megginson, david@megginson.com // This code is released into the Public Domain. // // $Id$ #include "commands.hxx" //////////////////////////////////////////////////////////////////////// // Implementation of SGCommandMgr class. //////////////////////////////////////////////////////////////////////// SGCommandMgr::SGCommandMgr () { // no-op } SGCommandMgr::~SGCommandMgr () { // no-op } void SGCommandMgr::addCommand (const string &name, command_t command) { _commands[name] = command; } SGCommandMgr::command_t SGCommandMgr::getCommand (const string &name) const { const command_map::const_iterator it = _commands.find(name); return (it != _commands.end() ? it->second : 0); } vector<string> SGCommandMgr::getCommandNames () const { vector<string> names; command_map::const_iterator it = _commands.begin(); command_map::const_iterator last = _commands.end(); while (it != last) { names.push_back(it->first); it++; } return names; } bool SGCommandMgr::execute (const string &name, const SGPropertyNode * arg) const { command_t command = getCommand(name); if (command == 0) return false; else return (*command)(arg); } bool SGCommandMgr::execute (const string &name) const { // FIXME SGPropertyNode node; execute(name, &node); } bool SGCommandMgr::execute (const string &name, bool value) const { // FIXME SGPropertyNode node; node.setBoolValue(value); execute(name, &node); } bool SGCommandMgr::execute (const string &name, int value) const { // FIXME SGPropertyNode node; node.setIntValue(value); execute(name, &node); } bool SGCommandMgr::execute (const string &name, long value) const { // FIXME SGPropertyNode node; node.setLongValue(value); execute(name, &node); } bool SGCommandMgr::execute (const string &name, float value) const { // FIXME SGPropertyNode node; node.setFloatValue(value); execute(name, &node); } bool SGCommandMgr::execute (const string &name, double value) const { // FIXME SGPropertyNode node; node.setDoubleValue(value); execute(name, &node); } bool SGCommandMgr::execute (const string &name, string value) const { // FIXME SGPropertyNode node; node.setStringValue(value); execute(name, &node); } // end of commands.cxx <commit_msg>- added missing return statements for execute methods<commit_after>// commands.cxx - encapsulated commands. // Started Spring 2001 by David Megginson, david@megginson.com // This code is released into the Public Domain. // // $Id$ #include "commands.hxx" //////////////////////////////////////////////////////////////////////// // Implementation of SGCommandMgr class. //////////////////////////////////////////////////////////////////////// SGCommandMgr::SGCommandMgr () { // no-op } SGCommandMgr::~SGCommandMgr () { // no-op } void SGCommandMgr::addCommand (const string &name, command_t command) { _commands[name] = command; } SGCommandMgr::command_t SGCommandMgr::getCommand (const string &name) const { const command_map::const_iterator it = _commands.find(name); return (it != _commands.end() ? it->second : 0); } vector<string> SGCommandMgr::getCommandNames () const { vector<string> names; command_map::const_iterator it = _commands.begin(); command_map::const_iterator last = _commands.end(); while (it != last) { names.push_back(it->first); it++; } return names; } bool SGCommandMgr::execute (const string &name, const SGPropertyNode * arg) const { command_t command = getCommand(name); if (command == 0) return false; else return (*command)(arg); } bool SGCommandMgr::execute (const string &name) const { // FIXME SGPropertyNode node; return execute(name, &node); } bool SGCommandMgr::execute (const string &name, bool value) const { // FIXME SGPropertyNode node; node.setBoolValue(value); return execute(name, &node); } bool SGCommandMgr::execute (const string &name, int value) const { // FIXME SGPropertyNode node; node.setIntValue(value); return execute(name, &node); } bool SGCommandMgr::execute (const string &name, long value) const { // FIXME SGPropertyNode node; node.setLongValue(value); return execute(name, &node); } bool SGCommandMgr::execute (const string &name, float value) const { // FIXME SGPropertyNode node; node.setFloatValue(value); return execute(name, &node); } bool SGCommandMgr::execute (const string &name, double value) const { // FIXME SGPropertyNode node; node.setDoubleValue(value); return execute(name, &node); } bool SGCommandMgr::execute (const string &name, string value) const { // FIXME SGPropertyNode node; node.setStringValue(value); return execute(name, &node); } // end of commands.cxx <|endoftext|>
<commit_before> #include "qt/info_dialog.hpp" #include "qt/mainwindow.hpp" #include "platform/platform.hpp" #include "platform/settings.hpp" #include "coding/file_reader.hpp" #include "base/logging.hpp" #include "base/macros.hpp" #include "base/object_tracker.hpp" #include "std/cstdio.hpp" #include "3party/Alohalytics/src/alohalytics.h" #include <QtCore/QDir> #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #include <QtGui/QApplication> #else #include <QtWidgets/QApplication> #endif namespace { class FinalizeBase { public: ~FinalizeBase() { // optional - clean allocated data in protobuf library // useful when using memory and resource leak utilites //google::protobuf::ShutdownProtobufLibrary(); } }; #if defined(OMIM_OS_WINDOWS) //&& defined(PROFILER_COMMON) class InitializeFinalize : public FinalizeBase { FILE * m_errFile; public: InitializeFinalize() { // App runs without error console under win32. m_errFile = ::freopen(".\\mapsme.log", "w", stderr); my::g_LogLevel = my::LDEBUG; //_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_DELAY_FREE_MEM_DF); //_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); } ~InitializeFinalize() { ::fclose(m_errFile); } }; #else typedef FinalizeBase InitializeFinalize; #endif } int main(int argc, char * argv[]) { InitializeFinalize mainGuard; UNUSED_VALUE(mainGuard); QApplication a(argc, argv); #ifdef DEBUG alohalytics::Stats::Instance().SetDebugMode(true); #endif GetPlatform().SetupMeasurementSystem(); // display EULA if needed char const * settingsEULA = "EulaAccepted"; bool eulaAccepted = false; if (!Settings::Get(settingsEULA, eulaAccepted) || !eulaAccepted) { QStringList buttons; buttons << "Accept" << "Decline"; string buffer; { ReaderPtr<Reader> reader = GetPlatform().GetReader("eula.html"); reader.ReadAsString(buffer); } qt::InfoDialog eulaDialog("MAPS.ME End User Licensing Agreement", buffer.c_str(), NULL, buttons); eulaAccepted = (eulaDialog.exec() == 1); Settings::Set(settingsEULA, eulaAccepted); } int returnCode = -1; if (eulaAccepted) // User has accepted EULA { qt::MainWindow w; w.show(); returnCode = a.exec(); } dbg::ObjectTracker::PrintLeaks(); LOG_SHORT(LINFO, ("MapsWithMe finished with code", returnCode)); return returnCode; } <commit_msg>Workaround for crash when parsing doubles, if decimal delimiter is comma instead of dot. TODO: Use locale-independent double parser.<commit_after> #include "qt/info_dialog.hpp" #include "qt/mainwindow.hpp" #include "platform/platform.hpp" #include "platform/settings.hpp" #include "coding/file_reader.hpp" #include "base/logging.hpp" #include "base/macros.hpp" #include "base/object_tracker.hpp" #include "std/cstdio.hpp" #include "std/cstdlib.hpp" #include "3party/Alohalytics/src/alohalytics.h" #include <QtCore/QDir> #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #include <QtGui/QApplication> #else #include <QtWidgets/QApplication> #endif namespace { class FinalizeBase { public: ~FinalizeBase() { // optional - clean allocated data in protobuf library // useful when using memory and resource leak utilites //google::protobuf::ShutdownProtobufLibrary(); } }; #if defined(OMIM_OS_WINDOWS) //&& defined(PROFILER_COMMON) class InitializeFinalize : public FinalizeBase { FILE * m_errFile; public: InitializeFinalize() { // App runs without error console under win32. m_errFile = ::freopen(".\\mapsme.log", "w", stderr); my::g_LogLevel = my::LDEBUG; //_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_DELAY_FREE_MEM_DF); //_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); } ~InitializeFinalize() { ::fclose(m_errFile); } }; #else typedef FinalizeBase InitializeFinalize; #endif } int main(int argc, char * argv[]) { // Our double parsing code (base/string_utils.hpp) needs dots as a floating point delimiters, not commas. // TODO: Refactor our doubles parsing code to use locale-independent delimiters. // For example, https://github.com/google/double-conversion can be used. // See http://dbaron.org/log/20121222-locale for more details. (void)::setenv("LC_NUMERIC", "C", 1); InitializeFinalize mainGuard; UNUSED_VALUE(mainGuard); QApplication a(argc, argv); #ifdef DEBUG alohalytics::Stats::Instance().SetDebugMode(true); #endif GetPlatform().SetupMeasurementSystem(); // display EULA if needed char const * settingsEULA = "EulaAccepted"; bool eulaAccepted = false; if (!Settings::Get(settingsEULA, eulaAccepted) || !eulaAccepted) { QStringList buttons; buttons << "Accept" << "Decline"; string buffer; { ReaderPtr<Reader> reader = GetPlatform().GetReader("eula.html"); reader.ReadAsString(buffer); } qt::InfoDialog eulaDialog("MAPS.ME End User Licensing Agreement", buffer.c_str(), NULL, buttons); eulaAccepted = (eulaDialog.exec() == 1); Settings::Set(settingsEULA, eulaAccepted); } int returnCode = -1; if (eulaAccepted) // User has accepted EULA { qt::MainWindow w; w.show(); returnCode = a.exec(); } dbg::ObjectTracker::PrintLeaks(); LOG_SHORT(LINFO, ("MapsWithMe finished with code", returnCode)); return returnCode; } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : D4.cpp * Author : Kazune Takahashi * Created : 2/21/2019, 12:09:38 AM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; const string base = "-"; void char_max(string &a, string b) { if (a == base) { a = b; } else if (a.size() < b.size()) { a = b; } else if (a.size() == b.size() && a < b) { a = b; } } ll X[10] = {0, 2, 5, 5, 4, 5, 6, 3, 7, 6}; string DP[10010]; int N, M; ll A[10]; int main() { cin >> N >> M; for (auto i = 0; i < M; i++) { cin >> A[i]; } for (auto i = 0; i < 10010; i++) { DP[i] = -1; } DP[0] = base; for (auto i = 0; i <= N; i++) { if (DP[i] == base) { continue; } for (auto j = 0; j < M; j++) { char_max(DP[i + X[A[j]]], DP[i] + (char)('0' + A[j])); } } cout << DP[N] << endl; }<commit_msg>tried D4.cpp to 'D'<commit_after>#define DEBUG 1 /** * File : D4.cpp * Author : Kazune Takahashi * Created : 2/21/2019, 12:09:38 AM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; const string base = "-"; void char_max(string &a, string b) { if (a == base) { a = b; } else if (a.size() < b.size()) { a = b; } else if (a.size() == b.size() && a < b) { a = b; } } ll X[10] = {0, 2, 5, 5, 4, 5, 6, 3, 7, 6}; string DP[10010]; int N, M; ll A[10]; int main() { cin >> N >> M; for (auto i = 0; i < M; i++) { cin >> A[i]; } for (auto i = 0; i < 10010; i++) { DP[i] = base; } DP[0] = base; for (auto i = 0; i <= N; i++) { if (DP[i] == base) { continue; } for (auto j = 0; j < M; j++) { char_max(DP[i + X[A[j]]], DP[i] + (char)('0' + A[j])); } } cout << DP[N] << endl; }<|endoftext|>
<commit_before>#define DEBUG 1 /** * File : E2.cpp * Author : Kazune Takahashi * Created : 2020/1/20 0:19:15 * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- class Sieve { static constexpr ll MAX_SIZE{1000010LL}; ll N; vector<bool> isprime; vector<ll> prime_nums; public: Sieve(ll N = MAX_SIZE) : N{N}, isprime(N, true), prime_nums{} { isprime[0] = isprime[1] = false; for (auto i = 2; i < N; i++) { if (isprime[i]) { prime_nums.push_back(i); for (auto j = 2 * i; j < N; j += i) { isprime[j] = false; } } } } bool is_prime(ll x) const { // 2 \leq x \leq MAX_SIZE^2 if (x < N) { return isprime[x]; } for (auto e : prime_nums) { if (x % e == 0) return false; } return true; } vector<ll> const &primes() const { return prime_nums; } vector<ll> factor_list(ll x) const { assert(x >= 2); vector<ll> res; auto it{prime_nums.begin()}; while (x != 1 && it != prime_nums.end()) { if (x % *it == 0) { res.push_back(*it); x /= *it; } else { ++it; } } if (x != 1) { res.push_back(x); } return res; } vector<tuple<ll, ll>> factor(ll x) const { auto factors{factor_list(x)}; vector<tuple<ll, ll>> res{make_tuple(factors[0], 0)}; for (auto x : factors) { if (x == get<0>(res.back())) { get<1>(res.back())++; } else { res.emplace_back(x, 1); } } return res; } }; void solve() { Sieve sieve; int N; cin >> N; vector<ll> A(N); for (auto i = 0; i < N; ++i) { cin >> A[i]; } map<ll, ll> M; for (auto i = 0; i < N; ++i) { auto f{sieve.factor(A[i])}; for (auto p : f) { if (M.find(get<0>(p)) == M.end()) { M[get<0>(p)] = get<1>(p); } else { ch_max(M[get<0>(p)], get<1>(p)); } } } mint lcm{1}; for (auto p : M) { for (auto i = 0; i < get<1>(p); ++i) { lcm *= get<0>(p); } } sleep(10); mint ans{0}; for (auto i = 0; i < N; ++i) { mint B{lcm / A[i]}; ans += B; } cout << ans << endl; } int main() { solve(); } <commit_msg>submit E2.cpp to 'E - Flatten' (abc152) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1 /** * File : E2.cpp * Author : Kazune Takahashi * Created : 2020/1/20 0:19:15 * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- class Sieve { static constexpr ll MAX_SIZE{1000010LL}; ll N; vector<bool> isprime; vector<ll> prime_nums; public: Sieve(ll N = MAX_SIZE) : N{N}, isprime(N, true), prime_nums{} { isprime[0] = isprime[1] = false; for (auto i = 2; i < N; i++) { if (isprime[i]) { prime_nums.push_back(i); for (auto j = 2 * i; j < N; j += i) { isprime[j] = false; } } } } bool is_prime(ll x) const { // 2 \leq x \leq MAX_SIZE^2 if (x < N) { return isprime[x]; } for (auto e : prime_nums) { if (x % e == 0) return false; } return true; } vector<ll> const &primes() const { return prime_nums; } vector<ll> factor_list(ll x) const { assert(x >= 2); vector<ll> res; auto it{prime_nums.begin()}; while (x != 1 && it != prime_nums.end()) { if (x % *it == 0) { res.push_back(*it); x /= *it; } else { ++it; } } if (x != 1) { res.push_back(x); } return res; } vector<tuple<ll, ll>> factor(ll x) const { auto factors{factor_list(x)}; vector<tuple<ll, ll>> res{make_tuple(factors[0], 0)}; for (auto x : factors) { if (x == get<0>(res.back())) { get<1>(res.back())++; } else { res.emplace_back(x, 1); } } return res; } }; void solve() { Sieve sieve; int N; cin >> N; vector<ll> A(N); for (auto i = 0; i < N; ++i) { cin >> A[i]; } map<ll, ll> M; for (auto i = 0; i < N; ++i) { auto f{sieve.factor(A[i])}; for (auto p : f) { if (M.find(get<0>(p)) == M.end()) { M[get<0>(p)] = get<1>(p); } else { ch_max(M[get<0>(p)], get<1>(p)); } } } sleep(10); mint lcm{1}; for (auto p : M) { for (auto i = 0; i < get<1>(p); ++i) { lcm *= get<0>(p); } } mint ans{0}; for (auto i = 0; i < N; ++i) { mint B{lcm / A[i]}; ans += B; } cout << ans << endl; } int main() { solve(); } <|endoftext|>
<commit_before>#include "Renderer.hpp" static const char* gammaVertShader = AL_STRINGIFY ( void main(void) { gl_TexCoord[0] = gl_MultiTexCoord0; gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; } ); static const char* gammaFragShader = AL_STRINGIFY ( uniform sampler2D texture; void main(void) { gl_FragColor = texture2D(texture, gl_TexCoord[0].st); } ); Renderer::Renderer(CubemapSource* cubemapSource) : al::OmniApp("AlloPlayer", false, 2048), cubemapSource(cubemapSource) { nav().smooth(0.8); for (int i = 0; i < 1; i++) { cubemapPool.push(nullptr); } std::function<StereoCubemap* (CubemapSource*, StereoCubemap*)> callback = boost::bind(&Renderer::onNextCubemap, this, _1, _2); cubemapSource->setOnNextCubemap(callback); for (int i = 0; i < StereoCubemap::MAX_EYES_COUNT * Cubemap::MAX_FACES_COUNT; i++) { textures.push_back(nullptr); } } Renderer::~Renderer() { } bool Renderer::onCreate() { std::cout << "OpenGL version: " << glGetString(GL_VERSION) << ", GLSL version " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl; al::Shader vert, frag; vert.source(gammaVertShader, al::Shader::VERTEX).compile(); vert.printLog(); frag.source(gammaFragShader, al::Shader::FRAGMENT).compile(); frag.printLog(); gammaShader.attach(vert).attach(frag).link(); gammaShader.printLog(); /*gammaShader.begin(); gammaShader.uniform("lighting", lightingAmount); gammaShader.uniform("texture", 0.0); gammaShader.end();*/ return OmniApp::onCreate(); } bool Renderer::onFrame() { now = al::MainLoop::now(); StereoCubemap* cubemap; if (cubemapBuffer.try_pop(cubemap)) { for (int j = 0; j < cubemap->getEyesCount(); j++) { Cubemap* eye = cubemap->getEye(j); for (int i = 0; i < eye->getFacesCount(); i++) { CubemapFace* face = eye->getFace(i); // The whole cubemap needs to be flipped in the AlloSphere // Therefore swap left and right face int texI = i; if (i == 0) { texI = 1; } else if (i == 1) { texI = 0; } al::Texture* tex = textures[texI + j * Cubemap::MAX_FACES_COUNT]; if (face) { // create texture if not already created if (!tex) { tex = new al::Texture(face->getContent()->getWidth(), face->getContent()->getHeight(), al::Graphics::RGBA, al::Graphics::UBYTE); textures[texI + j * Cubemap::MAX_FACES_COUNT] = tex; // In case a face is mono use the same the texture for left and right. // By doing so, image will become twice as bright in the AlloSphere. if (j == 0 && cubemap->getEyesCount() > 1 && cubemap->getEye(1)->getFacesCount() > i) { textures[texI + Cubemap::MAX_FACES_COUNT] = tex; } } void* pixels = tex->data<void>(); memcpy(pixels, face->getContent()->getPixels(), face->getContent()->getWidth() * face->getContent()->getHeight() * 4); if (onDisplayedCubemapFace) onDisplayedCubemapFace(this, i + j * Cubemap::MAX_FACES_COUNT); } } } cubemapPool.push(cubemap); } bool result = OmniApp::onFrame(); if (onDisplayedFrame) onDisplayedFrame(this); return result; } StereoCubemap* Renderer::onNextCubemap(CubemapSource* source, StereoCubemap* cubemap) { StereoCubemap* oldCubemap; if (!cubemapPool.try_pop(oldCubemap)) { if (cubemapPool.closed()) { abort(); } else { return cubemap; } } cubemapBuffer.push(cubemap); return oldCubemap; } void Renderer::onDraw(al::Graphics& gl) { int faceIndex = mOmni.face(); int eyeIndex = (mOmni.eye() <= 0.0f) ? 0 : 1; al::Texture* tex = textures[faceIndex + eyeIndex * Cubemap::MAX_FACES_COUNT]; // render cubemap if (tex) { // Increase gamma to make backdrop brighter in the AlloSphere gammaShader.begin(); /* varying vec2 texCoord; uniform float brightness; void main() { vec4 color = texture2D(texture, texCoord); // change brightness of color gl_FragColor = color; } */ // Borrow a temporary Mesh from Graphics al::Mesh& m = gl.mesh(); m.reset(); // Generate geometry m.primitive(al::Graphics::TRIANGLE_STRIP); m.vertex(-1, 1); m.vertex(-1, -1); m.vertex( 1, 1); m.vertex( 1, -1); // Add texture coordinates and flip cubemap m.texCoord(1,1); m.texCoord(1,0); m.texCoord(0,1); m.texCoord(0,0); // We must tell the GPU to use the texture when rendering primitives tex->bind(); gl.draw(m); tex->unbind(); gammaShader.end(); } } void Renderer::onMessage(al::osc::Message& m) { OmniApp::onMessage(m); } bool Renderer::onKeyDown(const al::Keyboard& k) { return true; } void Renderer::setOnDisplayedFrame(std::function<void (Renderer*)>& callback) { onDisplayedFrame = callback; } void Renderer::setOnDisplayedCubemapFace(std::function<void (Renderer*, int)>& callback) { onDisplayedCubemapFace = callback; } <commit_msg>Gamma shader working in AlloSphere<commit_after>#include "Renderer.hpp" static const char* gammaVertShader = AL_STRINGIFY ( void main(void) { gl_TexCoord[0] = gl_MultiTexCoord0; gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; } ); static const char* gammaFragShader = AL_STRINGIFY ( uniform sampler2D texture; uniform float pow; uniform float min; uniform float max; void main(void) { vec4 color = texture2D(texture, gl_TexCoord[0].st); color.x = pow(clamp(color.x, min, max), pow); color.y = pow(clamp(color.y, min, max), pow); color.z = pow(clamp(color.z, min, max), pow); gl_FragColor = color; } ); Renderer::Renderer(CubemapSource* cubemapSource) : al::OmniApp("AlloPlayer", false, 2048), cubemapSource(cubemapSource) { nav().smooth(0.8); for (int i = 0; i < 1; i++) { cubemapPool.push(nullptr); } std::function<StereoCubemap* (CubemapSource*, StereoCubemap*)> callback = boost::bind(&Renderer::onNextCubemap, this, _1, _2); cubemapSource->setOnNextCubemap(callback); for (int i = 0; i < StereoCubemap::MAX_EYES_COUNT * Cubemap::MAX_FACES_COUNT; i++) { textures.push_back(nullptr); } } Renderer::~Renderer() { } bool Renderer::onCreate() { std::cout << "OpenGL version: " << glGetString(GL_VERSION) << ", GLSL version " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl; al::Shader vert, frag; vert.source(gammaVertShader, al::Shader::VERTEX).compile(); vert.printLog(); frag.source(gammaFragShader, al::Shader::FRAGMENT).compile(); frag.printLog(); gammaShader.attach(vert).attach(frag).link(); gammaShader.printLog(); gammaShader.begin(); gammaShader.uniform("pow", 1.0f); gammaShader.uniform("min", 0.0f); gammaShader.uniform("max", 1.0f); gammaShader.end(); return OmniApp::onCreate(); } bool Renderer::onFrame() { now = al::MainLoop::now(); StereoCubemap* cubemap; if (cubemapBuffer.try_pop(cubemap)) { for (int j = 0; j < cubemap->getEyesCount(); j++) { Cubemap* eye = cubemap->getEye(j); for (int i = 0; i < eye->getFacesCount(); i++) { CubemapFace* face = eye->getFace(i); // The whole cubemap needs to be flipped in the AlloSphere // Therefore swap left and right face int texI = i; if (i == 0) { texI = 1; } else if (i == 1) { texI = 0; } al::Texture* tex = textures[texI + j * Cubemap::MAX_FACES_COUNT]; if (face) { // create texture if not already created if (!tex) { tex = new al::Texture(face->getContent()->getWidth(), face->getContent()->getHeight(), al::Graphics::RGBA, al::Graphics::UBYTE); textures[texI + j * Cubemap::MAX_FACES_COUNT] = tex; // In case a face is mono use the same the texture for left and right. // By doing so, image will become twice as bright in the AlloSphere. if (j == 0 && cubemap->getEyesCount() > 1 && cubemap->getEye(1)->getFacesCount() > i) { textures[texI + Cubemap::MAX_FACES_COUNT] = tex; } } void* pixels = tex->data<void>(); memcpy(pixels, face->getContent()->getPixels(), face->getContent()->getWidth() * face->getContent()->getHeight() * 4); if (onDisplayedCubemapFace) onDisplayedCubemapFace(this, i + j * Cubemap::MAX_FACES_COUNT); } } } cubemapPool.push(cubemap); } bool result = OmniApp::onFrame(); if (onDisplayedFrame) onDisplayedFrame(this); return result; } StereoCubemap* Renderer::onNextCubemap(CubemapSource* source, StereoCubemap* cubemap) { StereoCubemap* oldCubemap; if (!cubemapPool.try_pop(oldCubemap)) { if (cubemapPool.closed()) { abort(); } else { return cubemap; } } cubemapBuffer.push(cubemap); return oldCubemap; } void Renderer::onDraw(al::Graphics& gl) { int faceIndex = mOmni.face(); int eyeIndex = (mOmni.eye() <= 0.0f) ? 0 : 1; al::Texture* tex = textures[faceIndex + eyeIndex * Cubemap::MAX_FACES_COUNT]; // render cubemap if (tex) { // Configure gamma to make backdrop more visible in the AlloSphere gammaShader.begin(); // Borrow a temporary Mesh from Graphics al::Mesh& m = gl.mesh(); m.reset(); // Generate geometry m.primitive(al::Graphics::TRIANGLE_STRIP); m.vertex(-1, 1); m.vertex(-1, -1); m.vertex( 1, 1); m.vertex( 1, -1); // Add texture coordinates and flip cubemap m.texCoord(1,1); m.texCoord(1,0); m.texCoord(0,1); m.texCoord(0,0); // We must tell the GPU to use the texture when rendering primitives tex->bind(); gl.draw(m); tex->unbind(); gammaShader.end(); } } void Renderer::onMessage(al::osc::Message& m) { OmniApp::onMessage(m); } bool Renderer::onKeyDown(const al::Keyboard& k) { return true; } void Renderer::setOnDisplayedFrame(std::function<void (Renderer*)>& callback) { onDisplayedFrame = callback; } void Renderer::setOnDisplayedCubemapFace(std::function<void (Renderer*, int)>& callback) { onDisplayedCubemapFace = callback; } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /////////////////////////////////////////////////////////////////////////////// /// /// Class Payload /// /// Decodes rawdata from buffer and stores in TClonesArray. /// /// First version implement for Tracker /// /////////////////////////////////////////////////////////////////////////////// #include "AliMUONPayloadTracker.h" #include "AliRawReader.h" #include "AliRawDataHeader.h" #include "AliLog.h" #include "AliMUONDspHeader.h" #include "AliMUONBlockHeader.h" #include "AliMUONBusStruct.h" #include "AliMUONDDLTracker.h" ClassImp(AliMUONPayloadTracker) AliMUONPayloadTracker::AliMUONPayloadTracker() : TObject(), fMaxBlock(2), fMaxDsp(5), fMaxBus(5) { // // create an object to read MUON raw digits // Default ctor for monitoring purposes // fBusPatchManager = new AliMpBusPatch(); fBusPatchManager->ReadBusPatchFile(); fDDLTracker = new AliMUONDDLTracker(); fBusStruct = new AliMUONBusStruct(); fBlockHeader = new AliMUONBlockHeader(); fDspHeader = new AliMUONDspHeader(); } //_________________________________________________________________ AliMUONPayloadTracker::AliMUONPayloadTracker(const AliMUONPayloadTracker& stream) : TObject(stream) { // // copy ctor // AliFatal("copy constructor not implemented"); } //______________________________________________________________________ AliMUONPayloadTracker& AliMUONPayloadTracker::operator = (const AliMUONPayloadTracker& /* stream */) { // // assignment operator // AliFatal("assignment operator not implemented"); return *this; } //___________________________________ AliMUONPayloadTracker::~AliMUONPayloadTracker() { // // clean up // delete fBusPatchManager; delete fDDLTracker; delete fBusStruct; delete fBlockHeader; delete fDspHeader; } //______________________________________________________ Bool_t AliMUONPayloadTracker::Decode(UInt_t* buffer, Int_t ddl) { // reading tracker DDL // store buspatch info into Array // store only non-empty structures (buspatch info with datalength !=0) //Read Header Size of DDL,Block,DSP and BusPatch Int_t kBlockHeaderSize = fBlockHeader->GetHeaderLength(); Int_t kDspHeaderSize = fDspHeader->GetHeaderLength(); Int_t kBusPatchHeaderSize = fBusStruct->GetHeaderLength(); // Int_t totalDDLSize; Int_t totalBlockSize; Int_t totalDspSize; Int_t totalBusPatchSize; Int_t dataSize; Int_t iBusPerDSP[5]; // number of bus patches per DSP Int_t iDspMax; // number max of DSP per block // minimum data size (only header's) // Int_t blankDDLSize; Int_t blankBlockSize; Int_t blankDspSize; AliDebug(3, Form("DDL Number %d\n", ddl )); // getting DSP info fBusPatchManager->GetDspInfo(ddl/2, iDspMax, iBusPerDSP); // Each DDL is made with 2 Blocks each of which consists of 5 DSP's at most // and each of DSP has at most 5 buspatches. // This information is used to calculate the size of headers (Block and DSP) // which has empty data. // blankDDLSize = 2*kBlockHeaderSize + 2*iDspMax*kDspHeaderSize; blankBlockSize = kBlockHeaderSize + iDspMax*kDspHeaderSize; // totalDDLSize = sizeof(buffer)/4; for (Int_t i = 0; i < iDspMax; i++) { // blankDDLSize += 2*iBusPerDSP[i]*kBusPatchHeaderSize; blankBlockSize += iBusPerDSP[i]*kBusPatchHeaderSize; } // Compare the DDL header with an empty DDL header size to read the file // if(totalDDLSize > blankDDLSize) { //should not happen in real life // indexes Int_t indexDsp; Int_t indexBusPatch; Int_t index = 0; for(Int_t iBlock = 0; iBlock < 2 ;iBlock++){ // loop over 2 blocks // copy within padding words memcpy(fBlockHeader->GetHeader(),&buffer[index], (kBlockHeaderSize+1)*4); totalBlockSize = fBlockHeader->GetTotalLength(); fDDLTracker->AddBlkHeader(*fBlockHeader); if (fBlockHeader->GetPadding() == 0xDEAD) // skipping padding word index++; if(totalBlockSize > blankBlockSize) { // compare block header index += kBlockHeaderSize; for(Int_t iDsp = 0; iDsp < iDspMax ;iDsp++){ //DSP loop if (iDsp > fMaxDsp) break; memcpy(fDspHeader->GetHeader(),&buffer[index], kDspHeaderSize*4); totalDspSize = fDspHeader->GetTotalLength(); indexDsp = index; blankDspSize = kDspHeaderSize + iBusPerDSP[iDsp]*kBusPatchHeaderSize; // no data just header fDDLTracker->AddDspHeader(*fDspHeader, iBlock); if(totalDspSize > blankDspSize) { // Compare DSP Header index += kDspHeaderSize; for(Int_t iBusPatch = 0; iBusPatch < iBusPerDSP[iDsp]; iBusPatch++) { if (iBusPatch > fMaxBus) break; //copy buffer into header structure memcpy(fBusStruct->GetBusPatchHeader(), &buffer[index], kBusPatchHeaderSize*4); totalBusPatchSize = fBusStruct->GetTotalLength(); indexBusPatch = index; //Check Buspatch header, not empty events if(totalBusPatchSize > kBusPatchHeaderSize) { index += kBusPatchHeaderSize; dataSize = fBusStruct->GetLength(); Int_t bufSize = fBusStruct->GetBufSize(); if(dataSize > 0) { // check data present if (dataSize > bufSize) fBusStruct->SetAlloc(dataSize); //copy buffer into data structure memcpy(fBusStruct->GetData(), &buffer[index], dataSize*4); fBusStruct->SetBlockId(iBlock); // could be usefull in future applications ? fBusStruct->SetDspId(iDsp); fDDLTracker->AddBusPatch(*fBusStruct, iBlock, iDsp); } // dataSize test } // testing buspatch index = indexBusPatch + totalBusPatchSize; } //buspatch loop } // dsp test index = indexDsp + totalDspSize; } // dsp loop } //block test index = totalBlockSize; } //block loop // } //loop checking the header size of DDL return kTRUE; } //______________________________________________________ void AliMUONPayloadTracker::ResetDDL() { // reseting TClonesArray // after each DDL // fDDLTracker->GetBlkHeaderArray()->Delete(); } //______________________________________________________ void AliMUONPayloadTracker::SetMaxBlock(Int_t blk) { // set regional card number if (blk > 2) blk = 2; fMaxBlock = blk; } <commit_msg>Put header length in static (Christian)<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /////////////////////////////////////////////////////////////////////////////// /// /// Class Payload /// /// Decodes rawdata from buffer and stores in TClonesArray. /// /// First version implement for Tracker /// /////////////////////////////////////////////////////////////////////////////// #include "AliMUONPayloadTracker.h" #include "AliRawReader.h" #include "AliRawDataHeader.h" #include "AliLog.h" #include "AliMUONDspHeader.h" #include "AliMUONBlockHeader.h" #include "AliMUONBusStruct.h" #include "AliMUONDDLTracker.h" ClassImp(AliMUONPayloadTracker) AliMUONPayloadTracker::AliMUONPayloadTracker() : TObject(), fMaxBlock(2), fMaxDsp(5), fMaxBus(5) { // // create an object to read MUON raw digits // Default ctor for monitoring purposes // fBusPatchManager = new AliMpBusPatch(); fBusPatchManager->ReadBusPatchFile(); fDDLTracker = new AliMUONDDLTracker(); fBusStruct = new AliMUONBusStruct(); fBlockHeader = new AliMUONBlockHeader(); fDspHeader = new AliMUONDspHeader(); } //_________________________________________________________________ AliMUONPayloadTracker::AliMUONPayloadTracker(const AliMUONPayloadTracker& stream) : TObject(stream) { // // copy ctor // AliFatal("copy constructor not implemented"); } //______________________________________________________________________ AliMUONPayloadTracker& AliMUONPayloadTracker::operator = (const AliMUONPayloadTracker& /* stream */) { // // assignment operator // AliFatal("assignment operator not implemented"); return *this; } //___________________________________ AliMUONPayloadTracker::~AliMUONPayloadTracker() { // // clean up // delete fBusPatchManager; delete fDDLTracker; delete fBusStruct; delete fBlockHeader; delete fDspHeader; } //______________________________________________________ Bool_t AliMUONPayloadTracker::Decode(UInt_t* buffer, Int_t ddl) { // reading tracker DDL // store buspatch info into Array // store only non-empty structures (buspatch info with datalength !=0) //Read Header Size of DDL,Block,DSP and BusPatch static Int_t kBlockHeaderSize = fBlockHeader->GetHeaderLength(); static Int_t kDspHeaderSize = fDspHeader->GetHeaderLength(); static Int_t kBusPatchHeaderSize = fBusStruct->GetHeaderLength(); // Int_t totalDDLSize; Int_t totalBlockSize; Int_t totalDspSize; Int_t totalBusPatchSize; Int_t dataSize; Int_t iBusPerDSP[5]; // number of bus patches per DSP Int_t iDspMax; // number max of DSP per block // minimum data size (only header's) // Int_t blankDDLSize; Int_t blankBlockSize; Int_t blankDspSize; AliDebug(3, Form("DDL Number %d\n", ddl )); // getting DSP info fBusPatchManager->GetDspInfo(ddl/2, iDspMax, iBusPerDSP); // Each DDL is made with 2 Blocks each of which consists of 5 DSP's at most // and each of DSP has at most 5 buspatches. // This information is used to calculate the size of headers (Block and DSP) // which has empty data. // blankDDLSize = 2*kBlockHeaderSize + 2*iDspMax*kDspHeaderSize; blankBlockSize = kBlockHeaderSize + iDspMax*kDspHeaderSize; // totalDDLSize = sizeof(buffer)/4; for (Int_t i = 0; i < iDspMax; i++) { // blankDDLSize += 2*iBusPerDSP[i]*kBusPatchHeaderSize; blankBlockSize += iBusPerDSP[i]*kBusPatchHeaderSize; } // Compare the DDL header with an empty DDL header size to read the file // if(totalDDLSize > blankDDLSize) { //should not happen in real life // indexes Int_t indexDsp; Int_t indexBusPatch; Int_t index = 0; for(Int_t iBlock = 0; iBlock < 2 ;iBlock++){ // loop over 2 blocks // copy within padding words memcpy(fBlockHeader->GetHeader(),&buffer[index], (kBlockHeaderSize+1)*4); totalBlockSize = fBlockHeader->GetTotalLength(); fDDLTracker->AddBlkHeader(*fBlockHeader); if (fBlockHeader->GetPadding() == 0xDEAD) // skipping padding word index++; if(totalBlockSize > blankBlockSize) { // compare block header index += kBlockHeaderSize; for(Int_t iDsp = 0; iDsp < iDspMax ;iDsp++){ //DSP loop if (iDsp > fMaxDsp) break; memcpy(fDspHeader->GetHeader(),&buffer[index], kDspHeaderSize*4); totalDspSize = fDspHeader->GetTotalLength(); indexDsp = index; blankDspSize = kDspHeaderSize + iBusPerDSP[iDsp]*kBusPatchHeaderSize; // no data just header fDDLTracker->AddDspHeader(*fDspHeader, iBlock); if(totalDspSize > blankDspSize) { // Compare DSP Header index += kDspHeaderSize; for(Int_t iBusPatch = 0; iBusPatch < iBusPerDSP[iDsp]; iBusPatch++) { if (iBusPatch > fMaxBus) break; //copy buffer into header structure memcpy(fBusStruct->GetBusPatchHeader(), &buffer[index], kBusPatchHeaderSize*4); totalBusPatchSize = fBusStruct->GetTotalLength(); indexBusPatch = index; //Check Buspatch header, not empty events if(totalBusPatchSize > kBusPatchHeaderSize) { index += kBusPatchHeaderSize; dataSize = fBusStruct->GetLength(); Int_t bufSize = fBusStruct->GetBufSize(); if(dataSize > 0) { // check data present if (dataSize > bufSize) fBusStruct->SetAlloc(dataSize); //copy buffer into data structure memcpy(fBusStruct->GetData(), &buffer[index], dataSize*4); fBusStruct->SetBlockId(iBlock); // could be usefull in future applications ? fBusStruct->SetDspId(iDsp); fDDLTracker->AddBusPatch(*fBusStruct, iBlock, iDsp); } // dataSize test } // testing buspatch index = indexBusPatch + totalBusPatchSize; } //buspatch loop } // dsp test index = indexDsp + totalDspSize; } // dsp loop } //block test index = totalBlockSize; } //block loop // } //loop checking the header size of DDL return kTRUE; } //______________________________________________________ void AliMUONPayloadTracker::ResetDDL() { // reseting TClonesArray // after each DDL // fDDLTracker->GetBlkHeaderArray()->Delete(); } //______________________________________________________ void AliMUONPayloadTracker::SetMaxBlock(Int_t blk) { // set regional card number if (blk > 2) blk = 2; fMaxBlock = blk; } <|endoftext|>
<commit_before>#include "Semaphore.h" #ifdef WINDOWS #define WIN32_LEAN_AND_MEAN #include <Windows.h> #elif defined POSIX #include <errno.h> #endif using namespace Utilities; Semaphore::Semaphore() { #ifdef WINDOWS this->BaseSemaphore = CreateSemaphore(NULL, 0, 4294967295, NULL); #elif defined POSIX this->BaseSemaphore = new sem_t; sem_init(this->BaseSemaphore, 0 /* shared between threads */, 0); #endif } Semaphore::~Semaphore() { #ifdef WINDOWS CloseHandle(this->BaseSemaphore); #elif defined POSIX sem_destroy(this->BaseSemaphore); delete this->BaseSemaphore; #endif } void Semaphore::Increment() { #ifdef WINDOWS ReleaseSemaphore(this->BaseSemaphore, 1, NULL); #elif defined POSIX sem_post(this->BaseSemaphore); #endif } Semaphore::DecrementResult Semaphore::Decrement(uint32 timeout) { #ifdef WINDOWS DWORD result = WaitForSingleObject(this->BaseSemaphore, timeout); if (result == WAIT_TIMEOUT) return Semaphore::DecrementResult::TimedOut; else return Semaphore::DecrementResult::Success; #elif defined POSIX timespec ts; int result; ts.tv_nsec = timeout * 1000; while ((result = sem_timedwait(this->BaseSemaphore, &ts)) == -1 && errno == EINTR); if (result == ETIMEDOUT) return Semaphore::DecrementResult::TimedOut; else return Semaphore::DecrementResult::Success; #endif } <commit_msg>Fixed semaphore max count in Windows<commit_after>#include "Semaphore.h" #ifdef WINDOWS #define WIN32_LEAN_AND_MEAN #include <Windows.h> #elif defined POSIX #include <errno.h> #endif using namespace Utilities; Semaphore::Semaphore() { #ifdef WINDOWS this->BaseSemaphore = CreateSemaphore(NULL, 0, 10000, NULL); #elif defined POSIX this->BaseSemaphore = new sem_t; sem_init(this->BaseSemaphore, 0 /* shared between threads */, 0); #endif } Semaphore::~Semaphore() { #ifdef WINDOWS CloseHandle(this->BaseSemaphore); #elif defined POSIX sem_destroy(this->BaseSemaphore); delete this->BaseSemaphore; #endif } void Semaphore::Increment() { #ifdef WINDOWS ReleaseSemaphore(this->BaseSemaphore, 1, NULL); #elif defined POSIX sem_post(this->BaseSemaphore); #endif } Semaphore::DecrementResult Semaphore::Decrement(uint32 timeout) { #ifdef WINDOWS DWORD result = WaitForSingleObject(this->BaseSemaphore, timeout); if (result == WAIT_TIMEOUT) return Semaphore::DecrementResult::TimedOut; else return Semaphore::DecrementResult::Success; #elif defined POSIX timespec ts; int result; ts.tv_nsec = timeout * 1000; while ((result = sem_timedwait(this->BaseSemaphore, &ts)) == -1 && errno == EINTR); if (result == ETIMEDOUT) return Semaphore::DecrementResult::TimedOut; else return Semaphore::DecrementResult::Success; #endif } <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2014 The Communi Project * * This library 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 2 of the License, or (at your * option) any later version. * * This library 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 for more details. */ #include "ircbuffer.h" #include "ircbuffer_p.h" #include "ircbuffermodel.h" #include "ircbuffermodel_p.h" #include "ircconnection.h" #include "ircchannel.h" IRC_BEGIN_NAMESPACE /*! \file ircbuffer.h \brief \#include &lt;IrcBuffer&gt; */ /*! \class IrcBuffer ircbuffer.h <IrcBuffer> \ingroup models \brief Keeps track of buffer status. \sa IrcBufferModel */ /*! \fn void IrcBuffer::messageReceived(IrcMessage* message) This signal is emitted when a buffer specific message is received. The message may one of the following types: - IrcMessage::Join - IrcMessage::Kick - IrcMessage::Mode - IrcMessage::Names - IrcMessage::Nick - IrcMessage::Notice - IrcMessage::Numeric - IrcMessage::Part - IrcMessage::Private - IrcMessage::Quit - IrcMessage::Topic \sa IrcConnection::messageReceived(), IrcBufferModel::messageIgnored() */ #ifndef IRC_DOXYGEN IrcBufferPrivate::IrcBufferPrivate() : q_ptr(0), model(0), persistent(false), sticky(false) { } IrcBufferPrivate::~IrcBufferPrivate() { } void IrcBufferPrivate::init(const QString& title, IrcBufferModel* m) { name = title; setModel(m); } void IrcBufferPrivate::setName(const QString& value) { Q_Q(IrcBuffer); if (name != value) { const QString oldTitle = q->title(); name = value; emit q->nameChanged(name); emit q->titleChanged(q->title()); if (model) IrcBufferModelPrivate::get(model)->renameBuffer(oldTitle, q->title()); } } void IrcBufferPrivate::setPrefix(const QString& value) { Q_Q(IrcBuffer); if (prefix != value) { const QString oldTitle = q->title(); prefix = value; emit q->prefixChanged(prefix); emit q->titleChanged(q->title()); if (model) IrcBufferModelPrivate::get(model)->renameBuffer(oldTitle, q->title()); } } void IrcBufferPrivate::setModel(IrcBufferModel* value) { model = value; } bool IrcBufferPrivate::processMessage(IrcMessage* message) { Q_Q(IrcBuffer); bool processed = false; switch (message->type()) { case IrcMessage::Join: processed = processJoinMessage(static_cast<IrcJoinMessage*>(message)); break; case IrcMessage::Kick: processed = processKickMessage(static_cast<IrcKickMessage*>(message)); break; case IrcMessage::Mode: processed = processModeMessage(static_cast<IrcModeMessage*>(message)); break; case IrcMessage::Names: processed = processNamesMessage(static_cast<IrcNamesMessage*>(message)); break; case IrcMessage::Nick: processed = processNickMessage(static_cast<IrcNickMessage*>(message)); break; case IrcMessage::Notice: processed = processNoticeMessage(static_cast<IrcNoticeMessage*>(message)); break; case IrcMessage::Numeric: processed = processNumericMessage(static_cast<IrcNumericMessage*>(message)); break; case IrcMessage::Part: processed = processPartMessage(static_cast<IrcPartMessage*>(message)); break; case IrcMessage::Private: processed = processPrivateMessage(static_cast<IrcPrivateMessage*>(message)); break; case IrcMessage::Quit: processed = processQuitMessage(static_cast<IrcQuitMessage*>(message)); break; case IrcMessage::Topic: processed = processTopicMessage(static_cast<IrcTopicMessage*>(message)); break; default: break; } if (processed) emit q->messageReceived(message); return processed; } bool IrcBufferPrivate::processJoinMessage(IrcJoinMessage* message) { Q_UNUSED(message); return false; } bool IrcBufferPrivate::processKickMessage(IrcKickMessage* message) { Q_UNUSED(message); return false; } bool IrcBufferPrivate::processModeMessage(IrcModeMessage* message) { Q_UNUSED(message); return false; } bool IrcBufferPrivate::processNamesMessage(IrcNamesMessage* message) { Q_UNUSED(message); return false; } bool IrcBufferPrivate::processNickMessage(IrcNickMessage* message) { if (!message->nick().compare(name, Qt::CaseInsensitive)) { setName(message->newNick()); return true; } return !message->newNick().compare(name, Qt::CaseInsensitive); } bool IrcBufferPrivate::processNoticeMessage(IrcNoticeMessage* message) { Q_UNUSED(message); return true; } bool IrcBufferPrivate::processNumericMessage(IrcNumericMessage* message) { Q_UNUSED(message); return true; } bool IrcBufferPrivate::processPartMessage(IrcPartMessage* message) { Q_UNUSED(message); return false; } bool IrcBufferPrivate::processPrivateMessage(IrcPrivateMessage* message) { Q_UNUSED(message); return true; } bool IrcBufferPrivate::processQuitMessage(IrcQuitMessage* message) { return !message->nick().compare(name, Qt::CaseInsensitive); } bool IrcBufferPrivate::processTopicMessage(IrcTopicMessage* message) { Q_UNUSED(message); return false; } #endif // IRC_DOXYGEN /*! Constructs a new buffer object with \a parent. */ IrcBuffer::IrcBuffer(QObject* parent) : QObject(parent), d_ptr(new IrcBufferPrivate) { Q_D(IrcBuffer); d->q_ptr = this; } /*! \internal */ IrcBuffer::IrcBuffer(IrcBufferPrivate& dd, QObject* parent) : QObject(parent), d_ptr(&dd) { Q_D(IrcBuffer); d->q_ptr = this; } /*! Destructs the buffer object. */ IrcBuffer::~IrcBuffer() { emit destroyed(this); } /*! This property holds the whole buffer title. The title consists of \ref prefix and \ref name. \par Access function: \li QString <b>title</b>() const \par Notifier signal: \li void <b>titleChanged</b>(const QString& title) */ QString IrcBuffer::title() const { Q_D(const IrcBuffer); return d->prefix + d->name; } /*! This property holds the name part of the buffer \ref title. \par Access functions: \li QString <b>name</b>() const \li void <b>setName</b>(const QString& name) [slot] \par Notifier signal: \li void <b>nameChanged</b>(const QString& name) */ QString IrcBuffer::name() const { Q_D(const IrcBuffer); return d->name; } void IrcBuffer::setName(const QString& name) { Q_D(IrcBuffer); d->setName(name); } /*! This property holds the prefix part of the buffer \ref title. \par Access functions: \li QString <b>prefix</b>() const \li void <b>setPrefix</b>(const QString& prefix) [slot] \par Notifier signal: \li void <b>prefixChanged</b>(const QString& prefix) */ QString IrcBuffer::prefix() const { Q_D(const IrcBuffer); return d->prefix; } void IrcBuffer::setPrefix(const QString& prefix) { Q_D(IrcBuffer); return d->setPrefix(prefix); } /*! \property bool IrcBuffer::channel This property holds whether the buffer is a channel. \par Access function: \li bool <b>isChannel</b>() const \sa toChannel() */ bool IrcBuffer::isChannel() const { return inherits("IrcChannel"); } /*! Returns the buffer cast to a IrcChannel, if the class is actually a channel, \c 0 otherwise. \sa \ref channel "isChannel()" */ IrcChannel* IrcBuffer::toChannel() { return qobject_cast<IrcChannel*>(this); } /*! This property holds the connection of the buffer. \par Access function: \li \ref IrcConnection* <b>connection</b>() const */ IrcConnection* IrcBuffer::connection() const { Q_D(const IrcBuffer); return d->model ? d->model->connection() : 0; } /*! This property holds the network of the buffer. \par Access function: \li \ref IrcNetwork* <b>network</b>() const */ IrcNetwork* IrcBuffer::network() const { Q_D(const IrcBuffer); return d->model ? d->model->network() : 0; } /*! This property holds the model of the buffer. \par Access function: \li \ref IrcBufferModel* <b>model</b>() const */ IrcBufferModel* IrcBuffer::model() const { Q_D(const IrcBuffer); return d->model; } /*! \property bool IrcBuffer::active This property holds whether the buffer is active. A buffer is considered active when a %connection is established. Furthermore, channel buffers are only considered active when the user is on the channel. \par Access function: \li bool <b>isActive</b>() const \par Notifier signal: \li void <b>activeChanged</b>(bool active) \sa IrcConnection::connected */ bool IrcBuffer::isActive() const { if (IrcConnection* c = connection()) return c->isConnected(); return false; } /*! \property bool IrcBuffer::sticky This property holds whether the buffer is sticky. A sticky buffer stays in the beginning (Qt::AscendingOrder) or end (Qt::DescendingOrder) of the list of buffers in IrcBufferModel. The default value is \c false. \par Access functions: \li bool <b>isSticky</b>() const \li void <b>setSticky</b>(bool sticky) \par Notifier signal: \li void <b>stickyChanged</b>(bool sticky) */ bool IrcBuffer::isSticky() const { Q_D(const IrcBuffer); return d->sticky; } void IrcBuffer::setSticky(bool sticky) { Q_D(IrcBuffer); if (d->sticky != sticky) { d->sticky = sticky; emit stickyChanged(sticky); } } /*! \property bool IrcBuffer::persistent This property holds whether the buffer is persistent. The default value is \c false. A persistent buffer does not get removed and destructed when calling IrcBufferModel::clear(), or when when leaving the corresponding channel. In order to remove a persistent buffer, either explicitly call IrcBufferModel::remove() or delete the buffer. \par Access functions: \li bool <b>isPersistent</b>() const \li void <b>setPersistent</b>(bool persistent) \par Notifier signal: \li void <b>persistentChanged</b>(bool persistent) */ bool IrcBuffer::isPersistent() const { Q_D(const IrcBuffer); return d->persistent; } void IrcBuffer::setPersistent(bool persistent) { Q_D(IrcBuffer); if (d->persistent != persistent) { d->persistent = persistent; emit persistentChanged(persistent); } } /*! Sends a \a command to the server. This method is provided for convenience. It is equal to: \code IrcConnection* connection = buffer->connection(); connection->sendCommand(command); \endcode \sa IrcConnection::sendCommand() */ bool IrcBuffer::sendCommand(IrcCommand* command) { if (IrcConnection* c = connection()) return c->sendCommand(command); return false; } /*! Emits messageReceived() with \a message. IrcBufferModel handles only buffer specific messages and delivers them to the appropriate IrcBuffer instances. When applications decide to handle IrcBuffer::messageReceived(), IrcBufferModel::messageIgnored() makes it easy to implement handling for the rest, non-buffer specific messages. This method can be used to forward such ignored messages to the desired buffers (for instance the one that is currently active in the GUI). */ void IrcBuffer::receiveMessage(IrcMessage* message) { if (message) emit messageReceived(message); } #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug debug, const IrcBuffer* buffer) { if (!buffer) return debug << "IrcBuffer(0x0) "; debug.nospace() << buffer->metaObject()->className() << '(' << (void*) buffer; if (!buffer->objectName().isEmpty()) debug.nospace() << ", name=" << qPrintable(buffer->objectName()); if (!buffer->title().isEmpty()) debug.nospace() << ", title=" << qPrintable(buffer->title()); debug.nospace() << ')'; return debug.space(); } #endif // QT_NO_DEBUG_STREAM #include "moc_ircbuffer.cpp" IRC_END_NAMESPACE <commit_msg>Fix IrcBuffer::isChannel() for namespaced builds<commit_after>/* * Copyright (C) 2008-2014 The Communi Project * * This library 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 2 of the License, or (at your * option) any later version. * * This library 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 for more details. */ #include "ircbuffer.h" #include "ircbuffer_p.h" #include "ircbuffermodel.h" #include "ircbuffermodel_p.h" #include "ircconnection.h" #include "ircchannel.h" IRC_BEGIN_NAMESPACE /*! \file ircbuffer.h \brief \#include &lt;IrcBuffer&gt; */ /*! \class IrcBuffer ircbuffer.h <IrcBuffer> \ingroup models \brief Keeps track of buffer status. \sa IrcBufferModel */ /*! \fn void IrcBuffer::messageReceived(IrcMessage* message) This signal is emitted when a buffer specific message is received. The message may one of the following types: - IrcMessage::Join - IrcMessage::Kick - IrcMessage::Mode - IrcMessage::Names - IrcMessage::Nick - IrcMessage::Notice - IrcMessage::Numeric - IrcMessage::Part - IrcMessage::Private - IrcMessage::Quit - IrcMessage::Topic \sa IrcConnection::messageReceived(), IrcBufferModel::messageIgnored() */ #ifndef IRC_DOXYGEN IrcBufferPrivate::IrcBufferPrivate() : q_ptr(0), model(0), persistent(false), sticky(false) { } IrcBufferPrivate::~IrcBufferPrivate() { } void IrcBufferPrivate::init(const QString& title, IrcBufferModel* m) { name = title; setModel(m); } void IrcBufferPrivate::setName(const QString& value) { Q_Q(IrcBuffer); if (name != value) { const QString oldTitle = q->title(); name = value; emit q->nameChanged(name); emit q->titleChanged(q->title()); if (model) IrcBufferModelPrivate::get(model)->renameBuffer(oldTitle, q->title()); } } void IrcBufferPrivate::setPrefix(const QString& value) { Q_Q(IrcBuffer); if (prefix != value) { const QString oldTitle = q->title(); prefix = value; emit q->prefixChanged(prefix); emit q->titleChanged(q->title()); if (model) IrcBufferModelPrivate::get(model)->renameBuffer(oldTitle, q->title()); } } void IrcBufferPrivate::setModel(IrcBufferModel* value) { model = value; } bool IrcBufferPrivate::processMessage(IrcMessage* message) { Q_Q(IrcBuffer); bool processed = false; switch (message->type()) { case IrcMessage::Join: processed = processJoinMessage(static_cast<IrcJoinMessage*>(message)); break; case IrcMessage::Kick: processed = processKickMessage(static_cast<IrcKickMessage*>(message)); break; case IrcMessage::Mode: processed = processModeMessage(static_cast<IrcModeMessage*>(message)); break; case IrcMessage::Names: processed = processNamesMessage(static_cast<IrcNamesMessage*>(message)); break; case IrcMessage::Nick: processed = processNickMessage(static_cast<IrcNickMessage*>(message)); break; case IrcMessage::Notice: processed = processNoticeMessage(static_cast<IrcNoticeMessage*>(message)); break; case IrcMessage::Numeric: processed = processNumericMessage(static_cast<IrcNumericMessage*>(message)); break; case IrcMessage::Part: processed = processPartMessage(static_cast<IrcPartMessage*>(message)); break; case IrcMessage::Private: processed = processPrivateMessage(static_cast<IrcPrivateMessage*>(message)); break; case IrcMessage::Quit: processed = processQuitMessage(static_cast<IrcQuitMessage*>(message)); break; case IrcMessage::Topic: processed = processTopicMessage(static_cast<IrcTopicMessage*>(message)); break; default: break; } if (processed) emit q->messageReceived(message); return processed; } bool IrcBufferPrivate::processJoinMessage(IrcJoinMessage* message) { Q_UNUSED(message); return false; } bool IrcBufferPrivate::processKickMessage(IrcKickMessage* message) { Q_UNUSED(message); return false; } bool IrcBufferPrivate::processModeMessage(IrcModeMessage* message) { Q_UNUSED(message); return false; } bool IrcBufferPrivate::processNamesMessage(IrcNamesMessage* message) { Q_UNUSED(message); return false; } bool IrcBufferPrivate::processNickMessage(IrcNickMessage* message) { if (!message->nick().compare(name, Qt::CaseInsensitive)) { setName(message->newNick()); return true; } return !message->newNick().compare(name, Qt::CaseInsensitive); } bool IrcBufferPrivate::processNoticeMessage(IrcNoticeMessage* message) { Q_UNUSED(message); return true; } bool IrcBufferPrivate::processNumericMessage(IrcNumericMessage* message) { Q_UNUSED(message); return true; } bool IrcBufferPrivate::processPartMessage(IrcPartMessage* message) { Q_UNUSED(message); return false; } bool IrcBufferPrivate::processPrivateMessage(IrcPrivateMessage* message) { Q_UNUSED(message); return true; } bool IrcBufferPrivate::processQuitMessage(IrcQuitMessage* message) { return !message->nick().compare(name, Qt::CaseInsensitive); } bool IrcBufferPrivate::processTopicMessage(IrcTopicMessage* message) { Q_UNUSED(message); return false; } #endif // IRC_DOXYGEN /*! Constructs a new buffer object with \a parent. */ IrcBuffer::IrcBuffer(QObject* parent) : QObject(parent), d_ptr(new IrcBufferPrivate) { Q_D(IrcBuffer); d->q_ptr = this; } /*! \internal */ IrcBuffer::IrcBuffer(IrcBufferPrivate& dd, QObject* parent) : QObject(parent), d_ptr(&dd) { Q_D(IrcBuffer); d->q_ptr = this; } /*! Destructs the buffer object. */ IrcBuffer::~IrcBuffer() { emit destroyed(this); } /*! This property holds the whole buffer title. The title consists of \ref prefix and \ref name. \par Access function: \li QString <b>title</b>() const \par Notifier signal: \li void <b>titleChanged</b>(const QString& title) */ QString IrcBuffer::title() const { Q_D(const IrcBuffer); return d->prefix + d->name; } /*! This property holds the name part of the buffer \ref title. \par Access functions: \li QString <b>name</b>() const \li void <b>setName</b>(const QString& name) [slot] \par Notifier signal: \li void <b>nameChanged</b>(const QString& name) */ QString IrcBuffer::name() const { Q_D(const IrcBuffer); return d->name; } void IrcBuffer::setName(const QString& name) { Q_D(IrcBuffer); d->setName(name); } /*! This property holds the prefix part of the buffer \ref title. \par Access functions: \li QString <b>prefix</b>() const \li void <b>setPrefix</b>(const QString& prefix) [slot] \par Notifier signal: \li void <b>prefixChanged</b>(const QString& prefix) */ QString IrcBuffer::prefix() const { Q_D(const IrcBuffer); return d->prefix; } void IrcBuffer::setPrefix(const QString& prefix) { Q_D(IrcBuffer); return d->setPrefix(prefix); } /*! \property bool IrcBuffer::channel This property holds whether the buffer is a channel. \par Access function: \li bool <b>isChannel</b>() const \sa toChannel() */ bool IrcBuffer::isChannel() const { return qobject_cast<const IrcChannel*>(this); } /*! Returns the buffer cast to a IrcChannel, if the class is actually a channel, \c 0 otherwise. \sa \ref channel "isChannel()" */ IrcChannel* IrcBuffer::toChannel() { return qobject_cast<IrcChannel*>(this); } /*! This property holds the connection of the buffer. \par Access function: \li \ref IrcConnection* <b>connection</b>() const */ IrcConnection* IrcBuffer::connection() const { Q_D(const IrcBuffer); return d->model ? d->model->connection() : 0; } /*! This property holds the network of the buffer. \par Access function: \li \ref IrcNetwork* <b>network</b>() const */ IrcNetwork* IrcBuffer::network() const { Q_D(const IrcBuffer); return d->model ? d->model->network() : 0; } /*! This property holds the model of the buffer. \par Access function: \li \ref IrcBufferModel* <b>model</b>() const */ IrcBufferModel* IrcBuffer::model() const { Q_D(const IrcBuffer); return d->model; } /*! \property bool IrcBuffer::active This property holds whether the buffer is active. A buffer is considered active when a %connection is established. Furthermore, channel buffers are only considered active when the user is on the channel. \par Access function: \li bool <b>isActive</b>() const \par Notifier signal: \li void <b>activeChanged</b>(bool active) \sa IrcConnection::connected */ bool IrcBuffer::isActive() const { if (IrcConnection* c = connection()) return c->isConnected(); return false; } /*! \property bool IrcBuffer::sticky This property holds whether the buffer is sticky. A sticky buffer stays in the beginning (Qt::AscendingOrder) or end (Qt::DescendingOrder) of the list of buffers in IrcBufferModel. The default value is \c false. \par Access functions: \li bool <b>isSticky</b>() const \li void <b>setSticky</b>(bool sticky) \par Notifier signal: \li void <b>stickyChanged</b>(bool sticky) */ bool IrcBuffer::isSticky() const { Q_D(const IrcBuffer); return d->sticky; } void IrcBuffer::setSticky(bool sticky) { Q_D(IrcBuffer); if (d->sticky != sticky) { d->sticky = sticky; emit stickyChanged(sticky); } } /*! \property bool IrcBuffer::persistent This property holds whether the buffer is persistent. The default value is \c false. A persistent buffer does not get removed and destructed when calling IrcBufferModel::clear(), or when when leaving the corresponding channel. In order to remove a persistent buffer, either explicitly call IrcBufferModel::remove() or delete the buffer. \par Access functions: \li bool <b>isPersistent</b>() const \li void <b>setPersistent</b>(bool persistent) \par Notifier signal: \li void <b>persistentChanged</b>(bool persistent) */ bool IrcBuffer::isPersistent() const { Q_D(const IrcBuffer); return d->persistent; } void IrcBuffer::setPersistent(bool persistent) { Q_D(IrcBuffer); if (d->persistent != persistent) { d->persistent = persistent; emit persistentChanged(persistent); } } /*! Sends a \a command to the server. This method is provided for convenience. It is equal to: \code IrcConnection* connection = buffer->connection(); connection->sendCommand(command); \endcode \sa IrcConnection::sendCommand() */ bool IrcBuffer::sendCommand(IrcCommand* command) { if (IrcConnection* c = connection()) return c->sendCommand(command); return false; } /*! Emits messageReceived() with \a message. IrcBufferModel handles only buffer specific messages and delivers them to the appropriate IrcBuffer instances. When applications decide to handle IrcBuffer::messageReceived(), IrcBufferModel::messageIgnored() makes it easy to implement handling for the rest, non-buffer specific messages. This method can be used to forward such ignored messages to the desired buffers (for instance the one that is currently active in the GUI). */ void IrcBuffer::receiveMessage(IrcMessage* message) { if (message) emit messageReceived(message); } #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug debug, const IrcBuffer* buffer) { if (!buffer) return debug << "IrcBuffer(0x0) "; debug.nospace() << buffer->metaObject()->className() << '(' << (void*) buffer; if (!buffer->objectName().isEmpty()) debug.nospace() << ", name=" << qPrintable(buffer->objectName()); if (!buffer->title().isEmpty()) debug.nospace() << ", title=" << qPrintable(buffer->title()); debug.nospace() << ')'; return debug.space(); } #endif // QT_NO_DEBUG_STREAM #include "moc_ircbuffer.cpp" IRC_END_NAMESPACE <|endoftext|>
<commit_before>#include "Tests.h" #include "../Test/UnitTest++/UnitTest++.h" #include "Scheduler.h" //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace SimpleTask { static int sourceData = 0xFF33FF; static int resultData = 0; void MT_CALL_CONV Run(MT::FiberContext& context, void* userData) { resultData = *(int*)userData; } } // Checks one simple task TEST(RunOneSimpleTask) { MT::TaskScheduler scheduler; MT::TaskDesc task(SimpleTask::Run, &SimpleTask::sourceData); scheduler.RunTasks(MT::TaskGroup::GROUP_0, &task, 1); CHECK(scheduler.WaitAll(100)); CHECK_EQUAL(SimpleTask::sourceData, SimpleTask::resultData); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace LongTask { static int timeLimitMS = 100; void MT_CALL_CONV Run(MT::FiberContext& context, void* userData) { Sleep(timeLimitMS * 2); } } // Checks one simple task TEST(RunLongTaskAndNotFinish) { MT::TaskScheduler scheduler; MT::TaskDesc task(LongTask::Run, nullptr); scheduler.RunTasks(MT::TaskGroup::GROUP_0, &task, 1); CHECK(!scheduler.WaitAll(LongTask::timeLimitMS)); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace DeepSubtaskQueue { template<size_t N> void MT_CALL_CONV Fibonacci(MT::FiberContext& context, void* userData) { int& result = *(int*)userData; MT::TaskDesc tasks[2]; int a = -100; tasks[0] = MT::TaskDesc(Fibonacci<N - 1>, &a); int b = -100; tasks[1] = MT::TaskDesc(Fibonacci<N - 2>, &b); context.RunSubtasks(&tasks[0], ARRAY_SIZE(tasks)); result = a + b; } template<> void MT_CALL_CONV Fibonacci<0>(MT::FiberContext& context, void* userData) { *(int*)userData = 0; } template<> void MT_CALL_CONV Fibonacci<1>(MT::FiberContext& context, void* userData) { *(int*)userData = 1; } } // Checks one simple task TEST(DeepSubtaskQueue) { MT::TaskScheduler scheduler; int result = 0; MT::TaskDesc task(DeepSubtaskQueue::Fibonacci<13>, &result); scheduler.RunTasks(MT::TaskGroup::GROUP_0, &task, 1); CHECK(scheduler.WaitAll(200)); CHECK_EQUAL(result, 233); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int Tests::RunAll() { return UnitTest::RunAllTests(); } <commit_msg>Added SubTask group<commit_after>#include "Tests.h" #include "../Test/UnitTest++/UnitTest++.h" #include "Scheduler.h" //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace SimpleTask { static int sourceData = 0xFF33FF; static int resultData = 0; void MT_CALL_CONV Run(MT::FiberContext& context, void* userData) { resultData = *(int*)userData; } } // Checks one simple task TEST(RunOneSimpleTask) { MT::TaskScheduler scheduler; MT::TaskDesc task(SimpleTask::Run, &SimpleTask::sourceData); scheduler.RunTasks(MT::TaskGroup::GROUP_0, &task, 1); CHECK(scheduler.WaitAll(100)); CHECK_EQUAL(SimpleTask::sourceData, SimpleTask::resultData); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace LongTask { static int timeLimitMS = 100; void MT_CALL_CONV Run(MT::FiberContext& context, void* userData) { Sleep(timeLimitMS * 2); } } // Checks one simple task TEST(RunLongTaskAndNotFinish) { MT::TaskScheduler scheduler; MT::TaskDesc task(LongTask::Run, nullptr); scheduler.RunTasks(MT::TaskGroup::GROUP_0, &task, 1); CHECK(!scheduler.WaitAll(LongTask::timeLimitMS)); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace DeepSubtaskQueue { template<size_t N> void MT_CALL_CONV Fibonacci(MT::FiberContext& context, void* userData) { int& result = *(int*)userData; MT::TaskDesc tasks[2]; int a = -100; tasks[0] = MT::TaskDesc(Fibonacci<N - 1>, &a); int b = -100; tasks[1] = MT::TaskDesc(Fibonacci<N - 2>, &b); context.RunSubtasks(&tasks[0], ARRAY_SIZE(tasks)); result = a + b; } template<> void MT_CALL_CONV Fibonacci<0>(MT::FiberContext& context, void* userData) { *(int*)userData = 0; } template<> void MT_CALL_CONV Fibonacci<1>(MT::FiberContext& context, void* userData) { *(int*)userData = 1; } } // Checks one simple task TEST(DeepSubtaskQueue) { MT::TaskScheduler scheduler; int result = 0; MT::TaskDesc task(DeepSubtaskQueue::Fibonacci<13>, &result); scheduler.RunTasks(MT::TaskGroup::GROUP_0, &task, 1); CHECK(scheduler.WaitAll(200)); CHECK_EQUAL(result, 233); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace SubtaskGroup { static MT::TaskGroup::Type sourceGroup = MT::TaskGroup::GROUP_1; static MT::TaskGroup::Type resultGroup = MT::TaskGroup::GROUP_UNDEFINED; void MT_CALL_CONV Subtask(MT::FiberContext& context, void*) { resultGroup = context.activeTask->taskGroup; } void MT_CALL_CONV Task(MT::FiberContext& context, void*) { MT::TaskDesc task(Subtask, 0); context.RunSubtasks(&task, 1); } } // Checks one simple task TEST(SubtaskGroup) { MT::TaskScheduler scheduler; MT::TaskDesc task(SubtaskGroup::Task, 0); scheduler.RunTasks(SubtaskGroup::sourceGroup, &task, 1); CHECK(scheduler.WaitAll(200)); CHECK_EQUAL(SubtaskGroup::sourceGroup, SubtaskGroup::resultGroup); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int Tests::RunAll() { return UnitTest::RunAllTests(); } <|endoftext|>