text
stringlengths
8
6.88M
#pragma once #include "config.hpp" #include <array> #include <cstddef> #include <cstdint> #include <vector> namespace octotiger { struct fx_args { std::int64_t opts_eos; std::int64_t opts_problem; double opts_dual_energy_sw1; double opts_dual_energy_sw2; double physcon_A; double physcon_B; double physcon_c; std::int64_t er_i{}; std::int64_t fx_i{}; std::int64_t fy_i{}; std::int64_t fz_i{}; std::int64_t d{}; std::vector<double> rho{}; std::vector<double> sx{}; std::vector<double> sy{}; std::vector<double> sz{}; std::vector<double> egas{}; std::vector<double> tau{}; double fgamma{}; std::array<std::vector<double>, NRF> U{}; std::vector<double> mmw{}; std::vector<double> X_spc{}; std::vector<double> Z_spc{}; double dt{}; double clightinv{}; }; struct fx_outs { std::vector<double> sx{}; std::vector<double> sy{}; std::vector<double> sz{}; std::vector<double> egas{}; std::vector<double> tau{}; std::array<std::vector<double>, NRF> U{}; }; struct fx_case { std::size_t index{}; std::size_t data_size{}; fx_args args; fx_outs outs; }; fx_args load_case_args(std::size_t index); fx_outs load_case_outs(std::size_t index); fx_case import_case(std::size_t index); }
// // Created by zlc on 2021/5/26. // #include "../include/part_slam/gridfastslam/gridslamprocessor.h" namespace GMapping { using namespace std; // const double ScanMatcher::nullLikelihood = -.5; // 单个节点的构造函数: 树的节点,一个树存了以整条轨迹,一个节点表示这条轨迹中的其中一个点。存储激光雷达的整条轨迹 GridSlamProcessor::TNode::TNode(const OrientedPoint& p, TNode* n) { pose = p; parent = n; reading = 0; } GridSlamProcessor::TNode::~TNode() { if (parent) delete parent; } // 单个粒子结构体的构造函数 GridSlamProcessor::Particle::Particle(const ScanMatcherMap& m) : map(m), pose(0, 0, 0), weight(0), weightSum(0) { node = 0; } // GridSlamProcessor 主要类的 构造函数:初始化一些参数 GridSlamProcessor::GridSlamProcessor() { period_ = 3.0; // 两次更新时间的最小间隔 m_obsSigmaGain = 1; m_resampleThreshold = 0.5; // 粒子选择性重采样的阈值 m_minimumScore = 0.; // 认为匹配成功的最小得分阈值 } GridSlamProcessor::~GridSlamProcessor() { // 销毁所有粒子的轨迹 for (std::vector<Particle>::iterator it=m_particles_.begin(); it!=m_particles_.end(); it ++) { if (it->node) delete it->node; } } void GridSlamProcessor::setMatchingParameters(double urange, double range, double sigma, int kernel_size, double l_opt, double a_opt, int iterations, double likelihoodSigma, double likelihoodGain, unsigned int likelihoodSkip) { m_obsSigmaGain = likelihoodGain; m_matcher.setMatchingParameters(urange, range, sigma, kernel_size, l_opt, a_opt, iterations, likelihoodSigma, likelihoodSkip); } // 设置运动模型参数 void GridSlamProcessor::setMotionModelParameters(double srr, double srt, double str, double stt) { m_motionModel_.srr = srr; // srr 线性运动造成的线性误差的方差 m_motionModel_.srt = srt; // srt 线性运动造成的角度误差的方差 m_motionModel_.str = str; // str 旋转运动造成的线性误差的方差 m_motionModel_.stt = stt; // stt 旋转运动造成的角度误差的方差 } // 设置更新参数,只有当雷达走过一定的距离 或者 旋转过一定的角度才重新处理一帧数据 void GridSlamProcessor::setUpdateDistances(double linear, double angular, double resampleThreshold) { m_linearThresholdDistance = linear; m_angularThresholdDistance = angular; m_resampleThreshold = resampleThreshold; } void GridSlamProcessor::init(unsigned int size, double x_min, double y_min, double x_max, double y_max, double delta, OrientedPoint initialPose) { // 设置地图大小,分辨率 m_x_min = x_min; m_y_min = y_min; m_x_max = x_max; m_y_max = y_max; m_delta = delta; // 初始化每个粒子 m_particles_.clear(); // new一个树的根节点,初始位姿initialPose,根节点为0 TNode* node = new TNode(initialPose, 0); // 粒子对应的地图进行初始化 ScanMatcherMap lmap(Point(x_min+x_max, y_min+y_max)*.5, x_max-x_min, y_max-y_min, delta); // 为每个粒子,设置地图,初始位姿,之前的位姿,权重等等 for (unsigned int i=0; i<size; i ++) { m_particles_.push_back(Particle(lmap)); // 每个粒子设置的初始地图,同一个 m_particles_.back().pose = initialPose; // 每个粒子的初始位姿 m_particles_.back().setWeight(0); // 每个粒子的初始权重 m_particles_.back().node = node; // 每一个粒子设置初始父节点,同一个 } m_neff = (double)size; m_count_ = 0; // m_count表示这个函数被调用的次数 m_linearDistance_ = m_angularDistance_ = 0; } // △△△△△△ SLAM核心代码 △△△△△△ bool GridSlamProcessor::processScan(const RangeReading& reading, int adaptParticles) { // 得分当前激光雷达的里程计位姿 OrientedPoint relPose = reading.getPose(); // m_count表示这个函数被调用的次数 if (!m_count_) // 如果是第一次调用本函数 { m_odoPose_ = relPose; // 上一次的激光雷达里程计位姿 = 本次激光雷达里程计位姿 } // 对于每一个粒子,都要通过里程计运动模型更新每一个粒子对象存储的地图坐标系下的激光雷达位姿 int tmp_size = m_particles_.size(); // 这里做一下说明,对于vector数组的遍历,对比了以下,release模式下几乎无差别,这里用最易读的方式 for (int i=0; i<tmp_size; i ++) { // 对于每一个粒子,将从运动模型传播的激光雷达位姿存放到m_particles[i].pose (最新的地图坐标系下的激光雷达位姿) OrientedPoint& pose(m_particles_[i].pose); pose = m_motionModel_.drawFromMotion(m_particles_[i].pose, relPose, m_odoPose_); // 这里一定要区分三个位姿 // m_particles[i].pose:最新的地图坐标系下的激光雷达最优位姿 relPose:当前机关雷达里程计位姿 m_odoPose:表示上一次的激光雷达里程计位姿 } /*根据两次里程计的数据 计算出来激光雷达的线性位移和角度变化*/ OrientedPoint move = relPose - m_odoPose_; Point temp(move.x, move.y); // 激光雷达在里程计作用下的累计移动线性距离和累计角度变换,用于判断是否,进行核心算法处理 // 处理完后,m_linearDistance 和 m_angularDistance 清零 m_linearDistance_ += sqrt(temp * temp); // 两点之间距离公式 m_angularDistance_ += fabs(move.theta); // 更新上一次的激光雷达的里程计位姿 m_odoPose_ = relPose; // 做返回值用 bool processed = false; // 自己修改的,这个比较随意 last_update_time_ += 1.0; // 只有当激光雷达走过一定的距离 或者 旋转过一定的角度 或者 经一段指定的时间才处理激光数据 或者 处理第一帧数据 if (!m_count_ || m_linearDistance_ >= m_linearThresholdDistance || m_angularDistance_ >= m_angularThresholdDistance || (period_ >= 0.0 && (last_update_time_) >period_)) { last_update_time_ = 0; // 拷贝reading的scan的range数据 int beam_number = reading.getSize(); double* plainReading = new double[beam_number]; for (unsigned int i=0; i<beam_number; i ++) { plainReading[i] = reading.m_dists[i]; } // reading_copy数据用来放在每一个节点,构建地图用 RangeReading* reading_copy = new RangeReading(beam_number, &(reading.m_dists[0]), &(reading.m_angles[0])); // 如果不是第一帧数据 if (m_count_ > 0) { // 功能:为每一个粒子,在当前激光雷达位姿下,当前帧激光数据下,求解每个粒子的位姿最优值(策略:爬山,评价机制:得分机制(激光雷达在当前里程计位姿下激光数据和当前地图的的匹配程度)) // 求解每个粒子的权重 // 爬山算法:每一层,从不同方向寻找一个得分最高的一个值,直到出现得分开始下降的地方 // 得分算法:根据当前位姿下的一帧激光扫描点和地图的匹配程度,对每一个激光点做计算,累积得分,返回得分 // 通过扫描匹配寻找每一个粒子的激光雷达在地图坐标系下的最优位姿,并且计算粒子得分 scanMatch(plainReading); // 计算重采样的neff(粒子离散程度)的判断值 normalize(); // 重采样 if(resample(plainReading, adaptParticles, reading_copy)) { // 进行重采样之后,粒子的权重又会发生变化,更新归一化的权重,否则无需normalize normalize(); } } else { // 如果是第一帧数据,则可以直接计算activeArea,因此这个时候,对激光雷达的位置是非常确定的,就是(0,0,0) for (ParticleVector::iterator it=m_particles_.begin(); it!=m_particles_.end(); it ++) { // 拓展地图大小、找到地图的有效区域,单位patch,申请内存、更新每个栅格的内容 m_matcher.computeMap(it->map, it->pose, plainReading); // 为每个粒子创建路径的第一个节点。该节点的权重为0,父节点为it->node(这个时候为NULL)。 TNode* node = new TNode(it->pose, it->node); node->reading = reading_copy; // 根节点的激光雷达数据 it->node = node; } // 第一帧数据权重归一化更新 normalize(); } delete [] plainReading; // 激光雷达累计行走的多远的路程没有进行里程计的更新 每次更新完毕之后都要把这个数值清零 m_linearDistance_ = 0; m_angularDistance_ = 0; // 对激光帧计数 m_count_ ++; processed = true; } return processed; } // 找到最大权重粒子的序号 int GridSlamProcessor::getBestParticleIndex() const { unsigned int bi=0; double bw = -std::numeric_limits<double>::max(); for (unsigned int i=0; i<m_particles_.size(); i ++) { if (bw < m_particles_[i].weightSum) { bw = m_particles_[i].weightSum; // 粒子累计最大权重 bi = i; // 粒子序号 } } return (int) bi; } };
#ifndef _HS_SFM_BUNDLE_ADJUSTMENT_CAMERA_SHARED_ANALYTICAL_JACOBIAN_MATRIX_CALCULATOR_HPP_ #define _HS_SFM_BUNDLE_ADJUSTMENT_CAMERA_SHARED_ANALYTICAL_JACOBIAN_MATRIX_CALCULATOR_HPP_ #include "hs_sfm/bundle_adjustment/camera_shared_jacobian_matrix.hpp" namespace hs { namespace sfm { namespace ba { template <typename _VectorFunction> class CameraSharedAnalyticalJacobianMatrixCalculator; template <typename _Scalar> class CameraSharedAnalyticalJacobianMatrixCalculator< CameraSharedVectorFunction<_Scalar> > { public: typedef _Scalar Scalar; typedef int Err; typedef CameraSharedVectorFunction<Scalar> VectorFunction; typedef typename VectorFunction::XVector XVector; typedef typename VectorFunction::YVector YVector; typedef typename VectorFunction::Index Index; typedef CameraSharedJacobianMatrix<Scalar> JacobianMatrix; private: typedef typename VectorFunction::ImageCameraMap ImageCameraMap; typedef typename VectorFunction::FeatureMap FeatureMap; typedef typename VectorFunction::FeatureMapContainer FeatureMapContainer; typedef typename JacobianMatrix::DerivativeId DerivativeId; typedef typename JacobianMatrix::KeyMap KeyMap; typedef typename JacobianMatrix::KeyMapContainer KeyMapContainer; typedef EIGEN_VECTOR(Scalar, 3) Vector3; typedef EIGEN_VECTOR(Scalar, 2) Vector2; typedef EIGEN_VECTOR(Scalar, Eigen::Dynamic) VectorX; typedef EIGEN_MATRIX(Scalar, 3, 3) Matrix33; typedef EIGEN_MATRIX(Scalar, VectorFunction::params_per_key_, VectorFunction::params_per_point_) PointDerivative; typedef EIGEN_MATRIX(Scalar, VectorFunction::params_per_key_, VectorFunction::extrinsic_params_per_image_) ExtrinsicDerivative; typedef EIGEN_MATRIX(Scalar, VectorFunction::params_per_key_, 3) RadialDerivative; typedef EIGEN_MATRIX(Scalar, VectorFunction::params_per_key_, 2) DecenteringDerivative; typedef EIGEN_MATRIX(Scalar, VectorFunction::params_per_key_, 5) IntrinsicDerivative; typedef EIGEN_ROW_VECTOR(Scalar, VectorFunction::params_per_point_) RadiusPointDerivative; typedef EIGEN_ROW_VECTOR(Scalar, VectorFunction::extrinsic_params_per_image_) RadiusExtrinsicDerivative; public: Err operator() (const VectorFunction& vector_function, const XVector& x, JacobianMatrix& jacobian_matrix) const { Index number_of_images = vector_function.number_of_images(); Index number_of_points = vector_function.number_of_points(); Index number_of_cameras = vector_function.number_of_cameras(); Index number_of_keys = vector_function.number_of_keys(); const FeatureMapContainer& feature_maps = vector_function.feature_maps(); const ImageCameraMap& image_camera_map = vector_function.image_camera_map(); Index x_size = vector_function.GetXSize(); jacobian_matrix.Clear(); jacobian_matrix.set_number_of_images(number_of_images); jacobian_matrix.set_number_of_points(number_of_points); jacobian_matrix.set_number_of_cameras(number_of_cameras); jacobian_matrix.intrinsic_computations_mask() = vector_function.intrinsic_computations_mask(); Index point_params_size = vector_function.GetPointParamsSize(); Index extrinsic_params_size = vector_function.GetExtrinsicParamsSize(); Index intrinsic_params_size_per_camera = vector_function.GetIntrinsicParamsSizePerCamera(); Index x_point_begin = 0; Index x_image_begin = vector_function.is_fix_points() ? 0 : point_params_size; Index x_camera_begin = (vector_function.is_fix_points() ? 0 : point_params_size) + (vector_function.is_fix_images() ? 0 : extrinsic_params_size); for (Index i = 0; i < number_of_keys; i++) { const FeatureMap& feature_map = feature_maps[i]; Index image_id = feature_map.first; Index point_id = feature_map.second; Index camera_id = image_camera_map[image_id]; KeyMap key_map; key_map.point_id = point_id; key_map.image_id = image_id; key_map.camera_id = camera_id; jacobian_matrix.key_maps().push_back(key_map); Vector3 point = vector_function.is_fix_points() ? vector_function.fix_points()[point_id] : x.segment(point_id * VectorFunction::params_per_point_, VectorFunction::params_per_point_); Vector3 rotation, translation; if (vector_function.is_fix_images()) { rotation = vector_function.fix_images()[image_id].segment(0, 3); translation = vector_function.fix_images()[image_id].segment(3, 3); } else { rotation = x.segment(x_image_begin + image_id * VectorFunction::extrinsic_params_per_image_, 3); translation = x.segment(x_image_begin + image_id * VectorFunction::extrinsic_params_per_image_ + 3, 3); } VectorX intrinsic_params = vector_function.is_fix_cameras() ? vector_function.fix_cameras()[camera_id] : x.segment(x_camera_begin + camera_id * intrinsic_params_size_per_camera, intrinsic_params_size_per_camera); Vector2 normalized_key; VectorFunction::WorldPointToNormalizedKey(point, rotation, translation, normalized_key); PointDerivative pnpp; ExtrinsicDerivative pnpe; WorldPointToNormalizedPointDerivation(point, rotation, translation, pnpe, pnpp); Index intrinsic_offset = 0; RadialDerivative prdpr; PointDerivative prdpp; ExtrinsicDerivative prdpe; Vector2 rd; if (vector_function.intrinsic_computations_mask()[ COMPUTE_RADIAL_DISTORTION]) { Scalar k1 = intrinsic_params[intrinsic_offset + 0]; Scalar k2 = intrinsic_params[intrinsic_offset + 1]; Scalar k3 = intrinsic_params[intrinsic_offset + 2]; VectorFunction::GetRadialDistortDelta(k1, k2, k3, normalized_key, rd); RadialDistortDerivation(normalized_key, pnpp, pnpe, k1, k2, k3, prdpp, prdpe, prdpr); intrinsic_offset += 3; } DecenteringDerivative pddpd; PointDerivative pddpp; ExtrinsicDerivative pddpe; Vector2 dd; if (vector_function.intrinsic_computations_mask()[ COMPUTE_DECENTERING_DISTORTION]) { Scalar d1 = intrinsic_params[intrinsic_offset + 0]; Scalar d2 = intrinsic_params[intrinsic_offset + 1]; VectorFunction::GetDecenteringDistortDelta(d1, d2, normalized_key, dd); DecenteringDistortDerivation(normalized_key, pnpp, pnpe, d1, d2, pddpp, pddpe, pddpd); intrinsic_offset += 2; } if (vector_function.intrinsic_computations_mask()[ COMPUTE_RADIAL_DISTORTION]) { normalized_key += rd; pnpp += prdpp; pnpe += prdpe; } if (vector_function.intrinsic_computations_mask()[ COMPUTE_DECENTERING_DISTORTION]) { normalized_key += dd; pnpp += pddpp; pnpe += pddpe; } if (vector_function.intrinsic_computations_mask()[ COMPUTE_INTRINSIC_PARAMS]) { Scalar focal_length = intrinsic_params[intrinsic_offset + 0]; Scalar skew = intrinsic_params[intrinsic_offset + 1]; Scalar principal_x = intrinsic_params[intrinsic_offset + 2]; Scalar principal_y = intrinsic_params[intrinsic_offset + 3]; Scalar pixel_ratio = intrinsic_params[intrinsic_offset + 4]; if (!vector_function.is_fix_points()) { typename JacobianMatrix::PointDerivativeBlock point_block; point_block.point_id = point_id; point_block.key_id = i; IntrinsicPointDerivation(pnpp, focal_length, skew, pixel_ratio, point_block.derivative_block); jacobian_matrix.point_derivatives().push_back(point_block); } if (!vector_function.is_fix_images()) { typename JacobianMatrix::ImageDerivativeBlock image_block; image_block.image_id = image_id; image_block.key_id = i; IntrinsicExtrinsicDerivation(pnpe, focal_length, skew, pixel_ratio, image_block.derivative_block); jacobian_matrix.image_derivatives().push_back(image_block); } if (!vector_function.is_fix_cameras()) { typename JacobianMatrix::CameraDerivativeBlock camera_block; camera_block.derivative_block.resize( VectorFunction::params_per_key_, intrinsic_params_size_per_camera); camera_block.camera_id = camera_id; camera_block.key_id = i; intrinsic_offset = 0; if (vector_function.intrinsic_computations_mask()[ COMPUTE_RADIAL_DISTORTION]) { RadialDerivative pipr; IntrinsicRadialDerivation(prdpr, focal_length, skew, pixel_ratio, pipr); camera_block.derivative_block.block(0, intrinsic_offset, VectorFunction::params_per_key_, 3) = pipr; intrinsic_offset += 3; } if (vector_function.intrinsic_computations_mask()[ COMPUTE_DECENTERING_DISTORTION]) { DecenteringDerivative pipd; IntrinsicDecenteringDerivation( pddpd, focal_length, skew, pixel_ratio, pipd); camera_block.derivative_block.block(0, intrinsic_offset, VectorFunction::params_per_key_, 2) = pipd; intrinsic_offset += 2; } IntrinsicDerivative pipi; IntrinsicIntrinsicDerivation(normalized_key, focal_length, skew, principal_x, principal_y, pixel_ratio, pipi); camera_block.derivative_block.block(0, intrinsic_offset, VectorFunction::params_per_key_, 5) = pipi; jacobian_matrix.camera_derivatives().push_back(camera_block); } } else { if (!vector_function.is_fix_points()) { typename JacobianMatrix::PointDerivativeBlock point_block; point_block.point_id = point_id; point_block.key_id = i; point_block.derivative_block = pnpp; jacobian_matrix.point_derivatives().push_back(point_block); } if (!vector_function.is_fix_images()) { typename JacobianMatrix::ImageDerivativeBlock image_block; image_block.image_id = image_id; image_block.key_id = i; image_block.derivative_block = pnpe; jacobian_matrix.image_derivatives().push_back(image_block); } if (!vector_function.is_fix_cameras()) { typename JacobianMatrix::CameraDerivativeBlock camera_block; camera_block.derivative_block.resize( VectorFunction::params_per_key_, intrinsic_params_size_per_camera); camera_block.camera_id = camera_id; camera_block.key_id = i; intrinsic_offset = 0; if (vector_function.intrinsic_computations_mask()[ COMPUTE_RADIAL_DISTORTION]) { camera_block.derivative_block.block(0, intrinsic_offset, VectorFunction::params_per_key_, 3) = prdpr; intrinsic_offset += 3; } if (vector_function.intrinsic_computations_mask()[ COMPUTE_DECENTERING_DISTORTION]) { camera_block.derivative_block.block(0, intrinsic_offset, VectorFunction::params_per_key_, 2) = pddpd; intrinsic_offset += 2; } jacobian_matrix.camera_derivatives().push_back(camera_block); } } }// for (Index i = 0; i < number_of_keys; i++) if (!vector_function.is_fix_points()) jacobian_matrix.SetPointConstraints(vector_function.point_constraints()); if (!vector_function.is_fix_images()) jacobian_matrix.SetImageConstraints(vector_function.image_constraints()); if (!vector_function.is_fix_cameras()) jacobian_matrix.SetCameraConstraints( vector_function.camera_constraints()); return 0; } static Err WorldPointToNormalizedPointDerivation( const Vector3& p, const Vector3& r, const Vector3& t, ExtrinsicDerivative& extrinsic_derivative, PointDerivative& point_derivative) { Scalar theta = r.norm(); Scalar theta2 = theta * theta; Scalar theta4 = theta2 * theta2; Scalar d = r.dot(p); //sin(theta) Scalar st = std::sin(theta); //cos(theta) Scalar ct = std::cos(theta); //f = cos(theta) * p Vector3 f = ct * p; //\frac{\partial f}{\partial r} Matrix33 pfpr = p * (-st / theta * r).transpose(); //\frac{\partial f}{\partial p} Matrix33 pfpp = Matrix33::Identity() * ct; //s = sin(theta) / theta Scalar s = st / theta; //\frac{\partial s}{\partial r} Vector3 pspr = (ct * theta - st) / theta2 / theta * r; //v = r x p Vector3 v = r.cross(p); //\frac{\partial v}{\partial r} Matrix33 pvpr; pvpr << 0, p[2], -p[1], -p[2], 0, p[0], p[1], -p[0], 0; //\frac{\partial v}{\partial p} Matrix33 pvpp; pvpp << 0, -r[2], r[1], r[2], 0, -r[0], -r[1], r[0], 0; //c = (1 - cos(theta)) / theta^2 Scalar c = (1 - ct) / theta2; //\frac{partial c}{\partial r} Vector3 pcpr = (st * theta - 2 * (1 - ct)) / theta4 * r; //u = r^T * p * r Vector3 u = d * r; //\frac{partial u}{\partial r} Matrix33 pupr; pupr << d + r[0] * p[0], r[0] * p[1], r[0] * p[2], r[1] * p[0], d + r[1] * p[1], r[1] * p[2], r[2] * p[0], r[2] * p[1], d + r[2] * p[2]; //\frac{partial u}{\patial p} Matrix33 pupp; pupp << r[0] * r[0], r[0] * r[1], r[0] * r[2], r[1] * r[0], r[1] * r[1], r[1] * r[2], r[2] * r[0], r[2] * r[1], r[2] * r[2]; Vector3 y = f + s * v + c * u + t; //\frac{partial y}{\partial r} Matrix33 pypr = pfpr + v * pspr.transpose() + s * pvpr + u * pcpr.transpose() + c * pupr; //\frac{partial y}{\partial p} Matrix33 pypp = pfpp + s * pvpp + c * pupp; //\frac{partial y}{\partial t} is identity Matrix33 pypt = Matrix33::Identity(); for (Index m = 0; m < 3; m++) { //for r extrinsic_derivative(0, m) = (pypr(0, m) * y[2] - y[0] * pypr(2, m)) / y[2] / y[2]; extrinsic_derivative(1, m) = (pypr(1, m) * y[2] - y[1] * pypr(2, m)) / y[2] / y[2]; //for t extrinsic_derivative(0, 3 + m) = (pypt(0, m) * y[2] - y[0] * pypt(2, m)) / y[2] / y[2]; extrinsic_derivative(1, 3 + m) = (pypt(1, m) * y[2] - y[1] * pypt(2, m)) / y[2] / y[2]; } for (Index m = 0; m < 3; m++) { point_derivative(0, m) = (pypp(0, m) * y[2] - y[0] * pypp(2, m)) / y[2] / y[2]; point_derivative(1, m) = (pypp(1, m) * y[2] - y[1] * pypp(2, m)) / y[2] / y[2]; } return 0; } static Err RadialDistortDerivation(const Vector2& n, const PointDerivative& pnpp, const ExtrinsicDerivative& pnpe, Scalar k1, Scalar k2, Scalar k3, PointDerivative& prdpp, ExtrinsicDerivative& prdpe, RadialDerivative& radial_derivative) { Scalar r2 = n.squaredNorm(); Scalar r4 = r2 * r2; Scalar r6 = r2 * r4; RadiusPointDerivative pr2pp, pr4pp, pr6pp; RadiusExtrinsicDerivative pr2pe, pr4pe, pr6pe; pr2pp = Scalar(2) * n[0] * pnpp.row(0) + Scalar(2) * n[1] * pnpp.row(1); pr4pp = Scalar(2) * r2 * pr2pp; pr6pp = Scalar(3) * r4 * pr2pp; pr2pe = Scalar(2) * n[0] * pnpe.row(0) + Scalar(2) * n[1] * pnpe.row(1); pr4pe = Scalar(2) * r2 * pr2pe; pr6pe = Scalar(3) * r4 * pr2pe; Scalar coeff = k1 * r2 + k2 * r4 + k3 * r6; RadiusPointDerivative coeff_point_derivative = k1 * pr2pp + k2 * pr4pp + k3 * pr6pp; prdpp.row(0) = coeff_point_derivative * n[0] + coeff * pnpp.row(0); prdpp.row(1) = coeff_point_derivative * n[1] + coeff * pnpp.row(1); RadiusExtrinsicDerivative coeff_extrinsic_derivative = k1 * pr2pe + k2 * pr4pe + k3 * pr6pe; prdpe.row(0) = coeff_extrinsic_derivative * n[0] + coeff * pnpe.row(0); prdpe.row(1) = coeff_extrinsic_derivative * n[1] + coeff * pnpe.row(1); radial_derivative << r2 * n[0], r4 * n[0], r6 * n[0], r2 * n[1], r4 * n[1], r6 * n[1]; return 0; } static Err DecenteringDistortDerivation( const Vector2& n, const PointDerivative& pnpp, const ExtrinsicDerivative& pnpe, Scalar d1, Scalar d2, PointDerivative& pddpp, ExtrinsicDerivative& pddpe, DecenteringDerivative& decentering_derivative) { Scalar r2 = n.squaredNorm(); RadiusPointDerivative pr2pp = Scalar(2) * n[0] * pnpp.row(0) + Scalar(2) * n[1] * pnpp.row(1); RadiusExtrinsicDerivative pr2pe = Scalar(2) * n[0] * pnpe.row(0) + Scalar(2) * n[1] * pnpe.row(1); pddpp.row(0) = Scalar(2) * d1 * (pnpp.row(0) * n[1] + pnpp.row(1) * n[0]) + d2 * (pr2pp + Scalar(4) * n[0] * pnpp.row(0)); pddpp.row(1) = Scalar(2) * d2 * (pnpp.row(0) * n[1] + pnpp.row(1) * n[0]) + d1 * (pr2pp + Scalar(4) * n[1] * pnpp.row(1)); pddpe.row(0) = Scalar(2) * d1 * (pnpe.row(0) * n[1] + pnpe.row(1) * n[0]) + d2 * (pr2pe + Scalar(4) * n[0] * pnpe.row(0)); pddpe.row(1) = Scalar(2) * d2 * (pnpe.row(0) * n[1] + pnpe.row(1) * n[0]) + d1 * (pr2pe + Scalar(4) * n[1] * pnpe.row(1)); decentering_derivative << Scalar(2) * n[0] * n[1], r2 + Scalar(2) * n[0] * n[0], r2 + Scalar(2) * n[1] * n[1], Scalar(2) * n[0] * n[1]; return 0; } static void IntrinsicPointDerivation(const PointDerivative& pnpp, Scalar focal_length, Scalar skew, Scalar pixel_ratio, PointDerivative& pipp) { pipp.row(0) = focal_length * pnpp.row(0) + skew * pnpp.row(1); pipp.row(1) = focal_length * pixel_ratio * pnpp.row(1); } static void IntrinsicExtrinsicDerivation(const ExtrinsicDerivative& pnpe, Scalar focal_length, Scalar skew, Scalar pixel_ratio, ExtrinsicDerivative& pipe) { pipe.row(0) = focal_length * pnpe.row(0) + skew * pnpe.row(1); pipe.row(1) = focal_length * pixel_ratio * pnpe.row(1); } static void IntrinsicRadialDerivation(const RadialDerivative& prdpr, Scalar focal_length, Scalar skew, Scalar pixel_ratio, RadialDerivative& pipr) { pipr.row(0) = focal_length * prdpr.row(0) + skew * prdpr.row(1); pipr.row(1) = focal_length * pixel_ratio * prdpr.row(1); } static void IntrinsicDecenteringDerivation(const DecenteringDerivative& pddpd, Scalar focal_length, Scalar skew, Scalar pixel_ratio, DecenteringDerivative& pipd) { pipd.row(0) = focal_length * pddpd.row(0) + skew * pddpd.row(1); pipd.row(1) = focal_length * pixel_ratio * pddpd.row(1); } static void IntrinsicIntrinsicDerivation(const Vector2& n, Scalar focal_length, Scalar skew, Scalar principal_x, Scalar principal_y, Scalar pixel_ratio, IntrinsicDerivative& pipi) { pipi << n[0], n[1], Scalar(1), Scalar(0), Scalar(0), pixel_ratio * n[1], Scalar(0), Scalar(0), Scalar(1), focal_length * n[1]; } }; } } } #endif
#include <iostream> #include <vector> #include <map> using namespace std; vector<int> intersect(vector<int> &nums1, vector<int> &nums2) { map<int, int> m; for (int i = 0; i < nums1.size(); i++) { auto itr = m.find(nums1[i]); if (itr != m.end()) itr->second++; else m.insert(make_pair(nums1[i], 1)); } vector<int> intersection; for (int i = 0; i < nums2.size(); i++) { auto itr = m.find(nums2[i]); if (itr != m.end() && itr->second >= 1) { itr->second--; intersection.push_back(nums2[i]); } } return intersection; } int main() { vector<int> v1({4, 9, 5}), v2({9, 4, 9, 8, 4}), output = intersect(v1, v2); for (int i = 0; i < output.size(); i++) cout << output[i] << " "; cout << endl; return 0; }
#ifndef FASTCG_CONSTANT_BUFFER_H #define FASTCG_CONSTANT_BUFFER_H #include <glm/glm.hpp> #include <vector> #include <string> #include <memory> #include <initializer_list> #include <cstring> #include <cstdint> #include <cassert> #ifdef max #undef max #endif namespace FastCG { class ConstantBuffer { public: class Member { public: Member(const std::string &rName, float value) : mName(rName), mType(Type::FLOAT), mDefaultValue_float(value) { } Member(const std::string &rName, const glm::vec2 &rValue) : mName(rName), mType(Type::VEC2), mDefaultValue_vec2(rValue) { } Member(const std::string &rName, const glm::vec4 &rValue) : mName(rName), mType(Type::VEC4), mDefaultValue_vec4(rValue) { } Member(const Member &rOther) : mName(rOther.mName), mType(rOther.mType), mDefaultValue_vec4(rOther.mDefaultValue_vec4) // largest union member { } inline const auto &GetName() const { return mName; } inline bool IsFloat() const { return mType == Type::FLOAT; } inline bool IsVec2() const { return mType == Type::VEC2; } inline bool IsVec4() const { return mType == Type::VEC4; } private: enum class Type : uint8_t { FLOAT, VEC2, VEC4 }; std::string mName; Type mType; union { int32_t mDefaultValue_int; float mDefaultValue_float; glm::vec2 mDefaultValue_vec2; glm::vec4 mDefaultValue_vec4; }; inline const auto *GetValue() const { return (const void *)&mDefaultValue_int; } inline uint32_t GetSize() const { // FIXME: Using glsl type sizes switch (mType) { case Type::FLOAT: return 4; case Type::VEC2: return 8; case Type::VEC4: return 16; default: assert(false); } return 0; } friend class ConstantBuffer; }; ConstantBuffer(const std::vector<Member> &rMembers) : mMembers(rMembers) { Initialize(); } ConstantBuffer(const std::initializer_list<Member> &rMembers) : mMembers(rMembers) { Initialize(); } ConstantBuffer(const ConstantBuffer &rOther) : mAlignment(rOther.mAlignment), mMembers(rOther.mMembers), mOffsets(rOther.mOffsets), mSize(rOther.mSize) { mData = std::make_unique<uint8_t[]>(mSize); memcpy((void *)&mData[0], rOther.GetData(), mSize); } inline const auto &GetMembers() const { return mMembers; } inline bool GetMemberValue(const std::string &rName, float &rValue) const { return GetMemberValueInternal(rName, rValue); } inline bool GetMemberValue(const std::string &rName, glm::vec2 &rValue) const { return GetMemberValueInternal(rName, rValue); } inline bool GetMemberValue(const std::string &rName, glm::vec4 &rValue) const { return GetMemberValueInternal(rName, rValue); } inline bool SetMemberValue(const std::string &rName, float value) { return SetMemberValueInternal(rName, value); } inline bool SetMemberValue(const std::string &rName, const glm::vec2 &rValue) { return SetMemberValueInternal(rName, rValue); } inline bool SetMemberValue(const std::string &rName, const glm::vec4 &rValue) { return SetMemberValueInternal(rName, rValue); } inline uint32_t GetAlignment() const { return mAlignment; } inline uint32_t GetSize() const { return mSize; } inline const uint8_t *GetData() const { return mData.get(); } inline void SetData(const uint8_t *data, size_t offset, size_t size) { assert((offset + size) <= mSize); memcpy(mData.get() + offset, data, size); } private: uint32_t mAlignment{0}; // GPU memory alignment std::unique_ptr<uint8_t[]> mData; const std::vector<Member> mMembers; std::vector<uint32_t> mOffsets; uint32_t mSize{0}; inline void Initialize() { // FIXME: Using std140 layout rules for (const auto &rMember : mMembers) { auto memberSize = rMember.GetSize(); mAlignment = glm::max(memberSize, mAlignment); auto padding = mSize % memberSize; auto offset = mSize + padding; auto boundary = (offset + memberSize) % 16; if (boundary > 0 && boundary < memberSize) { offset += offset / 16; } mOffsets.emplace_back(offset); mSize = offset + memberSize; } mSize += mSize / 16; if (mSize > 0) { mData = std::make_unique<uint8_t[]>(mSize); for (size_t i = 0; i < mMembers.size(); ++i) { memcpy((void *)&mData[mOffsets[i]], mMembers[i].GetValue(), mMembers[i].GetSize()); } } } inline bool GetMemberOffset(const std::string &rName, uint32_t &rOffset) const { for (size_t i = 0; i < mMembers.size(); ++i) { if (mMembers[i].GetName() == rName) { rOffset = mOffsets[i]; return true; } } assert(false); return false; } template <typename T> inline bool SetMemberValueInternal(const std::string &rName, const T &rValue) { uint32_t offset; if (!GetMemberOffset(rName, offset)) { return false; } memcpy((void *)&mData[offset], (const void *)&rValue, sizeof(T)); return true; } template <typename T> inline bool GetMemberValueInternal(const std::string &rName, T &rValue) const { uint32_t offset; if (!GetMemberOffset(rName, offset)) { return false; } memcpy((void *)&rValue, &mData[offset], sizeof(T)); return true; } }; } #endif
/* * URITable.cpp * * Created on: Apr 17, 2010 * Author: root */ #include "URITable.h" #include "StringIDSegment.h" #include <string.h> URITable::URITable() { SINGLE.assign("single"); prefix_segment = NULL; suffix_segment = NULL; } URITable::URITable(const string dir) : SINGLE("single") { // TODO Auto-generated constructor stub prefix_segment = StringIDSegment::create(dir, "uri_prefix"); suffix_segment = StringIDSegment::create(dir, "uri_suffix"); prefix_segment->addStringToSegment(SINGLE); } URITable::~URITable() { // TODO Auto-generated destructor stub #ifdef DEBUG cout<<"destroy URITable"<<endl; #endif if(prefix_segment != NULL) delete prefix_segment; prefix_segment = NULL; if(suffix_segment != NULL) delete suffix_segment; suffix_segment = NULL; } Status URITable::getIdByURI(const char* URI,ID& id) { getPrefix(URI); if (prefix.equals(SINGLE.c_str())) { searchStr.clear(); searchStr.insert(searchStr.begin(), 2); searchStr.append(suffix.str, suffix.length); searchLen.str = searchStr.c_str(); searchLen.length = searchStr.length(); if (suffix_segment->findIdByString(id, &searchLen) == false) return URI_NOT_FOUND; } else { char temp[10]; ID prefixId; if (prefix_segment->findIdByString(prefixId, &prefix) == false) { return URI_NOT_FOUND; } else { sprintf(temp, "%d", prefixId); searchStr.assign(suffix.str, suffix.length); for (size_t i = 0; i < strlen(temp); i++) { #ifdef USE_C_STRING searchStr.insert(searchStr.begin() + i, temp[i] - '0' + 1); #else searchStr.insert(searchStr.begin() + i, temp[i] - '0'); #endif } searchLen.str = searchStr.c_str(); searchLen.length = searchStr.length(); if (suffix_segment->findIdByString(id, &searchLen) == false) return URI_NOT_FOUND; } } searchStr.clear(); return URI_FOUND; } Status URITable::getPrefix(const char* URI) { size_t size = strlen(URI); int i; for (i = size - 2; i >= 0; i--) { if (URI[i] == '/') break; } if (i == -1) { prefix.str = SINGLE.c_str(); prefix.length = SINGLE.length(); suffix.str = URI; suffix.length = size; } else { prefix.str = URI; prefix.length = i; suffix.str = URI + i + 1; suffix.length = size - i - 1; } return OK; } Status URITable::insertTable(const char* URI, ID& id) { getPrefix(URI); char temp[20]; ID prefixId; prefixId = 1; if(prefix_segment->findIdByString(prefixId, &prefix) == false) prefixId = prefix_segment->addStringToSegment(&prefix); sprintf(temp, "%d",prefixId); searchStr.assign(suffix.str, suffix.length); for(size_t i = 0; i < strlen(temp); i++) { #ifdef USE_C_STRING searchStr.insert(searchStr.begin() + i, temp[i] - '0' + 1);//suffix.insert(suffix.begin() + i, temp[i] - '0'); #else searchStr.insert(searchStr.begin() + i, temp[i] - '0'); #endif } searchLen.str = searchStr.c_str(); searchLen.length = searchStr.length(); id = suffix_segment->addStringToSegment(&searchLen); searchStr.clear(); return OK; } Status URITable::getURIById(string& URI, ID id) { URI.clear(); if (suffix_segment->findStringById(&suffix, id) == false) return URI_NOT_FOUND; char temp[10]; memset(temp, 0, 10); const char* ptr = suffix.str; int i; #ifdef USE_C_STRING for (i = 0; i < 10; i++) { if (ptr[i] > 10) break; temp[i] = (ptr[i] - 1) + '0'; } #else for(i = 0; i < 10; i++) { if(ptr[i] > 9) break; temp[i] = ptr[i] + '0'; } #endif ID prefixId = atoi(temp); if (prefixId == 1) URI.assign(suffix.str + 1, suffix.length - 1); else { if (prefix_segment->findStringById(&prefix, prefixId) == false) return URI_NOT_FOUND; URI.assign(prefix.str, prefix.length); URI.append("/"); URI.append(suffix.str + i, suffix.length - i); } return OK; } URITable* URITable::load(const string dir) { URITable* uriTable = new URITable(); uriTable->prefix_segment = StringIDSegment::load(dir, "uri_prefix"); uriTable->suffix_segment = StringIDSegment::load(dir, "uri_suffix"); return uriTable; } void URITable::dump() { prefix_segment->dump(); suffix_segment->dump(); }
#include<stdlib.h> #include<stdio.h> struct tree { int data; struct tree* left; struct tree* right; }; struct tree* root=NULL; struct tree* tnn(int data) { struct tree* ptr=(struct tree*)malloc(sizeof(struct tree)); ptr->data=data; ptr->left=NULL; ptr->right=NULL; return ptr; } struct tree* insert(struct tree *r,int ele) //time complexity for creating bst with n nodes is nlogn { struct tree* ptr1; struct tree* ptr=NULL; while(r!=NULL) { ptr=r; //back pointer coz after loop termination,r will be null if(ele==r->data) return NULL; //duplicates not allowed else if(ele<r->data) r=r->left; else r=r->right; } ptr1=tnn(ele); if(ptr!=NULL) //coz in case of root,ptr will be null { if(ele>ptr->data) ptr->right=ptr1; else ptr->left=ptr1; } return(ptr1); //only for inserting root,otherwise no use } void createBSTree() { char ch; int ele; int data; printf("\n enter root data:"); scanf("\n%d",&data); root=insert(root,data); printf("\n%d",root->data); do { printf("\n enter element"); scanf("\n %d",&ele); insert(root,ele); printf("\n do you want to continue(y/n)"); fflush(stdin); //to empty the buffer if there is any previous value already stored in it ch = getchar(); //to get input from user, stores it in char type variable ch; }while(ch=='y'||ch=='Y'); } void inorder(struct tree* ptr) { if(ptr!=NULL) { inorder(ptr->left); printf("\n%d",ptr->data); inorder(ptr->right); } } struct tree* IterativeBinarySearch(struct tree *r,int ele) { while(r!=NULL) { if(ele==r->data) return r; else if(ele<r->data) r=r->left; else r=r->right; } return NULL; } struct tree* RecursiveBinarySearch(struct tree *r,int ele) { if(r!=NULL) { if(ele==r->data) return r; else if(ele<r->data) RecursiveBinarySearch(r->left,ele); else RecursiveBinarySearch(r->right,ele) ; } return NULL; } int INS(struct tree* ptr) //finding inorder successori.e leftmost element of right subtree { while(ptr&&ptr->left) //i.e.while ptr1=null and ptr->left!=null { ptr=ptr->left; } return ptr->data; } int INP(struct tree* ptr) //finding inorder predessori.e rightmost element of left subtree { while(ptr&&ptr->right) { ptr=ptr->right; } return ptr->data; } struct tree* del(struct tree * ptr,int ele) { struct tree* ptr1; if(ptr!=NULL) { if(!ptr->left&&!ptr->right&&ptr->data==ele) ; //leaf node { if(ptr==root) //if root only { root=NULL; return NULL; } free(ptr); return NULL; } else //reaching/searching elemenT which we want to delete { if(ele>ptr->data) ptr->right=del(ptr->right,ele); else if(ele<ptr->data) ptr->left=del(ptr->left,ele); else { if(height(ptr->left)<height(ptr->right)) //will delete from where height is more so that height remains balanced coz if height is balanced then searching will be fast { ptr1=INS(ptr->right); //ptr1 is inorder successor here of ptr which we want to deletegly ptr->data=ptr1->data; ptr->right=del(ptr->right,ptr1->data); } else { ptr1=INP(ptr->left); ptr->data=ptr1->data; ptr->left=del(ptr->left,ptr1->data); } } } //end of else return ptr; } //end of if return NULL; } int height(struct tree * ptr) { int x,y; x=height(ptr->left) y=height(ptr->right); if(x>y) return x+1; else return y+1; } int main() { int ele; struct tree* ptr; createBSTree(); inorder(root); ptr=IterativeBinarySearch(root,10); printf("\n%d",ptr); ptr=RecursiveBinarySearch(root,10); printf("\n%d",ptr); printf("\n inorder successor of root is:%d",root->right); printf("\n inorder predessor is:%d",root->left); printf("\n enter elemnt to delete"); scanf("\n%d",&ele); del(root,ele); inorder(root); }
// // Copyright (c) 2003--2009 // Toon Knapen, Karl Meerbergen, Kresimir Fresl, // Thomas Klimpel and Rutger ter Borg // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // THIS FILE IS AUTOMATICALLY GENERATED // PLEASE DO NOT EDIT! // #ifndef BOOST_NUMERIC_BINDINGS_BLAS_LEVEL3_GEMM_HPP #define BOOST_NUMERIC_BINDINGS_BLAS_LEVEL3_GEMM_HPP #include <boost/mpl/bool.hpp> #include <boost/numeric/bindings/blas/detail/blas.h> #include <boost/numeric/bindings/traits/traits.hpp> #include <boost/numeric/bindings/traits/type_traits.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits/is_same.hpp> namespace boost { namespace numeric { namespace bindings { namespace blas { namespace level3 { // overloaded functions to call blas namespace detail { inline void gemm( char const transa, char const transb, integer_t const m, integer_t const n, integer_t const k, float const alpha, float* a, integer_t const lda, float* b, integer_t const ldb, float const beta, float* c, integer_t const ldc ) { BLAS_SGEMM( &transa, &transb, &m, &n, &k, &alpha, a, &lda, b, &ldb, &beta, c, &ldc ); } inline void gemm( char const transa, char const transb, integer_t const m, integer_t const n, integer_t const k, double const alpha, double* a, integer_t const lda, double* b, integer_t const ldb, double const beta, double* c, integer_t const ldc ) { BLAS_DGEMM( &transa, &transb, &m, &n, &k, &alpha, a, &lda, b, &ldb, &beta, c, &ldc ); } inline void gemm( char const transa, char const transb, integer_t const m, integer_t const n, integer_t const k, traits::complex_f const alpha, traits::complex_f* a, integer_t const lda, traits::complex_f* b, integer_t const ldb, traits::complex_f const beta, traits::complex_f* c, integer_t const ldc ) { BLAS_CGEMM( &transa, &transb, &m, &n, &k, traits::complex_ptr(&alpha), traits::complex_ptr(a), &lda, traits::complex_ptr(b), &ldb, traits::complex_ptr(&beta), traits::complex_ptr(c), &ldc ); } inline void gemm( char const transa, char const transb, integer_t const m, integer_t const n, integer_t const k, traits::complex_d const alpha, traits::complex_d* a, integer_t const lda, traits::complex_d* b, integer_t const ldb, traits::complex_d const beta, traits::complex_d* c, integer_t const ldc ) { BLAS_ZGEMM( &transa, &transb, &m, &n, &k, traits::complex_ptr(&alpha), traits::complex_ptr(a), &lda, traits::complex_ptr(b), &ldb, traits::complex_ptr(&beta), traits::complex_ptr(c), &ldc ); } } // value-type based template template< typename ValueType > struct gemm_impl { typedef ValueType value_type; typedef typename traits::type_traits<ValueType>::real_type real_type; typedef void return_type; // templated specialization template< typename MatrixA, typename MatrixB, typename MatrixC > static return_type invoke( char const transa, char const transb, integer_t const k, value_type const alpha, MatrixA& a, MatrixB& b, value_type const beta, MatrixC& c ) { BOOST_STATIC_ASSERT( (boost::is_same< typename traits::matrix_traits< MatrixA >::value_type, typename traits::matrix_traits< MatrixB >::value_type >::value) ); BOOST_STATIC_ASSERT( (boost::is_same< typename traits::matrix_traits< MatrixA >::value_type, typename traits::matrix_traits< MatrixC >::value_type >::value) ); detail::gemm( transa, transb, traits::matrix_num_rows(c), traits::matrix_num_columns(c), k, alpha, traits::matrix_storage(a), traits::leading_dimension(a), traits::matrix_storage(b), traits::leading_dimension(b), beta, traits::matrix_storage(c), traits::leading_dimension(c) ); } }; // low-level template function for direct calls to level3::gemm template< typename MatrixA, typename MatrixB, typename MatrixC > inline typename gemm_impl< typename traits::matrix_traits< MatrixA >::value_type >::return_type gemm( char const transa, char const transb, integer_t const k, typename traits::matrix_traits< MatrixA >::value_type const alpha, MatrixA& a, MatrixB& b, typename traits::matrix_traits< MatrixA >::value_type const beta, MatrixC& c ) { typedef typename traits::matrix_traits< MatrixA >::value_type value_type; gemm_impl< value_type >::invoke( transa, transb, k, alpha, a, b, beta, c ); } }}}}} // namespace boost::numeric::bindings::blas::level3 #endif
// // Copyright Jason Rice 2020 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef NBDL_CONCEPT_PATH_HPP #define NBDL_CONCEPT_PATH_HPP #include <boost/hana/concept/sequence.hpp> #include <boost/hana/is_empty.hpp> #include <type_traits> namespace nbdl { namespace hana = boost::hana; template <typename T> concept Path = hana::Sequence<T>::value; template <typename T> concept EmptyPath = Path<T> && decltype(hana::is_empty(std::declval<T>()))::value; } #endif
// we should find gcd of (a,b) // a can be massive 0 <= a <= 10 power of 250 // for b 0<= b <=10 power of some 4 // wkt gcd(a,b) = gcd(b,a%b) our main objective is to make a%b to be within integer range #include<bits/stdc++.h> using namespace std; int gcd(int a,int b) { if(b==0) { return a; } return gcd(b,a%b); } // here we are making a%b to be within range int solve(string a,int b) { int prev = 0; int res = 0; for(int i=0;i<a.length();i++) { int digit = a[i] - '0'; res = (((res%b)*(10%b))%b + (digit%b))%b; } return res; } int main() { int t; cin >> t; while(t--) { string a; cin >> a; int b; cin >> b; int value = solve(a,b) ;// a%b within int range cout << gcd(b,value); } return 0; }
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* rotateRight(ListNode* head, int k) { // 双指针法 ListNode* fast = head; ListNode* slow = head; if (head == nullptr) return nullptr; // 特判 int length = 1; while (fast->next != nullptr) { fast = fast->next; length++; } fast->next = head; int step = length - k % length; // 防止k太大 while (step > 1) { slow = slow->next; step--; } ListNode* newHead = slow->next; slow->next = nullptr; return newHead; } }; // reference https://leetcode-cn.com/problems/rotate-list/solution/61-xuan-zhuan-lian-biao-tu-wen-xiang-jie-by-sdwwld/ // 上述代码实现的过程所需的图解在Solution中,图解一目了然,故不再解释代码 // 简单来说,就是先让链表成环,然后把要移动的节点当作头结点,之后断开头结点前面的链接,从环再次变回链表。这时候就是结果。
#include "ovpCAlgorithmMatrixMaximum.h" #include <assert.h> using namespace OpenViBE; using namespace OpenViBE::Kernel; using namespace OpenViBE::Plugins; using namespace OpenViBEPlugins; using namespace OpenViBEPlugins::SignalProcessing; boolean CAlgorithmMatrixMaximum::initialize(void) { //bind input matrix parameters to actual matrix objects(below) that we are going to use ip_pMatrix.initialize(this->getInputParameter(OVP_Algorithm_MatrixMaximum_InputParameterId_Matrix)); op_pMatrix.initialize(this->getOutputParameter(OVP_Algorithm_MatrixMaximum_OutputParameterId_Matrix)); return true; } boolean CAlgorithmMatrixMaximum::uninitialize(void) { op_pMatrix.uninitialize(); ip_pMatrix.uninitialize(); return true; } boolean CAlgorithmMatrixMaximum::process(void) { //seems like triggers(flags) raised by default //checks the list of triggers (flags) whether OVP_Algorithm_MatrixMaximum_InputTriggerId_Initialize is raised if(this->isInputTriggerActive(OVP_Algorithm_MatrixMaximum_InputTriggerId_Initialize)) { int dimCount = ip_pMatrix->getDimensionCount(); if( dimCount != 2) { this->getLogManager() << LogLevel_Error << "The input matrix must have 2 dimensions"; return false; } //set output matrix op_pMatrix->setDimensionCount(2); op_pMatrix->setDimensionSize(0,1); // only one - maximum - vector op_pMatrix->setDimensionSize(1,ip_pMatrix->getDimensionSize(1)); // same number of elements in the vector as in the input matrix } if(this->isInputTriggerActive(OVP_Algorithm_MatrixMaximum_InputTriggerId_Process)) { // we iterate over the columns (second dimension) for(uint32 i=0; i<ip_pMatrix->getDimensionSize(1); i++) { float64 l_f64Maximum = ip_pMatrix->getBuffer()[i]; // and try to find the maximum among the values on column i for(uint32 j=1; j<ip_pMatrix->getDimensionSize(0); j++) { if(l_f64Maximum < ip_pMatrix->getBuffer()[i+j*ip_pMatrix->getDimensionSize(1)]) { l_f64Maximum = ip_pMatrix->getBuffer()[i+j*ip_pMatrix->getDimensionSize(1)]; } } //we intialized this output matrix already with 1 dimensional vector assert(op_pMatrix!=NULL); assert(op_pMatrix->getBuffer()!=NULL); //assert(i<op_pMatrix->getDimensionSize(1)); op_pMatrix->getBuffer()[i]= l_f64Maximum; } //raise trigger(flag) "Process Done" this->activateOutputTrigger(OVP_Algorithm_MatrixMaximum_OutputTriggerId_ProcessDone, true); } return true; }
#pragma once #include <iostream> #define SIMD_NONE 0 #define SIMD_SSE 10 #define SIMD_SSE2 20 #define SIMD_SSE3 30 #define SIMD_SSSE3 31 #define SIMD_SSE4_1 41 #define SIMD_SSE4_2 42 #define SIMD_AVX 50 #define SIMD_FMA3 51 #define SIMD_AVX2 60 #ifdef _MSC_VER #include <intrin.h> #if defined(__AVX2__) #define SIMD_SSE_VERSION SIMD_AVX2 #elif defined(__AVX__) #define SIMD_SSE_VERSION SIMD_AVX #elif (_M_IX86_FP == 2) || defined(_M_X64) || defined(_M_AMD64) #define SIMD_SSE_VERSION SIMD_SSE2 #elif _M_IX86_FP == 1 #define SIMD_SSE_VERSION SIMD_SSE #else #define SIMD_SSE_VERSION SIMD_NONE #endif #else // _MSVC_VER #include <x86intrin.h> #include <cpuid.h> #if defined(__AVX2__) #define SIMD_SSE_VERSION SIMD_AVX2 #elif defined(__FMA__) #define SIMD_SSE_VERSION SIMD_FMA3 #elif defined(__AVX__) #define SIMD_SSE_VERSION SIMD_AVX #elif defined(__SSE4_2__) #define SIMD_SSE_VERSION SIMD_SSE4_2 #elif defined(__SSE4_1__) #define SIMD_SSE_VERSION SIMD_SSE4_1 #elif defined(__SSSE3__) #define SIMD_SSE_VERSION SIMD_SSSE3 #elif defined(__SSE3__) #define SIMD_SSE_VERSION SIMD_SSE3 #elif defined(__SSE2__) #define SIMD_SSE_VERSION SIMD_SSE2 #elif defined(__SSE__) #define SIMD_SSE_VERSION SIMD_SSE #else #define SIMD_SSE_VERSION SIMD_NONE #endif #endif // _MSVC_VER #define SIMD_SUPPORTS(ver) SIMD_SSE_VERSION >= ver namespace simd { constexpr bool supports(int version) { return SIMD_SUPPORTS(version); } constexpr int sse_compile_version() { return SIMD_SSE_VERSION; } int sse_runtime_version() { #ifdef _MSC_VER int cpuInfo[4]; __cpuid(cpuInfo, 0); int id_count = cpuInfo[0]; if(id_count >= 7) { __cpuid(cpuInfo, 7); if(cpuInfo[1] & (1 << 5)) return SIMD_AVX2; } if(id_count >= 1) { __cpuid(cpuInfo, 1); if(cpuInfo[2] & (1 << 12)) return SIMD_FMA3; if(cpuInfo[2] & (1 << 28)) return SIMD_AVX; if(cpuInfo[2] & (1 << 20)) return SIMD_SSE4_2; if(cpuInfo[2] & (1 << 19)) return SIMD_SSE4_1; if(cpuInfo[2] & (1 << 9)) return SIMD_SSSE3; if(cpuInfo[2] & (1 << 0)) return SIMD_SSE3; if(cpuInfo[3] & (1 << 26)) return SIMD_SSE2; if(cpuInfo[3] & (1 << 25)) return SIMD_SSE; } #else // _MSC_VER unsigned int eax, ebx, ecx, edx; unsigned int id_count = __get_cpuid_max(0, nullptr); if(id_count >= 7) { __asm__ ("mov $0, %%ecx\n\t" "cpuid\n\t" : "=b"(ebx) : "0"(7) : "eax", "ecx", "edx"); if(ebx & bit_AVX2) return SIMD_AVX2; } if(id_count >= 1) { __asm__ ("cpuid\n\t" : "=c"(ecx), "=d"(edx) : "0"(7) : "eax", "ebx"); if(ecx & bit_FMA) return SIMD_FMA3; if(ecx & bit_AVX) return SIMD_AVX; if(ecx & bit_SSE4_2) return SIMD_SSE4_2; if(ecx & bit_SSE4_1) return SIMD_SSE4_1; if(ecx & bit_SSSE3) return SIMD_SSSE3; if(ecx & bit_SSE3) return SIMD_SSE3; if(edx & bit_SSE2) return SIMD_SSE2; if(edx & bit_SSE) return SIMD_SSE; } #endif // _MSC_VER return SIMD_NONE; } constexpr const char *version_name(int version) { switch(version) { case SIMD_SSE: return "SSE"; case SIMD_SSE2: return "SSE2"; case SIMD_SSE3: return "SSE3"; case SIMD_SSSE3: return "SSSE3"; case SIMD_SSE4_1: return "SSE4.1"; case SIMD_SSE4_2: return "SSE4.2"; case SIMD_AVX: return "AVX"; case SIMD_AVX2: return "AVX2"; case SIMD_FMA3: return "FMA3"; default: return "none"; } } } // namespace simd
// // Created by Amelia Chady on 11/27/2018. // An implementation of ArraySoundMap // #include "ArraySoundMap.h" #include "ArrayList.h" #include "LinkedList.h" #include "Util.h" #include <fstream> ArraySoundMap::ArraySoundMap() { fileName = "defaultSounds.txt"; } ArraySoundMap::ArraySoundMap(std::string fileName) { this->fileName = fileName; } ArraySoundMap::~ArraySoundMap() { delete soundArray; } void ArraySoundMap::read() { std::string currentLine; std::ifstream file; file.open(fileName, std::ios::in); if(!file.is_open()){ throw std::exception(); } std::getline(file, currentLine); while(currentLine.substr(0, 2) == "//" || currentLine.substr(0, 2) == "\r" ){ std::getline(file, currentLine); } soundArray = new ArrayList<Sound*>(std::stoi(currentLine)); // Make sure to add the currentLine size getline(file,currentLine); while(currentLine.substr(0, 1) != "#") { if (currentLine.substr(0, 2) != "//" && currentLine.substr(0, 2) != "\r") { soundArray->insertAtEnd(new Sound(trim(currentLine))); } getline(file, currentLine); } getline(file, currentLine); while(currentLine.substr(0, 1) != "#"){ if (currentLine.substr(0, 2) != "//" && currentLine.substr(0, 2) != "\r") { currentLine = trim(currentLine); List<std::string>* splitted = split(currentLine, " "); Sound* tempBase = getKey(splitted->getValueAt(0)); for(int i = 1; i < splitted->itemCount(); i++) { tempBase->addConnection(getKey(splitted->getValueAt(i))); } } getline(file, currentLine); } file.close(); } std::string ArraySoundMap::getFileName() { return fileName; } Sound* ArraySoundMap::getKey(std::string key) { key = trim(key); Sound* temp = nullptr; for(int i = 0; i < soundArray->itemCount(); i++){ Sound* temp = soundArray->getValueAt(i); //std::cout << temp->getSymbol() << std::endl; if(temp->getSymbol()==key){ return temp; } } throw std::invalid_argument("Key doesn't exist"); }
#include "ros/ros.h" #include "oroca_ros_tutorials/msgTutorial.h" #include "ceSerial.h" #include "parser_vercpp.hpp" #include <iostream> #include <string> #include <signal.h> typedef unsigned char BYTE; /* volatile int j=0; void handler(int sig){ j=1; return; } */ int main(int argc, char** argv){ ros::init(argc, argv, "ros_tutorial_msg_publisher"); ros::NodeHandle nh; ros::Publisher ros_tutorial_pub = nh.advertise<oroca_ros_tutorials::msgTutorial>("GPS_msg", 100); std::string portname = "/dev/ttyUSB0"; int baudrate = 9600; ublox_parser cUblox(portname, baudrate); ublox_parser::PARSING_TYPEDEF_UBX_M8P_PVT globalPVT; oroca_ros_tutorials::msgTutorial msg; ROS_INFO("GPS: 5hz, loop_rate: 10hz"); ros::Rate loop_rate(20); //Assume GPS sensor receive signal in 5hz while (cUblox.isInit && ros::ok()) { cUblox.run(); // once it ran, is valid always true? or true only when it got new data? if (cUblox.valid() == ublox_parser::PARSING_SUCCESS_) { cUblox.copyTo(&globalPVT); // because we should update our vehicle's location at least 5 times between two signals //std::cout<<"Valid"<<std::endl; ROS_INFO("Publish GPS Message"); msg.latitude= globalPVT.lat; msg.longitude=globalPVT.lon; msg.heading = globalPVT.headMot; // heading of motion msg.gSpeed=globalPVT.gSpeed; ros_tutorial_pub.publish(msg); loop_rate.sleep(); cUblox.set_valid_to_fail(); //ros::spinOnce(); } // else{ // cout<<"not valid"<<endl; // } }// end of stdout while }
#include <iostream> #include <queue> using namespace std; int m,n; int tmp; int cnt=0; int visit[1001][1001]={0,}; int G[1001][1001] ={0,}; queue<pair<int, int> > q; int dir[4][2] = {{0, 1}, {1,0}, {-1,0}, {0,-1}}; int generate(){ if(cnt==0) return 0; int day=1; while(!q.empty()){ int s = q.size(); for(int x=0; x<s; x++){ pair<int, int> cur = q.front(); q.pop(); if(visit[cur.first][cur.second]) continue; else visit[cur.first][cur.second]=1; for(int i=0; i<4; i++){ int tmp_x = cur.first+dir[i][0]; int tmp_y = cur.second+dir[i][1]; if(tmp_x>n-1 || tmp_y>m-1 || tmp_x<0 || tmp_y<0) continue; // visit아님 if(!G[tmp_x][tmp_y] && G[tmp_x][tmp_y]!=-1){ G[tmp_x][tmp_y] = 1; q.push(pair<int, int> (tmp_x, tmp_y)); cnt--; } if(cnt==0) return day; } } day++; } return -1; } int main(){ cin>>m>>n; for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ scanf("%d",&tmp); if(tmp==1) q.push(pair<int,int>(i,j)); else if(tmp==0) cnt++; G[i][j]=tmp; } } cout<<generate()<<endl; }
#include <iostream> using namespace std; struct Array { int *A; int size; int length; }; void Display(struct Array arr) { for(int i=0; i<arr.length; i++){ cout << arr.A[i] << " "; } } void Insert(struct Array *arr, int index, int x) { if(index >=0 && index <= arr->length){ for(int i=arr->length; i>index; i--){ arr->A[i] = arr->A[i-1]; } arr->A[index] = x; arr->length++; } } int main() { struct Array arr; int index, x; cout << "Enter the size of Array: "; cin >> arr.size; arr.A = new int[arr.size]; cout << "Enter the length of Array: "; cin >> arr.length; for(int i=0; i<arr.length; i++){ cout << "Enter element in index " << i << ": "; cin >> arr.A[i]; } cout << "Enter the index: "; cin >> index; cout << "Enter the element: "; cin >> x; Insert(&arr, index, x); Display(arr); return 0; }
#include <iostream> #include <string> #include <vector> #include <sstream> using namespace std; #include "UserInterface.h" #include "SimulatorLogic.h" #include "Consola.h" #define DEFAULT_BACKGROUND_COLOR Consola::PRETO #define BORDER_COLOR Consola::BRANCO #define TRACK_BORDER_COLOR Consola::VERDE #define PRINT_LOG_X 90 #define PRINT_LOG_Y 2 #define PRINT_MAP_X 90 #define PRINT_MAP_Y 25 #define PRINT_LEADERBOARD_X 90 #define PRINT_LEADERBOARD_Y 10 #define PRINT_RACE_INFORMATION_X 90 #define PRINT_RACE_INFORMATION_Y 10 #define PRINT_LIST_X 3 #define PRINT_LIST_Y 2 #define PRINT_COMMANDS_X 3 #define PRINT_COMMANDS_Y 2 #define MAP_SCALE 50 UserInterface::UserInterface(SimulatorLogic &simulator_logic) : simulator_logic(simulator_logic) { fillMode1CommandsVector(); fillMode2CommandsVector(); } UserInterface::~UserInterface() { for(int i = 0; i < mode1_commands.size(); i++) { delete mode1_commands[i]; } for(int i = 0; i < mode2_commands.size(); i++) { delete mode2_commands[i]; } } void UserInterface::run() { Consola::setBackgroundColor(DEFAULT_BACKGROUND_COLOR); while(simulator_logic.getMode() != SimulatorLogic::EXIT_SIMULATION) { Consola::clrscr(); if(simulator_logic.getMode() == SimulatorLogic::MODE_1) { runMode1(); } else if(simulator_logic.getMode() == SimulatorLogic::MODE_2) { printLeaderboard(PRINT_LEADERBOARD_X, PRINT_LEADERBOARD_Y); printMap(PRINT_MAP_X, PRINT_MAP_Y); printRaceInformation(PRINT_RACE_INFORMATION_X, PRINT_RACE_INFORMATION_Y); runMode2(); } } } void UserInterface::fillMode1CommandsVector() { mode1_commands.push_back(new Command("carregaP", "<nomeFicheiro>")); mode1_commands.push_back(new Command("carregaC", "<nomeFicheiro>")); mode1_commands.push_back(new Command("carregaA", "<nomeFicheiro>")); mode1_commands.push_back(new Command("cria", "<letraTipo> <dadosDoObjeto>")); mode1_commands.push_back(new Command("apaga", "<letraTipo> <identificador>")); mode1_commands.push_back(new Command("entranocarro", "<letraCarro> <nomePiloto>")); mode1_commands.push_back(new Command("saidocarro", "<letraCarro>")); mode1_commands.push_back(new Command("lista")); mode1_commands.push_back(new Command("savedgv", "<nome>")); mode1_commands.push_back(new Command("loaddgv", "<nome>")); mode1_commands.push_back(new Command("deldgv", "<nome>")); mode1_commands.push_back(new Command("campeonato")); mode1_commands.push_back(new Command("log")); mode1_commands.push_back(new Command("sair")); } void UserInterface::fillMode2CommandsVector() { mode2_commands.push_back(new Command("campeonato", "<A1> <A2> <An>")); mode2_commands.push_back(new Command("listacarros")); mode2_commands.push_back(new Command("carragabat", "<letraCarro> <Q>")); mode2_commands.push_back(new Command("carregatudo")); mode2_commands.push_back(new Command("corrida")); mode2_commands.push_back(new Command("acidente", "<letraCarro>")); mode2_commands.push_back(new Command("stop", "<nomePiloto>")); mode2_commands.push_back(new Command("destroi", "<letraCarro>")); mode2_commands.push_back(new Command("passatempo", "<n>")); mode2_commands.push_back(new Command("log")); mode2_commands.push_back(new Command("sair")); } void UserInterface::runMode1() { string introduced_command; vector<string> tokenized_command; introduced_command = printModeCommandsAndGetInput(mode1_commands, PRINT_COMMANDS_Y, PRINT_COMMANDS_X); tokenized_command = tokenizeCommand(introduced_command); try { if(tokenized_command[0] == "sair" && tokenized_command.size() == 1) { simulator_logic.exitSimulation(); } else if(tokenized_command[0] == "carregaP" && tokenized_command.size() == 2) { simulator_logic.loadPilots(tokenized_command[1]); } else if(tokenized_command[0] == "carregaC" && tokenized_command.size() == 2) { simulator_logic.loadCars(tokenized_command[1]); } else if(tokenized_command[0] == "carregaA" && tokenized_command.size() == 2) { simulator_logic.loadRaceTracks(tokenized_command[1]); } else if(tokenized_command[0] == "cria" && tokenized_command.size() >= 3) { tokenized_command.erase(tokenized_command.begin()); if(simulator_logic.validateCreateFunctionInput(tokenized_command)) { simulator_logic.create(tokenized_command); } else { last_error = "'" + introduced_command + "' is not a valid input. Try again!"; } } else if(tokenized_command[0] == "apaga" && tokenized_command.size() == 3) { simulator_logic.eliminate(tokenized_command[1], tokenized_command[2]); } else if(tokenized_command[0] == "entranocarro" && tokenized_command.size() >= 3) { string car_id = tokenized_command[1]; tokenized_command.erase(tokenized_command.begin()); tokenized_command.erase(tokenized_command.begin()); simulator_logic.enterInCar(car_id, tokenized_command); } else if(tokenized_command[0] == "saidocarro" && tokenized_command.size() == 2) { simulator_logic.getOutOfCar(tokenized_command[1]); } else if(tokenized_command[0] == "lista" && tokenized_command.size() == 1) { printList(simulator_logic.list(), PRINT_LIST_X, PRINT_LIST_Y); } else if(tokenized_command[0] == "savedgv" && tokenized_command.size() == 2) { simulator_logic.saveGeneralTravelOffice(tokenized_command[1]); } else if(tokenized_command[0] == "loaddgv" && tokenized_command.size() == 2) { simulator_logic.loadGeneralTravelOffice(tokenized_command[1]); } else if(tokenized_command[0] == "deldgv" && tokenized_command.size() == 2) { simulator_logic.deleteGeneralTravelOffice(tokenized_command[1]); } else if(tokenized_command[0] == "campeonato" && tokenized_command.size() == 1) { simulator_logic.startChampionship(); } else if(tokenized_command[0] == "log" && tokenized_command.size() == 1) { printLog(simulator_logic.log(), PRINT_LOG_X, PRINT_LOG_Y); } else { last_error = "'" + introduced_command + "' is not a valid input. Try again!"; } } catch(const ErrorException& e) { last_error = e.what(); } } void UserInterface::runMode2() { string introduced_command; vector<string> tokenized_command; introduced_command = printModeCommandsAndGetInput(mode2_commands, PRINT_COMMANDS_Y, PRINT_COMMANDS_X); tokenized_command = tokenizeCommand(introduced_command); try { if(tokenized_command[0] == "sair" && tokenized_command.size() == 1) { simulator_logic.leaveChampionship(); } else if(tokenized_command[0] == "campeonato" && tokenized_command.size() >= 2) { tokenized_command.erase(tokenized_command.begin()); simulator_logic.associateRacetracksToChampionship(tokenized_command); } else if(tokenized_command[0] == "listacarros" && tokenized_command.size() == 1) { printMap(PRINT_MAP_X, PRINT_MAP_Y); printList(simulator_logic.listCars(), PRINT_LIST_X, PRINT_LIST_Y); } else if(tokenized_command[0] == "carregabat" && tokenized_command.size() == 3) { simulator_logic.chargeBattery(tokenized_command[1], tokenized_command[2]); } else if(tokenized_command[0] == "carregatudo" && tokenized_command.size() == 1) { simulator_logic.chargeAllBatteries(); } else if(tokenized_command[0] == "corrida" && tokenized_command.size() == 1) { simulator_logic.startRace(); } else if(tokenized_command[0] == "acidente" && tokenized_command.size() == 2) { simulator_logic.provoceAccident(tokenized_command[1]); } else if(tokenized_command[0] == "stop" && tokenized_command.size() == 2) { simulator_logic.stopPilot(tokenized_command[1]); } else if(tokenized_command[0] == "destroi" && tokenized_command.size() == 2) { simulator_logic.destroiCar(tokenized_command[1]); } else if(tokenized_command[0] == "passatempo" && tokenized_command.size() == 2) { if(isInteger(tokenized_command[1]) == true) { int pass_time = convertStringToInt(tokenized_command[1]); for(int i = 0; i < pass_time; i++) { Consola::clrscr(); simulator_logic.passTime(); printMap(PRINT_MAP_X, PRINT_MAP_Y); printRaceInformation(PRINT_RACE_INFORMATION_X, PRINT_RACE_INFORMATION_Y); while(Consola::getch() != Consola::ENTER); } } } else if(tokenized_command[0] == "log" && tokenized_command.size() == 1) { printMap(PRINT_MAP_X, PRINT_MAP_Y); printLog(simulator_logic.log(), PRINT_LOG_X, PRINT_COMMANDS_Y); } else { last_error = "'" + introduced_command + "' is not a valid input. Try again!"; } } catch(const ErrorException& e) { last_error = e.what(); } } string UserInterface::printModeCommandsAndGetInput(const vector<Command*> &mode_commands, int y, int x) { string introduced_command; printBox(x - 2, y - 2, 40, 60); Consola::gotoxy(x, y); if(simulator_logic.getMode() == SimulatorLogic::MODE_1) { cout << "--------------- MODE 1 ------------------"; } else { cout << "--------------- MODE 2 ------------------"; } y = y + 2; for(int i = 0; i < mode_commands.size(); i++) { Consola::gotoxy(x, y); cout << mode_commands[i]->toString() << endl; y++; } y++; Consola::gotoxy(x, y); string temp = "Introduce your command: "; cout << temp; printLastErrors(x, y + 2); last_error.clear(); int input_position_x = x + temp.size(); int input_position_y = y; Consola::gotoxy(input_position_x, input_position_y); cin >> ws; getline(cin, introduced_command); return introduced_command; } void UserInterface::printMap(int x, int y) const { if(simulator_logic.raceInCourse() == false) { return; } printBox(x - 2, y - 2, 24, 60); Consola::gotoxy(x, y); cout << "--------------- MAP ------------------"; y = y + 2; vector<string> race_informations = simulator_logic.getMap(); int track_length = convertStringToInt(race_informations[0]); for(int i = 1; i < race_informations.size(); i++) { for(int j = 0; j < MAP_SCALE; j++) { Consola::setBackgroundColor(TRACK_BORDER_COLOR); Consola::gotoxy(x + j, y); cout << " "; } y++; istringstream informations_stream(race_informations[i]); char car_id; int car_distance; informations_stream >> car_id >> car_distance; Consola::setBackgroundColor(DEFAULT_BACKGROUND_COLOR); int position_in_screen = car_distance / (track_length / MAP_SCALE); Consola::gotoxy(x + position_in_screen, y); cout << car_id; y++; } for(int j = 0; j < MAP_SCALE; j++) { Consola::setBackgroundColor(TRACK_BORDER_COLOR); Consola::gotoxy(x + j, y); cout << " "; } Consola::setBackgroundColor(DEFAULT_BACKGROUND_COLOR); } void UserInterface::printLeaderboard(int x, int y) const { if(simulator_logic.championshipInCourse() == true && simulator_logic.raceInCourse() == false) { printBox(x - 2, y - 2, 15, 60); Consola::gotoxy(x, y); cout << "--------------- LEADERBOARD ------------------"; y = y + 2; vector<string> leaderboard = simulator_logic.getLeaderboard(); for(int i = 0; i < leaderboard.size(); i++) { istringstream leaderboard_stream(leaderboard[i]); int position; int points; string pilot_name; leaderboard_stream >> position >> points; leaderboard_stream >> ws; getline(leaderboard_stream, pilot_name); Consola::gotoxy(x, y); cout << position << ". " << pilot_name << " : " << points << " points"; y++; } } } void UserInterface::printRaceInformation(int x, int y) const { if(simulator_logic.championshipInCourse() == true && simulator_logic.raceInCourse() == true) { printBox(x - 2, y - 2, 15, 60); Consola::gotoxy(x, y); cout << "--------------- RACE INFORMATION ------------------"; y = y + 2; vector<string> race_information = simulator_logic.getRaceInformation(); Consola::gotoxy(x, y); cout << "Racetrack: " << race_information[0]; y = y + 2; for(int i = 1; i < race_information.size(); i++) { istringstream race_information_stream(race_information[i]); string car_brand; string car_id; string pilot_name; string pilot_type; float battery_consumption; float battery; int traveled_distance; int speed; race_information_stream >> car_id >> car_brand >> pilot_name >> pilot_type; race_information_stream >> battery >> battery_consumption >> traveled_distance >> speed; Consola::gotoxy(x, y); cout << i + 1 << ". " << car_id << " " << car_brand << " / " << pilot_name << " (" << pilot_type << ") - " << battery_consumption << " mAs, "; cout << battery << " mAh - " << traveled_distance << "m - " << speed << " m/s"; y++; } } } void UserInterface::printLog(const vector<string> message_log, int x, int y) const { printBox(x - 2, y - 2, 15, 60); Consola::gotoxy(x, y); cout << "--------------- LOG ------------------"; y = y + 2; for(int i = 0; i < message_log.size(); i++) { Consola::gotoxy(x, y); cout << message_log[i]; y++; } Consola::gotoxy(x, y); cout << "Prima ENTER para continuar"; while(Consola::getch() != Consola::ENTER); } void UserInterface::printList(const string list, int x, int y) const { istringstream list_stream(list); string temp; Consola::clrscr(); printBox(x - 2, y - 2, 24, 60); Consola::gotoxy(x, y); cout << "--------------- LIST ------------------"; y = y + 2; while(list_stream.eof() == false) { getline(list_stream, temp); Consola::gotoxy(x, y++); cout << temp; } Consola::gotoxy(x, ++y); cout << "Prima ENTER para continuar"; while(Consola::getch() != Consola::ENTER){} } void UserInterface::printBox(int x, int y, int height, int width) const { Consola::setBackgroundColor(BORDER_COLOR); for(int i = 0; i < height + 1; i++) { Consola::gotoxy(x, y); cout << " "; Consola::gotoxy(x-1, y); cout << " "; Consola::gotoxy(x + width, y); cout << " "; Consola::gotoxy(x + width + 1, y); cout << " "; y++; } y = y - height - 1; for(int i = 0; i < width + 1; i++) { Consola::gotoxy(x, y); cout << " "; Consola::gotoxy(x, y + height); cout << " "; x++; } Consola::setBackgroundColor(DEFAULT_BACKGROUND_COLOR); } void UserInterface::printLastErrors(int x, int y) const { istringstream last_error_stream(last_error); string temp; while(last_error_stream.eof() == false) { Consola::gotoxy(x, y++); getline(last_error_stream, temp); cout << temp; } } vector<string> UserInterface::tokenizeCommand(const string &command) const { vector<string> tokenized_command; istringstream input_stream(command); string temp; while(input_stream.eof() == false) { temp.clear(); input_stream >> ws; input_stream >> temp; if(temp.size() > 0) { tokenized_command.push_back(temp); } } return tokenized_command; } Command::Command(string name, string arguments_description) : name(name), arguments_description(arguments_description) {} Command::Command(string name) : name(name) {} string Command::toString() const { ostringstream output_stream; output_stream << name << " " << arguments_description; return output_stream.str(); } string Command::getName() const { return name; } int Command::getNumberOfArguments() const { return countWords(arguments_description); } int Command::countWords(const string &command) const { int i = 0; int contador = 0; while(command[i] == ' ' && i < command.size()) { i++; } while(i < command.size()) { while(command[i] != ' ' && i < command.size()) { i++; } i++; contador++; while(command[i] == ' ' && i < command.size()) { i++; } } return contador; } int UserInterface::convertStringToInt(string number) const { istringstream number_stream(number); int int_value; number_stream >> int_value; return int_value; } bool UserInterface::isInteger(string number) const { for(int i = 0; i < number.size(); i++) { if(number[i] < '0' || number[i] > '9') { return false; } } return true; }
/* Data Structure: Arrays and Strings * * Implement an algorithm to determine if a string has all unique chracters * Additionally: Implement this without using additional data structures or memory space. * -- basic use for arrays and strings * -- brute force : O(n^2) complexity and O(1) space complexity * * Notes: * consider ASCII for this problem. * UNICODE will increase the size of storage from char (1 byte) to int (4 bytes) * * If we can't use additional data structure then compare every char of the * string with every other char, and the time complexity is O(n^s) and O(1) space. * * * If we are allowed to modify the input string then we could sort the string * in O(n log n) time and then check linearly for neighboring chars are identical. * * The time complexity for this code is O(n) (one which stores a bitmask), where * n is the length of the string. The space complexity is O(1). * * The time complexity can also be thought of O(1) , since the for loop will * never iterate through more than 128 characters. * * Time complexity : O( Min(C, N) ) * Space complexity : O(C) * where C is the size of the character set and N is the length of string * */ #include <iostream> #include <string> using namespace std; // O(n2) worst case, but without using any additional memory bool isUniqueChars (string str) { if (str.size() > 128) return false; // looping and figure out for (int i = 0; i < str.size(); i++) { for (int j = i+1; j < str.size(); j++) { if (str[i] == str[j]) { //cout << str << ":does not have unique chars" << endl; return false; } } } //cout << str << ":does have unique chars" << endl; return true; } // use a bitmask to store the characters /* Bitmask will not be an optimized solution for a UNICODE use case, where there * are 2^32 possibilities and the bitmask (space requirements) will be a * constraint. Using a hash or dictionary to store known chars will be optimized. */ bool isUniqueChars_Ver2 (string str) { if (str.size() > 128) return false; //assumign ascii chars only char *charset = new char[128/8]; //one bit to store a char value for (int i = 0; i < str.size(); i++) { char c = str[i]; if (charset[c/8] & (0x1 << (c%8))) { //cout << "non unique char " << c << endl; delete [] charset; return false; } else { charset[c/8] |= (0x1 << (c%8)); } } delete [] charset; return true; } int main (int argc, char **argv) { //cout << "Program: isUnique" << endl << endl; if (argc != 2) { cout << "Error: Incorrect number of arguments." << endl; } std::string str(argv[1]); //if (isUniqueChars(str) == true) { if (isUniqueChars_Ver2(str) == true) { cout << str << ": has all unique chars" << endl; } else { cout << str << ": does not have all unique chars" << endl; } return 0; }
// Copyright 2018 Global Phasing Ltd. // // Selections. #ifndef GEMMI_SELECT_HPP_ #define GEMMI_SELECT_HPP_ #include <string> #include <cstdlib> // for strtol #include <cctype> // for isalpha #include <climits> // for INT_MIN, INT_MAX #include "util.hpp" // for fail #include "model.hpp" // for Model, Chain, etc #include "iterator.hpp" // for FilterProxy namespace gemmi { // from http://www.ccp4.ac.uk/html/pdbcur.html // Specification of the selection sets: // either // /mdl/chn/s1.i1-s2.i2/at[el]:aloc // or // /mdl/chn/*(res).ic/at[el]:aloc // struct Selection { struct List { bool all = true; bool inverted = false; std::string list; // comma-separated std::string str() const { if (all) return "*"; return inverted ? "!" + list : list; } }; struct SequenceId { int seqnum; char icode; std::string str() const { std::string s; if (seqnum != INT_MIN && seqnum != INT_MAX) s = std::to_string(seqnum); if (icode != '*') { s += '.'; if (icode != ' ') s += icode; } return s; } int compare(const SeqId& seqid) const { if (seqnum != *seqid.num) return seqnum < *seqid.num ? -1 : 1; if (icode != '*' && icode != seqid.icode) return icode < seqid.icode ? -1 : 1; return 0; } }; int mdl = 0; // 0 = all List chain_ids; SequenceId from_seqid = {INT_MIN, '*'}; SequenceId to_seqid = {INT_MAX, '*'}; List residue_names; List atom_names; List elements; List altlocs; std::string to_cid() const { std::string cid(1, '/'); if (mdl != 0) cid += std::to_string(mdl); cid += '/'; cid += chain_ids.str(); cid += '/'; cid += from_seqid.str(); if (!residue_names.all) { cid += residue_names.str(); } else { cid += '-'; cid += to_seqid.str(); } cid += '/'; cid += atom_names.str(); if (!elements.all) cid += "[" + elements.str() + "]"; if (!altlocs.all) cid += ":" + altlocs.str(); return cid; } static bool find_in_comma_separated_string(const std::string& name, const std::string& str) { if (name.length() >= str.length()) return name == str; for (size_t start=0, end=0; end != std::string::npos; start=end+1) { end = str.find(',', start); if (str.compare(start, end - start, name) == 0) return true; } return false; } // assumes that list.all is checked before this function is called static bool find_in_list(const std::string& name, const List& list) { bool found = find_in_comma_separated_string(name, list.list); return list.inverted ? !found : found; } bool matches(const gemmi::Model& model) const { return mdl == 0 || std::to_string(mdl) == model.name; } bool matches(const gemmi::Chain& chain) const { return chain_ids.all || find_in_list(chain.name, chain_ids); } bool matches(const gemmi::Residue& res) const { return (residue_names.all || find_in_list(res.name, residue_names)) && from_seqid.compare(res.seqid) <= 0 && to_seqid.compare(res.seqid) >= 0; } bool matches(const gemmi::Atom& a) const { return (atom_names.all || find_in_list(a.name, atom_names)) && (elements.all || find_in_list(a.element.uname(), elements)) && (altlocs.all || find_in_list(std::string(a.altloc ? 0 : 1, a.altloc), altlocs)); } bool matches(const gemmi::CRA& cra) const { return (cra.chain == nullptr || matches(*cra.chain)) && (cra.residue == nullptr || matches(*cra.residue)) && (cra.atom == nullptr || matches(*cra.atom)); } FilterProxy<Selection, Model> models(Structure& st) const { return FilterProxy<Selection, Model>{*this, st.models}; } FilterProxy<Selection, Chain> chains(Model& model) const { return FilterProxy<Selection, Chain>{*this, model.chains}; } FilterProxy<Selection, Residue> residues(Chain& chain) const { return FilterProxy<Selection, Residue>{*this, chain.residues}; } FilterProxy<Selection, Atom> atoms(Residue& residue) const { return FilterProxy<Selection, Atom>{*this, residue.atoms}; } }; namespace impl { int determine_omitted_cid_fields(const std::string& cid) { if (cid[0] == '/') return 0; // model if (std::isdigit(cid[0]) || cid[0] == '.' || cid[0] == '(' || cid[0] == '-') return 2; // residue size_t sep = cid.find_first_of("/(:["); if (sep == std::string::npos || cid[sep] == '/') return 1; // chain if (cid[sep] == '(') return 2; // residue return 3; // atom } Selection::List make_cid_list(const std::string& cid, size_t pos, size_t end) { Selection::List list; list.all = (cid[pos] == '*'); if (cid[pos] == '!') { list.inverted = true; ++pos; } list.list = cid.substr(pos, end - pos); return list; } Selection::SequenceId parse_cid_seqid(const std::string& cid, size_t& pos, int default_seqnum) { size_t initial_pos = pos; int seqnum = default_seqnum; char icode = ' '; if (cid[pos] == '*') { ++pos; icode = '*'; } else if (std::isdigit(cid[pos])) { char* endptr; seqnum = std::strtol(&cid[pos], &endptr, 10); pos = endptr - &cid[0]; } if (cid[pos] == '.') ++pos; if (initial_pos != pos && (std::isalpha(cid[pos]) || cid[pos] == '*')) icode = cid[pos++]; return {seqnum, icode}; } } // namespace impl inline Selection parse_cid(const std::string& cid) { Selection sel; if (cid.empty() || (cid.size() == 1 && cid[0] == '*')) return sel; int omit = impl::determine_omitted_cid_fields(cid); size_t sep = 0; // model if (omit == 0) { sep = cid.find('/', 1); if (sep != 1 && cid[1] != '*') { char* endptr; sel.mdl = std::strtol(&cid[1], &endptr, 10); size_t end_pos = endptr - &cid[0]; if (end_pos != sep && end_pos != cid.length()) fail("Expected model number first: " + cid); } } // chain if (omit <= 1 && sep != std::string::npos) { size_t pos = (sep == 0 ? 0 : sep + 1); sep = cid.find('/', pos); sel.chain_ids = impl::make_cid_list(cid, pos, sep); } // residue; MMDB CID syntax: s1.i1-s2.i2 or *(res).ic // In gemmi both 14.a and 14a are accepted. // *(ALA). and *(ALA) and (ALA). can be used instead of (ALA) for // compatibility with MMDB. if (omit <= 2 && sep != std::string::npos) { size_t pos = (sep == 0 ? 0 : sep + 1); if (cid[pos] != '(') sel.from_seqid = impl::parse_cid_seqid(cid, pos, INT_MIN); if (cid[pos] == '(') { ++pos; size_t right_br = cid.find(')', pos); sel.residue_names = impl::make_cid_list(cid, pos, right_br); pos = right_br + 1; } // allow "(RES)." and "(RES).*" and "(RES)*" if (cid[pos] == '.') ++pos; if (cid[pos] == '*') ++pos; if (cid[pos] == '-') { ++pos; sel.to_seqid = impl::parse_cid_seqid(cid, pos, INT_MAX); } sep = pos; } // atom; at[el]:aloc if (sep < cid.size()) { if (sep != 0 && cid[sep] != '/') fail("Invalid selection syntax: " + cid); size_t pos = (sep == 0 ? 0 : sep + 1); size_t end = cid.find_first_of("[:", pos); if (end != pos) sel.atom_names = impl::make_cid_list(cid, pos, end); if (end != std::string::npos) { if (cid[end] == '[') { pos = end + 1; end = cid.find(']', pos); sel.elements = impl::make_cid_list(cid, pos, end); sel.elements.list = to_upper(sel.elements.list); ++end; } if (cid[end] == ':') sel.altlocs = impl::make_cid_list(cid, end + 1, std::string::npos); else if (end < cid.length()) fail("Invalid selection syntax (after ']'): " + cid); } } return sel; } } // namespace gemmi #endif // vim:sw=2:ts=2:et
#ifndef PERF_TOOL_H #define PERF_TOOL_H #include <string> #include "Base.h" class PerfTool { public: // 开始性能检测 static std::string RTSP_EXPORT startCPUProfiler(); // 停止性能检测 static std::string RTSP_EXPORT stopCPUProfiler(); // 开始分析堆栈 static std::string RTSP_EXPORT startHeapProfiler(); // 停止堆栈分析 static std::string RTSP_EXPORT stopHeapProfiler(); private: static std::string mClassName; static bool mCpuProfiler; static bool mHeapProfiler; static std::string mCpuProfilerFile; static std::string mHeapProfilerFile; }; #endif
// MemoryManager.h // Handles memory pages. Yay! // #ifndef MEMORYMANAGER_H #define MEMORYMANAGER_H #include "copyright.h" #include "bitmap.h" #include "synch.h" class MemoryManager { public: MemoryManager(); ~MemoryManager(); int getPage(); void clearPage(int i); int freePages(); private: BitMap* bit_mem; int mem_size; Lock* mem_lock; }; #endif // MEMORYMANAGER_H
#pragma once #include <memory> #include <string> #include "drake/common/drake_copyable.h" #include "drake/common/drake_deprecated.h" #include "drake/multibody/multibody_tree/multibody_plant/multibody_plant.h" #include "drake/systems/controllers/inverse_dynamics.h" #include "drake/systems/controllers/pid_controller.h" #include "drake/systems/controllers/state_feedback_controller_interface.h" #include "drake/systems/framework/diagram.h" // Forward declaration keeps us from including RBT headers that significantly // slow compilation. template <class T> class RigidBodyTree; namespace drake { namespace systems { namespace controllers { /** * A state feedback controller that uses a PidController to generate desired * accelerations, which are then converted into torques using InverseDynamics. * More specifically, the output of this controller is: * `torque = inverse_dynamics(q, v, vd_d)`, * where `vd_d = kp(q* - q) + kd(v* - v) + ki int(q* - q) + vd*`. * `q` and `v` stand for the generalized position and velocity, and `vd` is * the generalized acceleration. `*` indicates reference values. * * This controller always has a BasicVector input port for estimated robot state * `(q, v)`, a BasicVector input port for reference robot state `(q*, v*)` and * a BasicVector output port for computed torque `torque`. A constructor flag * can be set to track reference acceleration `vd*` as well. When set, a * BasicVector input port is also declared, and it's content is used as `vd*`. * When unset, `vd*` is be treated as zero. * * Note that this class assumes the robot is fully actuated, its position * and velocity have the same dimension, and it does not have a floating base. * If violated, the program will abort. This controller was not designed for * closed loop systems: the controller accounts for neither constraint forces * nor actuator forces applied at loop constraints. Use on such systems is not * recommended. * * @tparam T The vector element type, which must be a valid Eigen scalar. * @see InverseDynamics for an accounting of all forces incorporated into the * inverse dynamics computation. * * Instantiated templates for the following kinds of T's are provided: * - double * * @ingroup control_systems */ template <typename T> class InverseDynamicsController : public Diagram<T>, public StateFeedbackControllerInterface<T> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(InverseDynamicsController) /** * Constructs the controller that takes ownership of a given RigidBodyTree * unique pointer. * @param robot Unique pointer whose ownership will be transferred to this * instance. * @param kp Position gain. * @param ki Integral gain. * @param kd Velocity gain. * @param has_reference_acceleration If true, there is an extra BasicVector * input port for `vd*`. If false, `vd*` is treated as zero, and no extra * input port is declared. */ InverseDynamicsController(std::unique_ptr<RigidBodyTree<T>> robot, const VectorX<double>& kp, const VectorX<double>& ki, const VectorX<double>& kd, bool has_reference_acceleration); /** * Constructs an inverse dynamics controller for the given `plant` model. * The %InverseDynamicsController holds an internal, non-owned reference to * the MultibodyPlant object so you must ensure that `plant` has a longer * lifetime than `this` %InverseDynamicsController. * @param plant The model of the plant for control. * @param kp Position gain. * @param ki Integral gain. * @param kd Velocity gain. * @param has_reference_acceleration If true, there is an extra BasicVector * input port for `vd*`. If false, `vd*` is treated as zero, and no extra * input port is declared. * @pre `plant` has been finalized (plant.is_finalized() returns `true`). * @throws std::exception if * - The plant is not finalized (see MultibodyPlant::Finalize()). * - The number of generalized velocities is not equal to the number of * generalized positions. * - The model is not fully actuated. * - Vector kp, ki and kd do not all have the same size equal to the number * of generalized positions. */ InverseDynamicsController( const multibody::multibody_plant::MultibodyPlant<T>& plant, const VectorX<double>& kp, const VectorX<double>& ki, const VectorX<double>& kd, bool has_reference_acceleration); ~InverseDynamicsController() override; /** * Sets the integral part of the PidController to @p value. * @p value must be a column vector of the appropriate size. */ void set_integral_value(Context<T>* context, const Eigen::Ref<const VectorX<T>>& value) const; /** * Returns the input port for the reference acceleration. */ const InputPort<T>& get_input_port_desired_acceleration() const { DRAKE_DEMAND(has_reference_acceleration_); DRAKE_DEMAND(input_port_index_desired_acceleration_ >= 0); return Diagram<T>::get_input_port(input_port_index_desired_acceleration_); } /** * Returns the input port for the estimated state. */ const InputPort<T>& get_input_port_estimated_state() const final { return this->get_input_port(input_port_index_estimated_state_); } /** * Returns the input port for the desired state. */ const InputPort<T>& get_input_port_desired_state() const final { return this->get_input_port(input_port_index_desired_state_); } /** * Returns the output port for computed control. */ const OutputPort<T>& get_output_port_control() const final { return this->get_output_port(output_port_index_control_); } /** * Returns a constant reference to the RigidBodyTree used for control. */ DRAKE_DEPRECATED("Please use get_rigid_body_tree_for_control().") const RigidBodyTree<T>& get_robot_for_control() const { if (rigid_body_tree_for_control_ == nullptr) { throw std::runtime_error( "This controller was created for a MultibodyPlant." "Use get_multibody_plant_for_control() instead."); } return *rigid_body_tree_for_control_; } /** * Returns a pointer to the const RigidBodyTree used for control. * @return `nullptr` if `this` was constructed using a MultibodyPlant. */ const RigidBodyTree<T>* get_rigid_body_tree_for_control() const { return rigid_body_tree_for_control_.get(); } /** * Returns a constant pointer to the MultibodyPlant used for control. * @return `nullptr` if `this` was constructed using a RigidBodyTree. */ const multibody::multibody_plant::MultibodyPlant<T>* get_multibody_plant_for_control() const { return multibody_plant_for_control_; } private: void SetUp(const VectorX<double>& kp, const VectorX<double>& ki, const VectorX<double>& kd, const controllers::InverseDynamics<T>& inverse_dynamics, DiagramBuilder<T>* diagram_builder); std::unique_ptr<RigidBodyTree<T>> rigid_body_tree_for_control_; const multibody::multibody_plant::MultibodyPlant<T>* multibody_plant_for_control_{nullptr}; PidController<T>* pid_{nullptr}; const bool has_reference_acceleration_{false}; int input_port_index_estimated_state_{-1}; int input_port_index_desired_state_{-1}; int input_port_index_desired_acceleration_{-1}; int output_port_index_control_{-1}; }; } // namespace controllers } // namespace systems } // namespace drake
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define maxN 100001 int ar[maxN],st[4*maxN]; void buildtree(int si,int ss,int se) { if(ss==se) { st[si]=ar[ss]; return; } int mid=(ss+se)/2; buildtree(2*si,ss,mid); buildtree(2*si+1,mid+1,se); st[si]=st[2*si]+st[2*si+1]; } ll query(int si,int ss,int se,int qs,int qe) { if(qs>qe)return 0; if(qs==ss && qe==se) return st[si]; int mid=(ss+se)/2; ll l=query(2*si,ss,mid,qs,min(qe,mid)); ll r=query(2*si+1,mid+1,se,max(qs,mid+1),qe); return l+r; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n,x; cin>>n; int b[2*n+1]; map<int,int>mp,loc; for(int i=1;i<=2*n;i++) cin>>b[i]; array<int,3> v[2*n]; int j=0; for(int i=2*n;i>=1;i--) { x=b[i]; mp[x]++; if(mp[x]==1) { loc[x]=i; ar[i]=1; } if(mp[x]==2) { ar[i]=2; v[j][0]=x; v[j][1]=i; v[j][2]=loc[x]; j++; } } buildtree(1,1,2*n); sort(v,v+j); for(int i=0;i<j;i++) cout<<query(1,1,2*n,v[i][1]+1,v[i][2])/3-1<<" "; cout<<"\n"; }
#include <iostream> #include <cstdio> #include <vector> using namespace std; int main(){ int a,b,c; cin >> a >> b >> c; vector<int > v(a+1); v[a] = 1; for(int i = c ; i < b ; i++){ v[i] = 1; } int num = 0; for(int i = 0 ; i < v.size() ; i++)if(v[i]==1)num++; cout << num; return 0; }
#ifndef MATH_Vec2d_3562362386348_HEADER #define MATH_Vec2d_3562362386348_HEADER #include "Common.h" namespace solar { //Two dimensional vector of doubles template<typename T> class Vec2 { public: T x, y; Vec2() { x = y = T(); } constexpr explicit Vec2(T x, T y = T()) :x(x), y(y) {} Vec2(const Vec2<T>&) = default; Vec2(Vec2&&) = default; Vec2<T>& operator=(const Vec2&) = default; Vec2<T>& operator=(Vec2&&) = default; ~Vec2() = default; T LengthSq() const { return static_cast<T>(x*x + y*y); } T Length() const { return static_cast<T>(sqrt(LengthSq())); } Vec2<T>& SetLength(T length) { this->Normalize(); (*this) *= length; return *this; } Vec2<T>& Normalize() { T length = Length(); if (length < epsilon<T>) throw Exception("Cannot normalize zero-length vector."); else { x /= length; y /= length; } return *this; } Vec2<T>& operator+=(T val) { x += val; y += val; return *this; } Vec2<T>& operator-=(T val) { x -= val; y -= val; return *this; } Vec2<T>& operator*=(T val) { x *= val; y *= val; return *this; } Vec2<T>& operator/=(T val) { if (std::abs(val) < epsilon<T>) throw Exception("Cannot divide by zero."); x /= val; y /= val; return *this; } Vec2<T>& operator+=(const Vec2<T>& other) { x += other.x; y += other.y; return *this; } Vec2<T>& operator-=(const Vec2<T>& other) { x -= other.x; y -= other.y; return *this; } Vec2<T>& operator*=(const Vec2<T>& other) { x *= other.x; y *= other.y; return *this; } Vec2<T>& operator/=(const Vec2<T>& other) { if (std::abs(other.x) < epsilon<T> || std::abs(other.y) < epsilon<T>) throw Exception("Cannot divide by a vector containing zero element."); x /= other.x; y /= other.y; return *this; } template<typename U> explicit operator Vec2<U>() const { return Vec2<U>(static_cast<U>(x), static_cast<U>(y)); } }; template<typename T> void swap(Vec2<T>& a, Vec2<T>& b) noexcept { using std::swap; swap(a.x, b.x); swap(a.y, b.y); } template<typename T> T DotProduct(const Vec2<T>& a, const Vec2<T>& b) { return a.x*b.x + a.y*b.y; } template<typename T> Vec2<T> operator+(const Vec2<T>& a, const Vec2<T>& b) { Vec2<T> temp(a); return temp += b; } template<typename T> Vec2<T> operator-(const Vec2<T>& a, const Vec2<T>& b) { Vec2<T> temp(a); return temp -= b; } template<typename T> Vec2<T> operator*(const Vec2<T>& a, const Vec2<T>& b) { Vec2<T> temp(a); return temp *= b; } template<typename T> Vec2<T> operator/(const Vec2<T>& a, const Vec2<T>& b) { Vec2<T> temp(a); return temp /= b; } template<typename T> Vec2<T> operator+(const Vec2<T>& a, T b) { Vec2<T> temp(a); return temp += b; } template<typename T> Vec2<T> operator-(const Vec2<T>& a, T b) { Vec2<T> temp(a); return temp -= b; } template<typename T> Vec2<T> operator*(const Vec2<T>& a, T b) { Vec2<T> temp(a); return temp *= b; } template<typename T> Vec2<T> operator/(const Vec2<T>& a, T b) { Vec2<T> temp(a); return temp /= b; } template<typename T> Vec2<T> operator+(T a, const Vec2<T>& b) { return b + a; } template<typename T> Vec2<T> operator-(T a, const Vec2<T>& b) { return b - a; } template<typename T> Vec2<T> operator*(T a, const Vec2<T>& b) { return b*a; } } #endif
/** * Date: 2019-11-08 21:59:30 * LastEditors: Aliver * LastEditTime: 2019-11-08 23:59:27 */ #include <iostream> #include <unistd.h> #include <cstdlib> #include <cstring> #include <fcntl.h> #include <sys/types.h> // mkfifo #include <sys/stat.h> #include <sys/wait.h> using namespace std; void exitWithError(const char *pro) { perror(pro); exit(EXIT_FAILURE); } int createFifo(const char *pathname, mode_t mode) { if (access(pathname, F_OK) == -1) if (mkfifo(pathname, mode) == -1) exitWithError("mkfifo"); return 0; } int removeFifo(const char *pathname) { if (unlink(pathname) == -1) exitWithError("unlink"); return 0; } int main(int argc, char *argv[]) { const char *pathname = "./fifo"; createFifo(pathname, 0666); int childPid = fork(); if (childPid == -1) exitWithError("fork"); if (childPid == 0) { // 只读打开管道 阻塞方式 直到write end连接后返回 int fd = open(pathname, O_RDONLY); if (fd == -1) exitWithError("open"); char buff[16]; read(fd, buff, sizeof(buff) - 1); cout << "pid-" << getpid() << " read from parent-" << getppid() << " : " << buff << endl; close(fd); exit(EXIT_SUCCESS); } else { // 只写打开管道 阻塞方式 直到read end连接后返回 int fd = open(pathname, O_WRONLY); if (fd == -1) exitWithError("open"); const char *str = "1750817-高鹏"; write(fd, str, strlen(str)); cout << "pid-" << getpid() << " write to child-" << childPid << " : " << str << endl; close(fd); wait(NULL); removeFifo(pathname); exit(EXIT_SUCCESS); } }
#include <string> typedef std::string SStr; typedef std::wstring WStr; typedef std::string String;
#pragma once #include "Types.hpp" namespace engine { Int64 StringToInt64(const char* str, const char** endPtr = nullptr); Uint32 StringLen(const char* str); } // namespace engine
/** * Copyright (C) 2017 Alibaba Group Holding Limited. All Rights Reserved. * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __I_V4L2_SERVICE_H__ #define __I_V4L2_SERVICE_H__ #include "multimedia/mm_cpp_utils.h" #include "multimedia/mm_errors.h" #include "multimedia/mm_cpp_utils.h" namespace YUNOS_MM { class IV4l2Service { public: enum V4l2Type { kTypeNone = 0, kTypeLocal = 1 << 0, kTypeProxy = 1 << 1 }; enum { kInvalidNodeId = 0 }; public: IV4l2Service() : mV4l2Type(false) {} virtual ~IV4l2Service() {} virtual bool isLocalNode(pid_t pid) = 0; virtual mm_status_t createNode(uint32_t *nodeId) = 0; virtual void destroyNode(uint32_t nodeId) = 0; public: bool mV4l2Type; public: static const char *serviceName() { return "com.yunos.v4l2.service"; } static const char *pathName() { return "/com/yunos/v4l2/service"; } static const char *iface() { return "com.yunos.v4l2.service.interface"; } }; } #endif //__I_V4L2_SERVICE_H__
#include "kernel.hh" #include <bscheduler/base/error.hh> #include <unistdx/base/make_object> namespace { inline bsc::kernel::id_type get_id(const bsc::kernel* rhs) { return !rhs ? bsc::mobile_kernel::no_id() : rhs->id(); } } void bsc::kernel::read(sys::pstream& in) { base_kernel::read(in); bool b = false; in >> b; if (b) { this->setf(kernel_flag::carries_parent); } assert(not this->_parent); in >> this->_parent_id; assert(not this->_principal); in >> this->_principal_id; this->setf(kernel_flag::parent_is_id); this->setf(kernel_flag::principal_is_id); } void bsc::kernel::write(sys::pstream& out) const { base_kernel::write(out); out << carries_parent(); if (this->moves_downstream()) { out << this->_parent_id << this->_principal_id; } else { if (this->isset(kernel_flag::parent_is_id)) { out << this->_parent_id; } else { out << get_id(this->_parent); } if (this->isset(kernel_flag::principal_is_id)) { out << this->_principal_id; } else { out << get_id(this->_principal); } } } void bsc::kernel::act() {} void bsc::kernel::react(kernel*) { BSCHEDULER_THROW(error, "empty react"); } void bsc::kernel::error(kernel* rhs) { this->react(rhs); } std::ostream& bsc::operator<<(std::ostream& out, const kernel& rhs) { const char state[] = { (rhs.moves_upstream() ? 'u' : '-'), (rhs.moves_downstream() ? 'd' : '-'), (rhs.moves_somewhere() ? 's' : '-'), (rhs.moves_everywhere() ? 'b' : '-'), 0 }; return out << sys::make_object( "state", state, "type", typeid(rhs).name(), "id", rhs.id(), "src", rhs.from(), "dst", rhs.to(), "ret", rhs.return_code(), "app", rhs.app(), "parent", rhs._parent, "principal", rhs._principal ); }
#include<bits/stdc++.h> using namespace std; typedef long long ll; void solve(){ int n; cin>>n; string s;cin>>s; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("op.txt","w",stdout); #endif int t=1; //cin>>t; while(t--){ solve(); } }
/*********************************************************************** created: 27/7/2015 author: Yaron Cohen-Tal *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2015 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS 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. ***************************************************************************/ #if !defined __ANDROID__ #error This file should only be used in Android. #endif #include "SamplesFramework.h" #include "CEGUI/RendererModules/OpenGL/GL.h" #include <jni.h> #include <cassert> #include <android/log.h> typedef jobject AndroidActivity; SamplesFramework* G_sampleFramework(0); void finishAndroidActivity(JNIEnv* env, AndroidActivity activity) { jclass activity_class(env->FindClass("android/app/Activity")); assert(env->IsSameObject(activity_class, 0) == (jboolean)JNI_FALSE); jmethodID finish_method(env->GetMethodID(activity_class, "finish", "()V")); assert(finish_method); env->CallVoidMethod(activity, finish_method); } extern "C" { JNIEXPORT void JNICALL Java_sample_1framework_cegui_MainActivity_nativeFinish (JNIEnv* env, jclass /*class_*/, AndroidActivity activity) { bool caught_exception(false); CEGUI_TRY { assert(G_sampleFramework); G_sampleFramework->cleanup(); CEGUI_DELETE_AO G_sampleFramework; G_sampleFramework = 0; } CEGUI_CATCH(const std::exception& exception) { G_sampleFramework->outputExceptionMessage(exception.what()); finishAndroidActivity(env, activity); } } JNIEXPORT void JNICALL Java_sample_1framework_cegui_MainActivity_init (JNIEnv* env, jclass /*class_*/, AndroidActivity activity, jstring log_file_java, jstring data_path_prefix_java) { bool caught_exception(false); CEGUI_TRY { assert(!G_sampleFramework); G_sampleFramework = new SamplesFramework(""); const char* log_file(env->GetStringUTFChars(log_file_java, 0)); const char* data_path_prefix (env->GetStringUTFChars(data_path_prefix_java, 0)); G_sampleFramework->initialise( CEGUI::String(reinterpret_cast<const CEGUI::utf8*>(log_file)), CEGUI::String( reinterpret_cast<const CEGUI::utf8*>(data_path_prefix))); env->ReleaseStringUTFChars(log_file_java, log_file); env->ReleaseStringUTFChars(data_path_prefix_java, data_path_prefix); } CEGUI_CATCH(const std::exception& exception) { G_sampleFramework->outputExceptionMessage(exception.what()); finishAndroidActivity(env, activity); } } JNIEXPORT void JNICALL Java_sample_1framework_cegui_MainActivity_render (JNIEnv* env, jclass /*class_*/, AndroidActivity activity) { bool caught_exception(false); CEGUI_TRY { glClear(GL_COLOR_BUFFER_BIT); G_sampleFramework->renderSingleFrame(0); } CEGUI_CATCH(const std::exception& exception) { G_sampleFramework->outputExceptionMessage(exception.what()); finishAndroidActivity(env, activity); } } } // extern "C"
#include "rectangle.hpp" #include <cmath> #include "color.hpp" #include "mat2.hpp" #include "vec2.hpp" #include "window.hpp" Rectangle::Rectangle() : min_{ 0.0,0.0 }, max_{ 1.0,1.0 }, color_{ 0,0,0 } {} Rectangle::Rectangle(Vec2 const& min, Vec2 const& max) : min_{ min }, max_{ max } {} Rectangle::Rectangle(Vec2 const& min, Vec2 const& max, Color const& color) : min_{ min }, max_{ max }, color_{ color } {} float Rectangle::laenge() const { return max_.y - min_.y; } float Rectangle::breite() const { return max_.x - min_.x; } float Rectangle::circumrefrence() const { return (2 * (laenge() + breite())); } Vec2 Rectangle::min() const { return min_; } Vec2 Rectangle::max() const { return max_; } /* void Rectangle::drawRect(Window const& win) const { win.draw_line(min_.x, min_.y, min_.x, max_.y, 0.0f, 0.0f, 0.0f); win.draw_line(min_.x, max_.y, max_.x, max_.y, 0.0f, 0.0f, 0.0f); win.draw_line(max_.x, max_.y, max_.x, min_.y, 0.0f, 0.0f, 0.0f); win.draw_line(max_.x, min_.y, min_.x, min_.y, 0.0f, 0.0f, 0.0f); return; } void Rectangle::drawRect(Window const& win, Color const& color) const{ win.draw_line(min_.x, min_.y, min_.x, max_.y, color.r, color.g, color.b); win.draw_line(min_.x, max_.y, max_.x, max_.y, color.r, color.g, color.b); win.draw_line(max_.x, max_.y, max_.x, min_.y, color.r, color.g, color.b); win.draw_line(max_.x, min_.y, min_.x, min_.y, color.r, color.g, color.b); return; }*/
// // Compiler/AST/StatementIf.cpp // // Brian T. Kelley <brian@briantkelley.com> // Copyright (c) 2007, 2008, 2011, 2012, 2014 Brian T. Kelley // // Chris Leahy <leahycm@gmail.com> // Copyright (c) 2007 Chris Leahy // // This software is licensed as described in the file LICENSE, which you should have received as part of this distribution. // #include "Compiler/AST/StatementIf.h" #include "Compiler/AST/Context.h" #include "Compiler/AST/Expression.h" #include "Compiler/AST/IStatementVisitor.h" #include "Compiler/AST/StatementBlock.h" using namespace Compiler::AST; StatementIf::StatementIf() : Statement(), m_expression(), m_trueStatementBlock(new StatementBlock()), m_falseStatementBlock(new StatementBlock()) { } void StatementIf::SetExpression(std::shared_ptr<Expression> expression) { m_expression = expression; expression->SetStatement(shared_from_this()); } void StatementIf::SetStatementBlock(std::shared_ptr<StatementBlock> statementBlock) { Statement::SetStatementBlock(statementBlock); GetTrueStatementBlock()->SetStatementBlock(statementBlock); GetFalseStatementBlock()->SetStatementBlock(statementBlock); } Statement::Kind StatementIf::GetKind() const { return Kind::If; } void StatementIf::ResolveTypes(const Context& context) { GetExpression()->ResolveTypes(context); GetTrueStatementBlock()->ResolveTypes(context); GetFalseStatementBlock()->ResolveTypes(context); } void StatementIf::ResolveNullTypes(const Context& context) { GetExpression()->ResolveNullTypes(context); GetTrueStatementBlock()->ResolveNullTypes(context); GetFalseStatementBlock()->ResolveNullTypes(context); } void StatementIf::Verify(const Context& context, Compiler::Diagnostics::IReporting& reporter) const { const std::shared_ptr<const Expression>& expression = GetExpression(); expression->Verify(context, reporter); if (expression->GetEvaluatesTo().GetKind() != Type::Kind::Boolean) { static const char *StatementNotBooleanErrorSTR = "Your %s must evaluate to a boolean!"; reporter.AddError(expression->GetFileRange(), StatementNotBooleanErrorSTR, "if"); } GetTrueStatementBlock()->Verify(context, reporter); GetFalseStatementBlock()->Verify(context, reporter); } void StatementIf::Accept(IStatementVisitor& visitor) const { visitor.Visit(*this); }
/* map.h -*- C++ -*- Rémi Attab (remi.attab@gmail.com), 20 Apr 2014 FreeBSD-style copyright and disclaimer apply std::map reflection. */ #pragma once #include "reflect.h" #include "dsl/basics.h" #include "dsl/template.h" #include "dsl/function.h" #include "dsl/operators.h" #include <map> namespace reflect { /******************************************************************************/ /* GENERIC MAP REFLECT */ /******************************************************************************/ namespace details { template<typename T_, typename KeyT, typename ValueT> void reflectMap(Type* type_) { reflectPlumbing(); reflectTypeTrait(map); reflectTypeValue(keyType, type<KeyT>()); reflectTypeValue(valueType, type<ValueT>()); reflectFn(size); reflectCustom(count) (const T_& value, const KeyT& k) -> size_t { return value.count(k); }; reflectCustom(operator[]) (T_& value, const KeyT& k) -> ValueT& { return value[k]; }; reflectCustom(at) (const T_& value, const KeyT& k) -> const ValueT& { auto it = value.find(k); if (it != value.end()) return it->second; reflectError("accessing unknown key in const map"); }; reflectCustom(keys) (const T_& value) -> std::vector<KeyT> { std::vector<KeyT> result; result.reserve(value.size()); for (auto& item : value) result.push_back(item.first); return result; }; } } // namespace details /******************************************************************************/ /* REFLECT MAP */ /******************************************************************************/ template<typename KeyT, typename ValueT> struct Reflect< std::map<KeyT, ValueT> > { typedef std::map<KeyT, ValueT> T_; static std::string id() { return "std::map<" + typeId<KeyT>() + "," + typeId<ValueT>() + ">"; } reflectTemplateLoader() static void reflect(Type* type) { details::reflectMap<T_, KeyT, ValueT>(type); } }; /******************************************************************************/ /* REFLECT UNORDERED MAP */ /******************************************************************************/ template<typename KeyT, typename ValueT> struct Reflect< std::unordered_map<KeyT, ValueT> > { typedef std::unordered_map<KeyT, ValueT> T_; static std::string id() { return "std::unordered_map<" + typeId<KeyT>() + "," + typeId<ValueT>() + ">"; } reflectTemplateLoader() static void reflect(Type* type) { details::reflectMap<T_, KeyT, ValueT>(type); } }; } // reflect
#ifndef MATHTOOLBOX_CONSTANTS_HPP #define MATHTOOLBOX_CONSTANTS_HPP namespace mathtoolbox { namespace constants { constexpr double pi = 3.14159265358979323846264338327950288; } } // namespace mathtoolbox #endif // MATHTOOLBOX_CONSTANTS_HPP
/* * wmcgui.h * created by WMCoolmon * * You may not sell or otherwise commercially exploit the source or things you * create based on the source. * */ #pragma once #include "globalincs/alphacolors.h" #include "globalincs/linklist.h" #include "globalincs/pstypes.h" #include "io/mouse.h" #include "ship/ship.h" #include "weapon/weapon.h" #include <string> #include <climits> //*****************************Low-level abstraction******************************* //Lame attempt to keep things from being exceedingly difficult when switching to ferrium #ifndef FERRIUM #define IMG_HANDLE int #define IMG_HANDLE_SET_INVALID(h) h = -1 #define IMG_HANDLE_IS_INVALID(h) (h==-1) #define IMG_HANDLE_IS_VALID(h) (h!=-1) #define IMG_HANDLE_SET_FRAME(dh,h,f)(dh = h + f) #define IMG_LOAD(f) bm_load(f) #define IMG_LOAD_ANIM(f,n,fps) bm_load_animation(f,n,fps) #define IMG_UNLOAD(a) bm_unload(a) #define IMG_SET(h) gr_set_bitmap(h) #define IMG_SET_FRAME(h, f) gr_set_bitmap(h + f) #define IMG_DRAW(x,y) gr_bitmap(x,y,GR_RESIZE_NONE) #define IMG_INFO(ha,w,h) bm_get_info(ha,w,h) #endif //*****************************LinkedList******************************* struct LinkedList { friend class GUISystem; friend class GUIObject; friend class Tree; friend struct TreeItem; friend class Window; public: struct LinkedList *next, *prev; LinkedList(){ next = this; prev = this; } virtual ~LinkedList(){ prev->next = next; next->prev = prev; } }; //*****************************ClassInfoEntry******************************* //This is chiefly used in conjunction with GUISystem to store information //about classes //T - Top //L - Left //R - Right //B - Bottom //N - Normal //M - Mouseovered //C - Clicked //S - Selected/Active (for windows) //D - Disabled //A - Active //I - Inactive //Types of CIEs #define CIE_NONE -1 #define CIE_IMAGE 0 #define CIE_IMAGE_NMCSD 1 #define CIE_IMAGE_BORDER 2 #define CIE_COORDS 3 #define CIE_TEXT 4 //NMCSD Handles #define CIE_HANDLE_N 0 #define CIE_HANDLE_M 1 #define CIE_HANDLE_C 3 #define CIE_HANDLE_S 3 #define CIE_HANDLE_D 4 //Border handles #define CIE_HANDLE_TL 0 #define CIE_HANDLE_TM 1 #define CIE_HANDLE_TR 2 #define CIE_HANDLE_ML 3 #define CIE_HANDLE_MR 4 #define CIE_HANDLE_BL 5 #define CIE_HANDLE_BM 6 #define CIE_HANDLE_BR 7 //Text #define CIE_COLOR_R 0 #define CIE_COLOR_G 1 #define CIE_COLOR_B 2 #define CIE_COLOR_A 3 //Return vals #define CIE_GC_NONE_SET 0 #define CIE_GC_X_SET (1<<0) #define CIE_GC_Y_SET (1<<1) #define CIE_GC_W_SET (1<<2) #define CIE_GC_H_SET (1<<3) //Global stuff #define CIE_NUM_HANDLES 8 //We need 8 for border union Handle { ubyte Colors[4]; IMG_HANDLE Image; }; //Individual info class ClassInfoEntry { int CIEType; Handle Handles[CIE_NUM_HANDLES]; int Coords[2]; public: //--CONSTRUCTORS ClassInfoEntry(); ~ClassInfoEntry(); //--SET FUNCTIONS void Parse(const char* tag, int in_type); //--GET FUNCTIONS int GetImageHandle(int ID=CIE_HANDLE_N){return Handles[ID].Image;} ubyte GetColorHandle(int ColorID, int ID=CIE_HANDLE_N){return Handles[ID].Colors[ColorID];} //Copies the coordinates to the given location if coordinates are set. int GetCoords(int *x, int *y); }; //Entries for an object, ie a window or button class ObjectClassInfoEntry { friend class GUIScreen; private: int Object; SCP_string Name; //Do we want this to only apply to a specific object? //If so, set name int Coords[4]; SCP_vector<ObjectClassInfoEntry> Subentries; SCP_vector<ClassInfoEntry> Entries; public: ObjectClassInfoEntry(){Object=-1;Coords[0]=Coords[1]=Coords[2]=Coords[3]=INT_MAX;} bool Parse(); int GetImageHandle(int id, int handle_num); int GetCoords(int id, int *x, int *y); int GetObjectCoords(int *x, int *y, int *w, int *h); }; //Entries for a screen. class ScreenClassInfoEntry : public LinkedList { friend class GUIScreen; private: SCP_string Name; SCP_vector<ObjectClassInfoEntry> Entries; public: bool Parse(); SCP_string GetName(){return Name;} }; //*****************************GUIObject******************************* //What type a GUIObject is, mostly for debugging #define GT_NONE 0 #define GT_WINDOW 1 #define GT_BUTTON 2 #define GT_MENU 3 #define GT_TEXT 4 #define GT_CHECKBOX 5 #define GT_IMAGEANIM 6 #define GT_HUDGAUGE 7 #define GT_SLIDER 8 #define GT_NUM_TYPES 9 //Total number of types //States of being for GUIObjects #define GST_NORMAL 0 #define GST_MOUSE_LEFT_BUTTON (1<<0) #define GST_MOUSE_RIGHT_BUTTON (1<<1) #define GST_MOUSE_MIDDLE_BUTTON (1<<2) #define GST_MOUSE_OVER (1<<3) #define GST_KEYBOARD_CTRL (1<<4) #define GST_KEYBOARD_ALT (1<<5) #define GST_KEYBOARD_SHIFT (1<<6) #define GST_KEYBOARD_KEYPRESS (1<<7) #define GST_MOUSE_PRESS (GST_MOUSE_LEFT_BUTTON | GST_MOUSE_RIGHT_BUTTON | GST_MOUSE_MIDDLE_BUTTON) #define GST_MOUSE_STATUS (GST_MOUSE_LEFT_BUTTON | GST_MOUSE_RIGHT_BUTTON | GST_MOUSE_MIDDLE_BUTTON | GST_MOUSE_OVER) #define GST_KEYBOARD_STATUS (GST_KEYBOARD_CTRL | GST_KEYBOARD_ALT | GST_KEYBOARD_SHIFT | GST_KEYBOARD_KEYPRESS) //GUIObject styles #define GS_NOAUTORESIZEX (1<<0) #define GS_NOAUTORESIZEY (1<<1) #define GS_HIDDEN (1<<2) #define GS_INTERNALCHILD (1<<3) //DoFrame return values #define OF_TRUE -1 #define OF_FALSE -2 //#define OF_DESTROYED -3 //If a call to DoFrame results in the object destroying itself //(ie the close button was pressed) class GUIObject : public LinkedList { friend class Slider; friend class Window; //Hack, because I can't figure out how to let it access protected friend class Menu; //This too friend class Text; //And this friend class Tree; //By, the way...THIS friend class Checkbox; friend class Button; friend class ImageAnim; friend class HUDGauge; friend class GUIScreen; friend class GUISystem; private: class GUISystem *OwnerSystem; //What system this object is associated with class GUIScreen *OwnerScreen; int Coords[4]; //Upper left corner (x, y) and lower right corner (x, y) int ChildCoords[4]; //Coordinates where children may frolick int Type; SCP_string Name; int LastStatus; int Status; int Style; class ObjectClassInfoEntry* InfoEntry; void (*CloseFunction)(GUIObject *caller); class GUIObject* Parent; LinkedList Children; int GetOIECoords(int *x1, int *y1, int *x2, int *y2); GUIObject *AddChildInternal(GUIObject* cgp); protected: //ON FUNCTIONS //These handle the calling of do functions, mostly. void OnDraw(float frametime); int OnFrame(float frametime, int *unused_queue); void OnMove(int dx, int dy); void OnRefreshSize(){if(DoRefreshSize() != OF_FALSE && Parent!=NULL)Parent->OnRefreshSize();} void OnRefreshSkin(){SetCIPointer(); DoRefreshSkin();} //DO FUNCTIONS //Used by individual objects to define actions when that event happens virtual void DoDraw(float /*frametime*/){} virtual int DoFrame(float /*frametime*/){return OF_FALSE;} virtual int DoRefreshSize(){return OF_FALSE;} virtual void DoRefreshSkin(){} virtual void DoMove(int /*dx*/, int /*dy*/){} virtual int DoMouseOver(float /*frametime*/){return OF_FALSE;} virtual int DoMouseDown(float /*frametime*/){return OF_FALSE;} virtual int DoMouseUp(float /*frametime*/){return OF_FALSE;} //In other words, a click virtual int DoMouseOut(float /*frametime*/){return OF_FALSE;} virtual int DoKeyState(float /*frametime*/){return OF_FALSE;} virtual int DoKeyPress(float /*frametime*/){return OF_FALSE;} //CALCULATESIZE //Sort of an on and do function; if you define your own, the following MUST be included at the end: //"if(Parent!=NULL)Parent->OnRefreshSize();" //PRIVATE ClassInfo FUNCTIONS void SetCIPointer(); int GetCIEImageHandle(int id, int handleid=0){if(InfoEntry!=NULL){return InfoEntry->GetImageHandle(id, handleid);}else{return -1;}} int GetCIECoords(int id, int *x, int *y); public: //CONSTRUCTION/DESTRUCTION //Derive your class's constructer from the GUIObject one GUIObject(const SCP_string &in_Name="", int x_coord = 0, int y_coord = 0, int x_width = -1, int y_height = -1, int in_style = 0); ~GUIObject() override; void Delete(); //CHILD FUNCTIONS //Used for managing children. :) GUIObject *AddChild(GUIObject* cgp); void DeleteChildren(GUIObject* exception = NULL); //SET FUNCTIONS void SetPosition(int x, int y); void SetCloseFunction(void (*in_closefunc)(GUIObject* caller)){CloseFunction = in_closefunc;} //GET FUNCTIONS int GetWidth(){return Coords[2]-Coords[0];} int GetHeight(){return Coords[3]-Coords[1];} }; //*****************************GUIScreen******************************* #define GSOF_NOTHINGPRESSED -1 #define GSOF_SOMETHINGPRESSED -2 class GUIScreen : public LinkedList { friend class GUISystem; private: SCP_string Name; GUISystem* OwnerSystem; ScreenClassInfoEntry* ScreenClassInfo; GUIObject Guiobjects; SCP_vector<GUIObject*> DeletionCache; public: GUIScreen(const SCP_string &in_Name=""); ~GUIScreen() override; ObjectClassInfoEntry *GetObjectClassInfo(GUIObject *cgp); //Set funcs GUIObject *Add(GUIObject* new_gauge); void DeleteObject(GUIObject* dgp); //On funcs int OnFrame(float frametime, bool doevents); }; //*****************************GUISystem******************************* class GUISystem { friend class GUIScreen; //I didn't want to do this, but it's the easiest way //to keep it from being confusing about how to remove GUIScreens private: GUIScreen Screens; GUIObject* ActiveObject; //Moving stuff GUIObject* GraspedGuiobject; int GraspingButton; //Button flag for button used to grasp the object int GraspedDiff[2]; //Diff between initial mouse position and object corner GUIObject* FocusGuiObject; //Linked list of screen class info bool ClassInfoParsed; ScreenClassInfoEntry ScreenClassInfo; //Mouse/status int MouseX; int MouseY; int KeyPressed; int Status, LastStatus; void DestroyClassInfo(); public: GUISystem(); ~GUISystem(); //----- GUIScreen* PushScreen(GUIScreen *csp); void PullScreen(GUIScreen *in_screen); ScreenClassInfoEntry *GetClassInfo(){return &ScreenClassInfo;} ScreenClassInfoEntry *GetScreenClassInfo(const SCP_string & screen_name); //----- //Set stuff void ParseClassInfo(const char* section); void SetActiveObject(GUIObject *cgp); void SetGraspedObject(GUIObject *cgp, int button); void SetFocusObject(GUIObject *cgp); //Get stuff int GetMouseX(){return MouseX;} int GetMouseY(){return MouseY;} int GetStatus(){return Status;} //int *GetLimits(){return Guiobjects.ChildCoords;} GUIObject* GetActiveObject(){return ActiveObject;} GUIObject* GetGraspedObject(){return GraspedGuiobject;} GUIObject* GetFocusObject(){return FocusGuiObject;} int GetKeyPressed(){return KeyPressed;} int OnFrame(float frametime, bool doevents, bool clearandflip); }; //*****************************Window******************************* #define W_BORDERWIDTH 1 #define W_BORDERHEIGHT 1 #define WS_NOTITLEBAR (1<<31) // doesn't have a title bar (ie, no title or min/close buttons) #define WS_NONMOVEABLE (1<<30) // can't be moved around #define WCI_CAPTION 0 #define WCI_CAPTION_TEXT 1 #define WCI_BORDER 2 #define WCI_BODY 3 #define WCI_HIDE 4 #define WCI_CLOSE 5 #define WCI_COORDS 6 #define WCI_NUM_ENTRIES 7 class Window : public GUIObject { SCP_string Caption; //Close bool CloseHighlight; int CloseCoords[4]; //Hide bool HideHighlight; int HideCoords[4]; //Caption text int CaptionCoords[4]; //Old height int UnhiddenHeight; //Skinning stuff //Left width, top height, right width, bottom height int BorderSizes[4]; bitmap_rect_list BorderRectLists[8]; bitmap_rect_list CaptionRectList; shader WindowShade; protected: void DoDraw(float frametime) override; void DoMove(int dx, int dy) override; int DoRefreshSize() override; int DoMouseOver(float frametime) override; int DoMouseDown(float frametime) override; int DoMouseUp(float frametime) override; int DoMouseOut(float frametime) override; bool HasChildren() { return NOT_EMPTY(&Children); } public: Window(const SCP_string& in_caption, int x_coord, int y_coord, int x_width = -1, int y_height = -1, int in_style = 0); void SetCaption(const SCP_string &in_caption){Caption = in_caption;} void ClearContent(); }; //*****************************Button******************************* //#define DEFAULT_BUTTON_WIDTH 50 #define B_BORDERWIDTH 1 #define B_BORDERHEIGHT 1 #define DEFAULT_BUTTON_HEIGHT 15 #define BS_STICKY (1<<31) //Button stays pressed #define BCI_COORDS 0 #define BCI_BUTTON 1 #define BCI_NUM_ENTRIES 2 class Button : public GUIObject { SCP_string Caption; void (*function)(Button *caller); bool IsDown; //Does it look pressed? protected: void DoDraw(float frametime) override; int DoRefreshSize() override; int DoMouseDown(float frametime) override; int DoMouseUp(float frametime) override; int DoMouseOut(float frametime) override; public: Button(const SCP_string &in_caption, int x_coord, int y_coord, void (*in_function)(Button *caller) = NULL, int x_width = -1, int y_height = -1, int in_style = 0); void SetPressed(bool in_isdown){IsDown = in_isdown;} }; //*****************************Tree******************************* //In pixels #define TI_BORDER_WIDTH 1 #define TI_BORDER_HEIGHT 1 #define TI_INITIAL_INDENT 2 #define TI_INITIAL_INDENT_VERTICAL 2 #define TI_INDENT_PER_LEVEL 10 #define TI_SPACE_BETWEEN_VERTICAL 2 // forward declaration class Tree; struct TreeItem : public LinkedList { friend class Tree; private: void (*Function)(Tree *caller); int Data; bool DeleteData; //Do we delete data for the user? bool ShowThis; bool ShowChildren; int Coords[4]; //For hit testing TreeItem *Parent; LinkedList Children; public: SCP_string Name; //Get TreeItem * GetParentItem(){return Parent;} int GetData(){return Data;} bool HasChildren(){return NOT_EMPTY(&Children);} void ClearAllItems(); TreeItem(); ~TreeItem() override; }; class Tree : public GUIObject { TreeItem Items; void *AssociatedItem; TreeItem *SelectedItem; TreeItem *HighlightedItem; TreeItem* HitTest(TreeItem *items); void MoveTreeItems(int dx, int dy, TreeItem *items); void CalcItemsSize(TreeItem *items, int *DrawData); void DrawItems(TreeItem *items); protected: void DoDraw(float frametime) override; void DoMove(int dx, int dy) override; int DoRefreshSize() override; int DoMouseOver(float frametime) override; int DoMouseDown(float frametime) override; int DoMouseUp(float frametime) override; public: Tree(const SCP_string &in_name, int x_coord, int y_coord, void* in_associateditem = NULL, int x_width = -1, int y_width = -1, int in_style = 0); //void LoadItemList(TreeItem *in_list, unsigned int count); TreeItem* AddItem(TreeItem *parent, const SCP_string &in_name, int in_data = 0, bool in_delete_data = true, void (*in_function)(Tree *caller) = NULL); void ClearItems(); TreeItem* GetSelectedItem(){return SelectedItem;} void SetSelectedItem(TreeItem *item); }; //*****************************Text******************************* #define MAX_TEXT_LINES 100 #define T_EDITTABLE (1<<31) //What type? #define T_ST_NONE 0 //No saving #define T_ST_INT (1<<0) #define T_ST_SINT (1<<1) #define T_ST_CHAR (1<<2) #define T_ST_FLOAT (1<<3) #define T_ST_UBYTE (1<<4) //When do we save changes? #define T_ST_ONENTER (1<<21) #define T_ST_CLOSE (1<<22) #define T_ST_REALTIME (1<<23) //If dynamically allocated, then how? #define T_ST_NEW (1<<30) //Allocated using new #define T_ST_MALLOC (1<<31) //Allocated using malloc class Text : public GUIObject { SCP_string Content; //Used to display stuff; change only from calculate func int NumLines; int LineLengths[MAX_TEXT_LINES]; const char *LineStartPoints[MAX_TEXT_LINES]; //Used for editing int CursorPos; //Line #, then position in line int SaveType; union { short *siSavePointer; int *iSavePointer; ubyte *ubSavePointer; float *flSavePointer; char *chSavePointer; char **chpSavePointer; }; union{int SaveMax;float flSaveMax;uint uSaveMax;}; union{int SaveMin;float flSaveMin;uint uSaveMin;}; protected: void DoDraw(float frametime) override; int DoRefreshSize() override; int DoMouseDown(float frametime) override; int DoKeyPress(float frametime) override; public: Text(const SCP_string &in_name, const SCP_string &in_content, int x_coord, int y_coord, int x_width = -1, int y_width = -1, int in_style = 0); //Set void SetText(const SCP_string &in_content); void SetText(int the_int); void SetText(float the_float); void SetSaveLoc(int *ptr, int save_method, int max_value=INT_MAX, int min_value=INT_MIN); void SetSaveLoc(short int *sint_ptr, int save_method, short int max_value=SHRT_MAX, short int min_value=SHRT_MIN); void SetSaveLoc(float *ptr, int save_method, float max_value=static_cast<float>(INT_MAX), float min_value=static_cast<float>(INT_MIN)); void SetSaveLoc(char *ptr, int save_method, uint max_len=UINT_MAX, uint min_len = 0); void SetSaveLoc(ubyte *ptr, int save_method, int max_value=UCHAR_MAX, int min_value=0); void SetSaveStringAlloc(char **ptr, int save_method, int mem_flags, uint max_len=UINT_MAX, uint min_len = 0); void AddLine(const SCP_string &in_line); //Get? bool Save(); void Load(); }; //*****************************Checkbox******************************* #define CB_TEXTCHECKDIST 2 class Checkbox : public GUIObject { SCP_string Label; void (*function)(Checkbox *caller); //For toggling flags with this thing int* FlagPtr; size_t Flag; ship_info* Sip; weapon_info* Wip; bool *BoolFlagPtr; int CheckCoords[4]; bool IsChecked; //Is it checked? int HighlightStatus; protected: void DoDraw(float frametime) override; void DoMove(int dx, int dy) override; int DoRefreshSize() override; int DoMouseOver(float frametime) override; int DoMouseDown(float frametime) override; int DoMouseUp(float frametime) override; int DoMouseOut(float frametime) override; public: Checkbox(const SCP_string &in_label, int x_coord, int y_coord, void (*in_function)(Checkbox *caller) = NULL, int x_width = -1, int y_height = DEFAULT_BUTTON_HEIGHT, int in_style = 0); bool GetChecked() { return IsChecked; } void SetLabel(const SCP_string &in_label) { Label = in_label; } void SetChecked(bool in_ischecked) { IsChecked = in_ischecked; } void SetFlag(int* in_flag_ptr, int in_flag) { FlagPtr = in_flag_ptr; Flag = in_flag; if ( (FlagPtr != NULL) && (*FlagPtr & Flag) ) { IsChecked = true; } } void SetFlag(uint* in_flag_ptr, int in_flag) { SetFlag((int*)in_flag_ptr, in_flag); } void SetFlag(flagset<Ship::Info_Flags>& in_flag_set, Ship::Info_Flags flag_value, ship_info* si) { FlagPtr = nullptr; Sip = si; Flag = static_cast<size_t>(flag_value); IsChecked = in_flag_set[flag_value]; } void SetFlag(flagset<Weapon::Info_Flags>& in_flag_set, Weapon::Info_Flags flag_value, weapon_info* wi) { FlagPtr = nullptr; Wip = wi; Flag = static_cast<size_t>(flag_value); IsChecked = in_flag_set[flag_value]; } void SetBool(bool *in_bool_ptr) { BoolFlagPtr = in_bool_ptr; } }; //*****************************ImageAnim******************************* #define PT_STOPPED 0 #define PT_PLAYING 1 #define PT_PLAYING_REVERSE 2 #define PT_STOPPED_REVERSE 3 #define IF_NONE 0 #define IF_BOUNCE 1 #define IF_REPEAT 2 #define IF_REVERSED 3 class ImageAnim : public GUIObject { SCP_string ImageAnimName; IMG_HANDLE ImageHandle; int TotalFrames; int FPS; bool IsSet; //Something of a hack, this is called so that //SetImage overrides skin image float Progress; float ElapsedTime; float TotalTime; int PlayType; int ImageFlags; protected: void DoDraw(float frametime) override; int DoRefreshSize() override; public: ImageAnim(const SCP_string &in_name, const SCP_string &in_imagename, int x_coord, int y_coord, int x_width = -1, int y_width = -1, int in_style = 0); void SetImage(const SCP_string &in_imagename); void Play(bool in_isreversed); void Pause(); void Stop(); }; //*****************************Slider******************************* class Slider : public GUIObject { SCP_string Label; void(*function)(Slider *caller); int BarCoords[4]; float SliderScale; // goes from 0.0 to 1.0f int SliderWidth; int BarWidth; int BarHeight; shader SliderShade; bool SliderGrabbed; float Min, Max; int GetSliderOffset(); float GetSliderPos(int x); void UpdateSlider(float x); protected: void DoDraw(float frametime) override; void DoMove(int dx, int dy) override; int DoRefreshSize() override; int DoMouseDown(float frametime) override; int DoMouseUp(float frametime) override; public: Slider(const SCP_string &in_label, float min, float max, int x_coord, int y_coord, void(*in_function)(Slider *caller) = NULL, int x_width = -1, int y_height = DEFAULT_BUTTON_HEIGHT, int in_style = 0); float GetSliderValue(); void SetSliderValue(float raw_val); }; //*****************************GLOBALS******************************* extern GUISystem GUI_system;
/* # Copyright 2018 Daniel Selsam. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== */ #include <string> #include <exception> #include <Eigen/Dense> #include "z3++.h" #include <cmath> #include <ctime> #include <cstdlib> #include <unordered_map> #include <map> #include <unordered_set> #include <set> #include <vector> #include <cstdio> #include <fstream> #include <algorithm> #include <sstream> using std::vector; using std::pair; using std::string; using std::unordered_map; using std::unordered_set; using std::set; #define MAX_UINT 4294967295 struct z3_expr_hash { unsigned operator()(z3::expr const & e) const { return e.hash(); } }; struct z3_expr_eq { bool operator()(z3::expr const & e1, z3::expr const & e2) const { return z3::eq(e1, e2); } }; template<typename T> using z3_expr_map = typename std::unordered_map<z3::expr, T, z3_expr_hash, z3_expr_eq>; using z3_expr_set = typename std::unordered_set<z3::expr, z3_expr_hash, z3_expr_eq>; class mstream { std::ostringstream m_strm; public: std::string str() const { return m_strm.str(); } template<typename T> mstream & operator<<(T const & t) { m_strm << t; return *this; } }; class SolverException : public std::exception { private: std::string _msg; public: explicit SolverException(const std::string & msg): _msg(msg) {} explicit SolverException(const mstream & msg): _msg(msg.str()) {} virtual const char* what() const throw() override { return _msg.c_str(); } }; struct Var { unsigned _idx; Var(unsigned idx): _idx(idx) {} unsigned idx() const { return _idx; } string repr() const { return string("Var(") + std::to_string(idx()) + ")"; } bool operator==(const Var & other) const { return idx() == other.idx(); } bool operator<(const Var & other) const { return idx() < other.idx(); } unsigned hash() const { return idx(); } }; namespace std { template <> struct hash<Var> { std::size_t operator()(const Var& var) const { return var.hash(); }}; } struct Lit { Var _var; bool _neg; Lit(Var var, bool neg): _var(var), _neg(neg) {} Var var() const { return _var; } bool neg() const { return _neg; } unsigned vidx(unsigned n_vars) const { return neg() ? var().idx() + n_vars : var().idx(); } Lit flip() const { return Lit(var(), !neg()); } string repr() const { return string("Lit(") + var().repr() + ", " + (neg() ? "1" : "0") + ")"; } bool operator==(const Lit & other) const { return var() == other.var() && neg() == other.neg(); } bool operator<(const Lit & other) const { return var() < other.var() || (var() == other.var() && neg() < other.neg()); } unsigned hash() const { return var().hash() + (neg() ? 100003 : 0); } // smallest 6-digit prime }; namespace std { template <> struct hash<Lit> { std::size_t operator()(const Lit& lit) const { return lit.hash(); }}; } enum class Assignment { POS, NEG, SKIP }; enum class Status { UNKNOWN, UNSAT, SAT }; static Status check_result_to_Status(z3::check_result const & cr) { switch (cr) { case z3::unknown: return Status::UNKNOWN; case z3::unsat: return Status::UNSAT; case z3::sat: return Status::SAT; } throw SolverException("check_result_to_Status: unexpected status from z3"); } struct Options { unsigned timeout_ms{MAX_UINT}; unsigned max_conflicts{MAX_UINT}; unsigned restart_max{MAX_UINT}; unsigned variable_decay{110}; bool override_incremental{false}; bool lookahead_simplify{false}; bool acce{false}; unsigned z3_replay_timeout_scale{10}; unsigned drat_trim_timeout_scale{200}; string logfilename{"/tmp/solver.log"}; }; class Context { z3::context _zctx; public: Context() {} z3::context & z() { return _zctx; } }; z3::expr mk_not(z3::expr const & lit) { if (lit.is_not()) { if (!lit.arg(0).is_const()) { throw SolverException(mstream() << "mk_not called on non-literal: " << lit); } return lit.arg(0); } else { if (!lit.is_const()) { throw SolverException(mstream() << "mk_not called on non-literal: " << lit); } return !lit; } } class Expr { z3::expr _zexpr; public: Expr(z3::expr const & zexpr): _zexpr(zexpr) {} z3::expr const & z() const { return _zexpr; } Expr flip() const { return Expr(mk_not(z())); } Expr var() const { return z().is_not() ? flip() : Expr(z()); } bool is_neg() const { return z().is_not(); } int ilit() const { z3::expr var = z().is_not() ? z().arg(0) : z(); if (!var.is_const()) { throw SolverException(mstream() << "ilit() called on non-literal: " << z()); } int ivar = var.decl().name().to_int(); return z().is_not() ? -ivar : ivar; } }; typedef Eigen::Array<bool,Eigen::Dynamic,1> ArrayXb; struct TFData { unsigned n_vars; unsigned n_clauses; Eigen::MatrixXi CL_idxs; TFData(unsigned n_vars, unsigned n_clauses, Eigen::MatrixXi const & CL_idxs): n_vars(n_vars), n_clauses(n_clauses), CL_idxs(CL_idxs) { if (n_vars == 0) { throw SolverException("Creating TFData with no variables"); } else if (n_clauses == 0) { throw SolverException("Creating TFData with no clauses"); } } ArrayXb core_var_mask; ArrayXb core_clause_mask; }; static void check_exists_and_nonempty(string const & filename) { std::ifstream f(filename); if (!f.good()) { throw SolverException(mstream() << "file '" << filename << "' does not exist"); } else if (f.peek() == std::ifstream::traits_type::eof()) { throw SolverException(mstream() << "file '" << filename << "' is empty"); } } static void system_throw(string const & cmd, string const & finally) { int ret = system(cmd.c_str()); if (WEXITSTATUS(ret) != 0) { system(finally.c_str()); throw SolverException(mstream() << "Executing '" << cmd << "' failed."); } } class Solver; struct TFDataManager { z3::expr_vector non_units; vector<z3::expr> pruned_clauses; z3_expr_map<Var> _non_unit_to_var; unsigned n_cells{0}; TFDataManager(Solver const & s); Var non_unit_to_var(z3::expr const & e) const { if (_non_unit_to_var.count(e)) { return _non_unit_to_var.at(e); } else { throw SolverException(mstream() << "expr not found in non_unit_to_var: " << e); } } Lit free_expr_to_lit(z3::expr const & e) const { if (e.is_not()) { return Lit(non_unit_to_var(e.arg(0)), true); } else if (!e.is_const()) { throw SolverException(mstream() << "zexpr_to_lit called on non-literal: " << e); } else { return Lit(non_unit_to_var(e), false); } } Eigen::MatrixXi to_CL_idxs() const { Eigen::MatrixXi CL_idxs = Eigen::MatrixXi(n_cells, 2); unsigned cell_idx = 0; for (unsigned c_idx = 0; c_idx < pruned_clauses.size(); ++c_idx) { for (unsigned arg_idx = 0; arg_idx < pruned_clauses[c_idx].num_args(); ++arg_idx) { CL_idxs(cell_idx, 0) = c_idx; CL_idxs(cell_idx, 1) = free_expr_to_lit(pruned_clauses[c_idx].arg(arg_idx)).vidx(non_units.size()); cell_idx++; } } return CL_idxs; } }; class Solver { public: Options _opts; z3::solver _zsolver; unsigned _orig_n_vars; // wrt original problem unsigned _total_n_vars; void set_options() { z().set(":lookahead.reward", "march_cu"); z().set(":lookahead.cube.cutoff", "depth"); z().set(":lookahead.cube.depth", (unsigned)1); z().set(":max_conflicts", _opts.max_conflicts); z().set(":sat.restart.max", _opts.restart_max); z().set(":sat.variable_decay", _opts.variable_decay); z().set(":override_incremental", _opts.override_incremental); z().set(":lookahead_simplify", _opts.lookahead_simplify); z().set(":acce", _opts.acce); z().set(":sat.force_cleanup", true); } void init_post_from() { _total_n_vars = z().units().size() + z().non_units().size(); _orig_n_vars = _total_n_vars; } void init_post_clone() { _total_n_vars = z().units().size() + z().non_units().size(); } z3::solver & z() { return _zsolver; } z3::solver const & z() const { return _zsolver; } public: Solver(Context & ctx, Options const & opts): _opts(opts), _zsolver(ctx.z(), "QF_FD") { set_options(); } Solver(Context & ctx, Options const & opts, Solver const & s): _opts(opts), _zsolver(ctx.z(), s.z(), z3::solver::translate()), _orig_n_vars(s._orig_n_vars) { set_options(); init_post_clone(); } Solver clone(Context & ctx) const { return Solver(ctx, _opts, *this); } void from_string(string const & s) { try { z().from_string(s.c_str()); } catch (...) { throw SolverException("error in Solver::from_string(...)"); } init_post_from(); } void from_file(string const & filename) { try { z().from_file(filename.c_str()); } catch (...) { throw SolverException("error in Solver::from_file(...)"); } init_post_from(); } string serialize() { return z().dimacs(); } string dimacs() { return z().dimacs(); } unsigned total_n_vars() const { return _total_n_vars; } void add(Expr const & expr) { z().add(expr.z()); } Status propagate() { z().set(":max_conflicts", (unsigned) 0); z3::check_result cr = z().check(); z().set(":max_conflicts", _opts.max_conflicts); return check_result_to_Status(cr); } Status check() { return check_with_timeout_ms(_opts.timeout_ms); } Status check_with_timeout_ms(unsigned timeout_ms) { z().set(":timeout", timeout_ms); z3::check_result result = z().check(); z().set(":timeout", (unsigned) MAX_UINT); if (result == z3::unknown) { return propagate(); } else { return check_result_to_Status(result); } } private: void validate_cube(z3::expr_vector const & cube) { if (cube.size() == 0) { throw SolverException("z3::cube() returned empty cube"); } else if (cube.size() > 1) { throw SolverException("unexpected cube of size > 1"); } } public: pair<Status, vector<Expr>> cube() { z3::solver::cube_generator cg = z().cubes(); z3::solver::cube_iterator start = cg.begin(); z3::solver::cube_iterator end = cg.end(); if (start == end) { return { Status::UNSAT, {} }; } z3::expr_vector cube1 = *start; validate_cube(cube1); assert(cube1.size() == 1); if (cube1[0].is_true()) { return { Status::SAT, {} }; } ++start; if (start == end) { /* failed lit */ return { Status::UNKNOWN, { Expr(cube1[0]) } }; } z3::expr_vector cube2 = *start; validate_cube(cube2); if (cube1 == cube2) { throw SolverException("Both cubes are the same: did you forget to increment the iterator?"); } ++start; if (start != end) { throw SolverException("z3::cube() returned more than two cubes"); } return { Status::UNKNOWN, { Expr(cube1[0]), Expr(cube2[0]) } }; } Expr get_free_var(unsigned v_idx) { // Warning: slow z3::expr_vector non_units = z().non_units(); if (v_idx >= non_units.size()) { throw SolverException("v_idx too big!"); } z3::expr e = non_units[v_idx]; return Expr(e); } TFData to_tf_data() const { //if (propagate() != Status::UNKNOWN) { throw SolverException("to_tf_data(): propagate does not return UNKNOWN"); } TFDataManager dm(*this); if (dm.non_units.size() == 0) { throw SolverException("to_tf_data() but no free variables"); } if (dm.pruned_clauses.size() == 0) { throw SolverException("to_tf_data() but no pruned clauses"); } return TFData(dm.non_units.size(), dm.pruned_clauses.size(), dm.to_CL_idxs()); } TFData to_tf_data_with_core() const { TFDataManager dm(*this); TFData tfd(dm.non_units.size(), dm.pruned_clauses.size(), dm.to_CL_idxs()); tfd.core_clause_mask = compute_core_clause_mask(dm.pruned_clauses); if ((unsigned) tfd.core_clause_mask.size() != dm.pruned_clauses.size()) { throw SolverException(mstream() << "error while computing core_clause_mask: wrong number of clauses: " << tfd.core_clause_mask.size() << " vs " << tfd.n_clauses); } tfd.core_var_mask = ArrayXb::Constant(tfd.n_vars, false); for (unsigned c_idx = 0; c_idx < dm.pruned_clauses.size(); ++c_idx) { if (tfd.core_clause_mask[c_idx]) { z3::expr const & clause = dm.pruned_clauses[c_idx]; for (unsigned arg_idx = 0; arg_idx < clause.num_args(); ++arg_idx) { tfd.core_var_mask[dm.free_expr_to_lit(clause.arg(arg_idx)).var().idx()] = true; } } } return tfd; } vector<z3::expr> get_pruned_clauses() const { z3::expr_vector zclauses = z().assertions(); vector<z3::expr> clauses; for (unsigned c_idx = 0; c_idx < zclauses.size(); ++c_idx) { if (zclauses[c_idx].is_or()) { clauses.push_back(zclauses[c_idx]); } } return clauses; } Solver clauses_to_solver(Context & ctx, vector<z3::expr> const & clauses, unsigned n_takes) const { if (n_takes > clauses.size()) { throw SolverException("n_takes too high"); } Solver s(ctx, _opts); for (unsigned i = 0; i < n_takes; ++i) { s.add(Expr(clauses[i])); } return s; } vector<TFData> get_more_cores(Context & ctx, unsigned max_tries, float percent_to_keep) const { // Current solver must be in UNKNOWN state, but must have been determined to be UNSAT vector<z3::expr> clauses = get_pruned_clauses(); std::srand(unsigned(std::time(0))); std::random_shuffle(clauses.begin(), clauses.end()); vector<TFData> results; unsigned n_take = clauses.size(); for (unsigned core_idx = 0; core_idx < max_tries; ++core_idx) { n_take = floor(n_take * percent_to_keep); Solver s = clauses_to_solver(ctx, clauses, n_take); Status status = s.check(); if (status == Status::UNSAT) { Solver s_unsat = clauses_to_solver(ctx, clauses, n_take); if (s_unsat.propagate() == Status::UNKNOWN) { results.push_back(s_unsat.to_tf_data_with_core()); } } else { break; } } return results; } private: static unordered_map<unsigned, unsigned> build_name_map_from_dimacs(string const & filename) { unordered_map<unsigned, unsigned> m; std::ifstream file(filename); string line; while (std::getline(file, line)) { std::istringstream iss(line); string result; if (std::getline(iss, result, ' ')) { if (result != "c") continue; std::getline(iss, result, ' '); unsigned dimacs_var = stoi(result); std::getline(iss, result, '\n'); string z3_var_name = result; if (z3_var_name.substr(0, 2) != "k!") { throw SolverException(mstream() << "found variable without k!<int> name: " << z3_var_name); } m.insert({stoi(z3_var_name.substr(2)), dimacs_var}); } } return m; } vector<vector<unsigned>> pruned_clauses_rename_to_dimacs_vars(vector<z3::expr> const & pruned_clauses, unordered_map<unsigned, unsigned> const & name_map) const { vector<vector<unsigned>> vs; for (z3::expr const & clause : pruned_clauses) { if (clause.num_args() < 2) { throw SolverException(mstream() << "or-clause with 1 argument:" << clause); } vs.emplace_back(); for (unsigned arg_idx = 0; arg_idx < clause.num_args(); ++arg_idx) { z3::expr e = clause.arg(arg_idx); bool neg = e.is_not(); e = neg ? e.arg(0) : e; if (!e.is_const()) { throw SolverException(mstream() << "expected constant: " << e); } unsigned var = name_map.at(e.decl().name().to_int()); unsigned lit = neg ? (var + total_n_vars()) : var; vs.back().push_back(lit); } std::sort(vs.back().begin(), vs.back().end()); } return vs; } vector<vector<unsigned>> clauses_prune_to_dimacs_vars(z3::expr_vector const & clauses) const { vector<vector<unsigned>> vs; for (unsigned c_idx = 0; c_idx < clauses.size(); ++c_idx) { z3::expr clause = clauses[c_idx]; if (clause.is_or()) { if (clause.num_args() < 2) { throw SolverException(mstream() << "or-clause with 1 argument: " << clause); } vs.emplace_back(); // prune the clauses for (unsigned arg_idx = 0; arg_idx < clause.num_args(); ++arg_idx) { z3::expr e = clause.arg(arg_idx); bool neg = e.is_not(); e = neg ? e.arg(0) : e; if (!e.is_const()) { throw SolverException(mstream() << "expected constant: " << e); } unsigned var = e.decl().name().to_int(); unsigned lit = neg ? (var + total_n_vars()) : var; vs.back().push_back(lit); } std::sort(vs.back().begin(), vs.back().end()); } } return vs; } string build_z3_drat_cmd(string const & drat_name, string const & dimacs_name) const { int buffer_size = 1000; char buffer[buffer_size]; int cx = snprintf(buffer, buffer_size, "z3 -T:%u sat.max_conflicts=%u sat.restart.max=%u sat.variable_decay=%u sat.override_incremental=%s sat.acce=%s sat.lookahead_simplify=%s sat.drat.file=%s %s >> %s", (_opts.z3_replay_timeout_scale * _opts.timeout_ms) / 1000, _opts.max_conflicts, _opts.restart_max, _opts.variable_decay, _opts.override_incremental ? "true" : "false", _opts.acce ? "true" : "false", _opts.lookahead_simplify ? "true" : "false", drat_name.c_str(), dimacs_name.c_str(), _opts.logfilename.c_str()); if (cx >= 0 && cx < buffer_size) { return string(buffer); } else { throw SolverException("z3 command too big for buffer!"); } } string build_drat_trim_cmd(string const & dimacs_name, string const & drat_name, string const & core_name) const { int buffer_size = 1000; char buffer[buffer_size]; int cx = snprintf(buffer, buffer_size, "drat-trim %s %s -c %s -t %u >> %s", dimacs_name.c_str(), drat_name.c_str(), core_name.c_str(), (_opts.drat_trim_timeout_scale * _opts.timeout_ms) / 1000, _opts.logfilename.c_str()); if (cx >= 0 && cx < buffer_size) { return string(buffer); } else { throw SolverException("drat-trim command too big for buffer!"); } } public: ArrayXb compute_core_clause_mask(vector<z3::expr> const & pruned_clauses) const { string prefix = std::tmpnam(nullptr); string dimacs_name = prefix + ".dimacs"; string drat_name = prefix + ".drat"; string core_name = prefix + ".core.dimacs"; std::ofstream dimacs_out(dimacs_name, std::ios_base::out); dimacs_out << z().dimacs(); dimacs_out.close(); string debug_rm_cmd = string("rm -f ") + drat_name + " " + core_name; string rm_cmd = string("rm -f ") + drat_name + " " + core_name + " " + dimacs_name; string z3_cmd = build_z3_drat_cmd(drat_name, dimacs_name); std::ofstream flog(_opts.logfilename, std::ios_base::app); flog << "Executing '" << z3_cmd << "'..." << std::endl; system_throw(z3_cmd, debug_rm_cmd); check_exists_and_nonempty(drat_name); string drat_trim_cmd = build_drat_trim_cmd(dimacs_name, drat_name, core_name); flog << "Executing '" << drat_trim_cmd << "'..." << std::endl; flog.close(); system_throw(drat_trim_cmd, debug_rm_cmd); check_exists_and_nonempty(core_name); z3::solver s_core(z().ctx(), "QF_FD"); s_core.from_file(core_name.c_str()); z3::expr_vector clauses_core = s_core.assertions(); unordered_map<unsigned, unsigned> name_map = build_name_map_from_dimacs(dimacs_name); vector<vector<unsigned>> oclauses = pruned_clauses_rename_to_dimacs_vars(pruned_clauses, name_map); // old vector<vector<unsigned>> nclauses = clauses_prune_to_dimacs_vars(clauses_core); // new // oclauses_permutation[k] is the index in the original oclauses of sorted oclauses[k]. vector<unsigned> oclauses_permutation; for (unsigned i = 0 ; i < oclauses.size(); ++i) { oclauses_permutation.push_back(i); } std::sort(oclauses_permutation.begin(), oclauses_permutation.end(), [&](const unsigned & i1, const unsigned & i2) { return (oclauses[i1] < oclauses[i2]); }); std::sort(oclauses.begin(), oclauses.end()); std::sort(nclauses.begin(), nclauses.end()); // construct core_clause_mask ArrayXb core_clause_mask = ArrayXb::Constant(oclauses.size(), false); unsigned o_idx = 0; // old_idx for (unsigned n_idx = 0; n_idx < nclauses.size(); ++n_idx) { while (oclauses[o_idx] != nclauses[n_idx]) { o_idx++; if (o_idx >= oclauses.size()) { throw SolverException(mstream() << "core clause not present in original clauses"); } } assert(oclauses[o_idx] == nclauses[n_idx]); core_clause_mask[oclauses_permutation[o_idx]] = true; } system_throw(rm_cmd, "echo 'no finally'"); return core_clause_mask; } private: vector<z3::expr> collect_pruned_clauses() const { // Warning: slow z3::expr_vector clauses = z().assertions(); vector<z3::expr> pruned_clauses; for (unsigned c_idx = 0; c_idx < clauses.size(); ++c_idx) { z3::expr const & clause = clauses[c_idx]; if (clause.is_or()) { if (clause.num_args() < 2) { throw SolverException(mstream() << "cleaned clause has singleton or: " << clause); } pruned_clauses.push_back(clause); } } return pruned_clauses; } public: void set_activity_scores(Eigen::ArrayXf const & pi, unsigned pi_scale) { z3::expr_vector non_units = z().non_units(); for (unsigned i = 0; i < non_units.size(); ++i) { double act = pi_scale * pi[i]; z().set_activity(non_units[i], act); } } }; Solver deserialize(Context & ctx, Options const & opts, string const & serial) { Solver s(ctx, opts); s.from_string(serial); return s; } TFDataManager::TFDataManager(Solver const & s): non_units(s.z().non_units()) { for (unsigned i = 0; i < non_units.size(); ++i) { _non_unit_to_var.insert({non_units[i], Var(i)}); } pruned_clauses = s.get_pruned_clauses(); for (z3::expr const & clause : pruned_clauses) { n_cells += clause.num_args(); } } // Pybind11 #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <pybind11/eigen.h> namespace py = pybind11; PYBIND11_MODULE(solver, m) { py::register_exception<SolverException>(m, "SolverException"); py::class_<Var>(m, "Var") .def(py::init<unsigned>(), py::arg("idx")) .def("idx", &Var::idx) .def("__str__", &Var::repr) .def("__repr__", &Var::repr) .def("__eq__", &Var::operator==) .def("__lt__", &Var::operator<) .def("__hash__", &Var::hash) .def(py::pickle([](const Var & var) { return var.idx(); }, [](unsigned idx) { return Var(idx); })); py::class_<Lit>(m, "Lit") .def(py::init<Var, bool>(), py::arg("var"), py::arg("sign")) .def("var", &Lit::var) .def("neg", &Lit::neg) .def("vidx", &Lit::vidx) .def("flip", &Lit::flip) .def("__str__", &Lit::repr) .def("__repr__", &Lit::repr) .def("__eq__", &Lit::operator==) .def("__lt__", &Lit::operator<) .def("__hash__", &Lit::hash) .def(py::pickle([](const Lit & lit) { return py::make_tuple(lit.var().idx(), lit.neg()); }, [](py::tuple t) { return Lit(Var(t[0].cast<unsigned>()), t[1].cast<bool>()); })); py::class_<Options>(m, "Options") .def(py::init<>()) .def_readwrite("timeout_ms", &Options::timeout_ms) .def_readwrite("max_conflicts", &Options::max_conflicts) .def_readwrite("restart_max", &Options::restart_max) .def_readwrite("variable_decay", &Options::variable_decay) .def_readwrite("override_incremental", &Options::override_incremental) .def_readwrite("lookahead_simplify", &Options::lookahead_simplify) .def_readwrite("acce", &Options::acce) .def_readwrite("z3_replay_timeout_scale", &Options::z3_replay_timeout_scale) .def_readwrite("drat_trim_timeout_scale", &Options::drat_trim_timeout_scale) .def_readwrite("logfilename", &Options::logfilename); py::class_<Context>(m, "Context") .def(py::init<>()); py::class_<Expr>(m, "Expr") .def("flip", &Expr::flip) .def("var", &Expr::var) .def("is_neg", &Expr::is_neg) .def("ilit", &Expr::ilit); // TODO(dselsam): make all caps to be consistent py::enum_<Status>(m, "Status") .value("UNKNOWN", Status::UNKNOWN) .value("UNSAT", Status::UNSAT) .value("SAT", Status::SAT); py::enum_<Assignment>(m, "Assignment") .value("POS", Assignment::POS) .value("NEG", Assignment::NEG) .value("SKIP", Assignment::SKIP); py::class_<TFData>(m, "TFData") .def_readonly("n_vars", &TFData::n_vars) .def_readonly("n_clauses", &TFData::n_clauses) .def_readonly("CL_idxs", &TFData::CL_idxs) .def_readonly("core_var_mask", &TFData::core_var_mask) .def_readonly("core_clause_mask", &TFData::core_clause_mask); py::class_<Solver>(m, "Solver") .def(py::init<Context &, Options const & >(), py::arg("ctx"), py::arg("opts"), py::keep_alive<1, 2>(), py::call_guard<py::gil_scoped_release>()) .def("clone", &Solver::clone, py::arg("ctx"), py::keep_alive<0, 2>(), py::call_guard<py::gil_scoped_release>()) .def("from_string", &Solver::from_string, py::arg("s"), py::call_guard<py::gil_scoped_release>()) .def("from_file", &Solver::from_file, py::arg("filename"), py::call_guard<py::gil_scoped_release>()) .def("serialize", &Solver::serialize, py::call_guard<py::gil_scoped_release>()) .def("dimacs", &Solver::dimacs, py::call_guard<py::gil_scoped_release>()) .def("add", &Solver::add, py::arg("expr")) .def("get_free_var", &Solver::get_free_var, py::arg("v_idx")) .def("propagate", &Solver::propagate, py::call_guard<py::gil_scoped_release>()) .def("check", &Solver::check, py::call_guard<py::gil_scoped_release>()) .def("check_with_timeout_ms", &Solver::check_with_timeout_ms, py::arg("timeout_ms"), py::call_guard<py::gil_scoped_release>()) .def("set_activity_scores", &Solver::set_activity_scores, py::arg("pi"), py::arg("pi_scale"), py::call_guard<py::gil_scoped_release>()) .def("cube", &Solver::cube, py::call_guard<py::gil_scoped_release>()) .def("to_tf_data", &Solver::to_tf_data, py::call_guard<py::gil_scoped_release>()) .def("to_tf_data_with_core", &Solver::to_tf_data_with_core, py::call_guard<py::gil_scoped_release>()) .def("get_more_cores", &Solver::get_more_cores, py::arg("ctx"), py::arg("max_tries"), py::arg("percent_to_keep"), py::call_guard<py::gil_scoped_release>()); m.def("deserialize", &deserialize, py::arg("ctx"), py::arg("opts"), py::arg("serial"), py::keep_alive<0, 1>(), py::call_guard<py::gil_scoped_release>()); }
/************************************************************* * > File Name : P4525.cpp * > Author : Tony * > Created Time : 2019/06/02 12:29:38 * > Algorithm : [Math]SimpsonIntegral **************************************************************/ #include <bits/stdc++.h> using namespace std; double a, b, c, d, l, r; inline double f(double x) { return (c * x + d) / (a * x + b); } inline double simpson(double l, double r) { double mid = (l + r) / 2; return (f(l) + 4 * f(mid) + f(r)) * (r - l) / 6; } double asr(double l, double r, double eps, double ans) { double mid = (l + r) / 2; double L = simpson(l, mid), R = simpson(mid, r); if (fabs(L + R - ans) <= 15 * eps) return L + R + (L + R - ans) / 15; return asr(l, mid, eps / 2, L) + asr(mid, r, eps / 2, R); } double integral(double l, double r, double eps) { return asr(l, r, eps, simpson(l, r)); } int main() { scanf("%lf%lf%lf%lf%lf%lf", &a, &b, &c, &d, &l, &r); printf("%.6lf\n", integral(l, r, 1e-6)); return 0; }
#include<bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; while(t--){ string s; cin >> s; int n = s.size(); if(s[n-2] == 'p' && s[n-1] == 'o') { cout << "FILIPINO" << endl; } else if(s[n-4] == 'm' && s[n-3] == 'a' && s[n-2] == 's' && s[n-1] == 'u'){ cout << "JAPANESE" << endl; } else if(s[n-4] == 'd' && s[n-3] == 'e' && s[n-2] == 's' && s[n-1] == 'u'){ cout << "JAPANESE" << endl; } else { cout << "KOREAN" << endl; } } return 0; }
#include <iostream> #include <stdlib.h> #include <string> #include <fstream> #include <map> #include <list> #include <sstream> #include <vector> #include "map_list.hpp" #include "map_signals.hpp" #include "component.hpp" #include "wire.hpp" # define TRUE 1 # define FALSE 0 #define CONSERVATIVE FALSE #define PRECISE TRUE class netlist_graph { private: //std::string cell_inst_name,cell_type_name,wire_name; bool default_model; map_signals input_to_dut,output_from_dut, signals_in_dut; map_signals input_to_dut_t,output_from_dut_t, signals_in_dut_t; std::map<std::string,AndGate*> cell_type_and; std::map<std::string,OrGate*> cell_type_or; std::map<std::string,NotGate*> cell_type_not; inst_wire cell_wires,cell_instances_input,cell_instances_output; bool input, output; public: netlist_graph(); //bool get_default_model(); void insert_data_input_to_dut(std::string ip_op_arr , bool val); void insert_data_output_from_dut(std::string ip_op_arr , bool val); void insert_data_input_to_dut_t(std::string ip_op_arr , bool val); void insert_data_output_from_dut_t(std::string ip_op_arr , bool val); void insert_and(std::string cell_inst_name); void insert_not(std::string cell_inst_name); void insert_or(std::string cell_inst_name); void insert_into_GATE(std::string cell_type_name, std::string cell_inst_name); void cell_wires_insert_data(std::string cell_inst_name, std::string wire_name); void ip_op_indicate(std::string cell_type_name,int word_count); bool get_bool_input(); bool get_bool_output(); void cell_instances_input_insert_data(std::string wire_name , std::string cell_inst_name); void cell_instances_output_insert_data(std::string wire_name,std::string cell_inst_name); std::pair<bool,std::list<std::string>> cell_instances_output_get_dat (std::string wire_name); void signals_in_dut_insert_data(std::string wire_name,bool val); void signals_in_dut_t_insert_data(std::string wire_name,bool val); void insert_input_Wire_GATE(std::string cell_type_name,std::string cell_inst_name,std::string wire_name); void insert_output_Wire_GATE(std::string cell_type_name,std::string cell_inst_name,std::string wire_name); void incr_and_set_ip_to_dut_val(std::string line,bool); void set_input_to_dut_begin(); void set_model_ALL_GATES(bool val); int get_number_of_inputs(); void build_graph(std::list<std::string>inst_with_nonDefault_model); std::vector<Wire*> get_op_wire_of_GATE(std::string curr_inst); std::vector<std::list<std::string>> propagate_thru_graph(); void print_datas(); void clear_map_signals_bool(); };
#include<bits/stdc++.h> using namespace std; vector<int> FindNumbersWithSum(vector<int> array,int sum) { int n = array.size(); vector<int> res(2,0); vector<int> nu; int resmin = INT_MAX,flag = 0; for(int i = 0; i < n; i++) { for(int j = i+1; j < n; j++) { if(array[j] == sum - array[i]) { if(resmin > array[i]*array[j]) { resmin = array[i]*array[j]; res[0] = array[i]; res[1] = array[j]; flag = 1; } } } } if(flag == 1) return res; else return nu; } int main() { int n; cin >> n; while (n--) { int s,m,t; vector<int> array; cin >> t >> s; for(int i = 0; i < t; i++) { cin >> m; array.push_back(m); } vector<int> res = FindNumbersWithSum(array,s); for(int i = 0; i < res.size(); i++) cout << res[i] << " "; cout << endl; } return 0; }
// // // gamma and related functions from Cephes library // see: http://www.netlib.org/cephes // // Copyright 1985, 1987, 2000 by Stephen L. Moshier // // #include "SpecFuncCephes.h" //#include "math.h" #include <cmath> #include <limits> //#include <stdlib.h> //namespace ROOT { //namespace Math { //namespace Cephes { static double kBig = 4.503599627370496e15; static double kBiginv = 2.22044604925031308085e-16; /* log( sqrt( 2*pi ) ) */ static double LS2PI = 0.91893853320467274178; // incomplete gamma function (complement integral) // igamc(a,x) = 1 - igam(a,x) // // inf. // - // 1 | | -t a-1 // = ----- | e t dt. // - | | // | (a) - // x // // // In this implementation both arguments must be positive. // The integral is evaluated by either a power series or // continued fraction expansion, depending on the relative // values of a and x. double igamc( double a, double x ) { double ans, ax, c, yc, r, t, y, z; double pk, pkm1, pkm2, qk, qkm1, qkm2; // LM: for negative values returns 0.0 // This is correct if a is a negative integer since Gamma(-n) = +/- inf if (a <= 0) return 0.0; if (x <= 0) return 1.0; if( (x < 1.0) || (x < a) ) return( 1.0 - igam(a,x) ); ax = a * std::log(x) - x - lgamma(a); if( ax < -kMAXLOG ) return( 0.0 ); ax = std::exp(ax); /* continued fraction */ y = 1.0 - a; z = x + y + 1.0; c = 0.0; pkm2 = 1.0; qkm2 = x; pkm1 = x + 1.0; qkm1 = z * x; ans = pkm1/qkm1; do { c += 1.0; y += 1.0; z += 2.0; yc = y * c; pk = pkm1 * z - pkm2 * yc; qk = qkm1 * z - qkm2 * yc; if(qk) { r = pk/qk; t = std::abs( (ans - r)/r ); ans = r; } else t = 1.0; pkm2 = pkm1; pkm1 = pk; qkm2 = qkm1; qkm1 = qk; if( std::abs(pk) > kBig ) { pkm2 *= kBiginv; pkm1 *= kBiginv; qkm2 *= kBiginv; qkm1 *= kBiginv; } } while( t > kMACHEP ); return( ans * ax ); } /* left tail of incomplete gamma function: * * inf. k * a -x - x * x e > ---------- * - - * k=0 | (a+k+1) * */ double igam( double a, double x ) { double ans, ax, c, r; // LM: for negative values returns 1.0 instead of zero // This is correct if a is a negative integer since Gamma(-n) = +/- inf if (a <= 0) return 1.0; if (x <= 0) return 0.0; if( (x > 1.0) && (x > a ) ) return( 1.0 - igamc(a,x) ); /* Compute x**a * exp(-x) / gamma(a) */ ax = a * std::log(x) - x - lgamma(a); if( ax < -kMAXLOG ) return( 0.0 ); ax = std::exp(ax); /* power series */ r = a; c = 1.0; ans = 1.0; do { r += 1.0; c *= x/r; ans += c; } while( c/ans > kMACHEP ); return( ans * ax/a ); } /*---------------------------------------------------------------------------*/ /* Logarithm of gamma function */ /* A[]: Stirling's formula expansion of log gamma * B[], C[]: log gamma function between 2 and 3 */ static double A[] = { 8.11614167470508450300E-4, -5.95061904284301438324E-4, 7.93650340457716943945E-4, -2.77777777730099687205E-3, 8.33333333333331927722E-2 }; static double B[] = { -1.37825152569120859100E3, -3.88016315134637840924E4, -3.31612992738871184744E5, -1.16237097492762307383E6, -1.72173700820839662146E6, -8.53555664245765465627E5 }; static double C[] = { /* 1.00000000000000000000E0, */ -3.51815701436523470549E2, -1.70642106651881159223E4, -2.20528590553854454839E5, -1.13933444367982507207E6, -2.53252307177582951285E6, -2.01889141433532773231E6 }; double lgam( double x ) { double p, q, u, w, z; int i; int sgngam = 1; if (x >= std::numeric_limits<double>::infinity()) return(std::numeric_limits<double>::infinity()); if( x < -34.0 ) { q = -x; w = lgam(q); p = std::floor(q); if( p==q )//_unur_FP_same(p,q) return (std::numeric_limits<double>::infinity()); i = (int) p; if( (i & 1) == 0 ) sgngam = -1; else sgngam = 1; z = q - p; if( z > 0.5 ) { p += 1.0; z = p - q; } z = q * std::sin( M_PI * z ); if( z == 0 ) return (std::numeric_limits<double>::infinity()); /* z = log(ROOT::Math::Pi()) - log( z ) - w;*/ z = std::log(M_PI) - std::log( z ) - w; return( z ); } if( x < 13.0 ) { z = 1.0; p = 0.0; u = x; while( u >= 3.0 ) { p -= 1.0; u = x + p; z *= u; } while( u < 2.0 ) { if( u == 0 ) return (std::numeric_limits<double>::infinity()); z /= u; p += 1.0; u = x + p; } if( z < 0.0 ) { sgngam = -1; z = -z; } else sgngam = 1; if( u == 2.0 ) return( std::log(z) ); p -= 2.0; x = x + p; p = x * Polynomialeval(x, B, 5 ) / Polynomial1eval( x, C, 6); return( std::log(z) + p ); } if( x > kMAXLGM ) return( sgngam * std::numeric_limits<double>::infinity() ); q = ( x - 0.5 ) * std::log(x) - x + LS2PI; if( x > 1.0e8 ) return( q ); p = 1.0/(x*x); if( x >= 1000.0 ) q += (( 7.9365079365079365079365e-4 * p - 2.7777777777777777777778e-3) *p + 0.0833333333333333333333) / x; else q += Polynomialeval( p, A, 4 ) / x; return( q ); } /*---------------------------------------------------------------------------*/ static double P[] = { 1.60119522476751861407E-4, 1.19135147006586384913E-3, 1.04213797561761569935E-2, 4.76367800457137231464E-2, 2.07448227648435975150E-1, 4.94214826801497100753E-1, 9.99999999999999996796E-1 }; static double Q[] = { -2.31581873324120129819E-5, 5.39605580493303397842E-4, -4.45641913851797240494E-3, 1.18139785222060435552E-2, 3.58236398605498653373E-2, -2.34591795718243348568E-1, 7.14304917030273074085E-2, 1.00000000000000000320E0 }; /* Stirling's formula for the gamma function */ static double STIR[5] = { 7.87311395793093628397E-4, -2.29549961613378126380E-4, -2.68132617805781232825E-3, 3.47222221605458667310E-3, 8.33333333333482257126E-2, }; #define SQTPI std::sqrt(2*M_PI) /* sqrt(2*pi) */ /* Stirling formula for the gamma function */ static double stirf( double x) { double y, w, v; w = 1.0/x; w = 1.0 + w * Polynomialeval( w, STIR, 4 ); y = exp(x); /* #define kMAXSTIR kMAXLOG/log(kMAXLOG) */ if( x > kMAXSTIR ) { /* Avoid overflow in pow() */ v = pow( x, 0.5 * x - 0.25 ); y = v * (v / y); } else { y = pow( x, x - 0.5 ) / y; } y = SQTPI * y * w; return( y ); } double gamma( double x ) { double p, q, z; int i; int sgngam = 1; if (x >=std::numeric_limits<double>::infinity()) return(x); q = std::abs(x); if( q > 33.0 ) { if( x < 0.0 ) { p = std::floor(q); if( p == q ) { return( sgngam * std::numeric_limits<double>::infinity()); } i = (int) p; if( (i & 1) == 0 ) sgngam = -1; z = q - p; if( z > 0.5 ) { p += 1.0; z = q - p; } z = q * std::sin( M_PI * z ); if( z == 0 ) { return( sgngam * std::numeric_limits<double>::infinity()); } z = std::abs(z); z = M_PI/(z * stirf(q) ); } else { z = stirf(x); } return( sgngam * z ); } z = 1.0; while( x >= 3.0 ) { x -= 1.0; z *= x; } while( x < 0.0 ) { if( x > -1.E-9 ) goto small; z /= x; x += 1.0; } while( x < 2.0 ) { if( x < 1.e-9 ) goto small; z /= x; x += 1.0; } if( x == 2.0 ) return(z); x -= 2.0; p = Polynomialeval( x, P, 6 ); q = Polynomialeval( x, Q, 7 ); return( z * p / q ); small: if( x == 0 ) return( std::numeric_limits<double>::infinity() ); else return( z/((1.0 + 0.5772156649015329 * x) * x) ); } /*---------------------------------------------------------------------------*/ //#define kMAXLGM 2.556348e305 /*---------------------------------------------------------------------------*/ /* implementation based on cephes log gamma */ double beta(double z, double w) { return std::exp(lgam(z) + lgam(w)- lgam(z+w) ); } /*---------------------------------------------------------------------------*/ /* inplementation of the incomplete beta function */ /** * DESCRIPTION: * * Returns incomplete beta integral of the arguments, evaluated * from zero to x. The function is defined as * * x * - - * | (a+b) | | a-1 b-1 * ----------- | t (1-t) dt. * - - | | * | (a) | (b) - * 0 * * The domain of definition is 0 <= x <= 1. In this * implementation a and b are restricted to positive values. * The integral from x to 1 may be obtained by the symmetry * relation * * 1 - incbet( a, b, x ) = incbet( b, a, 1-x ). * * The integral is evaluated by a continued fraction expansion * or, when b*x is small, by a power series. * * ACCURACY: * * Tested at uniformly distributed random points (a,b,x) with a and b * in "domain" and x between 0 and 1. * Relative error * arithmetic domain # trials peak rms * IEEE 0,5 10000 6.9e-15 4.5e-16 * IEEE 0,85 250000 2.2e-13 1.7e-14 * IEEE 0,1000 30000 5.3e-12 6.3e-13 * IEEE 0,10000 250000 9.3e-11 7.1e-12 * IEEE 0,100000 10000 8.7e-10 4.8e-11 * Outputs smaller than the IEEE gradual underflow threshold * were excluded from these statistics. * * ERROR MESSAGES: * message condition value returned * incbet domain x<0, x>1 0.0 * incbet underflow 0.0 * * Cephes Math Library, Release 2.8: June, 2000 * Copyright 1984, 1995, 2000 by Stephen L. Moshier */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /* for evaluation of error function */ /*---------------------------------------------------------------------------*/ static double erfP[] = { 2.46196981473530512524E-10, 5.64189564831068821977E-1, 7.46321056442269912687E0, 4.86371970985681366614E1, 1.96520832956077098242E2, 5.26445194995477358631E2, 9.34528527171957607540E2, 1.02755188689515710272E3, 5.57535335369399327526E2 }; static double erfQ[] = { /* 1.00000000000000000000E0,*/ 1.32281951154744992508E1, 8.67072140885989742329E1, 3.54937778887819891062E2, 9.75708501743205489753E2, 1.82390916687909736289E3, 2.24633760818710981792E3, 1.65666309194161350182E3, 5.57535340817727675546E2 }; static double erfR[] = { 5.64189583547755073984E-1, 1.27536670759978104416E0, 5.01905042251180477414E0, 6.16021097993053585195E0, 7.40974269950448939160E0, 2.97886665372100240670E0 }; static double erfS[] = { /* 1.00000000000000000000E0,*/ 2.26052863220117276590E0, 9.39603524938001434673E0, 1.20489539808096656605E1, 1.70814450747565897222E1, 9.60896809063285878198E0, 3.36907645100081516050E0 }; static double erfT[] = { 9.60497373987051638749E0, 9.00260197203842689217E1, 2.23200534594684319226E3, 7.00332514112805075473E3, 5.55923013010394962768E4 }; static double erfU[] = { /* 1.00000000000000000000E0,*/ 3.35617141647503099647E1, 5.21357949780152679795E2, 4.59432382970980127987E3, 2.26290000613890934246E4, 4.92673942608635921086E4 }; /*---------------------------------------------------------------------------*/ /* complementary error function */ /* For small x, erfc(x) = 1 - erf(x); otherwise rational */ /* approximations are computed. */ /*double erfc( double a ) { double p,q,x,y,z; if( a < 0.0 ) x = -a; else x = a; if( x < 1.0 ) return( 1.0 - erf(a) ); z = -a * a; if( z < -kMAXLOG ) { under: if( a < 0 ) return( 2.0 ); else return( 0.0 ); } z = exp(z); if( x < 8.0 ) { p = Polynomialeval( x, erfP, 8 ); q = Polynomial1eval( x, erfQ, 8 ); } else { p = Polynomialeval( x, erfR, 5 ); q = Polynomial1eval( x, erfS, 6 ); } y = (z * p)/q; if( a < 0 ) y = 2.0 - y; if( y == 0 ) goto under; return(y); } /*---------------------------------------------------------------------------*/ /* error function */ /* For 0 <= |x| < 1, erf(x) = x * P4(x**2)/Q5(x**2); otherwise */ /* erf(x) = 1 - erfc(x). */ /*double erf( double x) { double y, z; if( std::abs(x) > 1.0 ) return( 1.0 - ROOT::Math::Cephes::erfc(x) ); z = x * x; y = x * Polynomialeval( z, erfT, 4 ) / Polynomial1eval( z, erfU, 5 ); return( y ); }*/ //} // end namespace Cephes /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /* Routines used within this implementation */ /* * calculates a value of a polynomial of the form: * a[0]x^N+a[1]x^(N-1) + ... + a[N] */ double Polynomialeval(double x, double* a, unsigned int N) { if (N==0) return a[0]; else { double pom = a[0]; for (unsigned int i=1; i <= N; i++) pom = pom *x + a[i]; return pom; } } /* * calculates a value of a polynomial of the form: * x^N+a[0]x^(N-1) + ... + a[N-1] */ double Polynomial1eval(double x, double* a, unsigned int N) { if (N==0) return a[0]; else { double pom = x + a[0]; for (unsigned int i=1; i < N; i++) pom = pom *x + a[i]; return pom; } } //} // end namespace Math //} // end namespace ROOT
#pragma once #include "Elevator.h" #include <fstream> #define RUN Scheduling::getInstance() class Scheduling { public: static Scheduling* getInstance(); void assignment(); // 进行乘客分配 void execute(); // 执行分配的结果 Indicator schedulingMaking(const Elevator*); // 进行电梯调度 void clear(); void clearElevator(); void clearPassenger(); void addElevator(Elevator*); // 添加电梯 void addPassenger(Passenger*); // 添加乘客 bool allArrived() const; // 是否完成调度 int getArrivalNumber() const; int getPassengerNumber() const; void outputPosition(std::ofstream&); static int timer; private: Scheduling() { }; static Scheduling* instance; std::vector<Elevator*> elevators; // 电梯们 std::vector<Passenger*> passengers; // 待处理的乘客们 std::vector<Passenger*> arrivals; // 已到达的乘客们; }; static int initialTarget = 0; static int terminalTarget = 0; static bool assignmentPriority(const Elevator*, const Elevator*);
#pragma once #include <vector> #include <iostream> /*! * \brief The Interpolation class * stores the polynomial interpolation methods * \author Łukasz Dyraga * \version 1.0 */ class Interpolation//Lagrange { public: Interpolation(); double calculate(const double &arg, const std::vector<double> &valueX, const std::vector<double> &valueY)const; ~Interpolation(); };
#include<stdio.h> #include<iostream> #include<vector> #include<list> class Global_Clock { int counter; }; class JobGen_PJS : public Job { public: JobGen_PJS() : Job(){} }; class Node_PJS { }; class CCU_Node { int memory_usage; }; class PJS_Node { }; class CCU_PJS { }; class communication : Global_Clock, public JobGen_PJS, Node_PJS, CCU_Node, PJS_Node, CCU_PJS { public: communication() {} };
#include<bits/stdc++.h> #define mod 998244353 using namespace std; int main() { int n,a,k; cin>>n>>k; vector<int>v,v1; unordered_map<int,int>mp; long long sum=0; for(int i=0;i<n;i++) { cin>>a; v.push_back(a); mp[a]=i+1; } long long ans=1; sort(v.rbegin(),v.rend()); for(int i=0;i<k;i++) { sum+=v[i]; v1.push_back(mp[v[i]]); } sort(v1.begin(),v1.end()); for(int i=1;i<v1.size();i++){ ans*=(v1[i]-v1[i-1]); ans=ans%mod; } cout<<sum<<" "<<ans%mod<<'\n'; }
#ifndef TETRA_MESH_HELPER_H #define TETRA_MESH_HELPER_H #include "MeshHash.h" #include <max.h> #include <vector> #include <iostream> //------------------------------------------------------------------------------------ struct TetraMeshTriangle { public: void init() { vertexNr[0] = -1; vertexNr[1] = -1; vertexNr[2] = -1; } void set(int v0, int v1, int v2, int mat) { vertexNr[0] = v0; vertexNr[1] = v1; vertexNr[2] = v2; } bool containsVertexNr(int vNr) const { return vNr == vertexNr[0] || vNr == vertexNr[1] || vNr == vertexNr[2]; } // representation int vertexNr[3]; }; //------------------------------------------------------------------------------------ struct MeshTetraLink { int tetraNr; NxVec3 barycentricCoords; }; class TetraMeshHelper { public: TetraMeshHelper(); // to attach to tetra mesh void buildTetraLinks(const NxSoftBodyMeshDesc& mesh); void clear(); void transform(const NxMat34 &a); void getBounds(NxBounds3 &bounds) const { bounds = mBounds; } void setMesh(const Mesh& pMax); Mesh& getMesh() { return maxMesh; } void updateBounds(); bool updateTetraLinks(const NxMeshData &tetraMeshData); private: NxVec3 computeBaryCoords(NxVec3 vertex, NxVec3 p0, NxVec3 p1, NxVec3 p2, NxVec3 p3); std::vector<MeshTetraLink> mTetraLinks; NxBounds3 mBounds; Mesh maxMesh; }; #endif
/* To Include in the Description.ext: #include "Sounds\_Sounds.hpp" */ tracks[] = {}; class emp_phase { name = "EMP_Phase_M"; sound[] = {"saef_therift\Sounds\emp\emp_phase.ogg", 1, 1.0}; }; class emp_rift { name = "EMP_Rift_M"; sound[] = {"saef_therift\Sounds\emp\emp_rift.wss", 1, 1.0}; }; class emp_rift_ogg { name = "EMP_Rift_ogg_M"; sound[] = {"saef_therift\Sounds\emp\emp_rift.ogg", 1, 1.0}; }; class emp_boom { name = "EMP_Boom_M"; sound[] = {"saef_therift\Sounds\emp\emp_boom.ogg", 1, 1.0}; }; class RiftRadio_01 { name = "RiftRadio_01_M"; sound[] = {"saef_therift\Sounds\riftradio\RiftRadio_01.ogg", db + 0, 1.0}; }; class RiftRadio_02 { name = "RiftRadio_02_M"; sound[] = {"saef_therift\Sounds\riftradio\RiftRadio_02.ogg", db + 0, 1.0}; }; class RiftRadio_03 { name = "RiftRadio_03_M"; sound[] = {"saef_therift\Sounds\riftradio\RiftRadio_03.ogg", db + 0, 1.0}; }; class RiftRadio_04 { name = "RiftRadio_04_M"; sound[] = {"saef_therift\Sounds\riftradio\RiftRadio_04.ogg", db + 0, 1.0}; }; class RiftRadio_05 { name = "RiftRadio_05_M"; sound[] = {"saef_therift\Sounds\riftradio\RiftRadio_05.ogg", db + 0, 1.0}; }; class RiftRadio_06 { name = "RiftRadio_06_M"; sound[] = {"saef_therift\Sounds\riftradio\RiftRadio_06.ogg", db + 0, 1.0}; }; class RiftRadio_07 { name = "RiftRadio_07_M"; sound[] = {"saef_therift\Sounds\riftradio\RiftRadio_07.ogg", db + 0, 1.0}; }; class RiftRadio_08 { name = "RiftRadio_08_M"; sound[] = {"saef_therift\Sounds\riftradio\RiftRadio_08.ogg", db + 0, 1.0}; }; class RiftRadio_09 { name = "RiftRadio_09_M"; sound[] = {"saef_therift\Sounds\riftradio\RiftRadio_09.ogg", db + 0, 1.0}; }; class RiftRadio_10 { name = "RiftRadio_10_M"; sound[] = {"saef_therift\Sounds\riftradio\RiftRadio_10.ogg", db + 0, 1.0}; }; class RiftRadio_11 { name = "RiftRadio_11_M"; sound[] = {"saef_therift\Sounds\riftradio\RiftRadio_11.ogg", db + 0, 1.0}; }; class RiftRadio_12 { name = "RiftRadio_12_M"; sound[] = {"saef_therift\Sounds\riftradio\RiftRadio_12.ogg", db + 0, 1.0}; };
#ifndef DeviceSensor_h #define DeviceSensor_h #include "vector" #include "tuple" #include "../OneWire/OneWire.h" #include "../DallasTemperature/DallasTemperature.h" #include "Arduino.h" #include "../ArduinoJson/ArduinoJson.h" #include "SensorDatasheet.h" #include "SensorInDevice.h" // Data wire is plugged into port 0 #define ONE_WIRE_BUS 0 #define DEVICE_SENSOR_GET_FULL_BY_DEVICE_IN_APPLICATION_ID_RESPONSE_JSON_SIZE 4096 #define DEVICE_SENSOR_GET_FULL_BY_DEVICE_IN_APPLICATION_ID_TOPIC_PUB "DeviceSensor/GetFullByDeviceInApplicationIdIoT" #define DEVICE_SENSOR_GET_FULL_BY_DEVICE_IN_APPLICATION_ID_COMPLETED_TOPIC_SUB "DeviceSensor/GetFullByDeviceInApplicationIdCompletedIoT" #define DEVICE_SENSOR_SET_READ_INTERVAL_IN_MILLI_SECONDS_TOPIC_SUB "DeviceSensor/SetReadIntervalInMilliSecondsIoT" #define DEVICE_SENSOR_SET_PUBLISH_INTERVAL_IN_MILLI_SECONDS_TOPIC_SUB "DeviceSensor/SetPublishIntervalInMilliSecondsIoT" #define DEVICE_SENSOR_MESSAGE_TOPIC_PUB "DeviceSensor/MessageIoT" #define SENSOR_IN_DEVICE_SET_ORDINATION_TOPIC_SUB "SensorInDevice/SetOrdinationIoT" #define SENSOR_SET_LABEL_TOPIC_SUB "Sensor/SetLabelIoT" #define SENSOR_TEMP_DS_FAMILY_SET_RESOLUTION_TOPIC_SUB "SensorTempDSFamily/SetResolutionIoT" #define SENSOR_TRIGGER_INSERT_TOPIC_SUB "SensorTrigger/InsertIoT" #define SENSOR_TRIGGER_DELETE_TOPIC_SUB "SensorTrigger/DeleteIoT" #define SENSOR_TRIGGER_SET_TRIGGER_ON_TOPIC_SUB "SensorTrigger/SetTriggerOnIoT" #define SENSOR_TRIGGER_SET_BUZZER_ON_TOPIC_SUB "SensorTrigger/SetBuzzerOnIoT" #define SENSOR_TRIGGER_SET_TRIGGER_VALUE_TOPIC_SUB "SensorTrigger/SetTriggerValueIoT" #define SENSOR_UNIT_MEASUREMENT_SCALE_SET_DATASHEET_UNIT_MEASUREMENT_SCALE_TOPIC_SUB "SensorUnitMeasurementScale/SetDatasheetUnitMeasurementScaleIoT" #define SENSOR_UNIT_MEASUREMENT_SCALE_RANGE_SET_VALUE_TOPIC_SUB "SensorUnitMeasurementScale/SetRangeIoT" #define SENSOR_UNIT_MEASUREMENT_SCALE_CHART_LIMITER_SET_VALUE_TOPIC_SUB "SensorUnitMeasurementScale/SetChartLimiterIoT" namespace ART { class ESPDevice; class DeviceSensor { public: DeviceSensor(ESPDevice* espDevice); ~DeviceSensor(); void begin(); bool initialized(); void setSensorsByMQQTCallback(const char* json); bool read(); bool publish(); ESPDevice * getESPDevice(); std::tuple<SensorInDevice**, short> getSensorsInDevice(); void createSensorsJsonNestedArray(JsonObject& jsonObject); long getReadIntervalInMilliSeconds(); long getPublishIntervalInMilliSeconds(); SensorDatasheet * getSensorDatasheetByKey(SensorDatasheetEnum sensorDatasheetId, SensorTypeEnum sensorTypeId); private: ESPDevice * _espDevice; OneWire * _oneWire; DallasTemperature * _dallas; bool _initialized; bool _initializing; SensorInDevice * getSensorInDeviceBySensorId(const char* sensorId); Sensor * getSensorById(const char* sensorId); SensorTrigger * getSensorTriggerByKey(const char* sensorId, const char* sensorTriggerId); void createSensorJsonNestedObject(Sensor* sensor, JsonArray& root); String convertDeviceAddressToString(const uint8_t* deviceAddress); std::vector<SensorDatasheet*> _sensorDatasheets; std::vector<SensorInDevice*> _sensorsInDevice; uint64_t _readIntervalTimestamp; long _readIntervalInMilliSeconds; uint64_t _publishIntervalTimestamp; long _publishIntervalInMilliSeconds; void setLabel(const char* json); void setDatasheetUnitMeasurementScale(const char* json); void setResolution(const char* json); void setOrdination(const char* json); bool compareSensorInDevice(SensorInDevice* a, SensorInDevice* b); void insertTrigger(const char* json); bool deleteTrigger(const char* json); void setTriggerOn(const char* json); void setBuzzerOn(const char* json); void setTriggerValue(const char* json); void setRange(const char* json); void setChartLimiter(const char* json); void setReadIntervalInMilliSeconds(const char* json); void setPublishIntervalInMilliSeconds(const char* json); void onDeviceMQSubscribeDeviceInApplication(); void onDeviceMQUnSubscribeDeviceInApplication(); bool onDeviceMQSubscription(const char* topicKey, const char* json); }; } #endif
#define _CRT_SECURE_NO_WARNINGS //연산자 오버로딩 //+ - * / -> 기본 자료형에만 유효한 연산자, 클래스나 다른 자료형은 유효하지 않다. #include <cstdio> #include <cstring> class Vector { public: float X; float Y; Vector() { X = 0.0f; Y = 0.0f; } Vector(float x, float y) { this->X = x; this->Y = y; } void printInfo(float x, float y) { printf("%.2f, %.2f\n", x, y); } }; //벡터 덧셈 //Vector operator+(Vector v1, Vector v2) { //연산자 오버로딩 : 정적으로 할당(스택얼로케이티드) 했을때만 동작한다. Vector operator+(Vector& v1, Vector& v2) { // 값복사가 일어나지 않는다. 주소복사 -> 퍼포먼스가 좋다. return Vector(v1.X + v2.X, v1.Y + v2.Y); } int main() { Vector v1 = Vector(100,200); Vector v2 = Vector(1,2); Vector v3 = v1 + v2; v3.printInfo(v3.X,v3.Y); return 0; }
/*************************************************************************** * Filename : LayerStack.h * Name : Ori Lazar * Date : 29/10/2019 * Description : Declaration of a layer vector wrapper, contains all active application * which are iterated over every frame. .---. .'_:___". |__ --==| [ ] :[| |__| I=[| / / ____| |-/.____.' /___\ /___\ ***************************************************************************/ #pragma once #include "Layer.h" #include <vector> //todo: Implement reverse iterator, for propagating events in reverse namespace Exalted { class LayerStack { public: LayerStack() = default; ~LayerStack(); void PushLayer(Layer* layer); void PushOverlay(Layer* overlay); void PopLayer(Layer* layer); void PopOverlay(Layer* overlay); std::vector<Layer*>::iterator begin() { return m_Layers.begin(); } std::vector<Layer*>::iterator end() { return m_Layers.end(); } private: std::vector<Layer*> m_Layers; unsigned int m_LayerInsertIndex = 0; }; }
#include<bits/stdc++.h> using namespace std; int main(){ int n = 1000; int i = 0; unsigned long long sum = 0; while( ++i < n){ sum += ( (i%3 == 0 || i%5 == 0) ? i : 0 ); } printf("%llu\n", sum); }
#pragma one #ifndef __OUTPUT_H_ICLUDED__ #define __OUTPUT_H_ICLUDED__ #include <3ds.h> #include <string> #include <vector> #include <stdio.h> #include <stdint.h> #include <stddef.h> #include "../includes/utils.h" class Output { private: std::vector<std::string> messageLog; bool inReverse; public: Output(); ~Output(); void print(const std::string& message); void printAll(); void clear(); void setReverseFlag(const bool value); bool getReverseFlag() const; }; #endif
// -*- C++ -*- // // Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory, // Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC // // This file is part of FreePOOMA. // // FreePOOMA is free software; you can redistribute it and/or modify it // under the terms of the Expat license. // // 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 Expat // license for more details. // // You should have received a copy of the Expat license along with // FreePOOMA; see the file LICENSE. // #include <iostream> using std::cout; using std::endl; #include <stdlib.h> #include <vector> int main(int argc, char *argv[]) { cout << "sizeof(short) = " << sizeof(short) << endl; cout << "sizeof(int) = " << sizeof(int) << endl; cout << "sizeof(long) = " << sizeof(long) << endl; cout << "sizeof(long long) = " << sizeof(long long) << endl; cout << "sizeof(float) = " << sizeof(float) << endl; cout << "sizeof(double) = " << sizeof(double) << endl; cout << "sizeof(size_t) = " << sizeof(size_t) << endl; std::vector<int> a(10); cout << "sizeof(a.size()) = " << sizeof(a.size()) << endl; }
#ifndef BSCHEDULER_DAEMON_MASTER_DISCOVERER_HH #define BSCHEDULER_DAEMON_MASTER_DISCOVERER_HH #include <chrono> #include <iosfwd> #include <unistdx/base/log_message> #include <unistdx/net/interface_address> #include <unistdx/net/ipv4_address> #include <bscheduler/api.hh> #include <bscheduler/ppl/socket_pipeline_event.hh> #include "hierarchy.hh" #include "hierarchy_kernel.hh" #include "probe.hh" #include "prober.hh" #include "resident_kernel.hh" #include "tree_hierarchy_iterator.hh" namespace bsc { /// Timer which is used to periodically scan nodes /// to find the best principal node. class discovery_timer: public bsc::kernel {}; enum class probe_result { add_subordinate = 0, remove_subordinate, reject_subordinate, retain }; std::ostream& operator<<(std::ostream& out, probe_result rhs); class master_discoverer: public resident_kernel { public: typedef sys::ipv4_address addr_type; typedef addr_type::rep_type uint_type; typedef sys::interface_address<addr_type> ifaddr_type; typedef tree_hierarchy_iterator<addr_type> iterator; typedef hierarchy<addr_type> hierarchy_type; typedef std::chrono::system_clock clock_type; typedef clock_type::duration duration; typedef typename hierarchy_type::weight_type weight_type; enum class state_type { initial, waiting, probing }; private: /// Time period between subsequent network scans. duration _interval = std::chrono::minutes(1); uint_type _fanout = 10000; hierarchy_type _hierarchy; iterator _iterator, _end; state_type _state = state_type::initial; public: inline master_discoverer( const ifaddr_type& interface_address, const sys::port_type port, uint_type fanout ): _fanout(fanout), _hierarchy(interface_address, port), _iterator(interface_address, fanout) {} void on_start() override; void on_kernel(bsc::kernel* k) override; private: const ifaddr_type& interface_address() const noexcept { return this->_hierarchy.interface_address(); } sys::port_type port() const noexcept { return this->_hierarchy.port(); } void probe_next_node(); void send_timer(); void update_subordinates(probe* p); probe_result process_probe(probe* p); void update_principal(prober* p); inline void setstate(state_type rhs) noexcept { this->_state = rhs; } inline state_type state() const noexcept { return this->_state; } void on_event(socket_pipeline_kernel* k); void on_client_add(const sys::socket_address& endp); void on_client_remove(const sys::socket_address& endp); void broadcast_hierarchy(sys::socket_address ignored_endpoint = sys::socket_address()); void send_weight(const sys::socket_address& dest, weight_type w); void update_weights(hierarchy_kernel* k); template <class ... Args> inline void log(const char* fmt, const Args& ... args) { #if defined(BSCHEDULER_PROFILE_NODE_DISCOVERY) using namespace std::chrono; const auto now = system_clock::now().time_since_epoch(); const auto t = duration_cast<milliseconds>(now); std::string new_fmt; new_fmt += "[time since epoch _ms] "; new_fmt += fmt; sys::log_message("discoverer", new_fmt.data(), t.count(), args...); #else sys::log_message("discoverer", fmt, args ...); #endif } }; } #endif // vim:filetype=cpp
/* used to caculate the sin fuc @ amaswz superwenzg@gmail.com */ #include <cstdio> #include <cmath> #include <cstring> #include <sstream> #include <fstream> #include <iostream> using namespace std; typedef pair <double,double> Point; class Newdon_it { public: Newdon_it(const int num_of_inter_point) :_noip(num_of_inter_point), _rcon(0) { _array = new Point[_noip]; _ans = new double[_noip]; for(int i=0;i<_noip;i++) { cin>>_array[i].first>>_array[i].second; _ans[i] = _array[i].second; } }; void set_order(int order) { _order = order; } void res(double xt); void calcaute(); double calcaute_ret(int lhs,int rhs); void show_list(); private: int _noip; //插值点个数 int _order; int _rcon; // ret_controal_order_num Point *_array; //插值点数组 double *_ans; //牛顿插值表 }; void Newdon_it::calcaute() { for(int i=0;i<_noip;i++) { for(int j=_noip-1;j>i;j--) { _ans[j] = (_ans[j] - _ans[j-1] ) / ( _array[j].first - _array[j-1-i].first); } } } double Newdon_it::calcaute_ret(int lhs,int rhs) { if(lhs==rhs) { return _array[lhs].second; } else { double a,b,s; a=calcaute_ret(lhs+1,rhs); b=calcaute_ret(lhs,rhs-1); s= (a-b)/(_array[rhs].first-_array[lhs].first); if(lhs==0) { _ans[_rcon]=s; _rcon++; } return s; } } void Newdon_it::res(double xt) { double Res = 0; double iteration_part = 1; Res = _ans[0]; for(int i=1;i<_order;i++) { iteration_part *= (xt - _array[i-1].first); Res += _ans[i] * iteration_part; } cout<<Res<<endl; } void Newdon_it::show_list() { for(int i=0;i<_noip;i++) { cout<<_ans[i]<<endl; } } int main(int argc,char** argv) { int num_of_inter_point; //插值点的个数 int Order; //阶数 double xt; //欲计算的点 cout<<"输入插值点个数: "; cin>>num_of_inter_point; Newdon_it Ni(num_of_inter_point); Ni.calcaute_ret(0,num_of_inter_point); Ni.show_list(); cout << "输入欲计算阶数: "; cin >> Order; Ni.set_order(Order); cout << "输入欲计算点xt(control + c退出运算): "; while( cin>>xt ) Ni.res(xt); } /* 0.40 0.41075 0.55 0.57815 0.65 0.69675 0.80 0.88811 0.90 1.02652 1.05 1.25382 0.41075 1.116 0.28 0.197333 0.0312381 0.00029304 0.017037 1.017183 0.146447 1.157713 0.370590 1.448590 0.629410 1.876502 0.853553 2.347975 0.982963 2.672363 */
#ifndef SPRITE_H #define SPRITE_H #include <assert.h> #include <d3d9.h> // core direct3d #include <d3dx9.h> // aux libs #define SPRITE_READ_FROM_FILE -5925499 /* read the property from the file */ // Why is it -5925499? It was too likely // someone would WANT TO SCALE by -1. // So we chose a large, large value // You won't ever want to draw something // -5925499 pixels would you? // -5925499 also happens to be // a telephone number .. :). #define SPRITE_INFINITY_LONG -1 /* don't advance the frame rate */ #include "helperFunctions.h" #include "GDIPlusTexture.h" /// Defines a line for drawing struct Line { D3DXVECTOR2 start, end ; D3DCOLOR color ; float thickness ; Line() { start = end = D3DXVECTOR2() ; color = 0 ; thickness = 1; } Line( D3DXVECTOR2 iStart, D3DXVECTOR2 iEnd, D3DCOLOR iColor, float iThickness ) { start = iStart ; end = iEnd ; color = iColor ; thickness = iThickness ; // just waiting until there's variables pod and pad.. } } ; class Sprite { private: IDirect3DTexture9 *spritesheet ; D3DXIMAGE_INFO imageInfo ; const char *originalFilename ; int spriteWidth ; int spriteHeight ; // Animation and frame counting int n ; /*!< (n)umber frame you're on */ int numFrames ; /*!< the number of frames this sprite is known to have. A sheet can have some empty cells at the end that are not used. */ float internalClock ; // the internalClock that // keeps track of "what time it is". This is used // to change what sprite to draw with when enough // time has passed, based on the "secondsPerFrame" variable float secondsPerFrame ; // Amount of time to spend on each frame before advancing // debating whether to name this either // "secondsPerFrame" or "timeBetweenFrames" RECT *rects ; // CACHED set of source rectangles // to draw at each frame. A mild optimization // to avoid recomputing the source rects each frame. // If you have hundreds of sprites, this could add up public: //!!DELETE ME. // provide a ctor that accepts an HDC Sprite( int w, int h, IDirect3DTexture9 *tex ) { spriteWidth = w ; spriteHeight = h ; // haxx. ImageInfo doesn't make sense // for a generated texture, (which is generally // what this function is for) but we'll leave it // this way. imageInfo.Width = w ; imageInfo.Height = h ; imageInfo.MipLevels = 1 ; spritesheet = tex ; n = 0 ; numFrames = 1 ; internalClock = 0 ; secondsPerFrame = 1 ; originalFilename = "Generated texture (no file)" ; info( "Artifically created sprite w=%d h=%d", w, h ) ; } // This function assumes we're loading a // spritesheet for an animated sprite. // singleSpriteWidth and singleSpriteHeight // are the width and height for A SINGLE FRAME // of the animated sprite, not the SPRITESHEET itself. // backgroundColor GETS ERASED TO TRANSPARENT. // If you're using PNG images, then you don't // need a background color (because PNG supports // transparency inside the file itself) Sprite( IDirect3DDevice9 *gpu, const char *filename, D3DCOLOR backgroundColor = D3DCOLOR_ARGB( 0,0,0,0 ), // defaults to transparent black (i.e. no effect) // If you are loading in // a SPRITE SHEET, then singleSpriteWidth // and singleSpriteHeight should be // the width of a SINGLE IMAGE on that sheet. // SPRITE_READ_FROM_FILE for these two parameters // means we will assume // the entire sheet is meant to be a single sprite int singleSpriteWidth = SPRITE_READ_FROM_FILE, int singleSpriteHeight = SPRITE_READ_FROM_FILE, int numFramesToUse = SPRITE_READ_FROM_FILE, // If you specify SPRITE_READ_FROM_FILE, // then the number of frames it will count // are based on singleSpriteWidth // and singleSpriteHeight, // but it will assume every cell is used float timeBetweenFrames = 0.5f ) { originalFilename = filename ; if( !filename ) { bail( "NULL filename received in sprite load" ) ; } // initialize internal clock and animation parameters n = 0 ; internalClock = 0 ; secondsPerFrame = timeBetweenFrames ; // save these off spriteWidth = singleSpriteWidth ; spriteHeight = singleSpriteHeight ; numFrames = numFramesToUse ; // Some parameter value checking if( !spriteWidth ) warning( "Sprite width was 0. Not changing anything, but are you sure that's what you want?" ) ; if( !spriteHeight ) warning( "Sprite height was 0. Not changing anything, but are you sure that's what you want?" ) ; if( !numFrames ) warning( "numFrames was 0. Not changing anything, but are you sure that's what you want?" ) ; HRESULT hr ; // Here, we're loading from a file like normal hr = loadTexturePow2( gpu, filename, backgroundColor ) ; if( DX_CHECK( hr, "Texture load" ) ) { // If these are still SPRITE_READ_FROM_FILE, // then the user intended to have them // set by the file's properties if( spriteWidth == SPRITE_READ_FROM_FILE ) spriteWidth = imageInfo.Width ; if( spriteHeight == SPRITE_READ_FROM_FILE ) spriteHeight = imageInfo.Height ; // Compute maximum # frames allowable // based on the spritesheet texture // width and height and spriteWidth and // spriteHeight int numAcross = imageInfo.Width / spriteWidth ; // could be 1 int numDown = imageInfo.Height / spriteHeight ; // could be 1 also int maxFramesAllowable = numAcross * numDown ; // could be 1 to.. whatever // Make sure the number of frames is logical/possible if( numFrames > maxFramesAllowable ) { warning( "%d sprites (%d x %d) won't fit on your " "(%d x %d) sheet, defaulting to %d frames.", numFrames, spriteWidth, spriteHeight, imageInfo.Width, imageInfo.Height, maxFramesAllowable ) ; numFrames = maxFramesAllowable ; } if( numFrames == SPRITE_READ_FROM_FILE ) { numFrames = maxFramesAllowable ; info( "Defaulted to %d frames. Note I'm not " "checking for empty frames.", maxFramesAllowable ) ; } info( "'%s' loaded, width=%d, height=%d, numFrames=%d", filename, imageInfo.Width, imageInfo.Height, numFrames ) ; //!! Now, we should "cache up" the RECTs // to use on each frame. This makes // for a bit more memory usage, and // a bit of a hit up front, but // better runtime performance } else { warning( "Texture %s didn't load using D3DX function, trying GDI+ function..", originalFilename ) ; GDIPlusTexture * gdiPlusTex = GDIPlusTexture::CreateFromFile( gpu, filename ) ; // haxx spriteWidth = imageInfo.Width = gdiPlusTex->getWidth() ; spriteHeight = imageInfo.Height = gdiPlusTex->getHeight() ; numFrames = 1 ; secondsPerFrame = SPRITE_INFINITY_LONG ; // no animation spritesheet = gdiPlusTex->getTexture() ; delete gdiPlusTex ; if( !spritesheet ) { // Not extracting frames of an animated gif here, // but GIF2PNG (http://gnuwin32.sourceforge.net/packages/pngutils.htm) // for easy batch conversion of .gif to .png, even extracts // frames of an animated gif error( "Your texture %s has FAILED TO LOAD, does the file exist? " "Supported file formats, d3d: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. " "Supported file formats, gdi+: BMP, GIF, JPEG, PNG, TIFF, and EMF. " "Don't blame me, blame Microsoft. " "Loading placeholder texture instead, for now.", filename ) ; bail( "A texture failed to load" ) ; } } } ~Sprite() { SAFE_RELEASE( spritesheet ) ; } private: HRESULT loadTextureNonPow2( IDirect3DDevice9 *gpu, char *filename, D3DCOLOR backgroundColor ) { HRESULT hr = D3DXCreateTextureFromFileExA( gpu, filename, // D3DX_DEFAULT will round up to nearest power of 2, or // D3DX_DEFAULT_NONPOW2 for actual size. // !!NOTE: you probably should check if the // gpu supports NONPOW2 sprites before // going ahead with this. D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2, D3DX_FROM_FILE, // D3DX_FROM_FILE means no mips. // D3DX_DEFAULT will create a complete mipmap chain. 0, // Usage: you could make the tex a render target with D3DUSAGE_RENDERTARGET but we don't want to D3DFMT_UNKNOWN, // take the format from the file. D3DPOOL_MANAGED, // So we don't have to re-load textures if the device is lost D3DX_FILTER_NONE, // filter image !! CHANGES THE SIZE OF THE IMAGE! D3DX_FILTER_NONE, // filter mip !! CHANGES THE SIZE OF THE IMAGE! backgroundColor, // The background color we should // consider transparent. This gets replaced by // a completely CLEAR color. &this->imageInfo, NULL, // no palette &this->spritesheet // the texture member variable to store // the entire spritesheet in ) ; return hr ; } HRESULT loadTexturePow2( IDirect3DDevice9 *gpu, const char *filename, D3DCOLOR backgroundColor ) { // D3DXCreateTextureFromFile() // http://msdn.microsoft.com/en-us/library/ee417125%28VS.85%29.aspx HRESULT hr = D3DXCreateTextureFromFileExA( gpu, filename, // D3DX_DEFAULT will round up to nearest power of 2, or // D3DX_DEFAULT_NONPOW2 for actual size. D3DX_DEFAULT, D3DX_DEFAULT, D3DX_FROM_FILE, // D3DX_FROM_FILE means no mips. // D3DX_DEFAULT will create a complete mipmap chain. 0, // Usage: you could make the tex a render target with D3DUSAGE_RENDERTARGET but we don't want to D3DFMT_UNKNOWN, // take the format from the file. D3DPOOL_MANAGED, // So we don't have to re-load textures if the device is lost D3DX_FILTER_NONE, // filter image !! CHANGES THE SIZE OF THE IMAGE! D3DX_FILTER_NONE, // filter mip !! CHANGES THE SIZE OF THE IMAGE! backgroundColor, // The background color we should // consider transparent. This gets replaced by // a completely CLEAR color. &this->imageInfo, NULL, // no palette &this->spritesheet // the texture member variable to store // the entire spritesheet in ) ; return hr ; } public: float getTimePerFrame() { return secondsPerFrame ; } /// How long to stay at frame before advancing to the next frame. /// Set to any negative value (e.g. SPRITE_INFINITY_LONG) /// to prevent the sprite from animating void setTimePerFrame( float secondsToSpendOnEachFrame ) { secondsPerFrame = secondsToSpendOnEachFrame ; } void setFrame( int frameNumber ) { // no negative frame numbers! if( frameNumber < 0 ) { warning( "Attempt to set negative frame # %d on sprite=%s, " "setting to frame=0", frameNumber, originalFilename ) ; frameNumber = 0 ; } n = frameNumber ; // set the frame number if( n >= numFrames ) n = 0 ; } // advance this sprite by this much TIME void advance( float timeElapsed ) { // negative value for "secondsPerFrame" means // to NOT animate. if( secondsPerFrame < 0 ) // SPRITE_INFINITY_LONG is -1, return ; // we're not going to increment the frame. internalClock += timeElapsed ; // if we exceeded the amount of time to spend // on each frame .. if( internalClock > secondsPerFrame ) { n++ ; // .. then advance the frame number if( n >= numFrames ) n = 0 ; internalClock = 0 ; // .. and reset the internalClock to 0 } } // Gets you the rectangle for a specific frame public: //!! MAKE THIS PRIVATE so user must use getCurrentRectangle() RECT getRectForFrame( int frameIndex ) { if( frameIndex >= numFrames ) { warning( "Frame index out of bounds (frame=%d). Giving you the last frame instead.", frameIndex ) ; frameIndex = numFrames - 1 ; // because frames are // indexed from 0, so the LAST frame is numFrames - 1 // (because FIRST frame is frame 0, second frame = frame 1.. // so last frame = numFrames - 1) } // Now, how many sprites will there be // across the sheet? int numAcross = getSheetWidth() / spriteWidth ; int numDown = getSheetHeight() / spriteHeight ; // Get the row and column this frameIndex // falls in the sheet int row = frameIndex / numAcross ; int col = frameIndex % numAcross ; #pragma region Explaining how to get row and col /* 0 1 2 <- col _____________ |0 |1 |2 | 0 | x | x | x | |___|___|___| |3 |4 |5 | 1 | x | x | x | |___|___|___| ^ | row columns across rows go down frame numbers are in the boxes (the x is supposed to be a picture of the sprite in that frame) so, say I want frame 4. well that's int row = 4 / 3 = 1 [ INTEGER DIVISION, cuts off the decimal ] int col = 4 % 3 = 1 [ MODULUS.. 4 % 3 means "the remainder of when 4 is divided by 3". __Try it on paper__ to see. ] which means frame 4 sits at (1, 1). Which is correct when you look at the picture. In case you didn't know about INTEGER DIVISION its just a rule in C++ that if you divide two integers together the result is always __ROUNDED DOWN__ to the nearest integer. The decimal is basically LOST. Now say I want frame 1. Well, that's int row = 1 / 3 = 0 int col = 1 % 3 = 1 so frame 1 sits at (0, 1). ( In this notation here (0, 1) its (row,col), row goes first.) */ #pragma endregion // Compute the pixel location on the sprite sheet itself int pixelLocationX = col * spriteWidth ; int pixelLocationY = row * spriteHeight ; // Now create the bounds rectangle struct RECT rect ; rect.left = pixelLocationX ; rect.right = pixelLocationX + spriteWidth ; rect.top = pixelLocationY ; rect.bottom = pixelLocationY + spriteHeight ; // Let's assert to make sure the sprite // isn't out of bounds. // ( CAN assume spriteWidth, spriteHeight will be + // (checked in CTOR). ) if( rect.left < 0 || rect.top < 0 || rect.right > getSheetWidth() || rect.bottom > getSheetHeight() ) { error( "Internal error: sprite index out of bounds: " "l=%d t=%d r=%d b=%d, but sprite " "width=%d height=%d", rect.left, rect.top, rect.right, rect.bottom, getSheetWidth(), getSheetHeight() ) ; } return rect ; } public: // gets you the current rectangle for the sprite on this frame RECT getRect() { return getRectForFrame( n ) ; } // This really should return an // "instruction" type of object // which is a subrectangle to draw // of the texture for the current frame IDirect3DTexture9* getTexture() { return spritesheet ; } int getSpriteWidth() { return spriteWidth ; } int getSpriteHeight() { return spriteHeight ; } int getSheetWidth() { return imageInfo.Width ; } int getSheetHeight() { return imageInfo.Height ; } int getCenterX() { return getSpriteWidth() / 2 ; } int getCenterY() { return getSpriteHeight() / 2 ; } float getScaleXFor( float desiredWidth ) { return desiredWidth / getSpriteWidth() ; } float getScaleYFor( float desiredHeight ) { return desiredHeight / getSpriteHeight() ; } const char* getOriginalFilename() { return originalFilename ; } } ; #endif // SPRITE_H
// // Created by hw730 on 2020/6/12. // #ifndef DEFENCE_GAME_BULLETLINKLIST_H #define DEFENCE_GAME_BULLETLINKLIST_H class BulletLinkList { }; #endif //DEFENCE_GAME_BULLETLINKLIST_H
/* * Copyright (C) 2012-2016 Open Source Robotics Foundation * * 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. * */ /* * Author: Jennifer Buehler * Date: March 2017 */ #ifndef COLLISION_BENCHMARK_MESHSHAPEGENERATIONVTK_H #define COLLISION_BENCHMARK_MESHSHAPEGENERATIONVTK_H #include <vtkSmartPointer.h> #include <vtkPolyData.h> #include <vector> namespace collision_benchmark { /** * \param[in] radius radius of sphere * \param[in] theta number of points in the longitude direction * \param[in] phi number of points in the latitude direction * \param[in] latLongTessel Cause the sphere to be tessellated with edges along * the latitude and longitude lines. If off, triangles are generated at * non-polar regions, which results in edges that are not parallel to * latitude and longitude lines. This can be useful for generating a * wireframe sphere with natural latitude and longitude lines. * \return the polygon data */ vtkSmartPointer<vtkPolyData> makeSphereVtk(const double radius, const unsigned int theta, const unsigned int phi, const bool latLongTessel); /** * \param[in] radius radius of cylinder * \param[in] height height of cylinder * \param[in] resolution number of facets used to define cylinder. * \param[in] Turn on/off whether to cap cylinder with polygons. * \return the polygon data */ vtkSmartPointer<vtkPolyData> makeCylinderVtk(const double radius, const double height, const unsigned int resolution, const bool capping); /** * \param[in] x x dimension * \param[in] y y dimension * \param[in] z z dimension * \return the polygon data */ vtkSmartPointer<vtkPolyData> makeBoxVtk(const double x, const double y, const double z); /** * \brief Create a box using AABB cornder coordinates * \return the polygon data */ vtkSmartPointer<vtkPolyData> makeBoxVtk(const double xMin, const double xMax, const double yMin, const double yMax, const double zMin, const double zMax); /** * \brief Creates a cone * \param[in] radius base radius of the cone. * \param[in] height height of cone in its specified direction. * \param[in] resolution number of facets used to represent the cone. * \param[in] dir_x along with \e dir_y and \e dir_z: the orientation vector * of the cone. The vector does not have to be normalized. * The direction goes from the center of the base toward the apex. * \param[in] angle_deg angle of the cone. This is the angle between the axis of * the cone and a generatrix. Warning: this is not the aperture! * The aperture is twice this angle. * As a side effect, the angle plus height sets the base radius of the cone. * Angle is expressed in degrees. * \param[in] capping whether to cap the base of the cone with a polygon. * \return the polygon data */ vtkSmartPointer<vtkPolyData> makeConeVtk(const double radius, const double height, const unsigned int resolution, const double angle_deg, const bool capping, const double dir_x = 0, const double dir_y = 0, const double dir_z = 1); /** * \param[in] innerRadius the inner radius * \param[in] outerRadius the outer radius * \param[in] radialResolution number of points in radius direction. * \param[in] circumResolution number of points in circumferential direction. * \return the polygon data */ vtkSmartPointer<vtkPolyData> makeDiskVtk(const double innerRadius, const double outerRadius, const unsigned int radialResolution, const unsigned int circumResolution); /** * \param[in] xRad radius in x-direction * \param[in] yRad radius in y-direction * \param[in] zRad radius in z-direction * \param[in] uRes resolution in u-direction * \param[in] vRes resolution in v-direction * \return the polygon data */ vtkSmartPointer<vtkPolyData> makeEllipsoidVtk(const double xRad, const double yRad, const double zRad, const unsigned int uRes, const unsigned int vRes); /** * \param[in] ringRadius radius from the center to the middle of the * ring of the torus. * \param[in] crossRadius radius of the cross section of ring of the torus. * \param[in] uRes resolution in u-direction. Will create uRes-1 "circle * sections", e.g. with uRes = 4 it will be a triangle-shaped torus. * \param[in] vRes resolution in v-direction * \return the polygon data */ vtkSmartPointer<vtkPolyData> makeTorusVtk(const double ringRadius, const double crossRadius, const unsigned int uRes, const unsigned int vRes); // Simple helper for a point struct vPoint { double x, y, z; }; // Simple helper for a triangle index set struct vTriIdx { unsigned int v1, v2, v3; }; /** * \brief Gets the triangle soup out of the polygon data. * Will triangulate \e polydata first. * \param[in] polydata the polygon data * \param[out] vertices the vertices * \param[out] triangles the triangles */ void getTriangleSoup(const vtkSmartPointer<vtkPolyData>& polydata, std::vector<vPoint>& vertices, std::vector<vTriIdx>& triangles); /** * Triangulates the data and returns the triangulated data */ vtkSmartPointer<vtkPolyData> triangulate(const vtkSmartPointer<vtkPolyData>& polydata); // test method // void testMeshShapeGenerationVtk(); } // namespace #endif // COLLISION_BENCHMARK_MESHSHAPEGENERATIONVTK_H
#include <iostream> void reset(int &); int main() { int i = 4; std::cout << "initial value i = " << i << std::endl; reset(i); std::cout << "after reset: i = " << i << std::endl; std::cout << "Bye!\n"; return 0; } void reset(int & i) { i = 0; }
// Copyright (c) 2020 gladcow // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BTC_UTILS_CHAINPARAMS_H__ #define BTC_UTILS_CHAINPARAMS_H__ #include <vector> #include <string> namespace btc_utils { enum network_t { mainnet, testnet, regtest }; extern network_t g_network; /** The maximum allowed size for a serialized block, in bytes (only for buffer size limits) */ extern const unsigned int MAX_BLOCK_SERIALIZED_SIZE; constexpr unsigned int MESSAGE_START_SIZE = 4; typedef unsigned char start_marker_t[MESSAGE_START_SIZE]; const start_marker_t& message_start(); std::vector<unsigned char> base_58_pubkey_address_prefix(); std::vector<unsigned char> base_58_script_address_prefix(); std::string bech32_hrp(); } #endif // BTC_UTILS_CHAINPARAMS_H__
/*====================================================================* - Copyright (C) 2001 Leptonica. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - 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 ANY - 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. *====================================================================*/ /* * graphics.c * * Pta generation for arbitrary shapes built with lines * PTA *generatePtaLine() * PTA *generatePtaWideLine() * PTA *generatePtaBox() * PTA *generatePtaBoxa() * PTA *generatePtaHashBox() * PTA *generatePtaHashBoxa() * PTAA *generatePtaaBoxa() * PTAA *generatePtaaHashBoxa() * PTA *generatePtaPolyline() * PTA *convertPtaLineTo4cc() * PTA *generatePtaFilledCircle() * PTA *generatePtaFilledSquare() * PTA *generatePtaLineFromPt() * l_int32 locatePtRadially() * * Rendering function plots directly on images * l_int32 pixRenderPlotFromNuma() * l_int32 pixRenderPlotFromNumaGen() * PTA *makePlotPtaFromNuma() * PTA *makePlotPtaFromNumaGen() * * Pta rendering * l_int32 pixRenderPta() * l_int32 pixRenderPtaArb() * l_int32 pixRenderPtaBlend() * * Rendering of arbitrary shapes built with lines * l_int32 pixRenderLine() * l_int32 pixRenderLineArb() * l_int32 pixRenderLineBlend() * * l_int32 pixRenderBox() * l_int32 pixRenderBoxArb() * l_int32 pixRenderBoxBlend() * * l_int32 pixRenderBoxa() * l_int32 pixRenderBoxaArb() * l_int32 pixRenderBoxaBlend() * * l_int32 pixRenderHashBox() * l_int32 pixRenderHashBoxArb() * l_int32 pixRenderHashBoxBlend() * * l_int32 pixRenderHashBoxa() * l_int32 pixRenderHashBoxaArb() * l_int32 pixRenderHashBoxaBlend() * * l_int32 pixRenderPolyline() * l_int32 pixRenderPolylineArb() * l_int32 pixRenderPolylineBlend() * * l_int32 pixRenderRandomCmapPtaa() * * Rendering and filling of polygons * PIX *pixRenderPolygon() * PIX *pixFillPolygon() * * Contour rendering on grayscale images * PIX *pixRenderContours() * PIX *fpixAutoRenderContours() * PIX *fpixRenderContours() * * The line rendering functions are relatively crude, but they * get the job done for most simple situations. We use the pta * (array of points) as an intermediate data structure. For example, * to render a line we first generate a pta. * * Some rendering functions come in sets of three. For example * pixRenderLine() -- render on 1 bpp pix * pixRenderLineArb() -- render on 32 bpp pix with arbitrary (r,g,b) * pixRenderLineBlend() -- render on 32 bpp pix, blending the * (r,g,b) graphic object with the underlying rgb pixels. * * There are also procedures for plotting a function, computed * from the row or column pixels, directly on the image. */ #include <string.h> #include <math.h> #include "allheaders.h" /*------------------------------------------------------------------* * Pta generation for arbitrary shapes built with lines * *------------------------------------------------------------------*/ /*! * generatePtaLine() * * Input: x1, y1 (end point 1) * x2, y2 (end point 2) * Return: pta, or null on error * * Notes: * (1) Uses Bresenham line drawing, which results in an 8-connected line. */ PTA * generatePtaLine(l_int32 x1, l_int32 y1, l_int32 x2, l_int32 y2) { l_int32 npts, diff, getyofx, sign, i, x, y; l_float32 slope; PTA *pta; PROCNAME("generatePtaLine"); /* Generate line parameters */ if (x1 == x2 && y1 == y2) /* same point */ { npts = 1; } else if (L_ABS(x2 - x1) >= L_ABS(y2 - y1)) { getyofx = TRUE; npts = L_ABS(x2 - x1) + 1; diff = x2 - x1; sign = L_SIGN(x2 - x1); slope = (l_float32)(sign * (y2 - y1)) / (l_float32)diff; } else { getyofx = FALSE; npts = L_ABS(y2 - y1) + 1; diff = y2 - y1; sign = L_SIGN(y2 - y1); slope = (l_float32)(sign * (x2 - x1)) / (l_float32)diff; } if ((pta = ptaCreate(npts)) == NULL) { return (PTA *)ERROR_PTR("pta not made", procName, NULL); } if (npts == 1) /* degenerate case */ { ptaAddPt(pta, x1, y1); return pta; } /* Generate the set of points */ if (getyofx) /* y = y(x) */ { for (i = 0; i < npts; i++) { x = x1 + sign * i; y = (l_int32)(y1 + (l_float32)i * slope + 0.5); ptaAddPt(pta, x, y); } } else /* x = x(y) */ { for (i = 0; i < npts; i++) { x = (l_int32)(x1 + (l_float32)i * slope + 0.5); y = y1 + sign * i; ptaAddPt(pta, x, y); } } return pta; } /*! * generatePtaWideLine() * * Input: x1, y1 (end point 1) * x2, y2 (end point 2) * width * Return: ptaj, or null on error */ PTA * generatePtaWideLine(l_int32 x1, l_int32 y1, l_int32 x2, l_int32 y2, l_int32 width) { l_int32 i, x1a, x2a, y1a, y2a; PTA *pta, *ptaj; PROCNAME("generatePtaWideLine"); if (width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } if ((ptaj = generatePtaLine(x1, y1, x2, y2)) == NULL) { return (PTA *)ERROR_PTR("ptaj not made", procName, NULL); } if (width == 1) { return ptaj; } /* width > 1; estimate line direction & join */ if (L_ABS(x1 - x2) > L_ABS(y1 - y2)) /* "horizontal" line */ { for (i = 1; i < width; i++) { if ((i & 1) == 1) /* place above */ { y1a = y1 - (i + 1) / 2; y2a = y2 - (i + 1) / 2; } else /* place below */ { y1a = y1 + (i + 1) / 2; y2a = y2 + (i + 1) / 2; } if ((pta = generatePtaLine(x1, y1a, x2, y2a)) == NULL) { return (PTA *)ERROR_PTR("pta not made", procName, NULL); } ptaJoin(ptaj, pta, 0, -1); ptaDestroy(&pta); } } else /* "vertical" line */ { for (i = 1; i < width; i++) { if ((i & 1) == 1) /* place to left */ { x1a = x1 - (i + 1) / 2; x2a = x2 - (i + 1) / 2; } else /* place to right */ { x1a = x1 + (i + 1) / 2; x2a = x2 + (i + 1) / 2; } if ((pta = generatePtaLine(x1a, y1, x2a, y2)) == NULL) { return (PTA *)ERROR_PTR("pta not made", procName, NULL); } ptaJoin(ptaj, pta, 0, -1); ptaDestroy(&pta); } } return ptaj; } /*! * generatePtaBox() * * Input: box * width (of line) * Return: ptad, or null on error * * Notes: * (1) Because the box is constructed so that we don't have any * overlapping lines, there is no need to remove duplicates. */ PTA * generatePtaBox(BOX *box, l_int32 width) { l_int32 x, y, w, h; PTA *ptad, *pta; PROCNAME("generatePtaBox"); if (!box) { return (PTA *)ERROR_PTR("box not defined", procName, NULL); } if (width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } /* Generate line points and add them to the pta. */ boxGetGeometry(box, &x, &y, &w, &h); if (w == 0 || h == 0) { return (PTA *)ERROR_PTR("box has w = 0 or h = 0", procName, NULL); } ptad = ptaCreate(0); if ((width & 1) == 1) /* odd width */ { pta = generatePtaWideLine(x - width / 2, y, x + w - 1 + width / 2, y, width); ptaJoin(ptad, pta, 0, -1); ptaDestroy(&pta); pta = generatePtaWideLine(x + w - 1, y + 1 + width / 2, x + w - 1, y + h - 2 - width / 2, width); ptaJoin(ptad, pta, 0, -1); ptaDestroy(&pta); pta = generatePtaWideLine(x + w - 1 + width / 2, y + h - 1, x - width / 2, y + h - 1, width); ptaJoin(ptad, pta, 0, -1); ptaDestroy(&pta); pta = generatePtaWideLine(x, y + h - 2 - width / 2, x, y + 1 + width / 2, width); ptaJoin(ptad, pta, 0, -1); ptaDestroy(&pta); } else /* even width */ { pta = generatePtaWideLine(x - width / 2, y, x + w - 2 + width / 2, y, width); ptaJoin(ptad, pta, 0, -1); ptaDestroy(&pta); pta = generatePtaWideLine(x + w - 1, y + 0 + width / 2, x + w - 1, y + h - 2 - width / 2, width); ptaJoin(ptad, pta, 0, -1); ptaDestroy(&pta); pta = generatePtaWideLine(x + w - 2 + width / 2, y + h - 1, x - width / 2, y + h - 1, width); ptaJoin(ptad, pta, 0, -1); ptaDestroy(&pta); pta = generatePtaWideLine(x, y + h - 2 - width / 2, x, y + 0 + width / 2, width); ptaJoin(ptad, pta, 0, -1); ptaDestroy(&pta); } return ptad; } /*! * generatePtaBoxa() * * Input: boxa * width * removedups (1 to remove, 0 to leave) * Return: ptad, or null on error * * Notes: * (1) If the boxa has overlapping boxes, and if blending will * be used to give a transparent effect, transparency * artifacts at line intersections can be removed using * removedups = 1. */ PTA * generatePtaBoxa(BOXA *boxa, l_int32 width, l_int32 removedups) { l_int32 i, n; BOX *box; PTA *ptad, *ptat, *pta; PROCNAME("generatePtaBoxa"); if (!boxa) { return (PTA *)ERROR_PTR("boxa not defined", procName, NULL); } if (width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } n = boxaGetCount(boxa); ptat = ptaCreate(0); for (i = 0; i < n; i++) { box = boxaGetBox(boxa, i, L_CLONE); pta = generatePtaBox(box, width); ptaJoin(ptat, pta, 0, -1); ptaDestroy(&pta); boxDestroy(&box); } if (removedups) { ptad = ptaRemoveDuplicates(ptat, 0); } else { ptad = ptaClone(ptat); } ptaDestroy(&ptat); return ptad; } /*! * generatePtaHashBox() * * Input: box * spacing (spacing between lines; must be > 1) * width (of line) * orient (orientation of lines: L_HORIZONTAL_LINE, ...) * outline (0 to skip drawing box outline) * Return: ptad, or null on error * * Notes: * (1) The orientation takes on one of 4 orientations (horiz, vertical, * slope +1, slope -1). * (2) The full outline is also drawn if @outline = 1. */ PTA * generatePtaHashBox(BOX *box, l_int32 spacing, l_int32 width, l_int32 orient, l_int32 outline) { l_int32 bx, by, bh, bw, x, y, x1, y1, x2, y2, i, n, npts; PTA *ptad, *pta; PROCNAME("generatePtaHashBox"); if (!box) { return (PTA *)ERROR_PTR("box not defined", procName, NULL); } if (spacing <= 1) { return (PTA *)ERROR_PTR("spacing not > 1", procName, NULL); } if (orient != L_HORIZONTAL_LINE && orient != L_POS_SLOPE_LINE && orient != L_VERTICAL_LINE && orient != L_NEG_SLOPE_LINE) { return (PTA *)ERROR_PTR("invalid line orientation", procName, NULL); } boxGetGeometry(box, &bx, &by, &bw, &bh); if (bw == 0 || bh == 0) { return (PTA *)ERROR_PTR("box has bw = 0 or bh = 0", procName, NULL); } if (width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } /* Generate line points and add them to the pta. */ ptad = ptaCreate(0); if (outline) { pta = generatePtaBox(box, width); ptaJoin(ptad, pta, 0, -1); ptaDestroy(&pta); } if (orient == L_HORIZONTAL_LINE) { n = 1 + bh / spacing; for (i = 0; i < n; i++) { y = by + (i * (bh - 1)) / (n - 1); pta = generatePtaWideLine(bx, y, bx + bw - 1, y, width); ptaJoin(ptad, pta, 0, -1); ptaDestroy(&pta); } } else if (orient == L_VERTICAL_LINE) { n = 1 + bw / spacing; for (i = 0; i < n; i++) { x = bx + (i * (bw - 1)) / (n - 1); pta = generatePtaWideLine(x, by, x, by + bh - 1, width); ptaJoin(ptad, pta, 0, -1); ptaDestroy(&pta); } } else if (orient == L_POS_SLOPE_LINE) { n = 2 + (l_int32)((bw + bh) / (1.4 * spacing)); for (i = 0; i < n; i++) { x = (l_int32)(bx + (i + 0.5) * 1.4 * spacing); boxIntersectByLine(box, x, by - 1, 1.0, &x1, &y1, &x2, &y2, &npts); if (npts == 2) { pta = generatePtaWideLine(x1, y1, x2, y2, width); ptaJoin(ptad, pta, 0, -1); ptaDestroy(&pta); } } } else /* orient == L_NEG_SLOPE_LINE */ { n = 2 + (l_int32)((bw + bh) / (1.4 * spacing)); for (i = 0; i < n; i++) { x = (l_int32)(bx - bh + (i + 0.5) * 1.4 * spacing); boxIntersectByLine(box, x, by - 1, -1.0, &x1, &y1, &x2, &y2, &npts); if (npts == 2) { pta = generatePtaWideLine(x1, y1, x2, y2, width); ptaJoin(ptad, pta, 0, -1); ptaDestroy(&pta); } } } return ptad; } /*! * generatePtaHashBoxa() * * Input: boxa * spacing (spacing between lines; must be > 1) * width (of line) * orient (orientation of lines: L_HORIZONTAL_LINE, ...) * outline (0 to skip drawing box outline) * removedups (1 to remove, 0 to leave) * Return: ptad, or null on error * * Notes: * (1) The orientation takes on one of 4 orientations (horiz, vertical, * slope +1, slope -1). * (2) The full outline is also drawn if @outline = 1. * (3) If the boxa has overlapping boxes, and if blending will * be used to give a transparent effect, transparency * artifacts at line intersections can be removed using * removedups = 1. */ PTA * generatePtaHashBoxa(BOXA *boxa, l_int32 spacing, l_int32 width, l_int32 orient, l_int32 outline, l_int32 removedups) { l_int32 i, n; BOX *box; PTA *ptad, *ptat, *pta; PROCNAME("generatePtaHashBoxa"); if (!boxa) { return (PTA *)ERROR_PTR("boxa not defined", procName, NULL); } if (spacing <= 1) { return (PTA *)ERROR_PTR("spacing not > 1", procName, NULL); } if (width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } if (orient != L_HORIZONTAL_LINE && orient != L_POS_SLOPE_LINE && orient != L_VERTICAL_LINE && orient != L_NEG_SLOPE_LINE) { return (PTA *)ERROR_PTR("invalid line orientation", procName, NULL); } n = boxaGetCount(boxa); ptat = ptaCreate(0); for (i = 0; i < n; i++) { box = boxaGetBox(boxa, i, L_CLONE); pta = generatePtaHashBox(box, spacing, width, orient, outline); ptaJoin(ptat, pta, 0, -1); ptaDestroy(&pta); boxDestroy(&box); } if (removedups) { ptad = ptaRemoveDuplicates(ptat, 0); } else { ptad = ptaClone(ptat); } ptaDestroy(&ptat); return ptad; } /*! * generatePtaaBoxa() * * Input: boxa * Return: ptaa, or null on error * * Notes: * (1) This generates a pta of the four corners for each box in * the boxa. * (2) Each of these pta can be rendered onto a pix with random colors, * by using pixRenderRandomCmapPtaa() with closeflag = 1. */ PTAA * generatePtaaBoxa(BOXA *boxa) { l_int32 i, n, x, y, w, h; BOX *box; PTA *pta; PTAA *ptaa; PROCNAME("generatePtaaBoxa"); if (!boxa) { return (PTAA *)ERROR_PTR("boxa not defined", procName, NULL); } n = boxaGetCount(boxa); ptaa = ptaaCreate(n); for (i = 0; i < n; i++) { box = boxaGetBox(boxa, i, L_CLONE); boxGetGeometry(box, &x, &y, &w, &h); pta = ptaCreate(4); ptaAddPt(pta, x, y); ptaAddPt(pta, x + w - 1, y); ptaAddPt(pta, x + w - 1, y + h - 1); ptaAddPt(pta, x, y + h - 1); ptaaAddPta(ptaa, pta, L_INSERT); boxDestroy(&box); } return ptaa; } /*! * generatePtaaHashBoxa() * * Input: boxa * spacing (spacing between hash lines; must be > 1) * width (hash line width) * orient (orientation of lines: L_HORIZONTAL_LINE, ...) * outline (0 to skip drawing box outline) * Return: ptaa, or null on error * * Notes: * (1) The orientation takes on one of 4 orientations (horiz, vertical, * slope +1, slope -1). * (2) The full outline is also drawn if @outline = 1. * (3) Each of these pta can be rendered onto a pix with random colors, * by using pixRenderRandomCmapPtaa() with closeflag = 1. * */ PTAA * generatePtaaHashBoxa(BOXA *boxa, l_int32 spacing, l_int32 width, l_int32 orient, l_int32 outline) { l_int32 i, n; BOX *box; PTA *pta; PTAA *ptaa; PROCNAME("generatePtaaHashBoxa"); if (!boxa) { return (PTAA *)ERROR_PTR("boxa not defined", procName, NULL); } if (spacing <= 1) { return (PTAA *)ERROR_PTR("spacing not > 1", procName, NULL); } if (width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } if (orient != L_HORIZONTAL_LINE && orient != L_POS_SLOPE_LINE && orient != L_VERTICAL_LINE && orient != L_NEG_SLOPE_LINE) { return (PTAA *)ERROR_PTR("invalid line orientation", procName, NULL); } n = boxaGetCount(boxa); ptaa = ptaaCreate(n); for (i = 0; i < n; i++) { box = boxaGetBox(boxa, i, L_CLONE); pta = generatePtaHashBox(box, spacing, width, orient, outline); ptaaAddPta(ptaa, pta, L_INSERT); boxDestroy(&box); } return ptaa; } /*! * generatePtaPolyline() * * Input: pta (vertices of polyline) * width * closeflag (1 to close the contour; 0 otherwise) * removedups (1 to remove, 0 to leave) * Return: ptad, or null on error */ PTA * generatePtaPolyline(PTA *ptas, l_int32 width, l_int32 closeflag, l_int32 removedups) { l_int32 i, n, x1, y1, x2, y2; PTA *ptad, *ptat, *pta; PROCNAME("generatePtaPolyline"); if (!ptas) { return (PTA *)ERROR_PTR("ptas not defined", procName, NULL); } if (width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } n = ptaGetCount(ptas); ptat = ptaCreate(0); if (n < 2) /* nothing to do */ { return ptat; } ptaGetIPt(ptas, 0, &x1, &y1); for (i = 1; i < n; i++) { ptaGetIPt(ptas, i, &x2, &y2); pta = generatePtaWideLine(x1, y1, x2, y2, width); ptaJoin(ptat, pta, 0, -1); ptaDestroy(&pta); x1 = x2; y1 = y2; } if (closeflag) { ptaGetIPt(ptas, 0, &x2, &y2); pta = generatePtaWideLine(x1, y1, x2, y2, width); ptaJoin(ptat, pta, 0, -1); ptaDestroy(&pta); } if (removedups) { ptad = ptaRemoveDuplicates(ptat, 0); } else { ptad = ptaClone(ptat); } ptaDestroy(&ptat); return ptad; } /*! * convertPtaLineTo4cc() * * Input: ptas (8-connected line of points) * Return: ptad (4-connected line), or null on error * * Notes: * (1) When a polyline is generated with width = 1, the resulting * line is not 4-connected in general. This function adds * points as necessary to convert the line to 4-cconnected. * It is useful when rendering 1 bpp on a pix. * (2) Do not use this for lines generated with width > 1. */ PTA * convertPtaLineTo4cc(PTA *ptas) { l_int32 i, n, x, y, xp, yp; PTA *ptad; PROCNAME("convertPtaLineTo4cc"); if (!ptas) { return (PTA *)ERROR_PTR("ptas not defined", procName, NULL); } n = ptaGetCount(ptas); ptad = ptaCreate(n); ptaGetIPt(ptas, 0, &xp, &yp); ptaAddPt(ptad, xp, yp); for (i = 1; i < n; i++) { ptaGetIPt(ptas, i, &x, &y); if (x != xp && y != yp) /* diagonal */ { ptaAddPt(ptad, x, yp); } ptaAddPt(ptad, x, y); xp = x; yp = y; } return ptad; } /*! * generatePtaFilledCircle() * * Input: radius * Return: pta, or null on error * * Notes: * (1) The circle is has diameter = 2 * radius + 1. * (2) It is located with the center of the circle at the * point (radius, radius). * (3) Consequently, it typically must be translated if * it is to represent a set of pixels in an image. */ PTA * generatePtaFilledCircle(l_int32 radius) { l_int32 x, y; l_float32 radthresh, sqdist; PTA *pta; PROCNAME("generatePtaFilledCircle"); if (radius < 1) { return (PTA *)ERROR_PTR("radius must be >= 1", procName, NULL); } pta = ptaCreate(0); radthresh = (radius + 0.5) * (radius + 0.5); for (y = 0; y <= 2 * radius; y++) { for (x = 0; x <= 2 * radius; x++) { sqdist = (l_float32)((y - radius) * (y - radius) + (x - radius) * (x - radius)); if (sqdist <= radthresh) { ptaAddPt(pta, x, y); } } } return pta; } /*! * generatePtaFilledSquare() * * Input: side * Return: pta, or null on error * * Notes: * (1) The center of the square can be chosen to be at * (side / 2, side / 2). It must be translated by this amount * when used for replication. */ PTA * generatePtaFilledSquare(l_int32 side) { l_int32 x, y; PTA *pta; PROCNAME("generatePtaFilledSquare"); if (side < 1) { return (PTA *)ERROR_PTR("side must be > 0", procName, NULL); } pta = ptaCreate(0); for (y = 0; y < side; y++) for (x = 0; x < side; x++) { ptaAddPt(pta, x, y); } return pta; } /*! * generatePtaLineFromPt() * * Input: x, y (point of origination) * length (of line, including starting point) * radang (angle in radians, CW from horizontal) * Return: pta, or null on error * * Notes: * (1) The @length of the line is 1 greater than the distance * used in locatePtRadially(). Example: a distance of 1 * gives rise to a length of 2. */ PTA * generatePtaLineFromPt(l_int32 x, l_int32 y, l_float64 length, l_float64 radang) { l_int32 x2, y2; /* the point at the other end of the line */ x2 = x + (l_int32)((length - 1.0) * cos(radang)); y2 = y + (l_int32)((length - 1.0) * sin(radang)); return generatePtaLine(x, y, x2, y2); } /*! * locatePtRadially() * * Input: xr, yr (reference point) * radang (angle in radians, CW from horizontal) * dist (distance of point from reference point along line * given by the specified angle) * &x, &y (<return> location of point) * Return: 0 if OK, 1 on error */ l_int32 locatePtRadially(l_int32 xr, l_int32 yr, l_float64 dist, l_float64 radang, l_float64 *px, l_float64 *py) { PROCNAME("locatePtRadially"); if (!px || !py) { return ERROR_INT("&x and &y not both defined", procName, 1); } *px = xr + dist * cos(radang); *py = yr + dist * sin(radang); return 0; } /*------------------------------------------------------------------* * Rendering function plots directly on images * *------------------------------------------------------------------*/ /*! * pixRenderPlotFromNuma() * * Input: &pix (any type; replaced if not 32 bpp rgb) * numa (to be plotted) * plotloc (location of plot: L_PLOT_AT_TOP, etc) * linewidth (width of "line" that is drawn; between 1 and 7) * max (maximum excursion in pixels from baseline) * color (plot color: 0xrrggbb00) * Return: 0 if OK, 1 on error * * Notes: * (1) Simplified interface for plotting row or column aligned data * on a pix. * (2) This replaces @pix with a 32 bpp rgb version if it is not * already 32 bpp. It then draws the plot on the pix. * (3) See makePlotPtaFromNumaGen() for more details. */ l_int32 pixRenderPlotFromNuma(PIX **ppix, NUMA *na, l_int32 plotloc, l_int32 linewidth, l_int32 max, l_uint32 color) { l_int32 w, h, size, rval, gval, bval; PIX *pix1; PTA *pta; PROCNAME("pixRenderPlotFromNuma"); if (!ppix) { return ERROR_INT("&pix not defined", procName, 1); } if (*ppix == NULL) { return ERROR_INT("pix not defined", procName, 1); } pixGetDimensions(*ppix, &w, &h, NULL); size = (plotloc == L_PLOT_AT_TOP || plotloc == L_PLOT_AT_MID_HORIZ || plotloc == L_PLOT_AT_BOT) ? h : w; pta = makePlotPtaFromNuma(na, size, plotloc, linewidth, max); if (!pta) { return ERROR_INT("pta not made", procName, 1); } if (pixGetDepth(*ppix) != 32) { pix1 = pixConvertTo32(*ppix); pixDestroy(ppix); *ppix = pix1; } extractRGBValues(color, &rval, &gval, &bval); pixRenderPtaArb(*ppix, pta, rval, gval, bval); ptaDestroy(&pta); return 0; } /*! * makePlotPtaFromNuma() * * Input: numa * size (pix height for horizontal plot; width for vertical plot) * plotloc (location of plot: L_PLOT_AT_TOP, etc) * linewidth (width of "line" that is drawn; between 1 and 7) * max (maximum excursion in pixels from baseline) * Return: ptad, or null on error * * Notes: * (1) This generates points from @numa representing y(x) or x(y) * with respect to a pix. A horizontal plot y(x) is drawn for * a function of column position, and a vertical plot is drawn * for a function x(y) of row position. The baseline is located * so that all plot points will fit in the pix. * (2) See makePlotPtaFromNumaGen() for more details. */ PTA * makePlotPtaFromNuma(NUMA *na, l_int32 size, l_int32 plotloc, l_int32 linewidth, l_int32 max) { l_int32 orient, refpos; PROCNAME("makePlotPtaFromNuma"); if (!na) { return (PTA *)ERROR_PTR("na not defined", procName, NULL); } if (plotloc == L_PLOT_AT_TOP || plotloc == L_PLOT_AT_MID_HORIZ || plotloc == L_PLOT_AT_BOT) { orient = L_HORIZONTAL_LINE; } else if (plotloc == L_PLOT_AT_LEFT || plotloc == L_PLOT_AT_MID_VERT || plotloc == L_PLOT_AT_RIGHT) { orient = L_VERTICAL_LINE; } else { return (PTA *)ERROR_PTR("invalid plotloc", procName, NULL); } if (plotloc == L_PLOT_AT_LEFT || plotloc == L_PLOT_AT_TOP) { refpos = max; } else if (plotloc == L_PLOT_AT_MID_VERT || plotloc == L_PLOT_AT_MID_HORIZ) { refpos = size / 2; } else /* L_PLOT_AT_RIGHT || L_PLOT_AT_BOT */ { refpos = size - max - 1; } return makePlotPtaFromNumaGen(na, orient, linewidth, refpos, max, 1); } /*! * pixRenderPlotFromNumaGen() * * Input: &pix (any type; replaced if not 32 bpp rgb) * numa (to be plotted) * orient (L_HORIZONTAL_LINE, L_VERTICAL_LINE) * linewidth (width of "line" that is drawn; between 1 and 7) * refpos (reference position: y for horizontal and x for vertical) * max (maximum excursion in pixels from baseline) * drawref (1 to draw the reference line and the normal to it) * color (plot color: 0xrrggbb00) * Return: 0 if OK, 1 on error * * Notes: * (1) General interface for plotting row or column aligned data * on a pix. * (2) This replaces @pix with a 32 bpp rgb version if it is not * already 32 bpp. It then draws the plot on the pix. * (3) See makePlotPtaFromNumaGen() for other input parameters. */ l_int32 pixRenderPlotFromNumaGen(PIX **ppix, NUMA *na, l_int32 orient, l_int32 linewidth, l_int32 refpos, l_int32 max, l_int32 drawref, l_uint32 color) { l_int32 rval, gval, bval; PIX *pix1; PTA *pta; PROCNAME("pixRenderPlotFromNumaGen"); if (!ppix) { return ERROR_INT("&pix not defined", procName, 1); } if (*ppix == NULL) { return ERROR_INT("pix not defined", procName, 1); } pta = makePlotPtaFromNumaGen(na, orient, linewidth, refpos, max, drawref); if (!pta) { return ERROR_INT("pta not made", procName, 1); } if (pixGetDepth(*ppix) != 32) { pix1 = pixConvertTo32(*ppix); pixDestroy(ppix); *ppix = pix1; } extractRGBValues(color, &rval, &gval, &bval); pixRenderPtaArb(*ppix, pta, rval, gval, bval); ptaDestroy(&pta); return 0; } /*! * makePlotPtaFromNumaGen() * * Input: numa * orient (L_HORIZONTAL_LINE, L_VERTICAL_LINE) * linewidth (width of "line" that is drawn; between 1 and 7) * refpos (reference position: y for horizontal and x for vertical) * max (maximum excursion in pixels from baseline) * drawref (1 to draw the reference line and the normal to it) * Return: ptad, or null on error * * Notes: * (1) This generates points from @numa representing y(x) or x(y) * with respect to a pix. For y(x), we draw a horizontal line * at the reference position and a vertical line at the edge; then * we draw the values of @numa, scaled so that the maximum * excursion from the reference position is @max pixels. * (2) The start and delx parameters of @numa are used to refer * its values to the raster lines (L_VERTICAL_LINE) or columns * (L_HORIZONTAL_LINE). * (3) The linewidth is chosen in the interval [1 ... 7]. * (4) @refpos should be chosen so the plot is entirely within the pix * that it will be painted onto. * (5) This would typically be used to plot, in place, a function * computed along pixel rows or columns. */ PTA * makePlotPtaFromNumaGen(NUMA *na, l_int32 orient, l_int32 linewidth, l_int32 refpos, l_int32 max, l_int32 drawref) { l_int32 i, n, maxw, maxh; l_float32 minval, maxval, absval, val, scale, start, del; PTA *pta1, *pta2, *ptad; PROCNAME("makePlotPtaFromNumaGen"); if (!na) { return (PTA *)ERROR_PTR("na not defined", procName, NULL); } if (orient != L_HORIZONTAL_LINE && orient != L_VERTICAL_LINE) { return (PTA *)ERROR_PTR("invalid orient", procName, NULL); } if (linewidth < 1) { L_WARNING("linewidth < 1; setting to 1\n", procName); linewidth = 1; } if (linewidth > 7) { L_WARNING("linewidth > 7; setting to 7\n", procName); linewidth = 7; } numaGetMin(na, &minval, NULL); numaGetMax(na, &maxval, NULL); absval = L_MAX(L_ABS(minval), L_ABS(maxval)); scale = (l_float32)max / (l_float32)absval; n = numaGetCount(na); numaGetParameters(na, &start, &del); /* Generate the plot points */ pta1 = ptaCreate(n); for (i = 0; i < n; i++) { numaGetFValue(na, i, &val); if (orient == L_HORIZONTAL_LINE) { ptaAddPt(pta1, start + i * del, refpos + scale * val); maxw = (del >= 0) ? start + n * del + linewidth : start + linewidth; maxh = refpos + max + linewidth; } else /* vertical line */ { ptaAddPt(pta1, refpos + scale * val, start + i * del); maxw = refpos + max + linewidth; maxh = (del >= 0) ? start + n * del + linewidth : start + linewidth; } } /* Optionally, widen the plot */ if (linewidth > 1) { if (linewidth % 2 == 0) /* even linewidth; use side of a square */ { pta2 = generatePtaFilledSquare(linewidth); } else /* odd linewidth; use radius of a circle */ { pta2 = generatePtaFilledCircle(linewidth / 2); } ptad = ptaReplicatePattern(pta1, NULL, pta2, linewidth / 2, linewidth / 2, maxw, maxh); ptaDestroy(&pta2); } else { ptad = ptaClone(pta1); } ptaDestroy(&pta1); /* Optionally, add the reference lines */ if (drawref) { if (orient == L_HORIZONTAL_LINE) { pta1 = generatePtaLine(start, refpos, start + n * del, refpos); ptaJoin(ptad, pta1, 0, -1); ptaDestroy(&pta1); pta1 = generatePtaLine(start, refpos - max, start, refpos + max); ptaJoin(ptad, pta1, 0, -1); } else /* vertical line */ { pta1 = generatePtaLine(refpos, start, refpos, start + n * del); ptaJoin(ptad, pta1, 0, -1); ptaDestroy(&pta1); pta1 = generatePtaLine(refpos - max, start, refpos + max, start); ptaJoin(ptad, pta1, 0, -1); } ptaDestroy(&pta1); } return ptad; } /*------------------------------------------------------------------* * Pta generation for arbitrary shapes built with lines * *------------------------------------------------------------------*/ /*! * pixRenderPta() * * Input: pix * pta (arbitrary set of points) * op (one of L_SET_PIXELS, L_CLEAR_PIXELS, L_FLIP_PIXELS) * Return: 0 if OK, 1 on error * * Notes: * (1) L_SET_PIXELS puts all image bits in each pixel to 1 * (black for 1 bpp; white for depth > 1) * (2) L_CLEAR_PIXELS puts all image bits in each pixel to 0 * (white for 1 bpp; black for depth > 1) * (3) L_FLIP_PIXELS reverses all image bits in each pixel * (4) This function clips the rendering to the pix. It performs * clipping for functions such as pixRenderLine(), * pixRenderBox() and pixRenderBoxa(), that call pixRenderPta(). */ l_int32 pixRenderPta(PIX *pix, PTA *pta, l_int32 op) { l_int32 i, n, x, y, w, h, d, maxval; PROCNAME("pixRenderPta"); if (!pix) { return ERROR_INT("pix not defined", procName, 1); } if (!pta) { return ERROR_INT("pta not defined", procName, 1); } if (op != L_SET_PIXELS && op != L_CLEAR_PIXELS && op != L_FLIP_PIXELS) { return ERROR_INT("invalid op", procName, 1); } pixGetDimensions(pix, &w, &h, &d); maxval = 1; if (op == L_SET_PIXELS) { switch (d) { case 2: maxval = 0x3; break; case 4: maxval = 0xf; break; case 8: maxval = 0xff; break; case 16: maxval = 0xffff; break; case 32: maxval = 0xffffffff; break; } } n = ptaGetCount(pta); for (i = 0; i < n; i++) { ptaGetIPt(pta, i, &x, &y); if (x < 0 || x >= w) { continue; } if (y < 0 || y >= h) { continue; } switch (op) { case L_SET_PIXELS: pixSetPixel(pix, x, y, maxval); break; case L_CLEAR_PIXELS: pixClearPixel(pix, x, y); break; case L_FLIP_PIXELS: pixFlipPixel(pix, x, y); break; default: break; } } return 0; } /*! * pixRenderPtaArb() * * Input: pix (any depth, cmapped ok) * pta (arbitrary set of points) * rval, gval, bval * Return: 0 if OK, 1 on error * * Notes: * (1) If pix is colormapped, render this color (or the nearest * color if the cmap is full) on each pixel. * (2) If pix is not colormapped, do the best job you can using * the input colors: * - d = 1: set the pixels * - d = 2, 4, 8: average the input rgb value * - d = 32: use the input rgb value * (3) This function clips the rendering to the pix. */ l_int32 pixRenderPtaArb(PIX *pix, PTA *pta, l_uint8 rval, l_uint8 gval, l_uint8 bval) { l_int32 i, n, x, y, w, h, d, index; l_uint8 val; l_uint32 val32; PIXCMAP *cmap; PROCNAME("pixRenderPtaArb"); if (!pix) { return ERROR_INT("pix not defined", procName, 1); } if (!pta) { return ERROR_INT("pta not defined", procName, 1); } d = pixGetDepth(pix); if (d != 1 && d != 2 && d != 4 && d != 8 && d != 32) { return ERROR_INT("depth not in {1,2,4,8,32}", procName, 1); } if (d == 1) { pixRenderPta(pix, pta, L_SET_PIXELS); return 0; } cmap = pixGetColormap(pix); pixGetDimensions(pix, &w, &h, &d); if (cmap) { pixcmapAddNearestColor(cmap, rval, gval, bval, &index); } else { if (d == 2) { val = (rval + gval + bval) / (3 * 64); } else if (d == 4) { val = (rval + gval + bval) / (3 * 16); } else if (d == 8) { val = (rval + gval + bval) / 3; } else /* d == 32 */ { composeRGBPixel(rval, gval, bval, &val32); } } n = ptaGetCount(pta); for (i = 0; i < n; i++) { ptaGetIPt(pta, i, &x, &y); if (x < 0 || x >= w) { continue; } if (y < 0 || y >= h) { continue; } if (cmap) { pixSetPixel(pix, x, y, index); } else if (d == 32) { pixSetPixel(pix, x, y, val32); } else { pixSetPixel(pix, x, y, val); } } return 0; } /*! * pixRenderPtaBlend() * * Input: pix (32 bpp rgb) * pta (arbitrary set of points) * rval, gval, bval * Return: 0 if OK, 1 on error * * Notes: * (1) This function clips the rendering to the pix. */ l_int32 pixRenderPtaBlend(PIX *pix, PTA *pta, l_uint8 rval, l_uint8 gval, l_uint8 bval, l_float32 fract) { l_int32 i, n, x, y, w, h; l_uint8 nrval, ngval, nbval; l_uint32 val32; l_float32 frval, fgval, fbval; PROCNAME("pixRenderPtaBlend"); if (!pix) { return ERROR_INT("pix not defined", procName, 1); } if (!pta) { return ERROR_INT("pta not defined", procName, 1); } if (pixGetDepth(pix) != 32) { return ERROR_INT("depth not 32 bpp", procName, 1); } if (fract < 0.0 || fract > 1.0) { L_WARNING("fract must be in [0.0, 1.0]; setting to 0.5\n", procName); fract = 0.5; } pixGetDimensions(pix, &w, &h, NULL); n = ptaGetCount(pta); frval = fract * rval; fgval = fract * gval; fbval = fract * bval; for (i = 0; i < n; i++) { ptaGetIPt(pta, i, &x, &y); if (x < 0 || x >= w) { continue; } if (y < 0 || y >= h) { continue; } pixGetPixel(pix, x, y, &val32); nrval = GET_DATA_BYTE(&val32, COLOR_RED); nrval = (l_uint8)((1. - fract) * nrval + frval); ngval = GET_DATA_BYTE(&val32, COLOR_GREEN); ngval = (l_uint8)((1. - fract) * ngval + fgval); nbval = GET_DATA_BYTE(&val32, COLOR_BLUE); nbval = (l_uint8)((1. - fract) * nbval + fbval); composeRGBPixel(nrval, ngval, nbval, &val32); pixSetPixel(pix, x, y, val32); } return 0; } /*------------------------------------------------------------------* * Rendering of arbitrary shapes built with lines * *------------------------------------------------------------------*/ /*! * pixRenderLine() * * Input: pix * x1, y1 * x2, y2 * width (thickness of line) * op (one of L_SET_PIXELS, L_CLEAR_PIXELS, L_FLIP_PIXELS) * Return: 0 if OK, 1 on error */ l_int32 pixRenderLine(PIX *pix, l_int32 x1, l_int32 y1, l_int32 x2, l_int32 y2, l_int32 width, l_int32 op) { PTA *pta; PROCNAME("pixRenderLine"); if (!pix) { return ERROR_INT("pix not defined", procName, 1); } if (width < 1) { L_WARNING("width must be > 0; setting to 1\n", procName); width = 1; } if (op != L_SET_PIXELS && op != L_CLEAR_PIXELS && op != L_FLIP_PIXELS) { return ERROR_INT("invalid op", procName, 1); } if ((pta = generatePtaWideLine(x1, y1, x2, y2, width)) == NULL) { return ERROR_INT("pta not made", procName, 1); } pixRenderPta(pix, pta, op); ptaDestroy(&pta); return 0; } /*! * pixRenderLineArb() * * Input: pix * x1, y1 * x2, y2 * width (thickness of line) * rval, gval, bval * Return: 0 if OK, 1 on error */ l_int32 pixRenderLineArb(PIX *pix, l_int32 x1, l_int32 y1, l_int32 x2, l_int32 y2, l_int32 width, l_uint8 rval, l_uint8 gval, l_uint8 bval) { PTA *pta; PROCNAME("pixRenderLineArb"); if (!pix) { return ERROR_INT("pix not defined", procName, 1); } if (width < 1) { L_WARNING("width must be > 0; setting to 1\n", procName); width = 1; } if ((pta = generatePtaWideLine(x1, y1, x2, y2, width)) == NULL) { return ERROR_INT("pta not made", procName, 1); } pixRenderPtaArb(pix, pta, rval, gval, bval); ptaDestroy(&pta); return 0; } /*! * pixRenderLineBlend() * * Input: pix * x1, y1 * x2, y2 * width (thickness of line) * rval, gval, bval * fract * Return: 0 if OK, 1 on error */ l_int32 pixRenderLineBlend(PIX *pix, l_int32 x1, l_int32 y1, l_int32 x2, l_int32 y2, l_int32 width, l_uint8 rval, l_uint8 gval, l_uint8 bval, l_float32 fract) { PTA *pta; PROCNAME("pixRenderLineBlend"); if (!pix) { return ERROR_INT("pix not defined", procName, 1); } if (width < 1) { L_WARNING("width must be > 0; setting to 1\n", procName); width = 1; } if ((pta = generatePtaWideLine(x1, y1, x2, y2, width)) == NULL) { return ERROR_INT("pta not made", procName, 1); } pixRenderPtaBlend(pix, pta, rval, gval, bval, fract); ptaDestroy(&pta); return 0; } /*! * pixRenderBox() * * Input: pix * box * width (thickness of box lines) * op (one of L_SET_PIXELS, L_CLEAR_PIXELS, L_FLIP_PIXELS) * Return: 0 if OK, 1 on error */ l_int32 pixRenderBox(PIX *pix, BOX *box, l_int32 width, l_int32 op) { PTA *pta; PROCNAME("pixRenderBox"); if (!pix) { return ERROR_INT("pix not defined", procName, 1); } if (!box) { return ERROR_INT("box not defined", procName, 1); } if (width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } if (op != L_SET_PIXELS && op != L_CLEAR_PIXELS && op != L_FLIP_PIXELS) { return ERROR_INT("invalid op", procName, 1); } if ((pta = generatePtaBox(box, width)) == NULL) { return ERROR_INT("pta not made", procName, 1); } pixRenderPta(pix, pta, op); ptaDestroy(&pta); return 0; } /*! * pixRenderBoxArb() * * Input: pix (any depth, cmapped ok) * box * width (thickness of box lines) * rval, gval, bval * Return: 0 if OK, 1 on error */ l_int32 pixRenderBoxArb(PIX *pix, BOX *box, l_int32 width, l_uint8 rval, l_uint8 gval, l_uint8 bval) { PTA *pta; PROCNAME("pixRenderBoxArb"); if (!pix) { return ERROR_INT("pix not defined", procName, 1); } if (!box) { return ERROR_INT("box not defined", procName, 1); } if (width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } if ((pta = generatePtaBox(box, width)) == NULL) { return ERROR_INT("pta not made", procName, 1); } pixRenderPtaArb(pix, pta, rval, gval, bval); ptaDestroy(&pta); return 0; } /*! * pixRenderBoxBlend() * * Input: pix * box * width (thickness of box lines) * rval, gval, bval * fract (in [0.0 - 1.0]; complete transparency (no effect) * if 0.0; no transparency if 1.0) * Return: 0 if OK, 1 on error */ l_int32 pixRenderBoxBlend(PIX *pix, BOX *box, l_int32 width, l_uint8 rval, l_uint8 gval, l_uint8 bval, l_float32 fract) { PTA *pta; PROCNAME("pixRenderBoxBlend"); if (!pix) { return ERROR_INT("pix not defined", procName, 1); } if (!box) { return ERROR_INT("box not defined", procName, 1); } if (width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } if ((pta = generatePtaBox(box, width)) == NULL) { return ERROR_INT("pta not made", procName, 1); } pixRenderPtaBlend(pix, pta, rval, gval, bval, fract); ptaDestroy(&pta); return 0; } /*! * pixRenderBoxa() * * Input: pix * boxa * width (thickness of line) * op (one of L_SET_PIXELS, L_CLEAR_PIXELS, L_FLIP_PIXELS) * Return: 0 if OK, 1 on error */ l_int32 pixRenderBoxa(PIX *pix, BOXA *boxa, l_int32 width, l_int32 op) { PTA *pta; PROCNAME("pixRenderBoxa"); if (!pix) { return ERROR_INT("pix not defined", procName, 1); } if (!boxa) { return ERROR_INT("boxa not defined", procName, 1); } if (width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } if (op != L_SET_PIXELS && op != L_CLEAR_PIXELS && op != L_FLIP_PIXELS) { return ERROR_INT("invalid op", procName, 1); } if ((pta = generatePtaBoxa(boxa, width, 0)) == NULL) { return ERROR_INT("pta not made", procName, 1); } pixRenderPta(pix, pta, op); ptaDestroy(&pta); return 0; } /*! * pixRenderBoxaArb() * * Input: pix * boxa * width (thickness of line) * rval, gval, bval * Return: 0 if OK, 1 on error */ l_int32 pixRenderBoxaArb(PIX *pix, BOXA *boxa, l_int32 width, l_uint8 rval, l_uint8 gval, l_uint8 bval) { PTA *pta; PROCNAME("pixRenderBoxaArb"); if (!pix) { return ERROR_INT("pix not defined", procName, 1); } if (!boxa) { return ERROR_INT("boxa not defined", procName, 1); } if (width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } if ((pta = generatePtaBoxa(boxa, width, 0)) == NULL) { return ERROR_INT("pta not made", procName, 1); } pixRenderPtaArb(pix, pta, rval, gval, bval); ptaDestroy(&pta); return 0; } /*! * pixRenderBoxaBlend() * * Input: pix * boxa * width (thickness of line) * rval, gval, bval * fract (in [0.0 - 1.0]; complete transparency (no effect) * if 0.0; no transparency if 1.0) * removedups (1 to remove; 0 otherwise) * Return: 0 if OK, 1 on error */ l_int32 pixRenderBoxaBlend(PIX *pix, BOXA *boxa, l_int32 width, l_uint8 rval, l_uint8 gval, l_uint8 bval, l_float32 fract, l_int32 removedups) { PTA *pta; PROCNAME("pixRenderBoxaBlend"); if (!pix) { return ERROR_INT("pix not defined", procName, 1); } if (!boxa) { return ERROR_INT("boxa not defined", procName, 1); } if (width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } if ((pta = generatePtaBoxa(boxa, width, removedups)) == NULL) { return ERROR_INT("pta not made", procName, 1); } pixRenderPtaBlend(pix, pta, rval, gval, bval, fract); ptaDestroy(&pta); return 0; } /*! * pixRenderHashBox() * * Input: pix * box * spacing (spacing between lines; must be > 1) * width (thickness of box and hash lines) * orient (orientation of lines: L_HORIZONTAL_LINE, ...) * outline (0 to skip drawing box outline) * op (one of L_SET_PIXELS, L_CLEAR_PIXELS, L_FLIP_PIXELS) * Return: 0 if OK, 1 on error */ l_int32 pixRenderHashBox(PIX *pix, BOX *box, l_int32 spacing, l_int32 width, l_int32 orient, l_int32 outline, l_int32 op) { PTA *pta; PROCNAME("pixRenderHashBox"); if (!pix) { return ERROR_INT("pix not defined", procName, 1); } if (!box) { return ERROR_INT("box not defined", procName, 1); } if (spacing <= 1) { return ERROR_INT("spacing not > 1", procName, 1); } if (width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } if (orient != L_HORIZONTAL_LINE && orient != L_POS_SLOPE_LINE && orient != L_VERTICAL_LINE && orient != L_NEG_SLOPE_LINE) { return ERROR_INT("invalid line orientation", procName, 1); } if (op != L_SET_PIXELS && op != L_CLEAR_PIXELS && op != L_FLIP_PIXELS) { return ERROR_INT("invalid op", procName, 1); } pta = generatePtaHashBox(box, spacing, width, orient, outline); if (!pta) { return ERROR_INT("pta not made", procName, 1); } pixRenderPta(pix, pta, op); ptaDestroy(&pta); return 0; } /*! * pixRenderHashBoxArb() * * Input: pix * box * spacing (spacing between lines; must be > 1) * width (thickness of box and hash lines) * orient (orientation of lines: L_HORIZONTAL_LINE, ...) * outline (0 to skip drawing box outline) * rval, gval, bval * Return: 0 if OK, 1 on error */ l_int32 pixRenderHashBoxArb(PIX *pix, BOX *box, l_int32 spacing, l_int32 width, l_int32 orient, l_int32 outline, l_int32 rval, l_int32 gval, l_int32 bval) { PTA *pta; PROCNAME("pixRenderHashBoxArb"); if (!pix) { return ERROR_INT("pix not defined", procName, 1); } if (!box) { return ERROR_INT("box not defined", procName, 1); } if (spacing <= 1) { return ERROR_INT("spacing not > 1", procName, 1); } if (width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } if (orient != L_HORIZONTAL_LINE && orient != L_POS_SLOPE_LINE && orient != L_VERTICAL_LINE && orient != L_NEG_SLOPE_LINE) { return ERROR_INT("invalid line orientation", procName, 1); } pta = generatePtaHashBox(box, spacing, width, orient, outline); if (!pta) { return ERROR_INT("pta not made", procName, 1); } pixRenderPtaArb(pix, pta, rval, gval, bval); ptaDestroy(&pta); return 0; } /*! * pixRenderHashBoxBlend() * * Input: pix * box * spacing (spacing between lines; must be > 1) * width (thickness of box and hash lines) * orient (orientation of lines: L_HORIZONTAL_LINE, ...) * outline (0 to skip drawing box outline) * rval, gval, bval * fract (in [0.0 - 1.0]; complete transparency (no effect) * if 0.0; no transparency if 1.0) * Return: 0 if OK, 1 on error */ l_int32 pixRenderHashBoxBlend(PIX *pix, BOX *box, l_int32 spacing, l_int32 width, l_int32 orient, l_int32 outline, l_int32 rval, l_int32 gval, l_int32 bval, l_float32 fract) { PTA *pta; PROCNAME("pixRenderHashBoxBlend"); if (!pix) { return ERROR_INT("pix not defined", procName, 1); } if (!box) { return ERROR_INT("box not defined", procName, 1); } if (spacing <= 1) { return ERROR_INT("spacing not > 1", procName, 1); } if (width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } if (orient != L_HORIZONTAL_LINE && orient != L_POS_SLOPE_LINE && orient != L_VERTICAL_LINE && orient != L_NEG_SLOPE_LINE) { return ERROR_INT("invalid line orientation", procName, 1); } pta = generatePtaHashBox(box, spacing, width, orient, outline); if (!pta) { return ERROR_INT("pta not made", procName, 1); } pixRenderPtaBlend(pix, pta, rval, gval, bval, fract); ptaDestroy(&pta); return 0; } /*! * pixRenderHashBoxa() * * Input: pix * boxa * spacing (spacing between lines; must be > 1) * width (thickness of box and hash lines) * orient (orientation of lines: L_HORIZONTAL_LINE, ...) * outline (0 to skip drawing box outline) * op (one of L_SET_PIXELS, L_CLEAR_PIXELS, L_FLIP_PIXELS) * Return: 0 if OK, 1 on error */ l_int32 pixRenderHashBoxa(PIX *pix, BOXA *boxa, l_int32 spacing, l_int32 width, l_int32 orient, l_int32 outline, l_int32 op) { PTA *pta; PROCNAME("pixRenderHashBoxa"); if (!pix) { return ERROR_INT("pix not defined", procName, 1); } if (!boxa) { return ERROR_INT("boxa not defined", procName, 1); } if (spacing <= 1) { return ERROR_INT("spacing not > 1", procName, 1); } if (width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } if (orient != L_HORIZONTAL_LINE && orient != L_POS_SLOPE_LINE && orient != L_VERTICAL_LINE && orient != L_NEG_SLOPE_LINE) { return ERROR_INT("invalid line orientation", procName, 1); } if (op != L_SET_PIXELS && op != L_CLEAR_PIXELS && op != L_FLIP_PIXELS) { return ERROR_INT("invalid op", procName, 1); } pta = generatePtaHashBoxa(boxa, spacing, width, orient, outline, 1); if (!pta) { return ERROR_INT("pta not made", procName, 1); } pixRenderPta(pix, pta, op); ptaDestroy(&pta); return 0; } /*! * pixRenderHashBoxaArb() * * Input: pix * boxa * spacing (spacing between lines; must be > 1) * width (thickness of box and hash lines) * orient (orientation of lines: L_HORIZONTAL_LINE, ...) * outline (0 to skip drawing box outline) * rval, gval, bval * Return: 0 if OK, 1 on error */ l_int32 pixRenderHashBoxaArb(PIX *pix, BOXA *boxa, l_int32 spacing, l_int32 width, l_int32 orient, l_int32 outline, l_int32 rval, l_int32 gval, l_int32 bval) { PTA *pta; PROCNAME("pixRenderHashBoxArb"); if (!pix) { return ERROR_INT("pix not defined", procName, 1); } if (!boxa) { return ERROR_INT("boxa not defined", procName, 1); } if (spacing <= 1) { return ERROR_INT("spacing not > 1", procName, 1); } if (width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } if (orient != L_HORIZONTAL_LINE && orient != L_POS_SLOPE_LINE && orient != L_VERTICAL_LINE && orient != L_NEG_SLOPE_LINE) { return ERROR_INT("invalid line orientation", procName, 1); } pta = generatePtaHashBoxa(boxa, spacing, width, orient, outline, 1); if (!pta) { return ERROR_INT("pta not made", procName, 1); } pixRenderPtaArb(pix, pta, rval, gval, bval); ptaDestroy(&pta); return 0; } /*! * pixRenderHashBoxaBlend() * * Input: pix * boxa * spacing (spacing between lines; must be > 1) * width (thickness of box and hash lines) * orient (orientation of lines: L_HORIZONTAL_LINE, ...) * outline (0 to skip drawing box outline) * rval, gval, bval * fract (in [0.0 - 1.0]; complete transparency (no effect) * if 0.0; no transparency if 1.0) * Return: 0 if OK, 1 on error */ l_int32 pixRenderHashBoxaBlend(PIX *pix, BOXA *boxa, l_int32 spacing, l_int32 width, l_int32 orient, l_int32 outline, l_int32 rval, l_int32 gval, l_int32 bval, l_float32 fract) { PTA *pta; PROCNAME("pixRenderHashBoxaBlend"); if (!pix) { return ERROR_INT("pix not defined", procName, 1); } if (!boxa) { return ERROR_INT("boxa not defined", procName, 1); } if (spacing <= 1) { return ERROR_INT("spacing not > 1", procName, 1); } if (width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } if (orient != L_HORIZONTAL_LINE && orient != L_POS_SLOPE_LINE && orient != L_VERTICAL_LINE && orient != L_NEG_SLOPE_LINE) { return ERROR_INT("invalid line orientation", procName, 1); } pta = generatePtaHashBoxa(boxa, spacing, width, orient, outline, 1); if (!pta) { return ERROR_INT("pta not made", procName, 1); } pixRenderPtaBlend(pix, pta, rval, gval, bval, fract); ptaDestroy(&pta); return 0; } /*! * pixRenderPolyline() * * Input: pix * ptas * width (thickness of line) * op (one of L_SET_PIXELS, L_CLEAR_PIXELS, L_FLIP_PIXELS) * closeflag (1 to close the contour; 0 otherwise) * Return: 0 if OK, 1 on error * * Note: this renders a closed contour. */ l_int32 pixRenderPolyline(PIX *pix, PTA *ptas, l_int32 width, l_int32 op, l_int32 closeflag) { PTA *pta; PROCNAME("pixRenderPolyline"); if (!pix) { return ERROR_INT("pix not defined", procName, 1); } if (!ptas) { return ERROR_INT("ptas not defined", procName, 1); } if (width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } if (op != L_SET_PIXELS && op != L_CLEAR_PIXELS && op != L_FLIP_PIXELS) { return ERROR_INT("invalid op", procName, 1); } if ((pta = generatePtaPolyline(ptas, width, closeflag, 0)) == NULL) { return ERROR_INT("pta not made", procName, 1); } pixRenderPta(pix, pta, op); ptaDestroy(&pta); return 0; } /*! * pixRenderPolylineArb() * * Input: pix * ptas * width (thickness of line) * rval, gval, bval * closeflag (1 to close the contour; 0 otherwise) * Return: 0 if OK, 1 on error * * Note: this renders a closed contour. */ l_int32 pixRenderPolylineArb(PIX *pix, PTA *ptas, l_int32 width, l_uint8 rval, l_uint8 gval, l_uint8 bval, l_int32 closeflag) { PTA *pta; PROCNAME("pixRenderPolylineArb"); if (!pix) { return ERROR_INT("pix not defined", procName, 1); } if (!ptas) { return ERROR_INT("ptas not defined", procName, 1); } if (width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } if ((pta = generatePtaPolyline(ptas, width, closeflag, 0)) == NULL) { return ERROR_INT("pta not made", procName, 1); } pixRenderPtaArb(pix, pta, rval, gval, bval); ptaDestroy(&pta); return 0; } /*! * pixRenderPolylineBlend() * * Input: pix * ptas * width (thickness of line) * rval, gval, bval * fract (in [0.0 - 1.0]; complete transparency (no effect) * if 0.0; no transparency if 1.0) * closeflag (1 to close the contour; 0 otherwise) * removedups (1 to remove; 0 otherwise) * Return: 0 if OK, 1 on error */ l_int32 pixRenderPolylineBlend(PIX *pix, PTA *ptas, l_int32 width, l_uint8 rval, l_uint8 gval, l_uint8 bval, l_float32 fract, l_int32 closeflag, l_int32 removedups) { PTA *pta; PROCNAME("pixRenderPolylineBlend"); if (!pix) { return ERROR_INT("pix not defined", procName, 1); } if (!ptas) { return ERROR_INT("ptas not defined", procName, 1); } if (width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } if ((pta = generatePtaPolyline(ptas, width, closeflag, removedups)) == NULL) { return ERROR_INT("pta not made", procName, 1); } pixRenderPtaBlend(pix, pta, rval, gval, bval, fract); ptaDestroy(&pta); return 0; } /*! * pixRenderRandomCmapPtaa() * * Input: pix (1, 2, 4, 8, 16, 32 bpp) * ptaa * polyflag (1 to interpret each Pta as a polyline; 0 to simply * render the Pta as a set of pixels) * width (thickness of line; use only for polyline) * closeflag (1 to close the contour; 0 otherwise; * use only for polyline mode) * Return: pixd (cmapped, 8 bpp) or null on error * * Notes: * (1) This is a debugging routine, that displays a set of * pixels, selected by the set of Ptas in a Ptaa, * in a random color in a pix. * (2) If @polyflag == 1, each Pta is considered to be a polyline, * and is rendered using @width and @closeflag. Each polyline * is rendered in a random color. * (3) If @polyflag == 0, all points in each Pta are rendered in a * random color. The @width and @closeflag parameters are ignored. * (4) The output pix is 8 bpp and colormapped. Up to 254 * different, randomly selected colors, can be used. * (5) The rendered pixels replace the input pixels. They will * be clipped silently to the input pix. */ PIX * pixRenderRandomCmapPtaa(PIX *pix, PTAA *ptaa, l_int32 polyflag, l_int32 width, l_int32 closeflag) { l_int32 i, n, index, rval, gval, bval; PIXCMAP *cmap; PTA *pta, *ptat; PIX *pixd; PROCNAME("pixRenderRandomCmapPtaa"); if (!pix) { return (PIX *)ERROR_PTR("pix not defined", procName, NULL); } if (!ptaa) { return (PIX *)ERROR_PTR("ptaa not defined", procName, NULL); } if (polyflag != 0 && width < 1) { L_WARNING("width < 1; setting to 1\n", procName); width = 1; } pixd = pixConvertTo8(pix, FALSE); cmap = pixcmapCreateRandom(8, 1, 1); pixSetColormap(pixd, cmap); if ((n = ptaaGetCount(ptaa)) == 0) { return pixd; } for (i = 0; i < n; i++) { index = 1 + (i % 254); pixcmapGetColor(cmap, index, &rval, &gval, &bval); pta = ptaaGetPta(ptaa, i, L_CLONE); if (polyflag) { ptat = generatePtaPolyline(pta, width, closeflag, 0); } else { ptat = ptaClone(pta); } pixRenderPtaArb(pixd, ptat, rval, gval, bval); ptaDestroy(&pta); ptaDestroy(&ptat); } return pixd; } /*------------------------------------------------------------------* * Rendering and filling of polygons * *------------------------------------------------------------------*/ /*! * pixRenderPolygon() * * Input: ptas (of vertices, none repeated) * width (of polygon outline) * &xmin (<optional return> min x value of input pts) * &ymin (<optional return> min y value of input pts) * Return: pix (1 bpp, with outline generated), or null on error * * Notes: * (1) The pix is the minimum size required to contain the origin * and the polygon. For example, the max x value of the input * points is w - 1, where w is the pix width. * (2) The rendered line is 4-connected, so that an interior or * exterior 8-c.c. flood fill operation works properly. */ PIX * pixRenderPolygon(PTA *ptas, l_int32 width, l_int32 *pxmin, l_int32 *pymin) { l_float32 fxmin, fxmax, fymin, fymax; PIX *pixd; PTA *pta1, *pta2; PROCNAME("pixRenderPolygon"); if (pxmin) { *pxmin = 0; } if (pymin) { *pymin = 0; } if (!ptas) { return (PIX *)ERROR_PTR("ptas not defined", procName, NULL); } /* Generate a 4-connected polygon line */ if ((pta1 = generatePtaPolyline(ptas, width, 1, 0)) == NULL) { return (PIX *)ERROR_PTR("pta1 not made", procName, NULL); } if (width < 2) { pta2 = convertPtaLineTo4cc(pta1); } else { pta2 = ptaClone(pta1); } /* Render onto a minimum-sized pix */ ptaGetRange(pta2, &fxmin, &fxmax, &fymin, &fymax); if (pxmin) { *pxmin = (l_int32)(fxmin + 0.5); } if (pymin) { *pymin = (l_int32)(fymin + 0.5); } pixd = pixCreate((l_int32)(fxmax + 0.5) + 1, (l_int32)(fymax + 0.5) + 1, 1); pixRenderPolyline(pixd, pta2, width, L_SET_PIXELS, 1); ptaDestroy(&pta1); ptaDestroy(&pta2); return pixd; } /*! * pixFillPolygon() * * Input: pixs (1 bpp, with 4-connected polygon outline) * pta (vertices of the polygon) * xmin, ymin (min values of vertices of polygon) * Return: pixd (with outline filled), or null on error * * Notes: * (1) This fills the interior of the polygon, returning a * new pix. It works for both convex and non-convex polygons. * (2) To generate a filled polygon from a pta: * PIX *pixt = pixRenderPolygon(pta, 1, &xmin, &ymin); * PIX *pixd = pixFillPolygon(pixt, pta, xmin, ymin); * pixDestroy(&pixt); */ PIX * pixFillPolygon(PIX *pixs, PTA *pta, l_int32 xmin, l_int32 ymin) { l_int32 w, h, i, n, inside, found; l_int32 *xstart, *xend; PIX *pixi, *pixd; PROCNAME("pixFillPolygon"); if (!pixs || (pixGetDepth(pixs) != 1)) { return (PIX *)ERROR_PTR("pixs undefined or not 1 bpp", procName, NULL); } if (!pta) { return (PIX *)ERROR_PTR("pta not defined", procName, NULL); } pixGetDimensions(pixs, &w, &h, NULL); xstart = (l_int32 *)CALLOC(w / 2, sizeof(l_int32)); xend = (l_int32 *)CALLOC(w / 2, sizeof(l_int32)); /* Find a raster with 2 or more black runs. The first background * pixel after the end of the first run is likely to be inside * the polygon, and can be used as a seed pixel. */ found = FALSE; for (i = ymin + 1; i < h; i++) { pixFindHorizontalRuns(pixs, i, xstart, xend, &n); if (n > 1) { ptaPtInsidePolygon(pta, xend[0] + 1, i, &inside); if (inside) { found = TRUE; break; } } } if (!found) { L_WARNING("nothing found to fill\n", procName); FREE(xstart); FREE(xend); return 0; } /* Place the seed pixel in the output image */ pixd = pixCreateTemplate(pixs); pixSetPixel(pixd, xend[0] + 1, i, 1); /* Invert pixs to make a filling mask, and fill from the seed */ pixi = pixInvert(NULL, pixs); pixSeedfillBinary(pixd, pixd, pixi, 4); /* Add the pixels of the original polygon outline */ pixOr(pixd, pixd, pixs); pixDestroy(&pixi); FREE(xstart); FREE(xend); return pixd; } /*------------------------------------------------------------------* * Contour rendering on grayscale images * *------------------------------------------------------------------*/ /*! * pixRenderContours() * * Input: pixs (8 or 16 bpp; no colormap) * startval (value of lowest contour; must be in [0 ... maxval]) * incr (increment to next contour; must be > 0) * outdepth (either 1 or depth of pixs) * Return: pixd, or null on error * * Notes: * (1) The output can be either 1 bpp, showing just the contour * lines, or a copy of the input pixs with the contour lines * superposed. */ PIX * pixRenderContours(PIX *pixs, l_int32 startval, l_int32 incr, l_int32 outdepth) { l_int32 w, h, d, maxval, wpls, wpld, i, j, val, test; l_uint32 *datas, *datad, *lines, *lined; PIX *pixd; PROCNAME("pixRenderContours"); if (!pixs) { return (PIX *)ERROR_PTR("pixs not defined", procName, NULL); } if (pixGetColormap(pixs)) { return (PIX *)ERROR_PTR("pixs has colormap", procName, NULL); } pixGetDimensions(pixs, &w, &h, &d); if (d != 8 && d != 16) { return (PIX *)ERROR_PTR("pixs not 8 or 16 bpp", procName, NULL); } if (outdepth != 1 && outdepth != d) { L_WARNING("invalid outdepth; setting to 1\n", procName); outdepth = 1; } maxval = (1 << d) - 1; if (startval < 0 || startval > maxval) return (PIX *)ERROR_PTR("startval not in [0 ... maxval]", procName, NULL); if (incr < 1) { return (PIX *)ERROR_PTR("incr < 1", procName, NULL); } if (outdepth == d) { pixd = pixCopy(NULL, pixs); } else { pixd = pixCreate(w, h, 1); } pixCopyResolution(pixd, pixs); datad = pixGetData(pixd); wpld = pixGetWpl(pixd); datas = pixGetData(pixs); wpls = pixGetWpl(pixs); switch (d) { case 8: if (outdepth == 1) { for (i = 0; i < h; i++) { lines = datas + i * wpls; lined = datad + i * wpld; for (j = 0; j < w; j++) { val = GET_DATA_BYTE(lines, j); if (val < startval) { continue; } test = (val - startval) % incr; if (!test) { SET_DATA_BIT(lined, j); } } } } else /* outdepth == d */ { for (i = 0; i < h; i++) { lines = datas + i * wpls; lined = datad + i * wpld; for (j = 0; j < w; j++) { val = GET_DATA_BYTE(lines, j); if (val < startval) { continue; } test = (val - startval) % incr; if (!test) { SET_DATA_BYTE(lined, j, 0); } } } } break; case 16: if (outdepth == 1) { for (i = 0; i < h; i++) { lines = datas + i * wpls; lined = datad + i * wpld; for (j = 0; j < w; j++) { val = GET_DATA_TWO_BYTES(lines, j); if (val < startval) { continue; } test = (val - startval) % incr; if (!test) { SET_DATA_BIT(lined, j); } } } } else /* outdepth == d */ { for (i = 0; i < h; i++) { lines = datas + i * wpls; lined = datad + i * wpld; for (j = 0; j < w; j++) { val = GET_DATA_TWO_BYTES(lines, j); if (val < startval) { continue; } test = (val - startval) % incr; if (!test) { SET_DATA_TWO_BYTES(lined, j, 0); } } } } break; default: return (PIX *)ERROR_PTR("pixs not 8 or 16 bpp", procName, NULL); } return pixd; } /*! * fpixAutoRenderContours() * * Input: fpix * ncontours (> 1, < 500, typ. about 50) * Return: pixd (8 bpp), or null on error * * Notes: * (1) The increment is set to get approximately @ncontours. * (2) The proximity to the target value for contour display * is set to 0.15. * (3) Negative values are rendered in red; positive values as black. */ PIX * fpixAutoRenderContours(FPIX *fpix, l_int32 ncontours) { l_float32 minval, maxval, incr; PROCNAME("fpixAutoRenderContours"); if (!fpix) { return (PIX *)ERROR_PTR("fpix not defined", procName, NULL); } if (ncontours < 2 || ncontours > 500) { return (PIX *)ERROR_PTR("ncontours < 2 or > 500", procName, NULL); } fpixGetMin(fpix, &minval, NULL, NULL); fpixGetMax(fpix, &maxval, NULL, NULL); if (minval == maxval) { return (PIX *)ERROR_PTR("all values in fpix are equal", procName, NULL); } incr = (maxval - minval) / ((l_float32)ncontours - 1); return fpixRenderContours(fpix, incr, 0.15); } /*! * fpixRenderContours() * * Input: fpixs * incr (increment between contours; must be > 0.0) * proxim (required proximity to target value; default 0.15) * Return: pixd (8 bpp), or null on error * * Notes: * (1) Values are displayed when val/incr is within +-proxim * to an integer. The default value is 0.15; smaller values * result in thinner contour lines. * (2) Negative values are rendered in red; positive values as black. */ PIX * fpixRenderContours(FPIX *fpixs, l_float32 incr, l_float32 proxim) { l_int32 i, j, w, h, wpls, wpld; l_float32 val, invincr, finter, above, below, diff; l_uint32 *datad, *lined; l_float32 *datas, *lines; PIX *pixd; PIXCMAP *cmap; PROCNAME("fpixRenderContours"); if (!fpixs) { return (PIX *)ERROR_PTR("fpixs not defined", procName, NULL); } if (incr <= 0.0) { return (PIX *)ERROR_PTR("incr <= 0.0", procName, NULL); } if (proxim <= 0.0) { proxim = 0.15; /* default */ } fpixGetDimensions(fpixs, &w, &h); if ((pixd = pixCreate(w, h, 8)) == NULL) { return (PIX *)ERROR_PTR("pixd not made", procName, NULL); } cmap = pixcmapCreate(8); pixSetColormap(pixd, cmap); pixcmapAddColor(cmap, 255, 255, 255); /* white */ pixcmapAddColor(cmap, 0, 0, 0); /* black */ pixcmapAddColor(cmap, 255, 0, 0); /* red */ datas = fpixGetData(fpixs); wpls = fpixGetWpl(fpixs); datad = pixGetData(pixd); wpld = pixGetWpl(pixd); invincr = 1.0 / incr; for (i = 0; i < h; i++) { lines = datas + i * wpls; lined = datad + i * wpld; for (j = 0; j < w; j++) { val = lines[j]; finter = invincr * val; above = finter - floorf(finter); below = ceilf(finter) - finter; diff = L_MIN(above, below); if (diff <= proxim) { if (val < 0.0) { SET_DATA_BYTE(lined, j, 2); } else { SET_DATA_BYTE(lined, j, 1); } } } } return pixd; }
/* * Copyright (C) 2007-2015 Frank Mertens. * * Use of this source is governed by a BSD-style license that can be * found in the LICENSE file. * */ #include <flux/File> #include <flux/Dir> #include <flux/Singleton> #include <flux/Arguments> #include "NodeConfigProtocol.h" #include "ServiceRegistry.h" #include "ErrorLog.h" #include "NodeConfig.h" namespace fluxnode { NodeConfig::NodeConfig() {} void NodeConfig::load(int argc, char **argv) { Ref<Arguments> arguments = Arguments::parse(argc, argv); Ref<StringList> items = arguments->items(); MetaObject *nodePrototype = configProtocol()->lookup("Node"); arguments->validate(nodePrototype); Ref<MetaObject> config; if (items->count() > 0) { if (items->count() > 1) throw UsageError("Handling multiple input arguments at once is not supported"); String path = items->at(0); if (Dir::exists(path)) { directoryPath_ = path; } else { config = yason::parse(File::open(path)->map(), configProtocol()); } } if (!config) config = nodePrototype->clone(); arguments->override(config); String address = config->value("address"); int port = config->value("port"); String protocol = config->value("protocol"); int family = AF_UNSPEC; if (protocol->downcase() == "ipv6") family = AF_INET6; else if (protocol->downcase() == "ipv4") family = AF_INET; address_ = SocketAddress::resolve(address, "http", family, SOCK_STREAM); for (int i = 0; i < address_->count(); ++i) address_->at(i)->setPort(port); user_ = config->value("user"); version_ = config->value("version"); daemon_ = config->value("daemon"); serviceWindow_ = config->value("service_window"); errorLogConfig_ = LogConfig::load(cast<MetaObject>(config->value("error_log"))); accessLogConfig_ = LogConfig::load(cast<MetaObject>(config->value("access_log"))); serviceInstances_ = ServiceInstances::create(); if (config->hasChildren()) { for (int i = 0; i < config->children()->count(); ++i) { MetaObject *child = config->children()->at(i); ServiceDefinition *service = serviceRegistry()->serviceByName(child->className()); serviceInstances_->append(service->createInstance(child)); } } } NodeConfig *nodeConfig() { return Singleton<NodeConfig>::instance(); } } // namespace fluxnode
#ifndef FASTCG_IMGUI_SYSTEM_H #define FASTCG_IMGUI_SYSTEM_H #include <FastCG/Input/InputSystem.h> #include <FastCG/Core/System.h> #include <cstdint> namespace FastCG { struct ImGuiSystemArgs { const uint32_t &rScreenWidth; const uint32_t &rScreenHeight; }; class ImGuiSystem { FASTCG_DECLARE_SYSTEM(ImGuiSystem, ImGuiSystemArgs); private: const ImGuiSystemArgs mArgs; ImGuiSystem(const ImGuiSystemArgs &rArgs); ~ImGuiSystem(); void Initialize(); void BeginFrame(double deltaTime, KeyChange keyChanges[KEY_COUNT]); void EndFrame(); void Finalize(); }; } #endif
#include "LLQueue.h" template <class T> LLQueue<T>::LLQueue() { Front = Rear = nullptr; count = 0; } template <class T> LLQueue<T>::LLQueue(const LLQueue<T> &other) { if (count == 0) { this->LLQueue<T>::LLQueue(); } else { count = other.count; Node *cur = other.Front; Front = new Node(cur->data); Rear = Front; cur = cur->next; while (cur != nullptr) { Node *newNode = new Node(cur->data); Rear->next = newNode; Rear = newNode; cur = cur->next; } } } template <class T> LLQueue<T>::~LLQueue() { while (Front != nullptr) { Node *temp = Front; Front = Front->next; delete temp; } Rear = nullptr; count = 0; } template <class T> const LLQueue<T> &LLQueue<T>::operator=(const LLQueue<T> &other) { this->~LLQueue(); if (other.count != 0) { count = other.count; Node *cur = other.Front; Front = new Node(cur->data); Rear = Front; cur = cur->next; while (cur != nullptr) { Node *newNode = new Node(cur->data); Rear->next = newNode; Rear = newNode; cur = cur->next; } } return other; } //Capacity template <class T> int LLQueue<T>::size() { return count; } template <class T> bool LLQueue<T>::empty() { return count == 0; } //Modifiers template <class T> T LLQueue<T>::front() { if (Front == nullptr) return T(); return Front->data; } template <class T> void LLQueue<T>::enqueue(const T &item) { if (count == 0) { Front = new Node(item); Rear = Front; } else { Rear->next = new Node(item); Rear = Rear->next; } count++; } template <class T> bool LLQueue<T>::dequeue() { if (count == 0) return false; Node *temp = Front; Front = Front->next; delete temp; if (count == 1) Rear = nullptr; count--; return true; }
#pragma once #include "Polygon.hpp" class Circulo : public Polygon { private: float raio; const float pi; public: Circulo(float raio, bool boo); double getArea() override; double getPerimetro() override; };
#pragma once #include "Sensor.h" class Speed : public Sensor { public: Speed() {}; Speed(float value) : Sensor(value) {}; void update(); ~Speed(); };
#include "AdditionalParsing.h" Position AdditionalParsing::parseCoords(std::string coord) { char delimiter = ','; int lineDelim = coord.find(delimiter); std::string x, y; x = coord.substr(0, lineDelim); y = coord.substr(lineDelim + 1, coord.size()); return Position(atoi(x.c_str()), atoi(y.c_str())); }
#pragma once #include "Node.h" class LinkedList { private: Node * Head; Node* CreateNode(int val); // Returns the last node. Node* GetLastNode(); void DeleteAtStart(); public: LinkedList(); ~LinkedList(); // Inserts a value at the end. void Insert(int val); // Inserts the element at the start. void InsertAtStart(int val); // Inserts the value at a given index. void InsertAt(int index, int val); // Deletes the node at a given index. void DeleteAt(int index); // Prints the data on to the console. void Show(); };
#pragma once #include <vector> #include <string_view> #include <string> extern const size_t kStringReserve; class AkinatorTree { public: struct Node { size_t left_bound = 0; size_t right_bound = 0; size_t left = 0; // true subtree size_t right = 0; // false subtree size_t parent = 0; }; void ReadTree(const std::string& filename); void WriteTree(const std::string& filename) const; void UpdateTree(size_t current_node, const std::string& property, const std::string& new_node); std::string_view NodeToString(size_t node) const; const std::string& GetString() const; const std::vector<Node>& GetTree() const; inline bool IsLeaf(size_t node) const; size_t LCA(size_t first_node, size_t second_node) const; size_t NodeDepth(size_t node) const; private: void CreateRoot(); void Reserve(std::FILE* file); void BuildTree(std::FILE* file); std::vector<Node> tree_; std::string nodes_strings_; };
#include <iostream> #include <exception> #include <google/protobuf/compiler/importer.h> #include <google/protobuf/dynamic_message.h> #include "codec.h" void test_read_proto() { GOOGLE_PROTOBUF_VERIFY_VERSION; //muduo::Query query; //query.set_id(1); //query.set_questioner("Chen Shuo"); //query.add_question("Running?"); //std::string transport = encode(query); // 准备配置好文件系统 google::protobuf::compiler::DiskSourceTree sourceTree; // 将当前路径映射为项目根目录 , project_root 仅仅是个名字,你可以你想要的合法名字. sourceTree.MapPath("project_root","./"); // 配置动态编译器. google::protobuf::compiler::Importer importer(&sourceTree, NULL); // 动态编译proto源文件。 源文件在./query.proto . importer.Import("project_root/query.proto"); // 现在可以从编译器中提取类型的描述信息. auto descriptor1 = importer.pool()->FindMessageTypeByName("muduo.Query"); // 创建一个动态的消息工厂. google::protobuf::DynamicMessageFactory factory; // 从消息工厂中创建出一个类型原型. auto proto1 = factory.GetPrototype(descriptor1); // 构造一个可用的消息. auto message1= proto1->New(); // 下面是通过反射接口给字段赋值. auto reflection1 = message1->GetReflection(); auto filed1 = descriptor1->FindFieldByName("id"); reflection1->SetInt64(message1, filed1,1); auto filed2 = descriptor1->FindFieldByName("questioner"); reflection1->SetString(message1, filed2, "Chen Shuo"); auto filed3 = descriptor1->FindFieldByName("question"); reflection1->SetString(message1, filed3, "Running?"); // 打印看看 //std::cout << message1->DebugString(); std::string transport = encode(*message1); //print(transport); int32_t be32 = 0; std::copy(transport.begin(), transport.begin() + sizeof be32, reinterpret_cast<char*>(&be32)); int32_t len = ::ntohl(be32); assert(len == transport.size() - sizeof(be32)); // network library decodes length header and get the body of message std::string buf = transport.substr(sizeof(int32_t)); assert(len == buf.size()); auto message2 = decode(buf); assert(message2 != NULL); message2->PrintDebugString(); assert(message2->DebugString() == message1->DebugString()); delete message2; buf[buf.size() - 6]++; // oops, some data is corrupted auto badMsg = (decode(buf)); assert(badMsg == NULL); // 删除消息. delete message1 ; puts("test_read_proto=========================="); }
// it's same for both directed and undirected graph #include<bits/stdc++.h> using namespace std; bool solve(vector<int>* edges,int v) { if(v==0) { return true; } set<int> s[2]; queue<int> Q; // we will start from 0; Q.push(0); // we will insert 0 in first set s[0].insert(0); while(Q.size()!=0) { int cur = Q.front(); Q.pop(); int cur_set = s[0].count(cur) > 0 ? 0 : 1; for(int i=0;i<edges[cur].size();i++) { int adj = edges[cur][i]; // if adj is not in both the sets if(s[0].count(adj)==0 && s[1].count(adj)==0) { s[cur_set^1].insert(adj); Q.push(adj); } // if it is present in same set else if(s[cur_set].count(adj) > 0) { return false; } // else it is present is opposite set we will continue } } return true; } int main() { while(1) { int v,e; cin >> v >> e; if(v==0) { break; } vector<int>* edges = new vector<int>[v]; for(int i=0;i<e;i++) { int x,y; cin >> x >> y; edges[x].push_back(y); edges[y].push_back(x); } bool ans = solve(edges,v); if(ans) { cout << "BICOLORABLE" << endl; } else { cout << "NOT BICOLORABLE" << endl; } delete[] edges; } }
// 9. Palindrome Number // Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. // Example 1: // Input: 121 // Output: true // Example 2: // Input: -121 // Output: false // Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. // Example 3: // Input: 10 // Output: false // Explanation: Reads 01 from right to left. Therefore it is not a palindrome. // Follow up: // Could you solve it without converting the integer to a string? #include <limits.h> using namespace std; class Solution { public: bool isPalindrome(int x) { // Example 2 case if ( x < 0 ) return false; int maxINT_10 = INT_MAX/10; int minINT_10 = INT_MIN/10; // Method 1. Reverse the int and check if its equal to original // O(n) // Method 2. Pop first and last and check if equal until not satisfying invariant // O(n/2) ~ O(n) int result = 0; int tempX = x; while (tempX){ if ( result > maxINT_10 || result == maxINT_10 && tempX % 10 > 2 )return false; result = result * 10 + tempX % 10; tempX /= 10; } if ( result == x ) return true; else return false; } };
/* NO WARRANTY * * BECAUSE THE PROGRAM IS IN THE PUBLIC DOMAIN, THERE IS NO * WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE * LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE AUTHORS * AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT * WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO * THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD * THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL * NECESSARY SERVICING, REPAIR OR CORRECTION. * * IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN * WRITING WILL ANY AUTHOR, OR ANY OTHER PARTY WHO MAY MODIFY * AND/OR REDISTRIBUTE THE PROGRAM, BE LIABLE TO YOU FOR DAMAGES, * INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL * DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM * (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING * RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES * OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER * PROGRAMS), EVEN IF SUCH AUTHOR OR OTHER PARTY HAS BEEN ADVISED * OF THE POSSIBILITY OF SUCH DAMAGES. */ #include "stdafx.h" #include "resource.h" #include "SplashScreen.h" #include "Application\Debug\LogManager.h" BOOL CSplashScreenWnd::c_bShowSplashWnd; CSplashScreenWnd* CSplashScreenWnd::c_pSplashWnd; BEGIN_MESSAGE_MAP(CSplashScreenWnd, CWnd) //{{AFX_MSG_MAP(CSplashScreenWnd) ON_WM_CREATE() ON_WM_PAINT() ON_WM_TIMER() //}}AFX_MSG_MAP END_MESSAGE_MAP() //---------------------------------------------------------------------------- CSplashScreenWnd::CSplashScreenWnd(){ //---------------------------------------------------------------------------- PROC_TRACE; } //---------------------------------------------------------------------------- CSplashScreenWnd::~CSplashScreenWnd(){ //---------------------------------------------------------------------------- PROC_TRACE; // Statischen Fensterzeiger löschen ASSERT(c_pSplashWnd == this); c_pSplashWnd = NULL; } //---------------------------------------------------------------------------- void CSplashScreenWnd::EnableSplashScreen(BOOL bEnable /*= TRUE*/){ //---------------------------------------------------------------------------- PROC_TRACE; c_bShowSplashWnd = bEnable; } //---------------------------------------------------------------------------- void CSplashScreenWnd::ShowSplashScreen(CWnd* pParentWnd /*= NULL*/){ //---------------------------------------------------------------------------- PROC_TRACE; if (!c_bShowSplashWnd || c_pSplashWnd != NULL) return; // Neuen Begrüßungsbildschirm reservieren und erstellen c_pSplashWnd = new CSplashScreenWnd; if (!c_pSplashWnd->Create(pParentWnd)) delete c_pSplashWnd; else c_pSplashWnd->UpdateWindow(); } //---------------------------------------------------------------------------- BOOL CSplashScreenWnd::PretranslateAppMessage(MSG* pMsg){ //---------------------------------------------------------------------------- PROC_TRACE; if (c_pSplashWnd == NULL) return FALSE; // Begrüßungsbildschirm ausblenden, falls eine Tastatur- oder Mausnachricht empfangen wird. if (pMsg->message == WM_KEYDOWN || pMsg->message == WM_SYSKEYDOWN || pMsg->message == WM_LBUTTONDOWN || pMsg->message == WM_RBUTTONDOWN || pMsg->message == WM_MBUTTONDOWN || pMsg->message == WM_NCLBUTTONDOWN || pMsg->message == WM_NCRBUTTONDOWN || pMsg->message == WM_NCMBUTTONDOWN) { c_pSplashWnd->HideSplashScreen(); return TRUE; // Die Nachricht wurde hier behandelt } return FALSE; // Die Nachricht wurde nicht behandelt } //---------------------------------------------------------------------------- BOOL CSplashScreenWnd::Create(CWnd* pParentWnd /*= NULL*/){ //---------------------------------------------------------------------------- PROC_TRACE; if (!m_bitmap.LoadBitmap(IDB_SPLASH_SCREEN)) return FALSE; BITMAP bm; m_bitmap.GetBitmap(&bm); return CreateEx(0, AfxRegisterWndClass(0, AfxGetApp()->LoadStandardCursor(IDC_ARROW)), NULL, WS_POPUP | WS_VISIBLE, 0, 0, bm.bmWidth, bm.bmHeight, pParentWnd->GetSafeHwnd(), NULL); } //---------------------------------------------------------------------------- void CSplashScreenWnd::HideSplashScreen(){ //---------------------------------------------------------------------------- PROC_TRACE; // Fenster entfernen und Hauptrahmen aktualisieren DestroyWindow(); AfxGetMainWnd()->UpdateWindow(); } //---------------------------------------------------------------------------- void CSplashScreenWnd::PostNcDestroy(){ //---------------------------------------------------------------------------- PROC_TRACE; delete this; } //---------------------------------------------------------------------------- int CSplashScreenWnd::OnCreate(LPCREATESTRUCT lpCreateStruct){ //---------------------------------------------------------------------------- PROC_TRACE; if (CWnd::OnCreate(lpCreateStruct) == -1) return -1; // Fenster zentrieren CenterWindow(); // Zeitgeber festlegen, um den Begrüßungsbildschirm zu entfernen. SetTimer(1, 1750, NULL); return 0; } //---------------------------------------------------------------------------- void CSplashScreenWnd::OnPaint(){ //---------------------------------------------------------------------------- PROC_TRACE; CPaintDC dc(this); CDC dcImage; if (!dcImage.CreateCompatibleDC(&dc)) return; BITMAP bm; m_bitmap.GetBitmap(&bm); // Bild zeichnen CBitmap* pOldBitmap = dcImage.SelectObject(&m_bitmap); dc.BitBlt(0, 0, bm.bmWidth, bm.bmHeight, &dcImage, 0, 0, SRCCOPY); dcImage.SelectObject(pOldBitmap); } //---------------------------------------------------------------------------- void CSplashScreenWnd::OnTimer(UINT nIDEvent){ //---------------------------------------------------------------------------- PROC_TRACE; HideSplashScreen(); }
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "Windows.Devices.1.h" WINRT_EXPORT namespace winrt { namespace Windows::Devices { struct ILowLevelDevicesAggregateProvider : Windows::Foundation::IInspectable, impl::consume<ILowLevelDevicesAggregateProvider> { ILowLevelDevicesAggregateProvider(std::nullptr_t = nullptr) noexcept {} }; struct ILowLevelDevicesAggregateProviderFactory : Windows::Foundation::IInspectable, impl::consume<ILowLevelDevicesAggregateProviderFactory> { ILowLevelDevicesAggregateProviderFactory(std::nullptr_t = nullptr) noexcept {} }; struct ILowLevelDevicesController : Windows::Foundation::IInspectable, impl::consume<ILowLevelDevicesController> { ILowLevelDevicesController(std::nullptr_t = nullptr) noexcept {} }; struct ILowLevelDevicesControllerStatics : Windows::Foundation::IInspectable, impl::consume<ILowLevelDevicesControllerStatics> { ILowLevelDevicesControllerStatics(std::nullptr_t = nullptr) noexcept {} }; } }
#include "io.hpp" #include <vector> #include <fstream> #include <landstalker-lib/model/map.hpp> #include <landstalker-lib/model/map_connection.hpp> #include <landstalker-lib/tools/stringtools.hpp> #include <landstalker-lib/tools/json.hpp> #include "../logic_model/data/world_path.json.hxx" #include "../logic_model/world_node.hpp" #include "../logic_model/randomizer_world.hpp" namespace GraphvizWriter { constexpr const char* COLORS[] = { "indianred2", "lightslateblue", "limegreen", "deeppink2", "darkorchid3", "chocolate2", "darkturquoise" }; size_t COLORS_SIZE = 7; void write_logic_as_dot(const RandomizerWorld& world, const std::string& path) { std::ofstream graphviz(path); graphviz << "digraph {\n"; graphviz << "\tgraph [pad=0.5, nodesep=0.4, ranksep=1];\n"; graphviz << "\tnode[shape=rect];\n\n"; Json paths_json = Json::parse(WORLD_PATHS_JSON); uint32_t path_i = 0; for(const Json& json : paths_json) { WorldNode* from = world.node(json["fromId"]); WorldNode* to = world.node(json["toId"]); graphviz << "\t" << from->id() << " -> " << to->id() << " ["; if(json.contains("twoWay") && json.at("twoWay")) graphviz << "dir=both "; std::vector<std::string> required_names; if(json.contains("requiredItems")) for(const std::string item_name : json.at("requiredItems")) required_names.emplace_back(item_name); if(json.contains("requiredNodes")) for(const std::string node_id : json.at("requiredNodes")) required_names.emplace_back("Access to " + world.node(node_id)->name()); if(!required_names.empty()) { const char* current_color = COLORS[path_i % COLORS_SIZE]; graphviz << "color=" << current_color << " "; graphviz << "fontcolor=" << current_color << " "; graphviz << "label=\"" << stringtools::join(required_names, "\\n") << "\" "; } graphviz << "]\n"; path_i++; } graphviz << "\n"; for(auto& [id, node] : world.nodes()) graphviz << "\t" << id << " [label=\"" << node->name() << " [" << std::to_string(node->item_sources().size()) << "]\"]\n"; graphviz << "}\n"; } void write_maps_as_dot(const RandomizerWorld& world, const std::string& path) { std::ofstream graphviz(path); graphviz << "digraph {\n"; graphviz << "\tgraph [pad=0.5, nodesep=0.4, ranksep=1];\n"; graphviz << "\tnode[shape=rect];\n\n"; for(auto& [map_id, map] : world.maps()) { for(const MapConnection& connection : world.map_connections()) graphviz << "\t" << connection.map_id_1() << " -> " << connection.map_id_2() << "\n"; if(map->fall_destination() != 0xFFFF) graphviz << "\t" << map->id() << " -> " << map->fall_destination() << "\n"; if(map->climb_destination() != 0xFFFF) graphviz << "\t" << map->id() << " -> " << map->climb_destination() << "\n"; for(auto& [variant_map, flag] : map->variants()) { graphviz << "\t" << map->id() << " -> " << variant_map->id() << "[color=indianred2, penwidth=2]\n"; graphviz << "\t" << variant_map->id() << "[style=filled, fillcolor=indianred2]\n"; } } graphviz << "}\n"; } } // namespace graphviz end
#include<stdio.h> #include<malloc.h> int fib(int); int main(){ int n=999; fib(n); return 0; } int fib(int n){ long long f[n+1]; long long i; f[0]=0; f[1]=1; printf(" %d %d ", f[0],f[1]); for(i=2;i<n;i++){ f[i]=f[i-1]+f[i-2]; printf(" %d ", f[i]); } return f[n]; }
#pragma once #include <random> // Util Random is a singleton class that allows us to generate a random number within a fixed range // it uses elements from the C++11 update to replace the use of rand(). class UtilRandom { public: UtilRandom(); ~UtilRandom(); // GetRange returns a random number between min and max // it is poorly named, we're not really getting a range... float GetRange(float min, float max); private: // we use the mersenne twister implementation to generate our random numbers std::mt19937 mt; // we have a private static instance of the class static UtilRandom* _instance; public: // the static instance() function means we can control the number of instances allowed at any one time (here, one). static UtilRandom* instance() { if (!_instance) _instance = new UtilRandom; return _instance; } };
#pragma once #include <landstalker-lib/patches/game_patch.hpp> #include "../../logic_model/randomizer_world.hpp" #include "../../logic_model/world_teleport_tree.hpp" /** * This patch updates the map connections between the teleport tree maps to reflect potential changes that have * been made to the teleport tree pairs during generation (either through the "shuffleTrees" option or through * explicit choice of trees in plando) */ class PatchUpdateTeleportTreeConnections : public GamePatch { public: void alter_world(World& world) override { const RandomizerWorld& randomizer_world = reinterpret_cast<RandomizerWorld&>(world); std::vector<MapConnection*> map_connection_pool; for(const auto& pair : randomizer_world.teleport_tree_pairs()) { WorldTeleportTree* tree_1 = pair.first; WorldTeleportTree* tree_2 = pair.second; for(MapConnection* conn : world.map_connections(tree_1->map_id(), tree_1->paired_map_id())) if(!vectools::contains(map_connection_pool, conn)) map_connection_pool.emplace_back(conn); for(MapConnection* conn : world.map_connections(tree_2->map_id(), tree_2->paired_map_id())) if(!vectools::contains(map_connection_pool, conn)) map_connection_pool.emplace_back(conn); } uint8_t i=0; for(const auto& pair : randomizer_world.teleport_tree_pairs()) { WorldTeleportTree* tree_1 = pair.first; WorldTeleportTree* tree_2 = pair.second; tree_1->paired_map_id(tree_2->map_id()); tree_2->paired_map_id(tree_1->map_id()); // Pick map connections from the connection pool and set both map_ids to both ends of the pair MapConnection* conn_1 = map_connection_pool[i++]; conn_1->map_id_1(tree_1->map_id()); conn_1->map_id_2(tree_2->map_id()); MapConnection* conn_2 = map_connection_pool[i++]; conn_2->map_id_1(tree_2->map_id()); conn_2->map_id_2(tree_1->map_id()); } } };
#ifndef PISTOL_BULLET_H_INCLUDED #define PISTOL_BULLET_H_INCLUDED #include "gameobjects/weapons/bullet.h" #include <iostream> class PistolBullet : public Bullet { public: virtual bool on_wall_collision(const std::vector<Rectangle>& player_positions, std::function<void(int, double)> damage_player) override; virtual bool on_player_collision(int hit_player, const std::vector<Rectangle>& player_positions, std::function<void(int, double)> damage_player) override; virtual bool on_no_collision() override; virtual double get_velocity() const override; virtual ExplosionType get_explosion() const override{ return ExplosionType::PISTOL; } virtual bool on_blocker_collision(const std::vector<Rectangle>& player_positions, std::function<void(int, double)> damage_player) override { return true; } virtual void render(RenderList& list) const override; int ticks_alive = 0; private: virtual const char* bullet_image_name() const override; }; #endif
#include <iostream> #include "mystring.h" using namespace std; MyString::MyString(){ str = nullptr; strLength=0; } //------------------------ MyString::MyString(const char * str1) { int si=0; while (str1[si] != '\0'){ si++; } str = new char [si+1]; for(int i=0; i< si; i++) str[i] = str1[i]; str[si]='\0'; strLength = si; } //--------------------------- MyString::MyString(const MyString& str_obj) { int si=0; while (str_obj.str[si] != '\0'){ si++; } str = new char [si+1]; for(int i=0; i< si; i++) str[i] = str_obj.str[i]; str[si]='\0'; strLength = si; } //---------------------------- void MyString::assign(const MyString obj) { delete str; int si=0; while(obj.str[si] != '\0') si++; str = new char [si+1]; for(int i=0; i < si; i++) str[i] = obj.str[i]; str[si]='\0'; strLength = si; } //--------------------- void MyString::assign(const char *str1) { delete str; int si=0; while(str1[si] != '\0') si++; str = new char [si+1]; for(int i=0; i < si; i++) str[i] =str[i]; str[si]='\0'; strLength = si; } //-------------------- void MyString::display(){ if( str != nullptr) cout << str << endl; else{cout << "" << endl;} } //-------------------- int MyString::getLength(){ return strLength; } //--------------------------------- void MyString::append(char const *str1){ if(str != nullptr){ int si1=0,s2=strLength; while(str1[si1] != '\0') si1++; char *temp = new char [si1+s2+1]; //cout << si1+s2+1 << endl; for(int i=0; i< s2; i++) temp[i]=str[i]; for(int i=s2,j=0; i< si1+s2; i++) temp[i] =str1[j++]; temp[si1+s2] = '\0'; delete str; str = temp; } } //--------------------------- void MyString::append(const MyString &obj){ if(str != nullptr){ int si1=0,s2=strLength; while(obj.str[si1] != '\0') si1++; char *temp = new char [si1+s2+1]; //cout << si1+s2+1 << endl; for(int i=0; i< s2; i++) temp[i]=str[i]; for(int i=s2,j=0; i< si1+s2; i++) temp[i] =obj.str[j++]; temp[si1+s2] = '\0'; delete str; str = temp; } } //---------------------------- int MyString::compareTo(const char *str1){ if(str != nullptr){ int si=0,si1=0; // si1 index of str1 while(str1[si1] != '\0' && str[si1] !='\0'){ if(str1[si1] > str[si1]) return -1; else if(str[si1] > str1[si1]) return 1; si1++; } if(str1[si1] > str[si1]) return -1; else if(str[si1] > str1[si1]) return 1; else return 0; } } //-------------------------- int MyString::compareTo(const MyString obj){ if(str != nullptr){ int si=0,si1=0; // si1 index of str1 while(obj.str[si1] != '\0' && str[si1] !='\0'){ if(obj.str[si1] > str[si1]) return -1; else if(str[si1] > obj.str[si1]) return 1; si1++; } if(obj.str[si1] > str[si1]) return -1; else if(str[si1] > obj.str[si1]) return 1; else return 0; } } //------------ MyString::~MyString(){ delete str; str = nullptr; } int main(){ MyString s1; s1.display(); s1.assign("assigned string by const string"); s1.display(); cout << "assigning by object\n"; s1.assign(s1); s1.display(); MyString s2("this is string"); s2.display(); MyString s3(s2); s3.display(); s3.append("appended string"); s3.display(); s3.append(s2); s3.display(); cout << s2.compareTo("this is string"); cout << s2.compareTo(s3); system("pause"); }
#ifndef SCALEDEV_H #define SCALEDEV_H #include <QtCore> #include "iodev.h" class ScaledIoDev: public IoDev { public: ScaledIoDev() {} virtual ~ScaledIoDev()=0; protected: // наступні функції потрібні тільки на сервері, можливо їх варто винести в окремий клас і класам-нащадкам, які спілкуються із реальними присторями варто робити подвійне наслідування virtual void loadScale(QString fileName); // це завантажить шкали, це не повинно бути видно із-зовні, це погане рішення передавати ім’я файла void updateScaledValue(); // це поновить шкальовані значення //private : // Сховище даних. не наслідується, потібно тільки для компіляції, використовуються сховища нащадків // QHash<QString,QVector<qint16> > tags; // таблиця тегів // QVector<qint16> data_raw; // сирі дані із PLC // QHash<QString,QVector<double> > data_scale; // оброблені дані, хеш дублює tags. у векторі значення розташовані у наспупному порядку: value,zero,full }; #endif // SCALEDEV_H
#include "returncommand.h" #include "store.h" ReturnCommand::ReturnCommand():searchCustomer(0,"","") { } ReturnCommand::ReturnCommand(int customerID, char type, char subtype, std::string data): searchCustomer(customerID, "", "") { searchRentable = buildRentable(type, subtype, data); } ReturnCommand::~ReturnCommand() { delete searchRentable; } bool ReturnCommand::processCommand() { RentableStorage& rentables = getRentableStorage(); HashTable& customers = getHashTable(); Customer* actualCustomer; customers.retrieve(searchCustomer, actualCustomer); if(actualCustomer == nullptr) { std::cerr << "ERROR: Customer with ID " << searchCustomer.getCustomerID(); std::cerr<< " not found." << std::endl; return false; } Rentable* actualRentable; if(!rentables.retrieve(searchRentable, actualRentable)) { std::cerr << "ERROR: Rentable with title " << searchRentable->getTitle(); std::cerr<< " not carried in the store." << std::endl; return false; } //update in store actualRentable->addToStock(1); actualCustomer->returnRentable(1, *actualRentable); return true; }
#include "wizDocumentTransitionView.h" #include <QtGui> CWizDocumentTransitionView::CWizDocumentTransitionView(QWidget *parent) : QWidget(parent) { m_labelHint = new QLabel(this); QVBoxLayout* layout = new QVBoxLayout(); layout->addStretch(1); layout->addWidget(m_labelHint); layout->addStretch(1); setLayout(layout); } void CWizDocumentTransitionView::showAsMode(TransitionMode mode) { Q_UNUSED(mode); if (mode == Downloading) { m_labelHint->setText(tr("Downloading document from cloud server...")); } else if (mode == ErrorOccured) { m_labelHint->setText(tr("Error occured while loading document.")); } show(); }
// // TonalityEncoder.h // PianoPlayer // // Created by Ben Smith on 11/2/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #include "SpatialEncoder.h" class TonalityEncoder : public SpatialEncoder { public: TonalityEncoder(int tokenCount); // void DoEncoding(int token); void AddToken(int token); void DecayEncoding(const double& scalar); };
#include "compute_weighted_add.h" int main(int argc, char *argv[]) { if (auto error = initialize()) { return -1; } auto create_name = "compute_weighted_add"; SDL_Window *window; vkb::Instance instance; VkSurfaceKHR surface; if (auto error = create_window_instance_surface(create_name, window, instance, surface)) { return -1; } vkb::PhysicalDevice physical_device; vkb::Device device; VmaAllocator allocator; if (auto error = create_device_allocator(instance, surface, physical_device, device, allocator)) { return -1; } VkQueue graphics_queue, compute_queue; uint32_t graphics_queue_index, compute_queue_index; if (auto error = get_graphics_compute_queue( device, graphics_queue, graphics_queue_index, compute_queue, compute_queue_index)) { return -1; } VkCommandPool graphics_command_pool; if (auto error = create_command_pool(device, graphics_queue_index, graphics_command_pool)) { return -1; } VkCommandPool compute_command_pool; if (auto error = create_command_pool(device, compute_queue_index, compute_command_pool)) { return -1; } VkDescriptorPool descriptor_pool; if (auto error = create_descriptor_pool(device, descriptor_pool)) { return -1; } uint64_t length = 16384; VkBuffer buffer_storage_a; VmaAllocation allocation_storage_a; VmaAllocationInfo allocation_info_storage_a; if (auto error = compute_weighted_add::create_buffer_storage( allocator, length * ELEMENT_SIZE, buffer_storage_a, allocation_storage_a, allocation_info_storage_a)) { return -1; } auto pointer_a = (float4 *)allocation_info_storage_a.pMappedData; VkBuffer buffer_storage_b; VmaAllocation allocation_storage_b; VmaAllocationInfo allocation_info_storage_b; if (auto error = compute_weighted_add::create_buffer_storage( allocator, length * ELEMENT_SIZE, buffer_storage_b, allocation_storage_b, allocation_info_storage_b)) { return -1; } auto pointer_b = (float4 *)allocation_info_storage_b.pMappedData; pointer_b[4094] = vec4(.5f); VkBuffer buffer_storage_c; VmaAllocation allocation_storage_c; VmaAllocationInfo allocation_info_storage_c; if (auto error = compute_weighted_add::create_buffer_storage( allocator, length * ELEMENT_SIZE, buffer_storage_c, allocation_storage_c, allocation_info_storage_c)) { return -1; } auto pointer_c = (float4 *)allocation_info_storage_c.pMappedData; VkBuffer buffer_storage_d; VmaAllocation allocation_storage_d; VmaAllocationInfo allocation_info_storage_d; if (auto error = compute_weighted_add::create_buffer_storage( allocator, length * ELEMENT_SIZE, buffer_storage_d, allocation_storage_d, allocation_info_storage_d)) { return -1; } auto pointer_d = (float4 *)allocation_info_storage_d.pMappedData; ComputeWeightedAddConstants constants{ .weights = vec4(1.f, 1.f, 1.f, 1.f), .length = uvec2(length / ELEMENT_WIDTH, length % ELEMENT_WIDTH)}; if (constants.length.y > 0) { constants.length.x += 1; } VkBuffer buffer_uniform; VmaAllocation allocation_uniform; VmaAllocationInfo allocation_info_uniform; if (auto error = create_buffer_uniform(allocator, sizeof(constants), buffer_uniform, allocation_uniform, allocation_info_uniform)) { return -1; } memcpy(allocation_info_uniform.pMappedData, &constants, sizeof(constants)); VkDescriptorSetLayout set_layout; VkPipelineLayout pipeline_layout; if (auto error = compute_weighted_add::create_set_pipeline_layout( device, set_layout, pipeline_layout)) { return -1; } uint3 local_size = uvec3(16, 32, 1); auto module_name = "compute_weighted_add.hpp"; VkShaderModule shader_module; if (auto error = create_shader_module(device, module_name, shader_module)) { return -1; } auto entry_name = "compute_weighted_add_kernel"; VkPipeline pipeline; if (auto error = create_pipeline(device, pipeline_layout, shader_module, local_size, entry_name, pipeline)) { return -1; } vkb::Swapchain swapchain; std::vector<VkImage> images; std::vector<VkImageView> image_views; std::vector<VkFence> signal_fences; std::vector<VkSemaphore> wait_semaphores, signal_semaphores; std::vector<VkFence> wait_fences; std::vector<VkFramebuffer> framebuffers; VkRenderPass render_pass; if (auto error = create_swapchain_semaphores_fences_render_pass_framebuffers( device, swapchain, images, image_views, signal_fences, wait_semaphores, signal_semaphores, render_pass, framebuffers)) { return -1; } std::vector<VkDescriptorSet> descriptor_sets; if (auto error = compute_weighted_add::allocate_descriptor_sets( device, buffer_storage_a, allocation_info_storage_a, buffer_storage_b, allocation_info_storage_b, buffer_storage_c, allocation_info_storage_c, buffer_storage_d, allocation_info_storage_d, buffer_uniform, allocation_info_uniform, swapchain, image_views, set_layout, descriptor_pool, descriptor_sets)) { return -1; } std::vector<VkCommandBuffer> graphics_command_buffers; if (auto error = allocate_command_buffers( window, device, graphics_queue_index, graphics_command_pool, swapchain, graphics_command_buffers)) { return -1; } std::vector<VkCommandBuffer> compute_command_buffers; if (auto error = allocate_command_buffers( window, device, compute_queue_index, compute_command_pool, swapchain, compute_command_buffers)) { return -1; } uint32_t image_index = 0; if (vkWaitForFences(device.device, 1, &signal_fences[image_index], VK_TRUE, UINT64_MAX) != VK_SUCCESS) { return -1; } if (vkResetFences(device.device, 1, &signal_fences[image_index]) != VK_SUCCESS) { return -1; } if (vkResetCommandBuffer(compute_command_buffers[image_index], VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT) != VK_SUCCESS) { return -1; } VkCommandBufferBeginInfo begin_info = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; if (vkBeginCommandBuffer(compute_command_buffers[image_index], &begin_info) != VK_SUCCESS) { return -1; } vkCmdBindPipeline(compute_command_buffers[image_index], VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); vkCmdBindDescriptorSets(compute_command_buffers[image_index], VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_layout, 0, 1, &descriptor_sets[image_index], 0, nullptr); vkCmdDispatch(compute_command_buffers[image_index], length / (local_size.x * local_size.y) + 1, 1, 1); if (vkEndCommandBuffer(compute_command_buffers[image_index]) != VK_SUCCESS) { return -1; } VkPipelineStageFlags wait_stages[] = {VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT}; VkSubmitInfo submit_info = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .waitSemaphoreCount = 0, .pWaitSemaphores = nullptr, .pWaitDstStageMask = wait_stages, .commandBufferCount = 1, .pCommandBuffers = &compute_command_buffers[image_index], .signalSemaphoreCount = 0, .pSignalSemaphores = nullptr}; if (vkQueueSubmit(compute_queue, 1, &submit_info, signal_fences[image_index]) != VK_SUCCESS) { return -1; } vkDeviceWaitIdle(device.device); auto &element = pointer_a[4094]; std::cout << element.x << " " << element.y << " " << element.z << " " << element.w << "\n"; vkFreeCommandBuffers(device.device, compute_command_pool, compute_command_buffers.size(), compute_command_buffers.data()); vkFreeCommandBuffers(device.device, graphics_command_pool, graphics_command_buffers.size(), graphics_command_buffers.data()); vkFreeDescriptorSets(device.device, descriptor_pool, descriptor_sets.size(), descriptor_sets.data()); for (auto &framebuffer : framebuffers) { vkDestroyFramebuffer(device.device, framebuffer, nullptr); } vkDestroyRenderPass(device.device, render_pass, nullptr); for (auto &semaphore : signal_semaphores) { vkDestroySemaphore(device.device, semaphore, nullptr); } for (auto &semaphore : wait_semaphores) { vkDestroySemaphore(device.device, semaphore, nullptr); } for (auto &fence : signal_fences) { vkDestroyFence(device.device, fence, nullptr); } swapchain.destroy_image_views(image_views); vkb::destroy_swapchain(swapchain); vkDestroyPipeline(device.device, pipeline, nullptr); vkDestroyShaderModule(device.device, shader_module, nullptr); vkDestroyPipelineLayout(device.device, pipeline_layout, nullptr); vkDestroyDescriptorSetLayout(device.device, set_layout, nullptr); vmaDestroyBuffer(allocator, buffer_uniform, allocation_uniform); vmaDestroyBuffer(allocator, buffer_storage_d, allocation_storage_d); vmaDestroyBuffer(allocator, buffer_storage_c, allocation_storage_c); vmaDestroyBuffer(allocator, buffer_storage_b, allocation_storage_b); vmaDestroyBuffer(allocator, buffer_storage_a, allocation_storage_a); vkDestroyDescriptorPool(device.device, descriptor_pool, nullptr); vkDestroyCommandPool(device.device, compute_command_pool, nullptr); vkDestroyCommandPool(device.device, graphics_command_pool, nullptr); vmaDestroyAllocator(allocator); vkb::destroy_device(device); vkDestroySurfaceKHR(instance.instance, surface, nullptr); vkb::destroy_instance(instance); SDL_DestroyWindow(window); SDL_Quit(); return 0; }
#pragma once //DownArrowKey.h #ifndef _DOWNARROWKEY_H #define _DOWNARROWKEY_H #include "KeyAction.h" class DownArrowKey :public KeyAction { public: DownArrowKey(Form *form = 0); DownArrowKey(const DownArrowKey& source); ~DownArrowKey(); DownArrowKey& operator=(const DownArrowKey& source); virtual void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); }; #endif //_DOWNARROWKEY_H
#include "Bishop.h" Bishop::Bishop(int color, int row, int col) : ChessPiece(color, row, col) { if (color == 0) { this->symbol = 'B'; } else { this->symbol = 'b'; } this->name = "Bishop"; }; // Function to return Piece Name std::string Bishop::getName() const { return name; } // Function to get Piece symbol to print board for visualisation char Bishop::getSymbol() { return symbol; } /* Function to check if src_piece can be moved to spot with coord * (to_row, to_col). */ bool Bishop::canMove(ChessPiece *board[][8], int to_row, int to_col, // bool in_check, ChessPiece *white_pieces[], // ChessPiece *black_pieces[]) { // Calculate absolute vertical and horizontal offset distances int abs_dist_row = abs(this->getRow() - to_row); int abs_dist_col = abs(this->getCol() - to_col); // Check if Bishop is making a diagonal move if (abs_dist_row != abs_dist_col) { return false; } /* Check if there are any chess piece between the source and * destination location * D1 || D2 * ======== * D3 || D4 */ if (to_row < this->getRow()) { // Check for diagonal 1 if (to_col < this->getCol()) { for (int i = 1; i < abs_dist_row; i++) { if (board[this->getRow() - i][this->getCol() - i] != nullptr) { return false; } } } // Check for diagonal 2 if (to_col > this->getCol()) { for (int i = 1; i < abs_dist_row; i++) { if (board[this->getRow() - i][this->getCol() + i] != nullptr) { return false; } } } } if (to_row > this->getRow()) { // Check for diagonal 3 if (to_col < this->getCol()) { for (int i = 1; i < abs_dist_row; i++) { if (board[this->getRow() + i][this->getCol() - i] != nullptr) { return false; } } } // Check for diagonal 4 if (to_col > this->getCol()) { for (int i = 1; i < abs_dist_row; i++) { if (board[this->getRow() + i][this->getCol() + i] != nullptr) { return false; } } } } return true; }
#pragma once #include <string> #include <map> #include <list> #include "Game.h" #include "Command.h" using namespace std; class CommandFactory { private: map<string, Command*> mapping; public: CommandFactory(); ~CommandFactory(); void CreateCommand(string commandString, list<string>* parameters, Game* game); };
/* Author: Nayeemul Islam Swad Idea: - Let S = floor(sqrt(1)) + floor(sqrt(1)) + ... + floor(sqrt(n)) Notice that, for a fixed integer x, if floor(sqrt(y)) = x then x ^ 2 <= y < (x + 1) ^ 2. So, if f(x) is the number of times x appears into the sum S, f(x) is simply equal to the number of odd numbers in the range [x^2, (x + 1)^2). This can be easily computed, f(x) = x, if x is even f(x) = x + 1, otherwise - So, the contibution of x to the sum is f(x) * x, for all x < floor(sqrt(n)). Let, y = floor(sqrt(n)) - 1. 1 * f(1) + 2 * f(2) + ... + y * f(y) = [sum of (i * i + (1 if i is odd, 0 otherwise))] = [sum of (i * i)] + number of odd i = y * (y + 1) * (2 * y + 1) / 6 + (y + 1) / 2 Since y is really big, we need to be careful while computing this multiplication to avoid overflow. Finally, compute f(y + 1) separately and add (y + 1) * f(y + 1) to the sum found before. */ #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; #define x first #define y second #ifdef LOCAL #include "/Users/swad/Desktop/CP/debug.h" #endif const int N = int(1e5) + 10; const int MOD = int(1e8); int main() { #ifdef LOCAL freopen("in", "r", stdin); freopen("out", "w", stdout); #endif ull n; while (cin >> n) { if (n == 0) break; ull x = sqrt(n) - 1; ull t[3] = {x, x + 1, 2 * x + 1}; for (int i = 0; i < 3; i++) if (t[i] % 2 == 0) {t[i] /= 2; break;} for (int i = 0; i < 3; i++) if (t[i] % 3 == 0) {t[i] /= 3; break;} ull ans = 1ULL; for (int i = 0; i < 3; i++) (ans *= t[i]) %= MOD; x++; (ans += (x / 2) * (x / 2) % MOD) %= MOD; (ans += (n - x * x + 1 + x % 2) / 2 % MOD * x % MOD) %= MOD; cout << ans << "\n"; } return 0; }
/** MIT License Copyright (c) 2019 mpomaranski at gmail 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. */ #if defined _WIN32 #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include <winsock2.h> #include <windows.h> #endif #include "box_server.hpp" #include "box.hpp" #include "hdd_box_serialization_strategy.hpp" #include "mem_box_serialization_strategy.hpp" #include <easylogging++.h> #include <granada/util/application.h> #include <memory> #include <props.hpp> #include <sstream> using namespace std; using namespace cleric::data; cleric::data::BoxServer::BoxServer() : shouldStopDelayedWrite(false) { delayedWriteThread = make_unique<thread>([&]() { LOG(INFO) << "[BoxServer::delayedWriteThread] {thread_started}"; const auto MIN_WRITE_DELAY_MS = 100; while (true) { for (auto i = 0; i < MIN_WRITE_DELAY_MS; i++) { if (shouldStopDelayedWrite) { LOG(INFO) << "[BoxServer::delayedWriteThread] {thread_stopped}"; return; } this_thread::sleep_for(chrono::milliseconds(1)); } delayedWriteOnce(); } }); // TODO restore list of stored boxes - before the first release } cleric::data::BoxServer::~BoxServer() { try { // todo save list of stored boxes - before the first release shouldStopDelayedWrite = true; if (delayedWriteThread->joinable()) { delayedWriteThread->join(); } } catch (...) { // catch all } LOG(INFO) << "[BoxServer::BoxServer] {desytoying}"; } shared_ptr<Box> cleric::data::BoxServer::getBoxById(const cleric::BoxId &boxId) { lock_guard<mutex> lock(boxCacheMtx); auto cached = boxCache.find(boxId); if (cached == boxCache.end()) { // no box found, create one auto storageStrategy = granada::util::application::GetProperty( cleric::props::STORAGE_STRATEGY_PROP_NAME); auto retentionPeriod = std::chrono::hours(24 * 365); // TODO expose in configurtion auto maxEntries = 1000; // TODO expose in configurtion LOG(INFO) << "[BoxServer@" << (void *)this << "@" << this_thread::get_id() << "::getBoxById] {createBox} {boxId='" << boxId << "'" << " name='" << to_string(boxId) << "'" << " storageStrategy='" << storageStrategy << "'" << " retentionPeriod='" << retentionPeriod.count() << "'" << " maxEntries='" << maxEntries << "'}"; if (storageStrategy == cleric::props::STORAGE_STRATEGY_PROP_MEMORY) { std::unique_ptr<cleric::data::IBoxSerializationStrategy> serializer{ new MemBoxSerializationStrategy()}; auto box = make_shared<Box>(boxId, to_string((int)boxId), retentionPeriod, maxEntries, std::move(serializer)); boxCache[boxId] = box; LOG(INFO) << "[BoxServer::getBoxById] {createBox} {new_box}"; return box; } else if (storageStrategy == cleric::props::STORAGE_STRATEGY_PROP_HDD) { auto storagePath = granada::util::application::GetProperty( cleric::props::STORAGE_ROOT_PROP_NAME); std::unique_ptr<cleric::data::IBoxSerializationStrategy> serializer{ new HddBoxSerializationStrategy(boxId, storagePath)}; auto buff = serializer->get(); if (buff.size() != 0) { try { auto box = make_shared<Box>(std::move(serializer)); boxCache[boxId] = box; LOG(INFO) << "[BoxServer::getBoxById] {createBox} {deserialized}"; return box; } catch (const std::exception &e) { LOG(ERROR) << "[BoxServer::getBoxById] {createBox} " "{unexpected_exception} {what='" << e.what() << "'}"; } } if (!serializer) { // we're here because of the exception during derserialisation, recreate // serializer std::unique_ptr<cleric::data::IBoxSerializationStrategy> newSerializer{ new HddBoxSerializationStrategy(boxId, storagePath)}; serializer = move(newSerializer); } LOG(INFO) << "[BoxServer::getBoxById] {createBox} {new_box}"; auto box = make_shared<Box>(boxId, to_string((int)boxId), retentionPeriod, maxEntries, std::move(serializer)); boxCache[boxId] = box; return box; } else { throw illegal_state_exception("State strategy not known"); } } else { return cached->second; } } vector<::cleric::BoxId> cleric::data::BoxServer::getAllBoxes() const { vector<::cleric::BoxId> keys; transform(boxCache.begin(), boxCache.end(), back_inserter(keys), [](auto pair) { return pair.first; }); return keys; } void cleric::data::BoxServer::eraseAllData() { boxCache.clear(); } // delayed write of the box data void cleric::data::BoxServer::delayedWriteOnce() { try { vector<shared_ptr<cleric::data::Box>> toPersist; // TODO - benchmark when list is faster than vector; fix // before the stable release { unique_lock<mutex>(boxCacheMtx); for (auto &b : boxCache) { if (b.second->isDirty()) { toPersist.push_back(b.second); } } } for (auto &b : toPersist) { b->persist(); b->setDirty(false); } if (toPersist.size() > 0) { VLOG(1) << "[BoxServer::delayedWriteOnce] {persistBoxes} {toPersistSize='" << toPersist.size() << "'}"; } } catch (const std::exception &e) { LOG(ERROR) << "[BoxServer::delayedWriteOnce] {unexpected_exception} {what='" << e.what() << "'}"; } }
// // Bootscreen.cpp // // Copyright(c) 2013 - The Foreseeable Future, zhiayang@gmail.com // // Licensed under the Apache License Version 2.0. // #include <Kernel.hpp> // #include <Console.hpp> // #include <HardwareAbstraction/VideoOutput.hpp> // #include <Bootscreen.hpp> // #include <BitmapLibrary/BitmapLibrary.hpp> // #include <Memory.hpp> // #include <String.hpp> // #include <StandardIO.hpp> // #include <math.h> // using namespace Library; // using namespace Kernel::HardwareAbstraction::VideoOutput; // using namespace Kernel::HardwareAbstraction; // namespace Kernel { // namespace Bootscreen // { // void Initialise() // { // using Kernel::HardwareAbstraction::Filesystems::VFS::File; // File* bmpimg = new File("/System/Library/Resources/logo@0.5x.bmp"); // assert(bmpimg); // uint8_t* addr = new uint8_t[bmpimg->FileSize()]; // bmpimg->Read(addr); // File* nbmp = new File("/System/Library/Resources/name.bmp"); // assert(nbmp); // uint8_t* nma = new uint8_t[nbmp->FileSize()]; // nbmp->Read(nma); // // 35 31 32 IN SRGB // // 45 40 43 // // 26 23 24 IN RGB // Console::SetColour(0xFFFFFFFF); // Memory::Set32((void*) GetFramebufferAddress(), 0x00, (LinearFramebuffer::GetResX() * LinearFramebuffer::GetResY()) / 2); // LinearFramebuffer::backColour = 0x00; // BitmapLibrary::BitmapImage* bmp = new BitmapLibrary::BitmapImage((void*) addr); // BitmapLibrary::BitmapImage* ni = new BitmapLibrary::BitmapImage((void*) nma); // bmp->Render((uint16_t)((LinearFramebuffer::GetResX() - bmp->DIB->GetBitmapWidth()) / 2), (uint16_t)((LinearFramebuffer::GetResY() - math::abs(bmp->DIB->GetBitmapHeight())) / 2 - 40), LinearFramebuffer::GetResX(), (uint32_t*) GetFramebufferAddress()); // ni->Render((uint16_t)((LinearFramebuffer::GetResX() - ni->DIB->GetBitmapWidth()) / 2), (uint16_t)((LinearFramebuffer::GetResY() - math::abs(ni->DIB->GetBitmapHeight())) / 2 + 120), LinearFramebuffer::GetResX(), (uint32_t*) GetFramebufferAddress()); // delete[] nma; // delete[] addr; // } // void StartProgressBar() // { // string thing = string("[ ]"); // uint64_t l = String::Length(thing); // uint16_t xp = (uint16_t)(Console::GetCharsPerLine() - l) / 2 + 1; // uint16_t ox = Console::GetCursorX(), oy = Console::GetCursorY(); // uint16_t y = (uint16_t)(0.85 * Console::GetCharsPerColumn()) + 1; // for(int i = 0; i < 50; i++) // { // thing[i + 1] = '='; // { // Console::MoveCursor(0, y); // string spaces; // // clear the line. // for(uint64_t k = 0; k < Console::GetCharsPerLine(); k++) // { // spaces += ' '; // } // StandardIO::PrintString(spaces); // Console::MoveCursor(xp, y); // StandardIO::PrintString(thing); // Console::MoveCursor(ox, oy); // } // SLEEP(50); // } // } // void PrintMessage(const char* msg) // { // uint64_t l = String::Length(msg); // uint16_t xp = (uint16_t)(Console::GetCharsPerLine() - l) / 2 + 1; // uint16_t ox = Console::GetCursorX(), oy = Console::GetCursorY(); // uint16_t y = (uint16_t)(0.85 * Console::GetCharsPerColumn()); // Console::MoveCursor(0, y); // string spaces; // // clear the line. // for(uint64_t k = 0; k < Console::GetCharsPerLine(); k++) // { // spaces += ' '; // } // StandardIO::PrintString(spaces); // Console::MoveCursor(xp, y); // StandardIO::PrintString(msg); // Console::MoveCursor(ox, oy); // } // } // }
#include <iostream> enum class PolicyType {Default, Greedy, NotImplemented}; template<PolicyType T> struct priority { enum {val = 99}; }; template<> struct priority<PolicyType::Default> { enum {val = 0}; }; template<PolicyType T>class Policy { public: Policy() = default; ~Policy() = default; const int _priority = priority<T>::val; int set(){ //std::cout <<"Policy: " <<static_cast<int>(T) <<" "<<_priority<< std::endl; return 0; } }; static inline int add(int a, int b) { return a+b; } template<>class Policy<PolicyType::Greedy> { int value; int method; int goal; public: Policy():value(-1),method(-1), goal(add(10,20)){} Policy(int _value, int _method, int _goal):value(_value),method(_method),goal(_goal){} ~Policy() {} int set() { std::cout <<"Policy: " <<"PolicyType::Greedy "<< value << " " << method << " " << goal<< std::endl; return 0; } }; template<>class Policy<PolicyType::Default> { int value; int goal; const int _priority = priority<PolicyType::Default>::val; public: Policy(int _value, int _goal): value(_value), goal(_goal) {} ~Policy() {} int set() { std::cout <<"Policy: " << "PolicyType::Default" <<" "<< value << " " << goal<< std::endl; std::cout<<"priority: " << _priority<<std::endl; return 0; } }; template<PolicyType T> class TestClass { public: TestClass(int _id, const Policy<T> &_policy):id(_id), policy(_policy) {} TestClass() = default; ~TestClass(){} template <PolicyType TT> int set( Policy<TT> &&_policy) { _policy.set(); return 0; } int id; Policy<T> policy; }; struct Number_of_CPUs { enum {val = 48}; }; #if 0 //doesn't work here class AnotherPolicy { public: PolicyType type; int prior; AnotherPolicy(const PolicyType _type, const int _prior):type(_type), prior(_prior) {}; explicit AnotherPolicy(const PolicyType _type):type(_type),prior(priority<_type>::val){}; }; #endif int main() { Policy<PolicyType::Greedy> p{4,4,6}; p.set(); Policy<PolicyType::Default> d{4,10}; d.set(); Policy<PolicyType::NotImplemented> n; n.set(); PolicyType type = static_cast<PolicyType>(22); TestClass<PolicyType::Greedy> test1(34,Policy<PolicyType::Greedy>(4,5,6)); test1.policy.set(); TestClass<PolicyType::Greedy> test2; test2.set(Policy<PolicyType::Default>{6,12}); //AnotherPolicy test3(PolicyType::Default,5); //AnotherPolicy test4(PolicyType::Greedy); return 0; }
/* * LineHashIndex.cpp * * Created on: Nov 15, 2010 * Author: root */ #include "LineHashIndex.h" #include "MMapBuffer.h" #include "MemoryBuffer.h" #include "BitmapBuffer.h" #include <math.h> /** * linear fit; * f(x)=kx + b; * used to calculate the parameter k and b; */ static bool calculateLineKB(vector<LineHashIndex::Point>& a, double& k, double& b, int pointNo) { if (pointNo < 2) return false; double mX, mY, mXX, mXY; mX = mY = mXX = mXY = 0; int i; for (i = 0; i < pointNo; i++) { mX += a[i].x; mY += a[i].y; mXX += a[i].x * a[i].x; mXY += a[i].x * a[i].y; } if (mX * mX - mXX * pointNo == 0) return false; k = (mY * mX - mXY * pointNo) / (mX * mX - mXX * pointNo); b = (mXY * mX - mY * mXX) / (mX * mX - mXX * pointNo); return true; } LineHashIndex::LineHashIndex(ChunkManager& _chunkManager, IndexType index_type, XYType xy_type) : chunkManager(_chunkManager), indexType(index_type), xyType(xy_type) { // TODO Auto-generated constructor stub idTable = NULL; idTableEntries = NULL; lineHashIndexBase = NULL; startID[0] = startID[1] = startID[2] = startID[3] = UINT_MAX; } LineHashIndex::~LineHashIndex() { // TODO Auto-generated destructor stub idTable = NULL; idTableEntries = NULL; startPtr = NULL; endPtr = NULL; chunkMeta.clear(); swap(chunkMeta, chunkMeta); } /** * From startEntry to endEntry in idtableEntries build a line; * @param lineNo: the lineNo-th line to be build; */ bool LineHashIndex::buildLine(int startEntry, int endEntry, int lineNo) { vector<Point> vpt; Point pt; int i; //build lower limit line; for (i = startEntry; i < endEntry; i++) { pt.x = idTableEntries[i]; pt.y = i; vpt.push_back(pt); } double ktemp, btemp; int size = vpt.size(); if (calculateLineKB(vpt, ktemp, btemp, size) == false) return false; double difference = btemp; //(vpt[0].y - (ktemp * vpt[0].x + btemp)); double difference_final = difference; for (i = 1; i < size; i++) { difference = vpt[i].y - ktemp * vpt[i].x; //vpt[0].y - (ktemp * vpt[0].x + btemp); //cout<<"differnce: "<<difference<<endl; if ((difference < difference_final) == true) difference_final = difference; } btemp = difference_final; lowerk[lineNo] = ktemp; lowerb[lineNo] = btemp; startID[lineNo] = vpt[0].x; vpt.resize(0); //build upper limit line; for (i = startEntry; i < endEntry; i++) { pt.x = idTableEntries[i + 1]; pt.y = i; vpt.push_back(pt); } size = vpt.size(); calculateLineKB(vpt, ktemp, btemp, size); difference = btemp; //(vpt[0].y - (ktemp * vpt[0].x + btemp)); difference_final = difference; for (i = 1; i < size; i++) { difference = vpt[i].y - ktemp * vpt[i].x; //vpt[0].y - (ktemp * vpt[0].x + btemp); if (difference > difference_final) difference_final = difference; } btemp = difference_final; upperk[lineNo] = ktemp; upperb[lineNo] = btemp; return true; } static ID splitID[3] = { 255, 65535, 16777215 }; Status LineHashIndex::buildIndex(unsigned chunkType) //�������� chunkType: 1: x>y ; 2: x<y { if (idTable == NULL) { idTable = new MemoryBuffer(HASH_CAPACITY); idTableEntries = (ID*) idTable->getBuffer(); tableSize = 0; } const uchar* begin, *limit, *reader; ID x, y; int lineNo = 0; int startEntry = 0, endEntry = 0; if (chunkType == 1) { reader = chunkManager.getStartPtr(1); limit = chunkManager.getEndPtr(1); begin = reader; if (begin == limit){ return OK; } MetaData* metaData = (MetaData*) reader; x = metaData->minID; insertEntries(x); reader = reader + (int) (MemoryBuffer::pagesize - sizeof(ChunkManagerMeta)); while (reader < limit) { metaData = (MetaData*) reader; x = metaData->minID; insertEntries(x); if (x > splitID[lineNo]) { startEntry = endEntry; endEntry = tableSize; if (buildLine(startEntry, endEntry, lineNo) == true) { ++lineNo; } } reader = reader + (int) MemoryBuffer::pagesize; } reader = Chunk::skipBackward(limit, begin, chunkType); x = 0; Chunk::readXId(reader, x); insertEntries(x); startEntry = endEntry; endEntry = tableSize; if (buildLine(startEntry, endEntry, lineNo) == true) { ++lineNo; } } if (chunkType == 2) { reader = chunkManager.getStartPtr(2); limit = chunkManager.getEndPtr(2); begin = reader; if (begin == limit){ return OK; } while (reader < limit) { MetaData* metaData = (MetaData*) reader; x = metaData->minID; insertEntries(x); if (x > splitID[lineNo]) { startEntry = endEntry; endEntry = tableSize; if (buildLine(startEntry, endEntry, lineNo) == true) { ++lineNo; } } reader = reader + (int) MemoryBuffer::pagesize; } x = y = 0; reader = Chunk::skipBackward(limit, begin, chunkType); Chunk::readXYId(reader,x,y); insertEntries(x + y); startEntry = endEntry; endEntry = tableSize; if (buildLine(startEntry, endEntry, lineNo) == true) { ++lineNo; } } return OK; } bool LineHashIndex::isBufferFull() { return tableSize >= idTable->getSize() / 4; } void LineHashIndex::insertEntries(ID id) { if (isBufferFull()) { idTable->resize(HASH_CAPACITY); idTableEntries = (ID*) idTable->get_address(); } idTableEntries[tableSize] = id; tableSize++; } ID LineHashIndex::MetaID(size_t index) { assert(index < chunkMeta.size()); return chunkMeta[index].minIDx; } ID LineHashIndex::MetaYID(size_t index) { assert(index < chunkMeta.size()); return chunkMeta[index].minIDy; } size_t LineHashIndex::searchChunkFrank(ID id) { size_t low = 0, mid = 0, high = tableSize - 1; if (low == high){ return low; } while (low < high) { mid = low + (high-low) / 2; while (MetaID(mid) == id) { if (mid > 0 && MetaID(mid - 1) < id){ return mid - 1; } if (mid == 0){ return mid; } mid--; } if (MetaID(mid) < id){ low = mid + 1; } else if (MetaID(mid) > id){ high = mid; } } if (low > 0 && MetaID(low) >= id){ return low - 1; } else{ return low; } } size_t LineHashIndex::searchChunk(ID xID, ID yID){ if(MetaID(0) > xID || tableSize == 0){ return 0; } size_t offsetID = searchChunkFrank(xID); if(offsetID == tableSize-1){ return offsetID-1; } while(offsetID < tableSize-2){ if(MetaID(offsetID+1) == xID){ if(MetaYID(offsetID+1) > yID){ return offsetID; } else{ offsetID++; } } else{ return offsetID; } } return offsetID; } bool LineHashIndex::searchChunk(ID xID, ID yID, size_t& offsetID) //return the exactly which chunk the triple(xID, yID) is in { if(MetaID(0) > xID || tableSize == 0){ offsetID = 0; return false; } offsetID = searchChunkFrank(xID); if (offsetID == tableSize-1) { return false; } while (offsetID < tableSize - 2) { if (MetaID(offsetID + 1) == xID) { if (MetaYID(offsetID + 1) > yID) { return true; } else { offsetID++; } } else { return true; } } return true; } bool LineHashIndex::isQualify(size_t offsetId, ID xID, ID yID) { return (xID < MetaID(offsetId + 1) || (xID == MetaID(offsetId + 1) && yID < MetaYID(offsetId + 1))) && (xID > MetaID(offsetId) || (xID == MetaID(offsetId) && yID >= MetaYID(offsetId))); } void LineHashIndex::getOffsetPair(size_t offsetID, unsigned& offsetBegin, unsigned& offsetEnd) //get the offset of the data begin and end of the offsetIDth Chunk to the startPtr { if(tableSize == 0){ offsetEnd = offsetBegin = sizeof(MetaData); } offsetBegin = chunkMeta[offsetID].offsetBegin; MetaData* metaData = (MetaData*) (startPtr + offsetBegin - sizeof(MetaData)); offsetEnd = offsetBegin - sizeof(MetaData) + metaData->usedSpace; } size_t LineHashIndex::save(MMapBuffer*& indexBuffer) //tablesize , (startID, lowerk , lowerb, upperk, upperb) * 4 { char* writeBuf; size_t offset; if (indexBuffer == NULL) { indexBuffer = MMapBuffer::create(string(string(DATABASE_PATH) + "/BitmapBuffer_index").c_str(), sizeof(ID) + 16 * sizeof(double) + 4 * sizeof(ID)); writeBuf = indexBuffer->get_address(); offset = 0; } else { size_t size = indexBuffer->get_length(); indexBuffer->resize(size + sizeof(ID) + 16 * sizeof(double) + 4 * sizeof(ID), false); writeBuf = indexBuffer->get_address() + size; offset = size; } *(ID*) writeBuf = tableSize; writeBuf += sizeof(ID); for (int i = 0; i < 4; ++i) { *(ID*) writeBuf = startID[i]; writeBuf = writeBuf + sizeof(ID); *(double*) writeBuf = lowerk[i]; writeBuf = writeBuf + sizeof(double); *(double*) writeBuf = lowerb[i]; writeBuf = writeBuf + sizeof(double); *(double*) writeBuf = upperk[i]; writeBuf = writeBuf + sizeof(double); *(double*) writeBuf = upperb[i]; writeBuf = writeBuf + sizeof(double); } indexBuffer->flush(); delete idTable; idTable = NULL; return offset; } void LineHashIndex::updateLineIndex() { char* base = lineHashIndexBase; *(ID*) base = tableSize; base += sizeof(ID); for (int i = 0; i < 4; ++i) { *(ID*) base = startID[i]; base += sizeof(ID); *(double*) base = lowerk[i]; base += sizeof(double); *(double*) base = lowerb[i]; base += sizeof(double); *(double*) base = upperk[i]; base += sizeof(double); *(double*) base = upperb[i]; base += sizeof(double); } delete idTable; idTable = NULL; } void LineHashIndex::updateChunkMetaData(int offsetId) { if (offsetId == 0) { const uchar* reader = NULL; register ID x = 0, y = 0; reader = startPtr + chunkMeta[offsetId].offsetBegin; reader = Chunk::readXYId(reader,x,y); if (xyType == LineHashIndex::YBIGTHANX) { chunkMeta[offsetId].minIDx = x; chunkMeta[offsetId].minIDy = x + y; } else if (xyType == LineHashIndex::XBIGTHANY) { chunkMeta[offsetId].minIDx = x + y; chunkMeta[offsetId].minIDy = x; } } } LineHashIndex* LineHashIndex::load(ChunkManager& manager, IndexType index_type, XYType xy_type, char*buffer, size_t& offset) { LineHashIndex* index = new LineHashIndex(manager, index_type, xy_type); char* base = buffer + offset; index->lineHashIndexBase = base; index->tableSize = *((ID*) base); base = base + sizeof(ID); for (int i = 0; i < 4; ++i) { index->startID[i] = *(ID*) base; base = base + sizeof(ID); index->lowerk[i] = *(double*) base; base = base + sizeof(double); index->lowerb[i] = *(double*) base; base = base + sizeof(double); index->upperk[i] = *(double*) base; base = base + sizeof(double); index->upperb[i] = *(double*) base; base = base + sizeof(double); } offset = offset + sizeof(ID) + 16 * sizeof(double) + 4 * sizeof(ID); //get something useful for the index const uchar* reader; const uchar* temp; register ID x, y; if (index->xyType == LineHashIndex::YBIGTHANX) { index->startPtr = index->chunkManager.getStartPtr(1); index->endPtr = index->chunkManager.getEndPtr(1); if (index->startPtr == index->endPtr) { index->chunkMeta.push_back( { 0, 0, sizeof(MetaData) }); return index; } temp = index->startPtr + sizeof(MetaData); Chunk::readYId(Chunk::readXId(temp, x), y); index->chunkMeta.push_back( { x, x + y, sizeof(MetaData) }); reader = index->startPtr - sizeof(ChunkManagerMeta) + MemoryBuffer::pagesize; while (reader < index->endPtr) { temp = reader + sizeof(MetaData); Chunk::readYId(Chunk::readXId(temp, x), y); index->chunkMeta.push_back( { x, x + y, reader - index->startPtr + sizeof(MetaData) }); reader = reader + MemoryBuffer::pagesize; } reader = index->endPtr; reader = Chunk::skipBackward(reader, index->startPtr, 1); Chunk::readXYId(reader,x,y); index->chunkMeta.push_back( { x, x + y }); } else if (index->xyType == LineHashIndex::XBIGTHANY) { index->startPtr = index->chunkManager.getStartPtr(2); index->endPtr = index->chunkManager.getEndPtr(2); if (index->startPtr == index->endPtr) { index->chunkMeta.push_back( { 0, 0, sizeof(MetaData) }); return index; } temp = index->startPtr + sizeof(MetaData); Chunk::readYId(Chunk::readXId(temp, x), y); index->chunkMeta.push_back( { x + y, x, sizeof(MetaData) }); reader = index->startPtr + MemoryBuffer::pagesize; while (reader < index->endPtr) { temp = reader + sizeof(MetaData); Chunk::readYId(Chunk::readXId(temp, x), y); index->chunkMeta.push_back( { x + y, x, reader - index->startPtr + sizeof(MetaData) }); reader = reader + MemoryBuffer::pagesize; } reader = index->endPtr; reader = Chunk::skipBackward(reader, index->startPtr, 2); Chunk::readXYId(reader,x,y); index->chunkMeta.push_back( { x + y, x }); } return index; }
#include <iostream> #include <memory> #include <vector> using namespace std; // void fun int main(int argc, char *argv[]) { unique_ptr<int> p(new int(100)); // p.reset(); // p.release(); cout << *p << endl; unique_ptr<vector<int>> p2(new vector<int>()); p2->push_back(1000); cout << "size = " << p2->size() << endl; // delete(p2) p2; std::unique_ptr<int> p1(new int(5)); // std::unique_ptr<int> p2 = p1; // 编译会出错 std::unique_ptr<int> p3 = std::move(p1); // 转移所有权,现在那块内存归p3所有, p1成为无效的指针。 p3.reset(); //释放内存。 p1.reset(); //实际上什么都没做。 return 0; }
void getData() { h = dht.readHumidity(); t = dht.readTemperature(); f = dht.readTemperature(true); soilMoist = analogRead(A0); // Check if any reads failed and exit early (to try again). if (isnan(h) || isnan(t) || isnan(f) || isnan(soilMoist)) { Serial.println("Failed to read from DHT sensor!"); strcpy(celsiusTemp, "Failed"); strcpy(fahrenheitTemp, "Failed"); strcpy(humidityTemp, "Failed"); } else { // Computes temperature values in Celsius + Fahrenheit and Humidity hic = dht.computeHeatIndex(t, h, false); dtostrf(hic, 6, 2, celsiusTemp); hif = dht.computeHeatIndex(f, h); dtostrf(hif, 6, 2, fahrenheitTemp); dtostrf(h, 6, 2, humidityTemp); //You can delete the following Serial.print's, it's just for debugging purposes /* Serial.print("Humidity: "); Serial.print(h); Serial.print(" %\t Temperature: "); Serial.print(t); Serial.print(" *C "); Serial.print(f); Serial.print(" *F\t Heat index: "); Serial.print(hic); Serial.print(" *C "); Serial.print(hif); Serial.print(" *F"); Serial.print("Humidity: "); Serial.print(h); Serial.print(" %\t Temperature: "); Serial.print(t); Serial.print(" *C "); Serial.print(f); Serial.print(" *F\t Heat index: "); Serial.print(hic); Serial.print(" *C "); Serial.print(hif); Serial.println(" *F");*/ } } void checkStats() { getData(); if (!manual) { if (soilMoist <= 450) pump = "off"; else if (soilMoist > 450 && soilMoist < 1000) pump = "on"; else pump = "off"; } if (timer) { if ((lhour.toInt() - hour <= 0 && (lhour.toInt() + duration.toInt()) - hour >= 0) || (lhour.toInt() - hour >= 0 && (lhour.toInt() + duration.toInt()) - hour <= 0)) { light = "on"; Serial.println("time on"); } else { light = "off"; Serial.println("time off"); } } if (pump == "on") digitalWrite(pumpPin, LOW); else if (pump == "off") digitalWrite(pumpPin, HIGH); if (light == "on") digitalWrite(lightPin, LOW); else if (light == "off") digitalWrite(lightPin, HIGH); }
#ifndef Fader_h #define Fader_h #if ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #include "pins_arduino.h" #include "WConstants.h" #endif class Fader { public: Fader(int button, int led, int initial = 0); void init(); void check(); void toggle(); private: unsigned int _button; unsigned int _led; int _initial = 0; bool _buttonPressed = false; }; #endif
// NeoPixel Demo minimum // By the sons of the gun // released under the GPLv3 license to match the rest of the AdaFruit NeoPixel library #include <Adafruit_NeoPixel.h> #include <avr/power.h> // Which pin on the Arduino is connected to the NeoPixels? // On a Trinket or Gemma we suggest changing this to 1 #define PIN 6 // How many NeoPixels are attached to the adafruit flora? In here I have one #define NUMPIXELS 1 int switchPin = 9; // switch connected to digital pin 7 int switchValue; // a variable to keep track of when switch is pressed int j=0; //this is just for random int int myFavoriteColors[][3] = {{255, 0, 0}, // red {0, 0, 255}, // blue {0, 255, 0}, //green {200, 0, 200}, // purple {200, 200, 200}, // white }; // When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals. // Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest // example for more information on possible values. Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); int delayval = 1000; // delay for half a second void setup() { // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket #if defined (__AVR_ATtiny85__) if (F_CPU == 16000000) clock_prescale_set(clock_div_1); #endif // End of trinket special cod pinMode(switchPin, INPUT); // sets the switchPin to be an input digitalWrite(switchPin, HIGH); // sets the default (unpressed) state of switchPin to HIGH pixels.begin(); // This initializes the NeoPixel library. } void loop() { // For a set of NeoPixels the first NeoPixel is 0, second is 1, all the way up to the count of pixels minus one. switchValue = digitalRead(switchPin); // check to see if the switch is pressed if (switchValue == HIGH) { // if the switch is pressed then, } else { // otherwise, int j = random(0,5); delay(500); Serial.print(j); Serial.print(myFavoriteColors[j][0]); pixels.setPixelColor(0, pixels.Color(myFavoriteColors[j][0],myFavoriteColors[j][1],myFavoriteColors[j][2])); pixels.show(); // This sends the updated pixel color to the hardware } }