blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
2f93623efaa00f467c3495522b81c43ef2f223a4
708e834432e60d04677c611dd61657142498861d
/ch07/exercise7_31.h
58c315183c02d58382a53ea3b9d661f301451f13
[]
no_license
meixsh/cpp-primer
b60856a8c50537e83514181250a3ac62adef88af
8e0b654e6cb6f80842a4f4a76128c3d5b0b8832d
refs/heads/master
2023-01-20T05:17:43.895113
2020-11-19T08:35:33
2020-11-19T08:35:33
314,184,500
0
0
null
null
null
null
UTF-8
C++
false
false
51
h
class Y; class X { Y *py; }; class Y { X x; };
[ "meixsh@qq.com" ]
meixsh@qq.com
2b4aaeec5dd0c4f5636c0fe7ad88a2a765fc81bd
faad51c181c1ea6107b732a36ecd18b4b5fc5c32
/mythesis_body/src/vfh/pcl_object_recognition.hpp
6a5a762b522a6edca6e29611cc473bd11e9701b9
[]
no_license
gharghabi/MEng_thesis
35e2cdf0f4a90a7e4cb2d8dcbb2dd8492fa318d2
1eb1f0055f438946c6787b0e0c2e3beeb34b13bb
refs/heads/master
2016-09-10T18:00:53.688684
2014-11-12T18:22:47
2014-11-12T18:22:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
24,284
hpp
//#include "openni2pcl_reg.hpp" #include <iostream> #include <tuple> //#include <pcl/io/openni_grabber.h> #include <pcl/common/time.h> #include <iostream> #include <pcl/io/pcd_io.h> #include <pcl/features/shot_omp.h> #include <pcl/features/board.h> #include <pcl/keypoints/uniform_sampling.h> #include <pcl/recognition/cg/hough_3d.h> #include <pcl/recognition/cg/geometric_consistency.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/kdtree/impl/kdtree_flann.hpp> #include <pcl/common/transforms.h> #include <pcl/features/fpfh_omp.h> #include <pcl/filters/voxel_grid.h> #include <pcl/range_image/range_image.h> #include <pcl/features/range_image_border_extractor.h> #include <pcl/keypoints/narf_keypoint.h> #include <pcl/features/narf_descriptor.h> #include <pcl/keypoints/sift_keypoint.h> #include <pcl/console/parse.h> #include <pcl/sample_consensus/ransac.h> #include <pcl/sample_consensus/sac_model_plane.h> #include <pcl/sample_consensus/sac_model_sphere.h> #include <pcl/io/pcd_io.h> #include <pcl/visualization/cloud_viewer.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> //#include "OpenNI.h" #include <stdio.h> #include <iostream> #include "omp.h" #include "opencv2/highgui/highgui.hpp" #include "opencv2/core/core.hpp" #include "opencv/cv.h" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui_c.h" #include "opencv2/calib3d/calib3d.hpp" #include <pcl/features/normal_3d_omp.h> typedef pcl::PointXYZRGB PointType; typedef pcl::PointNormal NormalType; typedef pcl::ReferenceFrame RFType; typedef std::tuple<std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f> >,std::vector<pcl::Correspondences>> ClusterType; std::string model_filename; //Algorithm params bool show_keypoints_(false); bool show_correspondences(true); bool use_hough_(true); float model_ss_(0.005); //model sample size float scene_ss_(0.005); //scene sample size float rf_rad_(0.02); float descr_rad_(0.05); float cg_size_(0.007); float cg_thresh_(6.0f); bool narf(false); bool sift(true); //if both narf and sift are false a uniform sampling is used with radius model_ss_ and scene_ss_ bool fpfh(false); // if false shot descriptors are used bool ransac(false); const int distance = 700; //kinect cut-off distance // Parameters for sift computation float min_scale(0.001);//0.001 int n_octaves(6); int n_scales_per_octave (4); float min_contrast(0.1f); // parameters for narf computation float support_size(0.02); void showHelp (char *filename){ std::cout << std::endl; std::cout << "***************************************************************************" << std::endl; std::cout << "* *" << std::endl; std::cout << "* Real time object recognition - Usage Guide *" << std::endl; std::cout << "* *" << std::endl; std::cout << "***************************************************************************" << std::endl << std::endl; std::cout << "Usage: " << filename << " model_filename.pcd [Options]" << std::endl << std::endl; std::cout << "Options:" << std::endl; std::cout << " -h: Show this help." << std::endl; std::cout << " -show_keypoints: Show used keypoints." << std::endl; std::cout << " -show_correspondences: Show used correspondences." << std::endl; std::cout << " --algorithm (hough|gc): Clustering algorithm used (default Hough)." << std::endl; std::cout << " --keypoints (narf|sift|uniform): Keypoints detection algorithm (default uniform)." << std::endl; std::cout << " --descriptors (shot|fpfh): Descriptor type (default shot)." << std::endl; std::cout << " --model_ss val: Model uniform sampling radius (default 0.005)" << std::endl; std::cout << " --scene_ss val: Scene uniform sampling radius (default 0.005)" << std::endl; std::cout << " --rf_rad val: Hough reference frame radius (default 0.02)" << std::endl; std::cout << " --descr_rad val: Descriptor radius (default 0.03)" << std::endl; std::cout << " --cg_size val: Dimension of Hough's bins (default 0.007)" << std::endl; std::cout << " --cg_thresh val: Minimum number of positive votes for a match (default 6)" << std::endl << std::endl; std::cout << " --sift_min_scale: (default 0.001)" << std::endl; std::cout << " --sift_octaves: (default 6)" << std::endl; std::cout << " --sift_scales_per_octave: (default 4)" << std::endl; std::cout << " --sift_min_contrast: (default 0.3)" << std::endl << std::endl; std::cout << " --narf_support_size: (default 0.02)" << std::endl << std::endl; } void parseCommandLine (int argc, char *argv[]){ //Show help if (pcl::console::find_switch (argc, argv, "-h")) { showHelp (argv[0]); exit (0); } //Model & scene filenames //std::vector<int> filenames; //filenames = pcl::console::parse_file_extension_argument (argc, argv, ".pcd"); // if (filenames.size () != 1) // { // std::cout << "Filenames missing.\n"; // showHelp (argv[0]); // exit (-1); // } //model_filename = argv[filenames[0]]; //Program behavior if (pcl::console::find_switch (argc, argv, "-show_keypoints")) show_keypoints_ = true; if (pcl::console::find_switch (argc, argv, "-show_correspondences")) show_correspondences = true; std::string used_algorithm; if (pcl::console::parse_argument (argc, argv, "--algorithm", used_algorithm) != -1) { if (used_algorithm.compare ("hough") == 0) use_hough_ = true; else if (used_algorithm.compare ("gc") == 0) use_hough_ = false; else { std::cout << "Wrong algorithm name.\n"; showHelp (argv[0]); exit (-1); } } std::string used_keypoints; if (pcl::console::parse_argument (argc, argv, "--keypoints", used_keypoints) != -1) { if (used_keypoints.compare ("narf") == 0) narf = true; else if (used_keypoints.compare ("sift") == 0) sift = true; else if(used_keypoints.compare ("ransac") == 0) ransac = true; else if(used_keypoints.compare ("uniform") == 0) std::cout << "Using uniform sampling.\n"; } std::string used_descriptors; if (pcl::console::parse_argument (argc, argv, "--descriptors", used_descriptors) != -1) { if (used_descriptors.compare ("shot") == 0) fpfh = false; else if (used_descriptors.compare ("fpfh") == 0) fpfh = true; else { std::cout << "Wrong descriptors type .\n"; showHelp (argv[0]); exit (-1); } } //General parameters pcl::console::parse_argument (argc, argv, "--model_ss", model_ss_); pcl::console::parse_argument (argc, argv, "--scene_ss", scene_ss_); pcl::console::parse_argument (argc, argv, "--rf_rad", rf_rad_); pcl::console::parse_argument (argc, argv, "--descr_rad", descr_rad_); pcl::console::parse_argument (argc, argv, "--cg_size", cg_size_); pcl::console::parse_argument (argc, argv, "--cg_thresh", cg_thresh_); pcl::console::parse_argument (argc, argv, "--sift_min_scale", min_scale); pcl::console::parse_argument (argc, argv, "--sift_octaves", n_octaves); pcl::console::parse_argument (argc, argv, "--sift_scales_per_octave", n_scales_per_octave); pcl::console::parse_argument (argc, argv, "--sift_min_contrast", min_contrast); pcl::console::parse_argument (argc, argv, "--narf_support_size", support_size); } void SetViewPoint(pcl::PointCloud<PointType>::Ptr cloud){ cloud->sensor_origin_.setZero(); cloud->sensor_orientation_.w () = 0.0; cloud->sensor_orientation_.x () = 1.0; cloud->sensor_orientation_.y () = 0.0; cloud->sensor_orientation_.z () = 0.0; } void PrintTransformation(ClusterType cluster){ for (size_t i = 0; i < std::get<0>(cluster).size (); ++i) { std::cout << "\n Instance " << i + 1 << ":" << std::endl; std::cout << " Correspondences belonging to this instance: " << std::get<1>(cluster)[i].size () << std::endl; // Print the rotation matrix and translation vector Eigen::Matrix3f rotation = std::get<0>(cluster)[i].block<3,3>(0, 0); Eigen::Vector3f translation = std::get<0>(cluster)[i].block<3,1>(0, 3); printf ("\n"); printf (" | %6.3f %6.3f %6.3f | \n", rotation (0,0), rotation (0,1), rotation (0,2)); printf (" R = | %6.3f %6.3f %6.3f | \n", rotation (1,0), rotation (1,1), rotation (1,2)); printf (" | %6.3f %6.3f %6.3f | \n", rotation (2,0), rotation (2,1), rotation (2,2)); printf ("\n"); printf (" t = < %0.3f, %0.3f, %0.3f >\n", translation (0), translation (1), translation (2)); } } template <class T, class Estimator> class KeyDes{ public: typedef pcl::PointCloud<T> PD; typedef pcl::PointCloud<PointType> P; typedef pcl::PointCloud<NormalType> PN; typename PD::Ptr model_descriptors; typename PD::Ptr scene_descriptors; //typename P::Ptr model ; //typename P::Ptr model_keypoints; // typename P::Ptr scene; // typename P::Ptr scene_keypoints; // typename PN::Ptr model_normals; // typename PN::Ptr scene_normals; // bool created; //KeyDes(P::Ptr model, P::Ptr model_keypoints, P::Ptr scene, P::Ptr scene_keypoints, PN::Ptr model_normals, PN::Ptr scene_normals ): KeyDes(PD model_d,PD scene_d): model_descriptors (new PD (model_d)), scene_descriptors (new PD (scene_d)){} // model(model), // model_keypoints(model_keypoints), // scene(scene), // scene_keypoints(scene_keypoints), // model_normals(model_normals), // scene_normals(scene_normals){} // created(false){} pcl::CorrespondencesPtr run() { pcl::CorrespondencesPtr model_scene_corrs (new pcl::Correspondences ()); //create scene descriptors // std::cout << "calculating scene descriptors " <<std::endl; // Estimator est; // est.setInputCloud(scene_keypoints); // est.setSearchSurface(scene); // est.setInputNormals(scene_normals); // pcl::search::KdTree<pcl::PointXYZRGB>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZRGB>); // est.setSearchMethod(tree); // est.setRadiusSearch (descr_rad_); // est.compute (*scene_descriptors); // if(!created){ // //create model descriptors // std::cout << "calculating model descriptors " <<std::endl; // std::clock_t start; // double duration; // start = std::clock(); // est.setInputCloud(model_keypoints); // est.setSearchSurface(model); // est.setInputNormals(model_normals); // pcl::search::KdTree<pcl::PointXYZRGB>::Ptr tree2 (new pcl::search::KdTree<pcl::PointXYZRGB>); // est.setSearchMethod(tree2); // est.compute (*model_descriptors); // duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC; // std::cout<<"time 2: "<< duration <<'\n'; // created = true; // } pcl::KdTreeFLANN<T> match_search; //std::cout <<"calculated " << model_descriptors->size() << " for the model and " << scene_descriptors->size() << " for the scene" <<std::endl; // Find Model-Scene Correspondences with KdTree std::cout << "calculating correspondences " <<std::endl; match_search.setInputCloud (model_descriptors); // For each scene keypoint descriptor, find nearest neighbor into the model keypoints descriptor cloud and add it to the correspondences vector. #pragma omp parallel for for (size_t i = 0; i < scene_descriptors->size (); ++i) { std::vector<int> neigh_indices (1); std::vector<float> neigh_sqr_dists (1); int found_neighs = match_search.nearestKSearch (scene_descriptors->at(i), 1, neigh_indices, neigh_sqr_dists); if(found_neighs == 1 && neigh_sqr_dists[0] < 0.25f) // 0.25 std add match only if the squared descriptor distance is less than 0.25 (SHOT descriptor distances are between 0 and 1 by design) { pcl::Correspondence corr (neigh_indices[0], static_cast<int> (i), neigh_sqr_dists[0]); #pragma omp critical model_scene_corrs->push_back (corr); } } std::cout << "\tFound " <<model_scene_corrs->size ()<< " correspondences "<< std::endl; return model_scene_corrs; } }; class NormalEstimator{ public: pcl::NormalEstimationOMP<PointType, NormalType> norm_est; NormalEstimator() { norm_est.setKSearch (10); } NormalEstimator(int n_neighbours){//: NormalEstimator() {//ameneh //c++11 standard norm_est.setKSearch (n_neighbours); } pcl::PointCloud<NormalType>::Ptr get_normals(pcl::PointCloud<PointType>::Ptr cloud){ pcl::PointCloud<NormalType>::Ptr normals(new pcl::PointCloud<NormalType> ()); norm_est.setInputCloud (cloud); norm_est.compute (*normals); return normals; } }; class DownSampler{ public: pcl::VoxelGrid<pcl::PointXYZRGB> down_sampler_; DownSampler() { down_sampler_.setLeafSize (1.5, 1.5, 1.5); } DownSampler(float x, float y, float z){ down_sampler_.setLeafSize(x, y, z); } void SetSampleSize(float x, float y, float z){ down_sampler_.setLeafSize(x, y, z); } void DownSample(pcl::PointCloud<PointType>::Ptr cloud){ down_sampler_.setInputCloud(cloud); down_sampler_.filter(*cloud); } }; class Narf{ public: pcl::PointCloud<int> cloud_keypoint_indices_; Eigen::Affine3f cloud_sensor_pose_; bool rotation_invariant_; pcl::RangeImageBorderExtractor range_image_border_extractor_; pcl::NarfKeypoint narf_keypoint_detector_; Narf(): rotation_invariant_(true), cloud_sensor_pose_(Eigen::Affine3f::Identity ()) { narf_keypoint_detector_.setRangeImageBorderExtractor (&range_image_border_extractor_); narf_keypoint_detector_.getParameters().support_size = support_size; } void GetKeypoints(pcl::PointCloud<PointType>::Ptr cloud, pcl::PointCloud<PointType>::Ptr cloud_keypoints){ boost::shared_ptr<pcl::RangeImage>cloud_range_image_ptr_(new pcl::RangeImage); cloud_sensor_pose_ = Eigen::Affine3f (Eigen::Translation3f (cloud->sensor_origin_[0], cloud->sensor_origin_[1], cloud->sensor_origin_[2])) * Eigen::Affine3f (cloud->sensor_orientation_); pcl::RangeImage& cloud_range_image_ = *cloud_range_image_ptr_; narf_keypoint_detector_.setRangeImage (&cloud_range_image_); cloud_range_image_.createFromPointCloud(*cloud, pcl::deg2rad(0.5f), pcl::deg2rad(360.0f), pcl::deg2rad(180.0f), cloud_sensor_pose_, pcl::RangeImage::CAMERA_FRAME, 0.0, 0.0f, 1); cloud_range_image_.setUnseenToMaxRange(); narf_keypoint_detector_.compute(cloud_keypoint_indices_); cloud_keypoints->points.resize (cloud_keypoint_indices_.points.size ()); #pragma omp parallel for for (size_t i=0; i<cloud_keypoint_indices_.points.size (); ++i) cloud_keypoints->points[i].getVector3fMap () = cloud_range_image_.points[cloud_keypoint_indices_.points[i]].getVector3fMap (); } }; class Sift{ public: pcl::PointCloud<pcl::PointWithScale> cloud_result_; pcl::SIFTKeypoint<pcl::PointXYZRGB, pcl::PointWithScale> sift_; pcl::search::KdTree<pcl::PointXYZRGB>::Ptr tree_; //pcl::KdTreeFLANN<pcl::PointXYZRGB>::Ptr tree_ ;//(new KdTreeFLANN<pcl::PointXYZRGB> ()); Sift():tree_(new pcl::search::KdTree<pcl::PointXYZRGB>()){//tree_(new pcl::KdTreeFLANN<pcl::PointXYZRGB> ()){ sift_.setSearchMethod(tree_); sift_.setScales(min_scale, n_octaves, n_scales_per_octave); sift_.setMinimumContrast(min_contrast); } void GetKeypoints(pcl::PointCloud<PointType>::Ptr cloud, pcl::PointCloud<PointType>::Ptr cloud_keypoints) { sift_.setInputCloud(cloud); sift_.compute(cloud_result_); copyPointCloud(cloud_result_, *cloud_keypoints); } }; template <class T> class Ransac{ public: std::vector<int> cloud_inliers; void GetKeypoints(pcl::PointCloud<PointType>::Ptr cloud, pcl::PointCloud<PointType>::Ptr cloud_keypoints){ typename T::Ptr cloud_plane (new T (cloud)); pcl::RandomSampleConsensus<pcl::PointXYZRGB> model_ransac (cloud_plane); model_ransac.computeModel(); model_ransac.getInliers(cloud_inliers); pcl::copyPointCloud<pcl::PointXYZRGB>(*cloud, cloud_inliers, *cloud_keypoints); } }; class Uniform{ public: pcl::UniformSampling<PointType> uniform_sampling; pcl::PointCloud<int> sampled_indices; float cloud_ss_ ; void SetSamplingSize(float sampling_size){ cloud_ss_ = sampling_size; } void GetKeypoints(pcl::PointCloud<PointType>::Ptr cloud, pcl::PointCloud<PointType>::Ptr cloud_keypoints){ if (cloud_ss_ != 0){ uniform_sampling.setInputCloud (cloud); uniform_sampling.setRadiusSearch (cloud_ss_); uniform_sampling.compute (sampled_indices); pcl::copyPointCloud (*cloud, sampled_indices.points, *cloud_keypoints); }else std::cout << "no sampling size inserted" << std::endl; } }; class Hough{ public: ClusterType cluster; pcl::PointCloud<RFType>::Ptr model_rf_; pcl::PointCloud<RFType>::Ptr scene_rf_; pcl::BOARDLocalReferenceFrameEstimation<PointType, NormalType, RFType> rf_est_; pcl::Hough3DGrouping<PointType, PointType, RFType, RFType> clusterer_; bool created; Hough(): model_rf_(new pcl::PointCloud<RFType> ()), scene_rf_(new pcl::PointCloud<RFType> ()), created(false) { rf_est_.setFindHoles (true); rf_est_.setRadiusSearch (rf_rad_); clusterer_.setHoughBinSize (cg_size_); clusterer_.setHoughThreshold (cg_thresh_); clusterer_.setUseInterpolation (true); clusterer_.setUseDistanceWeight (false); } ClusterType GetClusters(pcl::PointCloud<pcl::PointXYZRGB>::Ptr model, pcl::PointCloud<pcl::PointXYZRGB>::Ptr model_keypoints, pcl::PointCloud<NormalType>::Ptr model_normals, pcl::PointCloud<pcl::PointXYZRGB>::Ptr scene, pcl::PointCloud<pcl::PointXYZRGB>::Ptr scene_keypoints, pcl::PointCloud<NormalType>::Ptr scene_normals, pcl::CorrespondencesPtr model_scene_corrs){ // Compute (Keypoints) Reference Frames only for Hough if(!created){ rf_est_.setInputCloud (model_keypoints); rf_est_.setInputNormals (model_normals); rf_est_.setSearchSurface (model); rf_est_.compute (*model_rf_); } //std::cout << "computed hough BOARD on model" <<std::endl; rf_est_.setInputCloud (scene_keypoints); rf_est_.setInputNormals (scene_normals); rf_est_.setSearchSurface (scene); rf_est_.compute (*scene_rf_); //std::cout << "computed hough BOARD on scene" <<std::endl; // Clustering if(!created){ clusterer_.setInputCloud (model_keypoints); clusterer_.setInputRf (model_rf_); created = true; } clusterer_.setSceneCloud (scene_keypoints); clusterer_.setSceneRf (scene_rf_); clusterer_.setModelSceneCorrespondences (model_scene_corrs); //std::cout << "prepared Hough for clustering" <<std::endl; //clusterer_.cluster (clustered_corrs); clusterer_.recognize (std::get<0>(cluster), std::get<1>(cluster)); return cluster; } }; class GCG{ public: pcl::GeometricConsistencyGrouping<PointType, PointType> gc_clusterer_; ClusterType cluster; GCG(){ gc_clusterer_.setGCSize (cg_size_); gc_clusterer_.setGCThreshold (cg_thresh_); } ClusterType GetClusters(pcl::PointCloud<PointType>::Ptr model_keypoints, pcl::PointCloud<PointType>::Ptr scene_keypoints, pcl::CorrespondencesPtr model_scene_corrs){ gc_clusterer_.setInputCloud (model_keypoints); gc_clusterer_.setSceneCloud (scene_keypoints); gc_clusterer_.setModelSceneCorrespondences (model_scene_corrs); //gc_clusterer_.cluster (clustered_corrs); gc_clusterer_.recognize (std::get<0>(cluster), std::get<1>(cluster)); return cluster; } }; class Visualizer{ public: pcl::visualization::PCLVisualizer viewer_; pcl::PointCloud<PointType>::Ptr off_scene_model_; pcl::PointCloud<PointType>::Ptr off_scene_model_keypoints_; bool to_stop; int iter; Visualizer(): off_scene_model_(new pcl::PointCloud<PointType> ()), off_scene_model_keypoints_(new pcl::PointCloud<PointType> ()), to_stop(false), iter(0){} void Visualize(pcl::PointCloud<PointType>::Ptr model, pcl::PointCloud<PointType>::Ptr model_keypoints, pcl::PointCloud<PointType>::Ptr scene, pcl::PointCloud<PointType>::Ptr scene_keypoints, ClusterType cluster){ if (viewer_.wasStopped ()) to_stop = true; SetViewPoint(scene); if(iter == 0) viewer_.addPointCloud (scene, "scene_cloud"); else viewer_.updatePointCloud (scene, "scene_cloud"); if (show_correspondences && iter == 0){ // We are translating the model so that it doesn't end in the middle of the scene representation pcl::transformPointCloud (*model, *off_scene_model_, Eigen::Vector3f (-1,0,0), Eigen::Quaternionf (1, 0, 0, 0)); pcl::transformPointCloud (*model_keypoints, *off_scene_model_keypoints_, Eigen::Vector3f (-1,0,0), Eigen::Quaternionf (1, 0, 0, 0)); SetViewPoint(off_scene_model_); SetViewPoint(off_scene_model_keypoints_); //pcl::visualization::PointCloudColorHandlerCustom<PointType> off_scene_model__color_handler (off_scene_model_, 255, 255, 128); viewer_.addPointCloud (off_scene_model_, "off_scene_model_"); } if (show_keypoints_){ pcl::visualization::PointCloudColorHandlerCustom<PointType> scene_keypoints_color_handler (scene_keypoints, 0, 0, 255); SetViewPoint(scene_keypoints); if(iter == 0) viewer_.addPointCloud (scene_keypoints, scene_keypoints_color_handler, "scene_keypoints"); else viewer_.updatePointCloud (scene_keypoints, scene_keypoints_color_handler, "scene_keypoints"); viewer_.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5, "scene_keypoints"); pcl::visualization::PointCloudColorHandlerCustom<PointType> off_scene_model_keypoints__color_handler (off_scene_model_keypoints_, 0, 0, 255); SetViewPoint(off_scene_model_keypoints_); if(iter == 0) viewer_.addPointCloud (off_scene_model_keypoints_, off_scene_model_keypoints__color_handler, "off_scene_model_keypoints_"); else viewer_.updatePointCloud (off_scene_model_keypoints_, off_scene_model_keypoints__color_handler, "off_scene_model_keypoints_"); viewer_.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5, "off_scene_model_keypoints_"); } for (size_t i = 0; i < std::get<0>(cluster).size (); ++i){ pcl::PointCloud<PointType>::Ptr rotated_model (new pcl::PointCloud<PointType> ()); pcl::transformPointCloud (*model, *rotated_model, std::get<0>(cluster)[i]); SetViewPoint(rotated_model); std::stringstream ss_cloud; ss_cloud << "instance" << i; pcl::visualization::PointCloudColorHandlerCustom<PointType> rotated_model_color_handler (rotated_model, 255, 0, 0); if(iter == 0) viewer_.addPointCloud (rotated_model, rotated_model_color_handler, ss_cloud.str ()); else viewer_.updatePointCloud (rotated_model, rotated_model_color_handler, ss_cloud.str ()); /* if (show_correspondences){ for (size_t j = 0; j < std::get<1>(cluster)[i].size (); ++j){ std::stringstream ss_line; ss_line << "correspondence_line" << i << "_" << j << "_" << iter; PointType& model_point = off_scene_model_keypoints_->at (std::get<1>(cluster)[i][j].index_query); PointType& scene_point = scene_keypoints->at (std::get<1>(cluster)[i][j].index_match); // We are drawing a line for each pair of clustered correspondences found between the model and the scene viewer_.addLine<PointType, PointType> (model_point, scene_point, 0, 255, 0, ss_line.str ()); } }*/ } viewer_.spinOnce(); iter++; } };
[ "sh.gharghabi@gmail.com" ]
sh.gharghabi@gmail.com
a6c453b93a8722bdcd53b19445113ebc55a0c00a
66c2098fa25ebee6876eef2fe204b24ef0e58160
/src/rs_filter_policy.h
e816d67156170c5bdf5b95c2dca3470d811f9fdd
[]
no_license
z7z8th/RSOrionDecoder
3afba3952386fa6755c247865111097ccae87c5b
071b40b8391b498f73da99a88482e3af9978870c
refs/heads/master
2020-06-05T06:56:56.748747
2019-06-25T10:45:48
2019-06-25T11:18:39
192,351,836
5
2
null
2019-06-18T00:54:35
2019-06-17T13:24:17
C
UTF-8
C++
false
false
561
h
#ifndef __RS_FILTER_POLICY_H__ #define __RS_FILTER_POLICY_H__ namespace readsense { struct FrameTrack { int lastFrame; int trackCount; }; struct RegionRatio { float xRatio = 0.0; float yRatio = 0.0; float widthRatio = 1.0; float heightRatio = 1.0; }; struct FilterPolicy { RegionRatio _regionRatio; int _faceWidthThreshold = 64; int _faceHeightThreshold = 64; int _faceQualityThreshold = 8; int _faceAngleThreshold = 90; int _onlySnapMaxFace = 0; int _snapIntervalFrame = 2; int _maxPituresPerTrack = 3; }; } #endif // __RS_FILTER_POLICY_H__
[ "ybzhao1989@gmail.com" ]
ybzhao1989@gmail.com
a8734dc66bfede22169565bdbe0436404a8fa43d
2b72cb1f41863b40a675816007c30ceb6c9c99eb
/BattleTank/Source/BattleTank/Public/TankMovementComponent.h
f2c3040b01ef3966a77dcf6984d98a16f45640a6
[]
no_license
ram5593/BattleTank
1375c62b31212c0b7a4e800da3379918d52d0d9d
9649e63dd2c8a77e6257c24c3aeca22c1d7765b8
refs/heads/master
2021-05-15T05:13:56.321648
2018-02-03T00:51:42
2018-02-03T00:51:42
117,838,897
0
0
null
null
null
null
UTF-8
C++
false
false
949
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/NavMovementComponent.h" #include "TankMovementComponent.generated.h" class UTankTrack; /** * */ UCLASS( ClassGroup = (Custom), meta = (BlueprintSpawnableComponent) ) class BATTLETANK_API UTankMovementComponent : public UNavMovementComponent { GENERATED_BODY() public: UFUNCTION(BlueprintCallable, Category=Input) void IntendMoveForward(float Throw); UFUNCTION(BlueprintCallable, Category = Setup) void Initialise(UTankTrack* LeftTrackToSet, UTankTrack* RightTankToSet); UFUNCTION(BlueprintCallable, Category = Setup) void IntendTurnRight(float Throw); private: UTankTrack* LeftTrack = nullptr; UTankTrack* RightTrack = nullptr; // called from the pathfinding logic by the AI controllers virtual void RequestDirectMove(const FVector& MoreVelocity, bool bForceMaxSpeed) override; };
[ "rmazerole@gmail.com" ]
rmazerole@gmail.com
8dbf8870f6f09df5b3eb181a0db7efca37309283
b268c986b8c3ad58cef649b123844f4cc9a904bc
/BRAINSCommonLib/itkBRAINSROIAutoImageFilter.h
4430e7b006f49eb650dc030c41cf201f2c5e60e5
[]
no_license
Slicer/BRAINSTools
c0848684e68bd0b85d1b33e9a5caeb749ec81262
c658c752a053ab2006929489d5f0e9297857ba18
refs/heads/slicer-2015-08-21-v4.5.0
2021-01-18T07:32:41.051518
2015-10-06T21:10:16
2015-11-03T16:30:19
21,228,900
5
5
null
2017-12-05T23:04:13
2014-06-26T05:19:24
C++
UTF-8
C++
false
false
7,291
h
/*========================================================================= * * Copyright SINAPSE: Scalable Informatics for Neuroscience, Processing and Software Engineering * The University of Iowa * * 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.txt * * 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. * *=========================================================================*/ /*========================================================================= * * Program: Insight Segmentation & Registration Toolkit * Module: $RCSfile: itkBRAINSROIAutoImageFilter.h,v $ * Language: C++ * Date: $Date: 2008-10-16 19:33:40 $ * Version: $Revision: 1.7 $ * * Copyright (c) Insight Software Consortium. All rights reserved. * See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. * * This software is distributed WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the above copyright notices for more information. * * =========================================================================*/ #ifndef __itkBRAINSROIAutoImageFilter_h #define __itkBRAINSROIAutoImageFilter_h // First make sure that the configuration is available. // This line can be removed once the optimized versions // gets integrated into the main directories. #include "itkConfigure.h" #include "itkImageToImageFilter.h" #include "itkImage.h" #include "itkImageMaskSpatialObject.h" #include "itkLargestForegroundFilledMaskImageFilter.h" #include "itkCastImageFilter.h" typedef itk::SpatialObject<3> SpatialObjectType; typedef SpatialObjectType::Pointer ImageMaskPointer; namespace itk { /** \class BRAINSROIAutoImageFilter * \brief This is a class to help with identifying common tissue * Regions in an image. * * \sa Image * \sa Neighborhood * * \ingroup IntensityImageFilters */ template <class TInputImage, class TOutputImage> class BRAINSROIAutoImageFilter : public ImageToImageFilter<TInputImage, TOutputImage> { public: /** Extract dimension from input and output image. */ itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension); itkStaticConstMacro(OutputImageDimension, unsigned int, TOutputImage::ImageDimension); /** Convenient typedefs for simplifying declarations. */ typedef TInputImage InputImageType; typedef TOutputImage OutputImageType; /** Standard class typedefs. */ typedef BRAINSROIAutoImageFilter Self; typedef ImageToImageFilter<InputImageType, OutputImageType> Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Method for creation through the object factory. */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(BRAINSROIAutoImageFilter, ImageToImageFilter); /** Image typedef support. */ typedef typename InputImageType::PixelType InputPixelType; typedef typename OutputImageType::PixelType OutputPixelType; typedef typename InputImageType::RegionType InputImageRegionType; typedef typename OutputImageType::RegionType OutputImageRegionType; typedef typename InputImageType::SizeType InputSizeType; typedef itk::Image<unsigned char, 3> UCHARIMAGE; typedef itk::ImageMaskSpatialObject<UCHARIMAGE::ImageDimension> ImageMaskSpatialObjectType; /** */ itkSetMacro(OtsuPercentileThreshold, double); itkGetConstMacro(OtsuPercentileThreshold, double); /** */ itkSetMacro(ThresholdCorrectionFactor, double); itkGetConstMacro(ThresholdCorrectionFactor, double); /** The closing size in mm, this is rounded up to the next closest number of * voxel by taking Spacing into account */ itkSetMacro(ClosingSize, double); itkGetConstMacro(ClosingSize, double); /** The dilation size in mm, this is rounded up to the next closest number of * voxel by taking Spacing into account */ itkSetMacro(DilateSize, double); itkGetConstMacro(DilateSize, double); // NOTE: This will generate a new spatial object each time it is called, and // not return the previous spatial object ImageMaskPointer GetSpatialObjectROI(void) { if( m_ResultMaskPointer.IsNull() ) // This is a cheap way to only create // the mask once, note that this is made // null when GenerateData is called. { typedef itk::CastImageFilter<OutputImageType, UCHARIMAGE> CastImageFilter; typename CastImageFilter::Pointer castFilter = CastImageFilter::New(); castFilter->SetInput( this->GetOutput() ); castFilter->Update(); // convert mask image to mask typename ImageMaskSpatialObjectType::Pointer mask = ImageMaskSpatialObjectType::New(); mask->SetImage( castFilter->GetOutput() ); mask->ComputeObjectToWorldTransform(); m_ResultMaskPointer = dynamic_cast<ImageMaskSpatialObjectType *>( mask.GetPointer() ); if( m_ResultMaskPointer.IsNull() ) { itkGenericExceptionMacro(<< "failed conversion to MaskSpatialObject"); } } return m_ResultMaskPointer; } typename UCHARIMAGE::ConstPointer GetBinaryImageROI() { ImageMaskPointer tmp = this->GetSpatialObjectROI(); typename UCHARIMAGE::ConstPointer rval = ITK_NULLPTR; if( tmp.IsNotNull() ) { const typename itk::ImageMaskSpatialObject<3>::ConstPointer imso = dynamic_cast<itk::ImageMaskSpatialObject<3> *>(tmp.GetPointer() ); if( imso.IsNull() ) { itkGenericExceptionMacro(<< "failed conversion to MaskSpatialObject"); } if( imso.IsNotNull() ) { rval = imso->GetImage(); } } return rval; } #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ itkConceptMacro( SameDimensionCheck, ( Concept::SameDimension<InputImageDimension, OutputImageDimension> ) ); /** End concept checking */ #endif protected: BRAINSROIAutoImageFilter(); virtual ~BRAINSROIAutoImageFilter() { } void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; void GenerateData() ITK_OVERRIDE; private: BRAINSROIAutoImageFilter(const Self &); // purposely not implemented void operator=(const Self &); // purposely not implemented double m_OtsuPercentileThreshold; double m_ThresholdCorrectionFactor; double m_ClosingSize; double m_DilateSize; ImageMaskPointer m_ResultMaskPointer; }; } // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION #include "itkBRAINSROIAutoImageFilter.hxx" #endif #endif
[ "hans-johnson@uiowa.edu" ]
hans-johnson@uiowa.edu
620934bfa19b61c2f12e520138e9b84857a9eba1
8e07ef71f6ba799b2832e887d3ad96883ddee5d7
/146-LRUCache.cpp
f0fb93b1b3e90ed8ed9c771e919c4bc718b98a96
[]
no_license
goaxe/LeetCode
a889f768a10cd2df874fc53a9ba5963766d1aa1d
8e4369e50acfaa1ef35175d2aaa542cb3efba42c
refs/heads/master
2021-01-24T02:53:28.708588
2015-08-01T09:21:51
2015-08-01T09:21:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,621
cpp
/*============================================================================= # FileName: 146-LRUCache.cpp # Desc: AC, 108ms # Author: Jian Huang # Email: huangjian1993@gmail.com # HomePage: https://cn.linkedin.com/in/huangjian1993 # Version: 0.0.1 # LastChange: 2015-08-01 09:10:38 # History: =============================================================================*/ #include <leetcode.h> struct ListNode1 { int key; int value; ListNode1 *prev; ListNode1 *next; ListNode1(int k, int v) { key = k; value = v; prev = NULL; next = NULL; } }; class LRUCache{ public: int capacity; ListNode1 *head, *tail; map<int, ListNode1 *> nodeMap; LRUCache(int capacity) { this->capacity = capacity; head = NULL; tail = NULL; } int get(int key) { if (nodeMap.find(key) != nodeMap.end()) { ListNode1 *node = nodeMap[key]; if (node == head) { } else if (node == tail) { ListNode1 *prev = tail->prev; prev->next = NULL; tail->prev = NULL; tail->next = head; head->prev = tail; head = tail; tail = prev; } else { ListNode1 *prev = node->prev, *next = node->next; prev->next = next; next->prev = prev; node->prev = NULL; node->next = head; head->prev = node; head = node; } return node->value; } return -1; } void set(int key, int value) { if (nodeMap.find(key) != nodeMap.end()) { ListNode1 *node = nodeMap[key]; node->value = value; if (node == head) { } else if (node == tail) { ListNode1 *prev = tail->prev; prev->next = NULL; tail->prev = NULL; tail->next = head; head->prev = tail; head = tail; tail = prev; } else { ListNode1 *prev = node->prev, *next = node->next; prev->next = next; next->prev = prev; node->prev = NULL; node->next = head; head->prev = node; head = node; } } else { if ((int)nodeMap.size() < capacity) { ListNode1 *node = new ListNode1(key, value); if (!head) { head = node; tail = node; } else { head->prev = node; node->next = head; head = node; } nodeMap.insert(pair<int, ListNode1*>(key, head)); } else { ListNode1 *node = new ListNode1(key, value); node->next = head; head->prev = node; head = node; nodeMap.erase(nodeMap.find(tail->key)); tail = tail->prev; tail->next = NULL; nodeMap.insert(pair<int, ListNode1*>(key, node)); } } } };
[ "huangjian1993@gmail.com" ]
huangjian1993@gmail.com
a2445c92a07aa1ede0dbf05f6c8c4307b4ec570a
72352139ee6aaa93e4a594c2ef0772ece3f66e6e
/src/OCGui/OpenGLCanvas.cpp
51bca2bd56eeff4ac9e211759208a82f8306141d
[ "MIT" ]
permissive
brunogouveia/OCGui
548d5c9186b2eab622f5552405727fc769e3e17d
e579e41389d3cfc39e6f2f8e69b8fc3328141044
refs/heads/master
2021-01-17T07:08:11.593355
2015-10-08T03:07:59
2015-10-08T03:07:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,395
cpp
#ifdef OCGUI_IMPLEMENTATION__ #include <OCGui/OpenGLCanvas.h> namespace OCGui { OpenGLCanvas::OpenGLCanvas(std::string&& label, int width, int height): Widget(std::move(label)), m_drawCallback(NULL), m_width(width), m_height(height) { } OpenGLCanvas::~OpenGLCanvas() {} void OpenGLCanvas::Draw(Vec2&& position, Vec2&& size) { if (m_content) { m_content->Draw(std::move(position), std::move(size)); } if (GetDrawCallback()) { GetDrawCallback()(std::move(m_position), m_position + m_size); } } bool OpenGLCanvas::HandleEvents(Vec2&& position, Vec2&& size) { if (m_content && m_content->HandleEvents(std::move(position), std::move(size))) { return true; } using namespace ImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiState& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(m_label.c_str()); Vec2 actualSize = Vec2(size.x ? size.x : m_width, size.y ? size.y : m_height); const ImRect bb(position, position + actualSize); ItemSize(bb, style.FramePadding.y); if (!ItemAdd(bb, &id)) return false; // Behavior const bool hovered = IsHovered(bb, id, true); if (hovered) { g.HoveredId = id; if ((!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt)) { if (g.IO.MouseClicked[0]) { SetActiveID(id, window); FocusWindow(window); } } } else if (g.ActiveId == id) { if (g.IO.MouseClicked[0]) { SetActiveID(0); } } bool held = false; if (g.ActiveId == id) { g.ActiveIdIsFocusedOnly = !g.IO.MouseDown[0]; if (g.IO.MouseDown[0]) { held = true; } } // Update position and size m_position = position; m_size = actualSize; return Widget::HandleEvents(std::move(position), std::move(size)); } } /* OCGui */ #endif
[ "bruno.henrique.gouveia@gmail.com" ]
bruno.henrique.gouveia@gmail.com
bca2e67403a2cc9a28e0e1ba8cdfaf0497abe8ad
7113cd2302f41512416b2f8f337131075904578a
/test/test_libmatrix_andrea.cpp
90a0454c6c91e97a92de861c502403f0e5184f3e
[]
no_license
AndreaC21/Projet-FMJ
92d381d2d29b4e72ecd9acb829596e78b7282e1f
627d33af1b3bd0cbbfaa26e591b9f60d94541de1
refs/heads/master
2023-08-09T10:48:38.144962
2021-09-15T18:43:44
2021-09-15T18:43:44
316,583,960
0
0
null
null
null
null
UTF-8
C++
false
false
2,906
cpp
// by Andréa Carpentier // using Tiago De Lima template // Tests libmatrix functionalities. #include <array> #include <vector> #include <iostream> #include "unit_test.hpp" #include "../include/libmatrix.hpp" using namespace libmatrix; using uint = unsigned int; int test_operator_mult_affect() { Vec3i u {2,2,3}; Vec3i v {6,6,9}; int scalar = 3; TestVector test_vec { { "u*=scalar == v", (u*=scalar)== v}, }; return run_tests( "Vector*=(scalar)", test_vec ); } int test_is_ortho_Vector() { Vec3i u {1,0,0}; Vec3i v {0,1,0}; Vec3i w {4,2,3}; TestVector test_vec { { "u.is_ortho(v)=", u.is_ortho(v)== true}, { "u.is_ortho(w)=", u.is_ortho(w)== false}, }; return run_tests( "Vector.is_ortho()", test_vec ); } int test_to_unit() { Vec3i u { 1,5,2}; Vec3r v {3,4,1}; Vec3r r{0.6,0.8,0.2}; TestVector test_vec { { "v.to_unit()=", v.to_unit()==r}, { "u.to_unit()=", u.to_unit()==vect3izero}, }; return run_tests( "Vector.to_unit()", test_vec ); } int test_inverse() { Mat33r m {{2,3,8},{6,0,-3},{-1,3,2}}; Mat33r r { {(float)1/15,(float)2/15,(float)-1/15}, {(float)-1/15,(float)4/45,(float)2/5}, {(float)2/15,(float)-1/15,(float)-2/15} }; TestVector test_vec { { "m.inverse()==r", m.inverse()== r}, }; return run_tests( "Matrix.inverse()", test_vec ); } int test_transpose() { Mat33r m {{2,3,8},{6,0,-3},{-1,3,2}}; Mat33r r {{2,6,-1},{3,0,3},{8,-3,2}}; TestVector test_vec { { "m.transpose()==r", m.transpose()== r}, }; return run_tests( "Matrix.transpose()", test_vec ); } int test_is_ortho_Matrix() { Mat33r m {{0,0,1},{1,0,0},{0,1,0}}; Mat33r m2 {{5,1,2},{1,5,-2},{2,-2,2}}; TestVector test_vec { { "m.is_ortho()==true", m.is_ortho()== true}, { "m2.is_ortho()==false", m2.is_ortho()== false}, }; return run_tests( "Matrix.is_ortho()", test_vec ); } int test_operator_mult_Matrix() { Mat33i m {{1,-1,2},{0,-3,1},{1,-2,4}}; Vec3i v1{2,1,-1}; Vec3i v2{-1,-4,-4}; TestVector test_vec { { "m*v1==v2", m*v1== v2}, }; return run_tests( "Matrix*Vector", test_vec ); } int main() { int nb_test = 7; int failures { 0 }; failures += test_operator_mult_affect(); failures += test_is_ortho_Vector(); failures += test_to_unit(); failures += test_inverse(); failures += test_transpose(); failures += test_is_ortho_Matrix(); failures += test_operator_mult_Matrix(); if( failures > 0 ) { std::cout << "Total failures : " << failures <<"/"<< nb_test << std::endl; std::cout << "TEST FAILED!!" << std::endl; return 1; } else { std::cout << "Success!" << std::endl; std::cout << (nb_test-failures) <<"/"<< nb_test << std::endl; return 0; } }
[ "andrea_carpentier@ens.univ-artois.fr" ]
andrea_carpentier@ens.univ-artois.fr
51622f673ce10e6017d427318eef82fb27fbefe4
ca7193f89b544d837c9172f61662f23fa674ee34
/C++/test.cpp
ca43551941515b494d446d402a765708af89174f
[]
no_license
KatizzZ/misssionA2Z
2e8ff3210f4cc6bcac04fc408b671ce36f319199
3639afd540ab8907bfec545a67a10404adb45bfc
refs/heads/master
2021-09-29T11:46:31.159571
2021-09-09T12:33:09
2021-09-09T12:33:09
244,320,315
1
0
null
2020-10-13T18:34:21
2020-03-02T08:40:18
C++
UTF-8
C++
false
false
498
cpp
void printArray(int arr[], int size) { for (int i = 0; i < size; i++) cout << arr[i] << " "; cout << endl; } int main() { int arr[] = {1, 2, 3, 4, 5, 6}; int n = sizeof(arr) / sizeof(arr[0]); // To print original array printArray(arr, n); // Function calling rvereseArray(arr, 0, n-1); cout << "Reversed array is" << endl; // To print the Reversed array printArray(arr, n); return 0; }
[ "shivamkatiyar110896@gmail.com" ]
shivamkatiyar110896@gmail.com
61af6d3afcbdc885fde44fc3950029c45828e3e7
b02eef564e53a479b1c40ed158cdabfb1305ec0c
/include/remod/module.h
cf2c66f458746443f5e5cfa6c32e196cdc51e04f
[ "MIT" ]
permissive
KevinW1998/ReMod-Core
f8858d66f78d233dbcab766ae94655b40ab90022
36f2c55b548d48303a74f388f11b94906e301461
refs/heads/master
2021-06-27T22:26:48.037567
2020-10-04T08:04:39
2020-10-04T08:04:51
134,573,079
0
0
null
null
null
null
UTF-8
C++
false
false
390
h
#pragma once namespace remod { class module { const char* m_module_name; public: constexpr module(const char* module_name) : m_module_name(module_name) {} constexpr bool is_main_module() const { return m_module_name == nullptr; } constexpr const char* get_module_name() const { return m_module_name; } }; constexpr const module main_module(nullptr); }
[ "kevin.waldock@gmail.com" ]
kevin.waldock@gmail.com
e2cfc514ceffbab429e1a83847dd567d59679766
fd8fdf41880f3f67f8e6413c297b5144097b50ad
/trunk/src/cgi/notice_cgi/cgi_sys_notice_get_for_pa.cpp
d8602fd7b9813d95011b24edfefba2cc876e8e99
[]
no_license
liuxuanhai/CGI_Web
c67d4db6a3a4de3714babbd31f095d2285545aac
273343bb06a170ac3086d633435e7bcaaa81e8c5
refs/heads/master
2020-03-18T12:27:40.035442
2016-09-28T11:18:26
2016-09-28T11:18:26
134,727,689
1
1
null
null
null
null
UTF-8
C++
false
false
2,884
cpp
#include "notice_server_cgi.h" #include "proto_io_tcp_client.h" class CgiSysNoticeGetForPa: public NoticeServerCgi { public: CgiSysNoticeGetForPa() : NoticeServerCgi(0, "config.ini", "logger.properties") { } bool InnerProcess() { uint64_t iPaAppidMd5 = strtoul(((string)GetInput().GetValue("pa_appid_md5")).c_str(),NULL,10); uint32_t iPagesize = (uint32_t) GetInput().GetValue("pagesize"); uint64_t iLimitTs = strtoul(((string)GetInput().GetValue("limit_ts")).c_str(),NULL,10); ZERO_INT_RETURN(iPaAppidMd5); ::common::protoio::ProtoIOTcpClient client(m_notice_server_ip, m_notice_server_port); std::string strErrMsg = ""; ::hoosho::msg::Msg stRequest; ::hoosho::msg::Msg stResponse; ::hoosho::msg::MsgHead* header = stRequest.mutable_head(); uint32_t iSeq = 1; header->set_seq(iSeq); header->set_cmd(hoosho::msg::QUERY_SYS_NOTICE_ALL_REQ); ::hoosho::sysnotice::QuerySysNoticeAllReq* req = stRequest.mutable_sys_notice_query_all_req(); req->set_pa_appid_md5(iPaAppidMd5); req->set_pagesize(iPagesize); req->set_limit_ts(iLimitTs); if (client.io(stRequest, stResponse, strErrMsg) < 0) { LOG4CPLUS_DEBUG(logger, "failed, strErrMsg=" << strErrMsg << std::endl;); return -1; } std::ostringstream oss; if (stResponse.head().cmd() == hoosho::msg::QUERY_SYS_NOTICE_ALL_RES && stResponse.head().seq() == iSeq) { if (stResponse.head().result() == hoosho::msg::E_OK) { LOG4CPLUS_DEBUG(logger, "succe!!\n"<<stResponse.Utf8DebugString() << std::endl); const hoosho::sysnotice::QuerySysNoticeAllRes& res = stResponse.sys_notice_query_all_res(); int iSize = res.sys_notice_list_size(); for (int i = 0; i < iSize; i++) { lce::cgi::CAnyValue stSysNotice; stSysNotice["pa_appid_md5"] = int_2_str(res.sys_notice_list(i).pa_appid_md5()); stSysNotice["create_ts"] = res.sys_notice_list(i).create_ts(); stSysNotice["title"] = res.sys_notice_list(i).title(); stSysNotice["content"] = res.sys_notice_list(i).content(); GetAnyValue()["sys_notice_list"].push_back(stSysNotice); } DoReply(CGI_RET_CODE_OK); } else if (stResponse.head().result() == hoosho::msg::E_SERVER_INNER_ERROR) { LOG4CPLUS_DEBUG(logger, "error!! result= 1" << std::endl); LOG4CPLUS_DEBUG(logger, stResponse.Utf8DebugString() << std::endl); DoReply(CGI_RET_CODE_SERVER_BUSY); } else { LOG4CPLUS_DEBUG(logger, "error!! result no 1 or 0" << std::endl); LOG4CPLUS_DEBUG(logger, stResponse.Utf8DebugString() << std::endl); DoReply(CGI_RET_CODE_SERVER_BUSY); } } else { LOG4CPLUS_DEBUG(logger, "error!! what 7 package?" << std::endl); LOG4CPLUS_DEBUG(logger, stResponse.Utf8DebugString() << std::endl); DoReply(CGI_RET_CODE_SERVER_BUSY); } return true; } }; int main() { CgiSysNoticeGetForPa cgi; if (!cgi.Run()) { return -1; } return 0; }
[ "penghuijun6738@163.com" ]
penghuijun6738@163.com
ab88e98d1d5cc6485a486c4bced43dbde3ff2c50
7e0de190260f7ec4bc14bf21eaa1c845a8d36d9f
/crossLaserTest/XMLReader.h
9907c0ca99a480d44894fa3caf427799b399c263
[]
no_license
PengZhai19960213/TestProject
fb4248cd2706db23ee58023669a2f9df108665d6
7c00fecbc5e626ac9c63a1d0815ded1212115c82
refs/heads/master
2020-07-16T19:39:53.808392
2018-07-02T09:17:59
2018-07-02T09:17:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,722
h
#pragma once #include "SharedMethod.h" #include "SharedHead.h" #include ".\TinyXML\tinyxml.h" #include ".\TinyXML\tinystr.h" #include "scannerSharedHeader.h" class XMLReader { public: XMLReader(){ } ///读取单个相机的内参数、畸变参数、误差参数、标定板外参数 static bool readCamPara(std::string filename,CamPara& m_camPara); ///读取相机组姿态参数,读取了Left_Mid、Right_Mid和Right_Left //static bool readCamGroupPara(std::string filename,CamGroupPara& m_camGroupPara); ///读取角点数据,包括图像尺寸、角点二维坐标、三维坐标(z=0)、每针角点数、图像索引 static bool readCornerData(std::string filename, CalibrationData& m_cornerData); ///读取三维点云数据 static bool readPointsCloud(std::string filename, std::vector<cv::Point3f>& m_points); ///读取光笔标定的结果 static bool readLightPenPara(std::string filename,std::vector<TagPoint3f>& pnts,cv::Point3f& pnt); ///读取相机和投影机参数,包括各自的内参数、畸变参数,以及联合标定参数 static bool ReadCamProPara(std::string filename, CamPara& camPara, CamPara& proPara, RT& camproRT); ///读取姿态参数,以4乘4矩阵形式 static bool ReadRT44(std::string filename,vector<Mat>& Inputs); static bool ReadRT33(std::string filename, vector<Mat>& Inputs); //*************************************zzl add *****************************// ///读取立体标靶标定参数文件 //static bool readObjPara( std::string filename,ObjectPara& ObjParam ); //static bool readpos61(std::string filename,vector<Vec6f>& pose); //************************************庄磊磊***********************************// static bool ReadStereoPara(std::string filename, CamPara& camLPara, CamPara& camRPara, struct RT& relativeRT,Size& imgSize); //读取二维点文件 static bool ReadPoints(std::string filename,vector<Point>& points); //************************************蔡永凯***********************************// static bool ReadSettingPara(std::string filename, laserScannerSetting& setParam); private: ///解析内参数元素 static bool parseIntrinsicparametersElement(TiXmlHandle hDoc, CamPara& m_camPara); ///解析畸变元素 static bool parseDistortionsElement(TiXmlHandle hDoc, CamPara& m_camPara); ///解析误差元素,不参与计算不需要解析 static bool parseErrorElement(TiXmlHandle hDoc, CamPara& m_camPara); ///解析图像尺寸元素 static bool parseImageSizeElement(TiXmlHandle hDoc, CalibrationData& m_cornerData); ///解析角点二维坐标元素 static bool parseCornerPointsElement(TiXmlHandle hDoc,const vector<int>& CornerNumPerFrame,CalibrationData& m_cornerData); ///解析角点三维点(z=0)元素 static bool parseFeaturePointsElement(TiXmlHandle hDoc,const vector<int>& CornerNumPerFrame, CalibrationData& m_cornerData); ///解析每针角点数元素 static bool parseCornerNumPerFrameElement(TiXmlHandle hDoc, vector<int>& CornerNumPerFrame); ///解析标定图片索引元素 static bool parseFrameNumListElement(TiXmlHandle hDoc, CalibrationData& m_cornerData); //*****************庄磊磊******************// ///解析左相机内参数元素 static bool parseCamLIntrinsicparametersElement(TiXmlHandle hDoc, CamPara& m_camPara); //解析右相机内参数元素 static bool parseCamRIntrinsicparametersElement(TiXmlHandle hDoc, CamPara& m_camPara); //解析左相机畸变元素 static bool parseCamLDistortionsElement(TiXmlHandle hDoc, CamPara& m_camPara); //解析右相机畸变元素 static bool parseCamRDistortionsElement(TiXmlHandle hDoc, CamPara& m_camPara); //解析RT元素 static bool parseRTElement(TiXmlHandle hDoc,RT& steroRTPara); //解析立体参数中Size元素 static bool parseStereoParaSize(TiXmlHandle hDoc,Size& imgSize); //解析二维点文件 static bool parsePoints(TiXmlHandle hDoc,vector<Point>& points); //************************庄磊磊*****************************// ///解析Left_Mid元素 //static bool parseLeftMidElement(TiXmlHandle hDoc, CamGroupPara& m_camGroupPara); ///解析Right_Mid元素 //static bool parseRightMidElement(TiXmlHandle hDoc, CamGroupPara& m_camGroupPara); ///解析Right_Left元素 //static bool parseRightLeftElement(TiXmlHandle hDoc, CamGroupPara& m_camGroupPara); ///解析标定板外参数元素 static bool parseImageRTElement(TiXmlHandle hDoc, CamPara& m_camPara); ///解析联合标定文件中相机标定元素 static bool parseIntrinsicCamParametersElement( TiXmlHandle hDoc, CamPara& camPara ); ///解析联合标定文件中相机畸变元素 static bool parseCamDistortionsElement(TiXmlHandle hDoc, CamPara& camPara); ///解析联合标定文件中投影机标定元素 static bool parseIntrinsicProParametersElement( TiXmlHandle hDoc, CamPara& proPara ); ///解析联合标定文件中投影机畸变元素 static bool parseProDistortionsElement(TiXmlHandle hDoc, CamPara& proPara); ///解析联合标定外参数元素 static bool parsesteroRTElement(TiXmlHandle hDoc, RT& steroRTPara); //************************蔡永凯*****************************// //解析测头设置参数 static bool parseSettingParaElement(TiXmlHandle hDoc, laserScannerSetting& setParam); //***************ZZL add****************************// ///解析立体标靶标定特征点尺寸元素 //static bool parseFacePntsElement( TiXmlHandle hDoc, ObjectPara& ObjParam ); /////解析立体标靶面相对位姿关系元素 //static bool parseRT2oneElement( TiXmlHandle hDoc, ObjectPara& ObjParam ); };
[ "1039219088@qq.com" ]
1039219088@qq.com
13121d3285ac6fdf0e81023d9eb0a3836cb43d62
01837a379a09f74f7ef43807533093fa716e71ac
/src/host/hiksdk/HikSdkParser2.h
f9298ca9363579d78a6fa3cdf12d36c8f21b5e09
[]
no_license
lasuax/jorhy-prj
ba2061d3faf4768cf2e12ee2484f8db51003bd3e
d22ded7ece50fb36aa032dad2cc01deac457b37f
refs/heads/master
2021-05-05T08:06:01.954941
2014-01-13T14:03:30
2014-01-13T14:03:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
914
h
#ifndef __HIKSDKPARSER2_H_ #define __HIKSDKPARSER2_H_ #include "j_includes.h" #include "x_time.h" #include "faac.h" #include "HikSdkParserDef.h" #define DATA_BUFFER_SIZE (1024 * 1024) #define HIK_PACK_LENGHT(x) (((*(x + 3) & 0xFF) << 8) + (*(x + 2) & 0xFF)) #define HIK_PACK_LENGHT2(x) (((*(x + 2) & 0xFF) << 8) + (*(x + 3) & 0xFF) + 4) class CHikSdkParser2 : public J_MediaParser { public: CHikSdkParser2(); ~CHikSdkParser2(); public: ///J_VideoParser virtual int Init(int nDataType = jo_video_normal); virtual int Deinit(); virtual int InputData(const char *pData, int nLen); virtual int GetOnePacket(char *pData, J_StreamHeader &streamHeader); private: int GetDataFlag(); private: char *m_pDataBuff; int m_nDataSize; HikStreamHead m_hikStreamHead; char *m_pOutBuff; bool m_bIsComplate;; j_uint32_t m_nDataLen; j_uint32_t m_nFrameLen; j_uint32_t m_frameNum; }; #endif //~__HIKSDKPARSER2_H_
[ "root@localhost.localdomain" ]
root@localhost.localdomain
47c1710bd30e8218600deeea04ffdb32e9101251
44ab57520bb1a9b48045cb1ee9baee8816b44a5b
/EngineTesting/Code/CoreTools/CoreToolsTesting/ObjectSystemsSuite/Detail/StreamSizeTestingEnum.h
4e8bbe19096fde881d2814e39190ee8df4647ef0
[ "BSD-3-Clause" ]
permissive
WuyangPeng/Engine
d5d81fd4ec18795679ce99552ab9809f3b205409
738fde5660449e87ccd4f4878f7bf2a443ae9f1f
refs/heads/master
2023-08-17T17:01:41.765963
2023-08-16T07:27:05
2023-08-16T07:27:05
246,266,843
10
0
null
null
null
null
GB18030
C++
false
false
546
h
/// Copyright (c) 2010-2023 /// Threading Core Render Engine /// /// 作者:彭武阳,彭晔恩,彭晔泽 /// 联系作者:94458936@qq.com /// /// 标准:std:c++20 /// 引擎测试版本:0.9.0.6 (2023/04/18 16:01) #ifndef CORE_TOOLS_OBJECT_SYSTEMS_STREAM_SIZE_TESTING_ENUM_H #define CORE_TOOLS_OBJECT_SYSTEMS_STREAM_SIZE_TESTING_ENUM_H #include "CoreTools/CoreToolsDll.h" namespace CoreTools { enum class StreamSizeTestingEnum { TestingEnum }; } #endif // CORE_TOOLS_OBJECT_SYSTEMS_STREAM_SIZE_TESTING_ENUM_H
[ "94458936@qq.com" ]
94458936@qq.com
53059ad84fe17c7eed4f118c3a897dd981b5daf2
e99a6334561af772065469c2ba49ec16e02264c8
/export/windows/cpp/obj/src/flixel/system/debug/completion/CompletionHandler.cpp
ef7265e396b9671a008760f913130389565adaff
[]
no_license
theleper676/Project13
adfe838254cac6359d7fb38984380800460bf221
424e0b430e76a59b95d6e6ee3c1706d498e87f76
refs/heads/master
2021-06-17T07:52:23.213394
2017-05-01T14:17:32
2017-05-01T14:19:50
null
0
0
null
null
null
null
UTF-8
C++
false
true
21,849
cpp
// Generated by Haxe 3.4.2 (git build master @ 890f8c7) #include <hxcpp.h> #ifndef INCLUDED_EReg #include <EReg.h> #endif #ifndef INCLUDED_StringTools #include <StringTools.h> #endif #ifndef INCLUDED_flixel_FlxG #include <flixel/FlxG.h> #endif #ifndef INCLUDED_flixel_FlxGame #include <flixel/FlxGame.h> #endif #ifndef INCLUDED_flixel_system_debug_FlxDebugger #include <flixel/system/debug/FlxDebugger.h> #endif #ifndef INCLUDED_flixel_system_debug_Window #include <flixel/system/debug/Window.h> #endif #ifndef INCLUDED_flixel_system_debug_completion_CompletionHandler #include <flixel/system/debug/completion/CompletionHandler.h> #endif #ifndef INCLUDED_flixel_system_debug_completion_CompletionList #include <flixel/system/debug/completion/CompletionList.h> #endif #ifndef INCLUDED_flixel_system_debug_watch_Watch #include <flixel/system/debug/watch/Watch.h> #endif #ifndef INCLUDED_flixel_system_debug_watch_WatchEntryData #include <flixel/system/debug/watch/WatchEntryData.h> #endif #ifndef INCLUDED_flixel_system_frontEnds_WatchFrontEnd #include <flixel/system/frontEnds/WatchFrontEnd.h> #endif #ifndef INCLUDED_flixel_util_FlxArrayUtil #include <flixel/util/FlxArrayUtil.h> #endif #ifndef INCLUDED_openfl__legacy_display_DisplayObject #include <openfl/_legacy/display/DisplayObject.h> #endif #ifndef INCLUDED_openfl__legacy_display_DisplayObjectContainer #include <openfl/_legacy/display/DisplayObjectContainer.h> #endif #ifndef INCLUDED_openfl__legacy_display_IBitmapDrawable #include <openfl/_legacy/display/IBitmapDrawable.h> #endif #ifndef INCLUDED_openfl__legacy_display_InteractiveObject #include <openfl/_legacy/display/InteractiveObject.h> #endif #ifndef INCLUDED_openfl__legacy_display_Sprite #include <openfl/_legacy/display/Sprite.h> #endif #ifndef INCLUDED_openfl__legacy_events_Event #include <openfl/_legacy/events/Event.h> #endif #ifndef INCLUDED_openfl__legacy_events_EventDispatcher #include <openfl/_legacy/events/EventDispatcher.h> #endif #ifndef INCLUDED_openfl__legacy_events_IEventDispatcher #include <openfl/_legacy/events/IEventDispatcher.h> #endif #ifndef INCLUDED_openfl__legacy_events_KeyboardEvent #include <openfl/_legacy/events/KeyboardEvent.h> #endif #ifndef INCLUDED_openfl__legacy_text_TextField #include <openfl/_legacy/text/TextField.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_d4c828664754b74a_14_new,"flixel.system.debug.completion.CompletionHandler","new",0xfa133d96,"flixel.system.debug.completion.CompletionHandler.new","flixel/system/debug/completion/CompletionHandler.hx",14,0x776a5e1a) HX_LOCAL_STACK_FRAME(_hx_pos_d4c828664754b74a_34_getTextUntilCaret,"flixel.system.debug.completion.CompletionHandler","getTextUntilCaret",0x57018dfe,"flixel.system.debug.completion.CompletionHandler.getTextUntilCaret","flixel/system/debug/completion/CompletionHandler.hx",34,0x776a5e1a) HX_LOCAL_STACK_FRAME(_hx_pos_d4c828664754b74a_41_getCaretIndex,"flixel.system.debug.completion.CompletionHandler","getCaretIndex",0x5ae25f7b,"flixel.system.debug.completion.CompletionHandler.getCaretIndex","flixel/system/debug/completion/CompletionHandler.hx",41,0x776a5e1a) HX_LOCAL_STACK_FRAME(_hx_pos_d4c828664754b74a_48_onKeyUp,"flixel.system.debug.completion.CompletionHandler","onKeyUp",0x7f599871,"flixel.system.debug.completion.CompletionHandler.onKeyUp","flixel/system/debug/completion/CompletionHandler.hx",48,0x776a5e1a) HX_LOCAL_STACK_FRAME(_hx_pos_d4c828664754b74a_75_invokeCompletion,"flixel.system.debug.completion.CompletionHandler","invokeCompletion",0x74f655be,"flixel.system.debug.completion.CompletionHandler.invokeCompletion","flixel/system/debug/completion/CompletionHandler.hx",75,0x776a5e1a) HX_LOCAL_STACK_FRAME(_hx_pos_d4c828664754b74a_111_getGlobals,"flixel.system.debug.completion.CompletionHandler","getGlobals",0x3af6d144,"flixel.system.debug.completion.CompletionHandler.getGlobals","flixel/system/debug/completion/CompletionHandler.hx",111,0x776a5e1a) HX_LOCAL_STACK_FRAME(_hx_pos_d4c828664754b74a_116_getCharXPosition,"flixel.system.debug.completion.CompletionHandler","getCharXPosition",0x2e5e3e1f,"flixel.system.debug.completion.CompletionHandler.getCharXPosition","flixel/system/debug/completion/CompletionHandler.hx",116,0x776a5e1a) HX_LOCAL_STACK_FRAME(_hx_pos_d4c828664754b74a_126_getCompletedText,"flixel.system.debug.completion.CompletionHandler","getCompletedText",0xf1336e6c,"flixel.system.debug.completion.CompletionHandler.getCompletedText","flixel/system/debug/completion/CompletionHandler.hx",126,0x776a5e1a) HX_LOCAL_STACK_FRAME(_hx_pos_d4c828664754b74a_130_completed,"flixel.system.debug.completion.CompletionHandler","completed",0x0b4edb41,"flixel.system.debug.completion.CompletionHandler.completed","flixel/system/debug/completion/CompletionHandler.hx",130,0x776a5e1a) HX_LOCAL_STACK_FRAME(_hx_pos_d4c828664754b74a_138_selectionChanged,"flixel.system.debug.completion.CompletionHandler","selectionChanged",0xb4bbcb12,"flixel.system.debug.completion.CompletionHandler.selectionChanged","flixel/system/debug/completion/CompletionHandler.hx",138,0x776a5e1a) HX_LOCAL_STACK_FRAME(_hx_pos_d4c828664754b74a_154_completionClosed,"flixel.system.debug.completion.CompletionHandler","completionClosed",0xa9f12ef2,"flixel.system.debug.completion.CompletionHandler.completionClosed","flixel/system/debug/completion/CompletionHandler.hx",154,0x776a5e1a) HX_LOCAL_STACK_FRAME(_hx_pos_d4c828664754b74a_163_getPathBeforeDot,"flixel.system.debug.completion.CompletionHandler","getPathBeforeDot",0x9fcc8f79,"flixel.system.debug.completion.CompletionHandler.getPathBeforeDot","flixel/system/debug/completion/CompletionHandler.hx",163,0x776a5e1a) HX_LOCAL_STACK_FRAME(_hx_pos_d4c828664754b74a_170_getWordAfterDot,"flixel.system.debug.completion.CompletionHandler","getWordAfterDot",0x4edfa1a3,"flixel.system.debug.completion.CompletionHandler.getWordAfterDot","flixel/system/debug/completion/CompletionHandler.hx",170,0x776a5e1a) HX_LOCAL_STACK_FRAME(_hx_pos_d4c828664754b74a_185_getLastWord,"flixel.system.debug.completion.CompletionHandler","getLastWord",0xa19a712c,"flixel.system.debug.completion.CompletionHandler.getLastWord","flixel/system/debug/completion/CompletionHandler.hx",185,0x776a5e1a) namespace flixel{ namespace _hx_system{ namespace debug{ namespace completion{ void CompletionHandler_obj::__construct( ::flixel::_hx_system::debug::completion::CompletionList completionList, ::openfl::_legacy::text::TextField input){ HX_STACKFRAME(&_hx_pos_d4c828664754b74a_14_new) HXLINE( 18) this->watchingSelection = false; HXLINE( 22) this->completionList = completionList; HXLINE( 23) this->input = input; HXLINE( 25) completionList->completed = this->completed_dyn(); HXLINE( 26) completionList->selectionChanged = this->selectionChanged_dyn(); HXLINE( 27) completionList->closed = this->completionClosed_dyn(); HXLINE( 29) input->addEventListener(::openfl::_legacy::events::KeyboardEvent_obj::KEY_UP,this->onKeyUp_dyn(),null(),null(),null()); } Dynamic CompletionHandler_obj::__CreateEmpty() { return new CompletionHandler_obj; } void *CompletionHandler_obj::_hx_vtable = 0; Dynamic CompletionHandler_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< CompletionHandler_obj > _hx_result = new CompletionHandler_obj(); _hx_result->__construct(inArgs[0],inArgs[1]); return _hx_result; } bool CompletionHandler_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x189c214e; } ::String CompletionHandler_obj::getTextUntilCaret(){ HX_STACKFRAME(&_hx_pos_d4c828664754b74a_34_getTextUntilCaret) HXDLIN( 34) ::String _hx_tmp = this->input->get_text(); HXDLIN( 34) return _hx_tmp.substring((int)0,this->getCaretIndex()); } HX_DEFINE_DYNAMIC_FUNC0(CompletionHandler_obj,getTextUntilCaret,return ) int CompletionHandler_obj::getCaretIndex(){ HX_STACKFRAME(&_hx_pos_d4c828664754b74a_41_getCaretIndex) HXDLIN( 41) return this->input->get_text().length; } HX_DEFINE_DYNAMIC_FUNC0(CompletionHandler_obj,getCaretIndex,return ) void CompletionHandler_obj::onKeyUp( ::openfl::_legacy::events::KeyboardEvent e){ HX_STACKFRAME(&_hx_pos_d4c828664754b74a_48_onKeyUp) HXLINE( 49) ::String text = this->getTextUntilCaret(); HXLINE( 52) bool _hx_tmp; HXDLIN( 52) bool _hx_tmp1; HXDLIN( 52) if (!(::StringTools_obj::endsWith(text,HX_(")",29,00,00,00)))) { HXLINE( 52) _hx_tmp1 = ::StringTools_obj::endsWith(text,HX_("\"",22,00,00,00)); } else { HXLINE( 52) _hx_tmp1 = true; } HXDLIN( 52) if (!(_hx_tmp1)) { HXLINE( 52) _hx_tmp = ::StringTools_obj::endsWith(text,HX_("'",27,00,00,00)); } else { HXLINE( 52) _hx_tmp = true; } HXDLIN( 52) if (_hx_tmp) { HXLINE( 54) this->completionList->close(); HXLINE( 55) return; } HXLINE( 58) { HXLINE( 58) int _g = e->keyCode; HXDLIN( 58) switch((int)(_g)){ case (int)13: case (int)27: case (int)38: case (int)40: { } break; case (int)37: case (int)39: { HXLINE( 61) this->completionList->close(); } break; default:{ HXLINE( 67) ::String _hx_tmp2 = this->getPathBeforeDot(text); HXDLIN( 67) this->invokeCompletion(_hx_tmp2,(e->keyCode == (int)190)); HXLINE( 69) if (this->completionList->get_visible()) { HXLINE( 70) ::flixel::_hx_system::debug::completion::CompletionList _hx_tmp3 = this->completionList; HXDLIN( 70) _hx_tmp3->set_filter(this->getWordAfterDot(text)); } } } } } HX_DEFINE_DYNAMIC_FUNC1(CompletionHandler_obj,onKeyUp,(void)) void CompletionHandler_obj::invokeCompletion(::String path,bool isPeriod){ HX_STACKFRAME(&_hx_pos_d4c828664754b74a_75_invokeCompletion) } HX_DEFINE_DYNAMIC_FUNC2(CompletionHandler_obj,invokeCompletion,(void)) ::Array< ::String > CompletionHandler_obj::getGlobals(){ HX_STACKFRAME(&_hx_pos_d4c828664754b74a_111_getGlobals) HXDLIN( 111) return ::Array_obj< ::String >::__new(0); } HX_DEFINE_DYNAMIC_FUNC0(CompletionHandler_obj,getGlobals,return ) Float CompletionHandler_obj::getCharXPosition(){ HX_STACKFRAME(&_hx_pos_d4c828664754b74a_116_getCharXPosition) HXLINE( 117) Float pos = ((Float)0.0); HXLINE( 118) { HXLINE( 118) int _g1 = (int)0; HXDLIN( 118) int _g = this->getCaretIndex(); HXDLIN( 118) while((_g1 < _g)){ HXLINE( 118) _g1 = (_g1 + (int)1); HXDLIN( 118) int i = (_g1 - (int)1); HXLINE( 119) pos = (pos + (int)6); } } HXLINE( 120) return pos; } HX_DEFINE_DYNAMIC_FUNC0(CompletionHandler_obj,getCharXPosition,return ) ::String CompletionHandler_obj::getCompletedText(::String text,::String selectedItem){ HX_GC_STACKFRAME(&_hx_pos_d4c828664754b74a_126_getCompletedText) HXDLIN( 126) return ::EReg_obj::__alloc( HX_CTX ,(this->getWordAfterDot(text) + HX_("$",24,00,00,00)),HX_("g",67,00,00,00))->replace(text,selectedItem); } HX_DEFINE_DYNAMIC_FUNC2(CompletionHandler_obj,getCompletedText,return ) void CompletionHandler_obj::completed(::String selectedItem){ HX_STACKFRAME(&_hx_pos_d4c828664754b74a_130_completed) HXLINE( 131) ::String textUntilCaret = this->getTextUntilCaret(); HXLINE( 132) ::String insert = this->getCompletedText(textUntilCaret,selectedItem); HXLINE( 133) ::openfl::_legacy::text::TextField _hx_tmp = this->input; HXDLIN( 133) ::String _hx_tmp1 = this->input->get_text(); HXDLIN( 133) _hx_tmp->set_text((insert + _hx_tmp1.substr(this->getCaretIndex(),null()))); HXLINE( 134) this->input->setSelection(insert.length,insert.length); } HX_DEFINE_DYNAMIC_FUNC1(CompletionHandler_obj,completed,(void)) void CompletionHandler_obj::selectionChanged(::String selectedItem){ HX_STACKFRAME(&_hx_pos_d4c828664754b74a_138_selectionChanged) } HX_DEFINE_DYNAMIC_FUNC1(CompletionHandler_obj,selectionChanged,(void)) void CompletionHandler_obj::completionClosed(){ HX_STACKFRAME(&_hx_pos_d4c828664754b74a_154_completionClosed) HXLINE( 155) if (!(this->watchingSelection)) { HXLINE( 156) return; } HXLINE( 158) { HXLINE( 158) ::flixel::_hx_system::frontEnds::WatchFrontEnd _this = ::flixel::FlxG_obj::watch; HXDLIN( 158) ::flixel::_hx_system::debug::watch::Watch _hx_tmp = ::flixel::FlxG_obj::game->debugger->watch; HXDLIN( 158) _hx_tmp->remove(HX_("Selection",2c,d8,ed,2f),::flixel::_hx_system::debug::watch::WatchEntryData_obj::QUICK(null())); } HXLINE( 159) this->watchingSelection = false; } HX_DEFINE_DYNAMIC_FUNC0(CompletionHandler_obj,completionClosed,(void)) ::String CompletionHandler_obj::getPathBeforeDot(::String text){ HX_STACKFRAME(&_hx_pos_d4c828664754b74a_163_getPathBeforeDot) HXLINE( 164) ::String lastWord = this->getLastWord(text); HXLINE( 165) int dotIndex = lastWord.lastIndexOf(HX_(".",2e,00,00,00),null()); HXLINE( 166) return lastWord.substr((int)0,dotIndex); } HX_DEFINE_DYNAMIC_FUNC1(CompletionHandler_obj,getPathBeforeDot,return ) ::String CompletionHandler_obj::getWordAfterDot(::String text){ HX_STACKFRAME(&_hx_pos_d4c828664754b74a_170_getWordAfterDot) HXLINE( 171) ::String lastWord = this->getLastWord(text); HXLINE( 173) int index = lastWord.lastIndexOf(HX_(".",2e,00,00,00),null()); HXLINE( 174) if ((index < (int)0)) { HXLINE( 175) index = (int)0; } else { HXLINE( 177) index = (index + (int)1); } HXLINE( 179) ::String word = lastWord.substr(index,null()); HXLINE( 180) if (hx::IsNull( word )) { HXLINE( 180) return HX_("",00,00,00,00); } else { HXLINE( 180) return word; } HXDLIN( 180) return null(); } HX_DEFINE_DYNAMIC_FUNC1(CompletionHandler_obj,getWordAfterDot,return ) ::String CompletionHandler_obj::getLastWord(::String text){ HX_GC_STACKFRAME(&_hx_pos_d4c828664754b74a_185_getLastWord) HXDLIN( 185) return ( (::String)(::flixel::util::FlxArrayUtil_obj::last( ::EReg_obj::__alloc( HX_CTX ,HX_("([^.a-zA-Z0-9_\\[\\]\"']+)",90,0f,11,57),HX_("g",67,00,00,00))->split(text))) ); } HX_DEFINE_DYNAMIC_FUNC1(CompletionHandler_obj,getLastWord,return ) hx::ObjectPtr< CompletionHandler_obj > CompletionHandler_obj::__new( ::flixel::_hx_system::debug::completion::CompletionList completionList, ::openfl::_legacy::text::TextField input) { hx::ObjectPtr< CompletionHandler_obj > __this = new CompletionHandler_obj(); __this->__construct(completionList,input); return __this; } hx::ObjectPtr< CompletionHandler_obj > CompletionHandler_obj::__alloc(hx::Ctx *_hx_ctx, ::flixel::_hx_system::debug::completion::CompletionList completionList, ::openfl::_legacy::text::TextField input) { CompletionHandler_obj *__this = (CompletionHandler_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(CompletionHandler_obj), true, "flixel.system.debug.completion.CompletionHandler")); *(void **)__this = CompletionHandler_obj::_hx_vtable; __this->__construct(completionList,input); return __this; } CompletionHandler_obj::CompletionHandler_obj() { } void CompletionHandler_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(CompletionHandler); HX_MARK_MEMBER_NAME(completionList,"completionList"); HX_MARK_MEMBER_NAME(input,"input"); HX_MARK_MEMBER_NAME(watchingSelection,"watchingSelection"); HX_MARK_END_CLASS(); } void CompletionHandler_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(completionList,"completionList"); HX_VISIT_MEMBER_NAME(input,"input"); HX_VISIT_MEMBER_NAME(watchingSelection,"watchingSelection"); } hx::Val CompletionHandler_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 5: if (HX_FIELD_EQ(inName,"input") ) { return hx::Val( input ); } break; case 7: if (HX_FIELD_EQ(inName,"onKeyUp") ) { return hx::Val( onKeyUp_dyn() ); } break; case 9: if (HX_FIELD_EQ(inName,"completed") ) { return hx::Val( completed_dyn() ); } break; case 10: if (HX_FIELD_EQ(inName,"getGlobals") ) { return hx::Val( getGlobals_dyn() ); } break; case 11: if (HX_FIELD_EQ(inName,"getLastWord") ) { return hx::Val( getLastWord_dyn() ); } break; case 13: if (HX_FIELD_EQ(inName,"getCaretIndex") ) { return hx::Val( getCaretIndex_dyn() ); } break; case 14: if (HX_FIELD_EQ(inName,"completionList") ) { return hx::Val( completionList ); } break; case 15: if (HX_FIELD_EQ(inName,"getWordAfterDot") ) { return hx::Val( getWordAfterDot_dyn() ); } break; case 16: if (HX_FIELD_EQ(inName,"invokeCompletion") ) { return hx::Val( invokeCompletion_dyn() ); } if (HX_FIELD_EQ(inName,"getCharXPosition") ) { return hx::Val( getCharXPosition_dyn() ); } if (HX_FIELD_EQ(inName,"getCompletedText") ) { return hx::Val( getCompletedText_dyn() ); } if (HX_FIELD_EQ(inName,"selectionChanged") ) { return hx::Val( selectionChanged_dyn() ); } if (HX_FIELD_EQ(inName,"completionClosed") ) { return hx::Val( completionClosed_dyn() ); } if (HX_FIELD_EQ(inName,"getPathBeforeDot") ) { return hx::Val( getPathBeforeDot_dyn() ); } break; case 17: if (HX_FIELD_EQ(inName,"watchingSelection") ) { return hx::Val( watchingSelection ); } if (HX_FIELD_EQ(inName,"getTextUntilCaret") ) { return hx::Val( getTextUntilCaret_dyn() ); } } return super::__Field(inName,inCallProp); } hx::Val CompletionHandler_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 5: if (HX_FIELD_EQ(inName,"input") ) { input=inValue.Cast< ::openfl::_legacy::text::TextField >(); return inValue; } break; case 14: if (HX_FIELD_EQ(inName,"completionList") ) { completionList=inValue.Cast< ::flixel::_hx_system::debug::completion::CompletionList >(); return inValue; } break; case 17: if (HX_FIELD_EQ(inName,"watchingSelection") ) { watchingSelection=inValue.Cast< bool >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void CompletionHandler_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_HCSTRING("completionList","\x9a","\xd1","\x5d","\x23")); outFields->push(HX_HCSTRING("input","\x0a","\xc4","\x1d","\xbe")); outFields->push(HX_HCSTRING("watchingSelection","\xd9","\xef","\xce","\x5e")); super::__GetFields(outFields); }; #if HXCPP_SCRIPTABLE static hx::StorageInfo CompletionHandler_obj_sMemberStorageInfo[] = { {hx::fsObject /*::flixel::_hx_system::debug::completion::CompletionList*/ ,(int)offsetof(CompletionHandler_obj,completionList),HX_HCSTRING("completionList","\x9a","\xd1","\x5d","\x23")}, {hx::fsObject /*::openfl::_legacy::text::TextField*/ ,(int)offsetof(CompletionHandler_obj,input),HX_HCSTRING("input","\x0a","\xc4","\x1d","\xbe")}, {hx::fsBool,(int)offsetof(CompletionHandler_obj,watchingSelection),HX_HCSTRING("watchingSelection","\xd9","\xef","\xce","\x5e")}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo *CompletionHandler_obj_sStaticStorageInfo = 0; #endif static ::String CompletionHandler_obj_sMemberFields[] = { HX_HCSTRING("completionList","\x9a","\xd1","\x5d","\x23"), HX_HCSTRING("input","\x0a","\xc4","\x1d","\xbe"), HX_HCSTRING("watchingSelection","\xd9","\xef","\xce","\x5e"), HX_HCSTRING("getTextUntilCaret","\x48","\xae","\xe9","\xdc"), HX_HCSTRING("getCaretIndex","\xc5","\x12","\xce","\x39"), HX_HCSTRING("onKeyUp","\x3b","\x58","\x3c","\x75"), HX_HCSTRING("invokeCompletion","\xb4","\x4c","\x06","\xfd"), HX_HCSTRING("getGlobals","\xba","\x8b","\x9a","\x63"), HX_HCSTRING("getCharXPosition","\x15","\x35","\x6e","\xb6"), HX_HCSTRING("getCompletedText","\x62","\x65","\x43","\x79"), HX_HCSTRING("completed","\x8b","\xa1","\x38","\x4f"), HX_HCSTRING("selectionChanged","\x08","\xc2","\xcb","\x3c"), HX_HCSTRING("completionClosed","\xe8","\x25","\x01","\x32"), HX_HCSTRING("getPathBeforeDot","\x6f","\x86","\xdc","\x27"), HX_HCSTRING("getWordAfterDot","\x6d","\x3b","\x96","\x86"), HX_HCSTRING("getLastWord","\xf6","\xdd","\x39","\x08"), ::String(null()) }; static void CompletionHandler_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(CompletionHandler_obj::__mClass,"__mClass"); }; #ifdef HXCPP_VISIT_ALLOCS static void CompletionHandler_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(CompletionHandler_obj::__mClass,"__mClass"); }; #endif hx::Class CompletionHandler_obj::__mClass; void CompletionHandler_obj::__register() { hx::Object *dummy = new CompletionHandler_obj; CompletionHandler_obj::_hx_vtable = *(void **)dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_HCSTRING("flixel.system.debug.completion.CompletionHandler","\xa4","\x7a","\x5b","\x41"); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mMarkFunc = CompletionHandler_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = hx::Class_obj::dupFunctions(CompletionHandler_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< CompletionHandler_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = CompletionHandler_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = CompletionHandler_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = CompletionHandler_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace flixel } // end namespace system } // end namespace debug } // end namespace completion
[ "yoav.levin@gmail.com" ]
yoav.levin@gmail.com
4549e66f3761ab779017d330e99a7c854ab377c4
ec7cf198f0d1abd3627b1a8796918c5ec7c86db8
/lib/SmartThings/SmartThingsEthernet.h
decd108e7799ffb522a4daa8daf86e29124f2617
[]
no_license
vassil-vassilev/HomeAC
975397274ca56f1699b36f4fbc79ad1ad599b349
31fce41c6b0922bea430418a9772aaf8c8dbad72
refs/heads/master
2021-08-23T19:39:08.034026
2017-12-06T07:59:36
2017-12-06T07:59:36
110,470,523
0
0
null
null
null
null
UTF-8
C++
false
false
3,012
h
//******************************************************************************* // SmartThings Arduino Ethernet Library // // License // (C) Copyright 2017 Dan Ogorchock // // History // 2017-02-04 Dan Ogorchock Created // 2017-05-02 Dan Ogorchock Add support for W5500 Ethernet2 Shield //******************************************************************************* #ifndef __SMARTTHINGSETHERNET_H__ #define __SMARTTHINGSETHERNET_H__ #include "SmartThings.h" //******************************************************************************* // Using Ethernet Shield //******************************************************************************* #include <IPAddress.h> /* //#if defined ARDUINO_ARCH_AVR //#include <SPI.h> //#include <Ethernet.h> //#elif defined ARDUINO_ARCH_ESP8266 //#include <ESP8266WiFi.h> //#endif */ namespace st { class SmartThingsEthernet: public SmartThings { private: protected: IPAddress st_hubIP; uint16_t st_serverPort; uint16_t st_hubPort; bool st_DHCP; public: //******************************************************************************* /// @brief SmartThings Ethernet Constructor - DHCP /// @param[in] serverPort - TCP/IP Port of the Arduino /// @param[in] hubIP - TCP/IP Address of the ST Hub /// @param[in] hubPort - TCP/IP Port of the ST Hub /// @param[in] callout - Set the Callout Function that is called on Msg Reception /// @param[in] shieldType (optional) - Set the Reported SheildType to the Server /// @param[in] enableDebug (optional) - Enable internal Library debug //******************************************************************************* SmartThingsEthernet(uint16_t serverPort, IPAddress hubIP, uint16_t hubPort, SmartThingsCallout_t *callout, String shieldType = "EthernetShield", bool enableDebug = false, int transmitInterval = 100, bool DHCP = true); //******************************************************************************* /// Destructor //******************************************************************************* ~SmartThingsEthernet(); //******************************************************************************* /// Initialize SmartThings Library //******************************************************************************* virtual void init(void) = 0; //all derived classes must implement this pure virtual function //******************************************************************************* /// Run SmartThings Library //******************************************************************************* virtual void run(void) = 0; //all derived classes must implement this pure virtual function //******************************************************************************* /// Send Message to the Hub //******************************************************************************* virtual void send(String message) = 0; //all derived classes must implement this pure virtual function }; } #endif
[ "vassilev.vassil@gmail.com" ]
vassilev.vassil@gmail.com
eb29bd1c5e7e9bec4aa2601a50cda2742cbeb6c5
6f4887d435b9420c7c1ac20c9b618bbdfe16464c
/10class/Aktobe/Пицца.cpp
380d5c0161c1cb0c48fd4bae4542f8d726fc8116
[]
no_license
beloofficial/Dev-C
4af8b69e58b07543a062360d9b17b0024759f0e2
64471bf2a2da7d3bf40f15445e397112648c189f
refs/heads/master
2022-01-10T22:36:33.601075
2019-05-04T09:18:59
2019-05-04T09:18:59
184,855,569
2
0
null
null
null
null
UTF-8
C++
false
false
508
cpp
#include<iostream> #include<deque> #include<algorithm> using namespace std; deque<int >s; int main() { long long int n,m,a[111111],l=0,k; cin>>n>>m; for(int i=1;i<=n;i++) { cin>>a[i]; } sort(a+1,a+n+1); for(int i=1;i<=n;i++) { s.push_front(a[i]); } k=n; for(int i=1;i<=n/2+1;i++) { if(s.front()+s.back()==m){cout<<s.back()<<" "<<s.front();l++;break;} else if(s.front()+s.back()>m){s.pop_front();} else {s.pop_back();} } if(l==0)cout<<0<<" "<<0; return 0; }
[ "amantay.or@gmail.com" ]
amantay.or@gmail.com
2071defc151cf80eb8afd2fb086ebfe11f9c6cac
e7d5a58c142fbd18c237438f799f35b11f6966fd
/lib/assimp/code/glTFAssetWriter.h
4ddae7d535a1a5a648da468e694aece4c1465433
[ "LGPL-2.0-or-later", "BSD-3-Clause", "MIT" ]
permissive
OpenGL-adepts/OpenGL-playground
143d7966ad961b06abce7de6968e011ddcd55143
263e3143f4f2d12b520667aa10b08804a1180677
refs/heads/master
2020-03-17T03:18:30.377834
2018-05-17T16:47:02
2018-05-17T16:47:02
133,229,244
1
0
MIT
2018-05-20T18:35:00
2018-05-13T11:06:11
C++
UTF-8
C++
false
false
2,519
h
/* Open Asset Import Library (assimp) ---------------------------------------------------------------------- Copyright (c) 2006-2016, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------- */ /** @file glTFWriter.h * Declares a class to write gltf/glb files * * glTF Extensions Support: * KHR_binary_glTF: full * KHR_materials_common: full */ #ifndef glTFAssetWriter_H_INC #define glTFAssetWriter_H_INC #include "glTFAsset.h" namespace glTF { using rapidjson::MemoryPoolAllocator; class AssetWriter { template<class T> friend struct LazyDictWriter; private: void WriteBinaryData(IOStream* outfile, size_t sceneLength); void WriteMetadata(); void WriteExtensionsUsed(); template<class T> void WriteObjects(LazyDict<T>& d); public: Document mDoc; Asset& mAsset; MemoryPoolAllocator<>& mAl; AssetWriter(Asset& asset); void WriteFile(const char* path); }; } // Include the implementation of the methods #include "glTFAssetWriter.inl" #endif
[ "michal.martyniak@linux.pl" ]
michal.martyniak@linux.pl
10a787fe168042e2bd6d5fe2f6bee3cca31ce4d0
9d364070c646239b2efad7abbab58f4ad602ef7b
/platform/external/chromium_org/components/precache/content/precache_manager_factory.h
df60ef8f6b2932089d50a656f8ead43f0e5cab82
[ "BSD-3-Clause" ]
permissive
denix123/a32_ul
4ffe304b13c1266b6c7409d790979eb8e3b0379c
b2fd25640704f37d5248da9cc147ed267d4771c2
refs/heads/master
2021-01-17T20:21:17.196296
2016-08-16T04:30:53
2016-08-16T04:30:53
65,786,970
0
2
null
2020-03-06T22:00:52
2016-08-16T04:15:54
null
UTF-8
C++
false
false
1,092
h
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_PRECACHE_CONTENT_PRECACHE_MANAGER_FACTORY_H_ #define COMPONENTS_PRECACHE_CONTENT_PRECACHE_MANAGER_FACTORY_H_ #include "base/basictypes.h" #include "base/memory/singleton.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" namespace content { class BrowserContext; } namespace precache { class PrecacheManager; class PrecacheManagerFactory : public BrowserContextKeyedServiceFactory { public: static PrecacheManager* GetForBrowserContext( content::BrowserContext* browser_context); static PrecacheManagerFactory* GetInstance(); private: friend struct DefaultSingletonTraits<PrecacheManagerFactory>; PrecacheManagerFactory(); virtual ~PrecacheManagerFactory(); virtual KeyedService* BuildServiceInstanceFor( content::BrowserContext* browser_context) const OVERRIDE; DISALLOW_COPY_AND_ASSIGN(PrecacheManagerFactory); }; } #endif
[ "allegrant@mail.ru" ]
allegrant@mail.ru
2fd17ad61ef9b22761a342d260a496cd547adac9
dad2738af1cddb3a60575430589ea125bd72bed3
/代码库/Dev c++/蓝桥杯/九数组分数.cpp
2b72d9aa13679914298dd801d24db9020e3ecf6d
[]
no_license
llwwlql/Dictionary
2f44e18474185304336f9b363ce533616af7ca8c
9f9f7ed81d5a872975eea9f9140845036745f98f
refs/heads/master
2021-01-09T20:04:08.101099
2016-06-17T01:37:00
2016-06-17T01:37:00
61,336,773
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
445
cpp
#include <stdio.h> void test(int x[]) { int a = x[0]*1000 + x[1]*100 + x[2]*10 + x[3]; int b = x[4]*10000 + x[5]*1000 + x[6]*100 + x[7]*10 + x[8]; if(a*3==b) printf("%d / %d\n", a, b); } void f(int x[], int k) { int i,t; if(k>=9){ test(x); return; } for(i=k; i<9; i++){ t=x[k]; x[k]=x[i]; x[i]=t; f(x,k+1); t=x[k]; x[k]=x[i]; x[i]=t; // Ìî¿Õ´¦ } } int main() { int x[] = {1,2,3,4,5,6,7,8,9}; f(x,0); return 0; }
[ "逯其鲁" ]
逯其鲁
04e31019b0e973d3f98eb037dca3d0c6b192da70
17af5ccbd2437823c8fd7d0c3190d721687fb6fe
/@twc_config_jointop/addons/ffaa_estatico/config.cpp
517168a27e209f6cf4c9e8a00fcf8d5f47aa6cbe
[]
no_license
Mallas011/Modset
7e55b80fd71bf7209f92ad1485b6f6621fd40c46
9a618879555eea4f2808cdd3c2fe7e093f133ffd
refs/heads/master
2021-05-25T11:53:48.901059
2018-03-28T23:40:55
2018-03-28T23:41:05
127,314,709
0
0
null
2018-03-29T15:57:41
2018-03-29T15:57:41
null
UTF-8
C++
false
false
7,207
cpp
class WeaponCloudsGun; class Mode_SemiAuto; class Mode_Burst; class CfgPatches { class ffaa_estatico { units[]= { "TWC_Milan" }; weapons[]= { "ffaa_estatico_milan" }; requiredVersion=1; requiredAddons[]= { "A3_Static_F_Gamma", "uk3cb_baf_equipment", "A3_CargoPoses_F", "A3_Armor_F_Slammer", "A3_Weapons_F" }; }; }; class CfgFunctions { class twc_Milan { tag="TWC"; class FunctionsMilan { file="ffaa_estatico\script"; class AddMilanMissile { }; class RemoveMilanMissile { }; class AssembleMilan { }; class DisassembleMilan { }; }; }; }; class Extended_PostInit_EventHandlers { class TWC_MILAN_INIT { init="execVM '\ffaa_estatico\script\init.sqf';"; }; }; class CfgAmmo { class MissileBase; class ffaa_estatico_m_milan: MissileBase { model="\A3\weapons_f\launchers\nlaw\nlaw_rocket.p3d"; hit=2000; indirectHit=20; indirectHitRange=2; cost=500; irLock=1; airLock=0; laserLock=1; manualControl=1; maxControlRange=6000; soundHit1[]= { "ffaa_estatico\sound\explosion1.wss", 3.1622801, 1, 2200 }; soundHit2[]= { "ffaa_estatico\sound\explosion2.wss", 3.1622801, 1, 2200 }; multiSoundHit[]= { "soundHit1", 0.5, "soundHit2", 0.5 }; effectsMissileInit="RocketBackEffectsRPG"; initTime=0; trackOversteer=1; trackLead=1; timeToLive=23; maneuvrability=12; simulationStep=0.0020000001; sideAirFriction=0.2; maxSpeed=200; thrustTime=4; thrust=150; fuseDistance=50; effectsMissile="missile2"; whistleDist=4; weaponLockSystem="2 + 16"; }; }; class CfgMagazines { class VehicleMagazine; class TWC_Milan_Missile_Mag: VehicleMagazine { scope=2; displayName="Misil Milan"; ammo="ffaa_estatico_M_milan"; initSpeed=55.1688; count=1; maxLeadSpeed=10; nameSound="missiles"; }; }; class cfgWeapons { class MissileLauncher; class TWC_Milan_Weapon: MissileLauncher { displayName="Milan"; minRange=10; minRangeProbab=0.60000002; midRange=1000; midRangeProbab=0.69999999; maxRange=2000; maxRangeProbab=0.001; reloadTime=1; magazines[]= { "TWC_Milan_Missile_Mag" }; cursorAim=""; cursorSize=1; sounds[]= { "StandardSound" }; class StandardSound { weaponSoundEffect="DefaultRifle"; begin1[]= { "ffaa_estatico\sound\spike_fire_v3_A", 1.4125376, 1, 1100 }; soundBegin[]= { "begin1", 1 }; }; soundFly[]= { "ffaa_estatico\sound\rocket_fly_1", 1, 1.1, 700 }; canLock=0; magazineReloadTime=3; aiRateOfFire=5; aiRateOfFireDistance=1400; }; class ACE_ItemCore; class InventoryItem_Base_F; class TWC_MilanMissileItem: ACE_ItemCore { scope=2; picture="\ffaa_estatico\images\MilanMissile.paa"; displayName="Milan Missile"; descriptionShort="Missile Used in Milan"; descriptionUse=""; class ItemInfo: InventoryItem_Base_F { mass=146.3; }; }; class UK3CB_BAF_L16; class TWC_Milan_Tripod_Disassemabled:UK3CB_BAF_L16 { author="FakeMatty"; scope=2; displayName="Milan Tripod"; picture="\ffaa_estatico\ico\staticY_CA.paa"; icon="\ffaa_estatico\ico\icomap_backpack_ca.paa"; mass=88; faction="twc_faction"; class assembleInfo { primary=0; base=""; assembleTo=""; dissasembleTo[]={}; displayName=""; }; }; class TWC_Milan_Launcher_Disassemabled:UK3CB_BAF_L16 { scope=2; displayName="Milan Launcher"; author="FakeMatty"; picture="\ffaa_estatico\ico\staticX_CA.paa"; icon="\ffaa_estatico\ico\icomap_backpack_ca.paa"; mass=106.7; }; }; class WeaponCloudsMGun; class DefaultEventhandlers; class CfgVehicles { class LandVehicle; class StaticWeapon: LandVehicle { class Turrets; class MainTurret; }; class StaticMGWeapon: StaticWeapon { }; class StaticATWeapon: StaticWeapon { }; class StaticAAWeapon: StaticWeapon { }; class StaticCannon: StaticWeapon { class ViewOptics; }; class StaticGrenadeLauncher: StaticWeapon { class ViewOptics; }; class StaticMortar: StaticWeapon { }; class TWC_Milan: StaticATWeapon { vehicleClass="Static"; scope=2; side=1; faction="twc_faction"; crew="I_Soldier_F"; typicalCargo[]= { "I_Soldier_F" }; model="\ffaa_estatico\ffaa_milan_tripode.p3d"; picture="\ffaa_estatico\ico\milan_ca.paa"; icon="\ffaa_estatico\icomap\icomap_metis_at13_CA.paa"; mapSize=2.5; displayName="$STR_FFAA_TRIPODE_MILAN"; author="$STR_FFAA_AUTOR_FFAAMOD"; /*class Eventhandlers: DefaultEventhandlers { init=""; fired="(_this select 0) RemoveMagazine 'TWC_Milan_Missile_Mag'"; };*/ class Turrets: Turrets { class MainTurret: MainTurret { weapons[]= { "TWC_Milan_Weapon" }; magazines[]= { "TWC_Milan_Missile_Mag" }; gunnerAction="Metis_Gunner"; gunnerOpticsModel="\ffaa_estatico\2Dscope_Metis"; gunnerOpticsEffect[]= { "OpticsCHAbera1", "OpticsBlur2" }; memoryPointsGetInGunner="pos_gunner_dir"; memoryPointsGetInGunnerDir="pos_gunner"; minTurn=-180; maxTurn=180; initTurn=0; minElev=-10; maxElev=10; initElev=0; gunnerForceOptics=1; class ViewGunner { initAngleX=5; minAngleX=-30; maxAngleX=30; initAngleY=0; minAngleY=-100; maxAngleY=100; initFov=0.69999999; minFov=0.25; maxFov=1.1; }; class ViewOptics { initAngleX=0; minAngleX=-30; maxAngleX=30; initAngleY=0; minAngleY=-100; maxAngleY=100; initFov=0.078000002; minFov=0.078000002; maxFov=0.078000002; visionMode[]= { "Normal" }; thermalMode[]={4,5}; }; }; }; }; /*/ class Bag_Base; class Weapon_Bag_Base: Bag_Base { class assembleInfo; }; class Twc_Tripod: Weapon_Bag_Base { author="$STR_FFAA_AUTOR_FFAAMOD"; scope=2; displayName="Milan Tripod"; model="\ffaa_estatico\StaticY.p3d"; picture="\ffaa_estatico\ico\staticY_CA.paa"; icon="\ffaa_estatico\ico\icomap_backpack_ca.paa"; mass=180; faction="ffaa"; class assembleInfo { primary=0; base=""; assembleTo=""; dissasembleTo[]={}; displayName=""; }; }; class twc_Weapon_Bag_Base: Weapon_Bag_Base { author="$STR_FFAA_AUTOR_FFAAMOD"; model="\ffaa_estatico\StaticX.p3d"; picture="\ffaa_estatico\ico\staticX_CA.paa"; icon="\ffaa_estatico\ico\icomap_backpack_ca.paa"; mass=320; class assembleInfo { primary=1; base="Twc_Tripod"; assembleTo=""; dissasembleTo[]={}; displayName=""; }; }; class TWC_milan_Bag: twc_Weapon_Bag_Base { scope=2; author="$STR_FFAA_AUTOR_FFAAMOD"; displayName="Milan Launcher"; class assembleInfo: assembleInfo { displayName="$STR_FFAA_TRIPODE_MILAN"; assembleTo="TWC_Milan"; }; }; /*/ }; class CfgMovesBasic { class DefaultDie; class ManActions { Metis_Gunner="Metis_Gunner"; }; }; class CfgMovesMaleSdr: CfgMovesBasic { class States { class Crew; class AmovPercMstpSnonWnonDnon; class Metis_Gunner: Crew { file="ffaa_estatico\anim\Metis_Gunner.rtm"; interpolateTo[]= { "KIA_SPG_Gunner", 1 }; }; }; }; class cfgMods { author="FFAA MOD"; };
[ "neciota@gmail.com" ]
neciota@gmail.com
41d44aec7214cdc4aa0d556e915544f00eb39cc6
6abaf62b3597610ed8b35f637552ea2a829dbd7e
/src/Services/StringizeService/ConstStringHolderMemory.h
1dafea1b589065303a7f7004a92b8cf571872e7d
[]
no_license
codacy-badger/Mengine
baac6696d51c6eae1201f345698e76755d30dd29
36f98378eec5e6351eacc7d9b463c472b9888fd0
refs/heads/master
2020-06-24T17:38:21.976520
2019-07-26T14:37:15
2019-07-26T14:37:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
448
h
#pragma once #include "Config/String.h" #include "Kernel/ConstStringHolder.h" namespace Mengine { class ConstStringHolderMemory : public ConstStringHolder { public: ConstStringHolderMemory(); ~ConstStringHolderMemory() override; public: void setValue( const Char * _value, ConstStringHolder::size_type _size, hash_type _hash ); protected: Char * m_buff; }; }
[ "irov13@mail.ru" ]
irov13@mail.ru
25c7d07dfac3ac5a598b225280e42583a8af6863
c15d609dd18c2341d0bc0a2be08f4906916b14fc
/SepherdGame/GraphicDev.h
d4944dee4014c6838d12dcfbbef5b91432e6a7a9
[]
no_license
ismw-git/SepherdGame
14f0462e54f7d8854bd3459c98a8ab678b84a241
024042272924f13ac31f6d92f4c44095426493c3
refs/heads/master
2020-05-09T16:14:24.891024
2019-04-14T09:38:19
2019-04-14T09:38:19
181,264,007
1
0
null
2019-04-14T05:22:29
2019-04-14T05:22:27
null
UTF-8
C++
false
false
420
h
#ifndef GraphicDev_h__ #define GraphicDev_h__ #include "Engine_Define.h" class CTransform; class CGraphicDev { DECLARE_SINGLETON(CGraphicDev) private: explicit CGraphicDev(void); ~CGraphicDev(void); public: void Set_DC(HDC BackDC); HDC Get_DC(void); void Set_Transform(CTransform* pTransform); CTransform* Get_Transform(void); private: HDC m_RenderedDC; CTransform* m_pTransform; }; #endif // !GraphicDev_h__
[ "doun1290@naver.com" ]
doun1290@naver.com
64bf820a75194c2d7815f96b32e06cc2f55c5744
019b1b4fc4a0c8bf0f65f5bec2431599e5de5300
/chrome/renderer/safe_browsing/phishing_dom_feature_extractor_browsertest.cc
221e8ebde435bdecf292ed626b2aaed706502a7b
[ "BSD-3-Clause" ]
permissive
wyrover/downloader
bd61b858d82ad437df36fbbaaf58d293f2f77445
a2239a4de6b8b545d6d88f6beccaad2b0c831e07
refs/heads/master
2020-12-30T14:45:13.193034
2017-04-23T07:39:04
2017-04-23T07:39:04
91,083,169
1
2
null
2017-05-12T11:06:42
2017-05-12T11:06:42
null
UTF-8
C++
false
false
24,709
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/safe_browsing/phishing_dom_feature_extractor.h" #include "base/bind.h" #include "base/callback.h" #include "base/memory/weak_ptr.h" #include "base/thread_task_runner_handle.h" #include "base/time/time.h" #include "chrome/renderer/chrome_content_renderer_client.h" #include "chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.h" #include "chrome/renderer/extensions/chrome_extensions_renderer_client.h" #include "chrome/renderer/safe_browsing/features.h" #include "chrome/renderer/safe_browsing/mock_feature_extractor_clock.h" #include "chrome/renderer/safe_browsing/test_utils.h" #include "chrome/renderer/spellchecker/spellcheck.h" #include "chrome/test/base/chrome_render_view_test.h" #include "content/public/common/content_switches.h" #include "content/public/renderer/render_frame.h" #include "content/public/test/test_utils.h" #include "extensions/renderer/dispatcher.h" #include "net/base/escape.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "testing/gmock/include/gmock/gmock.h" #include "third_party/WebKit/public/platform/URLConversion.h" #include "third_party/WebKit/public/platform/WebString.h" #include "third_party/WebKit/public/web/WebFrame.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebScriptSource.h" using ::testing::DoAll; using ::testing::Invoke; using ::testing::Return; namespace safe_browsing { // TestPhishingDOMFeatureExtractor has nearly identical behavior as // PhishingDOMFeatureExtractor, except the IsExternalDomain() and // CompleteURL() functions. This is to work around the fact that // ChromeRenderViewTest object does not know where the html content is hosted. class TestPhishingDOMFeatureExtractor : public PhishingDOMFeatureExtractor { public: explicit TestPhishingDOMFeatureExtractor(FeatureExtractorClock* clock) : PhishingDOMFeatureExtractor(clock) {} void SetDocumentDomain(std::string domain) { base_domain_ = domain; } void SetURLToFrameDomainCheckingMap( const base::hash_map<std::string, std::string>& checking_map) { url_to_frame_domain_map_ = checking_map; } void Reset() { base_domain_.clear(); url_to_frame_domain_map_.clear(); } private: // LoadHTML() function in RenderViewTest only loads html as data, // thus cur_frame_data_->domain is empty. Therefore, in base class // PhishingDOMFeatureExtractor::IsExternalDomain() will always return false. // Overriding IsExternalDomain(..) to work around this problem. bool IsExternalDomain(const GURL& url, std::string* domain) const override { DCHECK(domain); *domain = net::registry_controlled_domains::GetDomainAndRegistry( url, net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES); if (domain->empty()) *domain = url.spec(); // If this html only has one frame, use base_domain_ to determine if url // is external. if (!base_domain_.empty()) { return !url.DomainIs(base_domain_); } else { // html contains multiple frames, need to check against // its corresponding frame's domain. auto it = url_to_frame_domain_map_.find(url.spec()); if (it != url_to_frame_domain_map_.end()) { const std::string document_domain = it->second; return !url.DomainIs(document_domain); } NOTREACHED() << "Testing input setup is incorrect. " "Please check url_to_frame_domain_map_ setup."; return true; } } // For similar reason as above, PhishingDOMFeatureExtractor::CompeteURL(..) // always returns empty WebURL. Overriding this CompeteURL(..) to work around // this issue. blink::WebURL CompleteURL(const blink::WebElement& element, const blink::WebString& partial_url) override { GURL parsed_url(GURL(partial_url.utf8())); GURL full_url; if (parsed_url.has_scheme()) { // This is already a complete URL. full_url = GURL(blink::WebStringToGURL(partial_url)); } else if (!base_domain_.empty()) { // This is a partial URL and only one frame in testing html. full_url = GURL("http://" + base_domain_).Resolve(partial_url); } else { auto it = url_to_frame_domain_map_.find(partial_url.utf8()); if (it != url_to_frame_domain_map_.end()) { const std::string frame_domain = it->second; full_url = GURL("http://" + it->second).Resolve(partial_url.utf8()); url_to_frame_domain_map_[full_url.spec()] = it->second; } else { NOTREACHED() << "Testing input setup is incorrect. " "Please check url_to_frame_domain_map_ setup."; } } return blink::WebURL(full_url); } // If there is only main frame, we use base_domain_ to track where // the html content is hosted. std::string base_domain_; // If html contains multiple frame/iframe, we track domain of each frame by // using this map, where keys are the urls mentioned in the html content, // values are the domains of the corresponding frames. base::hash_map<std::string, std::string> url_to_frame_domain_map_; }; class TestChromeContentRendererClient : public ChromeContentRendererClient { public: TestChromeContentRendererClient() {} ~TestChromeContentRendererClient() override {} // Since visited_link_slave_ in ChromeContentRenderClient never get initiated, // overrides VisitedLinkedHash() function to prevent crashing. unsigned long long VisitedLinkHash(const char* canonical_url, size_t length) override { return 0LL; } }; class PhishingDOMFeatureExtractorTest : public ChromeRenderViewTest { public: PhishingDOMFeatureExtractorTest() : success_(false), message_loop_(new content::MessageLoopRunner), weak_factory_(this) {} bool GetSuccess() { return success_; } void ResetTest() { success_ = false; message_loop_ = new content::MessageLoopRunner; extractor_->Reset(); } void ExtractFeaturesAcrossFrames( const std::string& html_content, FeatureMap* features, const base::hash_map<std::string, std::string>& url_frame_domain_map) { extractor_->SetURLToFrameDomainCheckingMap(url_frame_domain_map); LoadHTML(html_content.c_str()); extractor_->ExtractFeatures( GetMainFrame()->document(), features, base::Bind(&PhishingDOMFeatureExtractorTest::AnotherExtractionDone, weak_factory_.GetWeakPtr())); message_loop_->Run(); } void ExtractFeatures(const std::string& document_domain, const std::string& html_content, FeatureMap* features) { extractor_->SetDocumentDomain(document_domain); LoadHTML(html_content.c_str()); extractor_->ExtractFeatures( GetMainFrame()->document(), features, base::Bind(&PhishingDOMFeatureExtractorTest::AnotherExtractionDone, weak_factory_.GetWeakPtr())); message_loop_->Run(); } // Helper for the SubframeRemoval test that posts a message to remove // the iframe "frame1" from the document. void ScheduleRemoveIframe() { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&PhishingDOMFeatureExtractorTest::RemoveIframe, weak_factory_.GetWeakPtr())); } protected: void SetUp() override { ChromeRenderViewTest::SetUp(); extractor_.reset(new TestPhishingDOMFeatureExtractor(&clock_)); } void TearDown() override { extractor_.reset(nullptr); ChromeRenderViewTest::TearDown(); } content::ContentRendererClient* CreateContentRendererClient() override { ChromeContentRendererClient* client = new TestChromeContentRendererClient(); #if defined(ENABLE_EXTENSIONS) extension_dispatcher_delegate_.reset( new ChromeExtensionsDispatcherDelegate()); ChromeExtensionsRendererClient* ext_client = ChromeExtensionsRendererClient::GetInstance(); ext_client->SetExtensionDispatcherForTest(make_scoped_ptr( new extensions::Dispatcher(extension_dispatcher_delegate_.get()))); #endif #if defined(ENABLE_SPELLCHECK) client->SetSpellcheck(new SpellCheck()); #endif return client; } void AnotherExtractionDone(bool success) { success_ = success; message_loop_->QuitClosure().Run(); } // Does the actual work of removing the iframe "frame1" from the document. void RemoveIframe() { blink::WebFrame* main_frame = GetMainFrame(); ASSERT_TRUE(main_frame); main_frame->executeScript(blink::WebString( "document.body.removeChild(document.getElementById('frame1'));")); } MockFeatureExtractorClock clock_; bool success_; scoped_ptr<TestPhishingDOMFeatureExtractor> extractor_; scoped_refptr<content::MessageLoopRunner> message_loop_; base::WeakPtrFactory<PhishingDOMFeatureExtractorTest> weak_factory_; }; TEST_F(PhishingDOMFeatureExtractorTest, FormFeatures) { // This test doesn't exercise the extraction timing. EXPECT_CALL(clock_, Now()).WillRepeatedly(Return(base::TimeTicks::Now())); FeatureMap expected_features; expected_features.AddBooleanFeature(features::kPageHasForms); expected_features.AddRealFeature(features::kPageActionOtherDomainFreq, 0.25); expected_features.AddBooleanFeature(features::kPageHasTextInputs); expected_features.AddBooleanFeature(features::kPageHasCheckInputs); expected_features.AddBooleanFeature(features::kPageActionURL + std::string("http://cgi.host.com/submit")); expected_features.AddBooleanFeature(features::kPageActionURL + std::string("http://other.com/")); GURL url("http://host.com/query"); expected_features.AddBooleanFeature(features::kPageActionURL + url.spec()); FeatureMap features; EXPECT_FALSE(GetSuccess()); ExtractFeatures( "host.com", "<html><head><body>" "<form action=\"query\"><input type=text><input type=checkbox></form>" "<form action=\"http://cgi.host.com/submit\"></form>" "<form action=\"http://other.com/\"></form>" "<form action=\"query\"></form>" "<form></form></body></html>", &features); EXPECT_TRUE(GetSuccess()); ExpectFeatureMapsAreEqual(features, expected_features); expected_features.Clear(); expected_features.AddBooleanFeature(features::kPageHasRadioInputs); expected_features.AddBooleanFeature(features::kPageHasPswdInputs); features.Clear(); ResetTest(); EXPECT_FALSE(GetSuccess()); ExtractFeatures("host.com", "<html><head><body>" "<input type=\"radio\"><input type=password></body></html>", &features); EXPECT_TRUE(GetSuccess()); ExpectFeatureMapsAreEqual(features, expected_features); expected_features.Clear(); expected_features.AddBooleanFeature(features::kPageHasTextInputs); features.Clear(); ResetTest(); EXPECT_FALSE(GetSuccess()); ExtractFeatures("host.com", "<html><head><body><input></body></html>", &features); EXPECT_TRUE(GetSuccess()); ExpectFeatureMapsAreEqual(features, expected_features); expected_features.Clear(); expected_features.AddBooleanFeature(features::kPageHasTextInputs); features.Clear(); ResetTest(); EXPECT_FALSE(GetSuccess()); ExtractFeatures("host.com", "<html><head><body><input type=\"invalid\"></body></html>", &features); EXPECT_TRUE(GetSuccess()); ExpectFeatureMapsAreEqual(features, expected_features); } TEST_F(PhishingDOMFeatureExtractorTest, LinkFeatures) { // This test doesn't exercise the extraction timing. EXPECT_CALL(clock_, Now()).WillRepeatedly(Return(base::TimeTicks::Now())); FeatureMap expected_features; expected_features.AddRealFeature(features::kPageExternalLinksFreq, 0.5); expected_features.AddRealFeature(features::kPageSecureLinksFreq, 0.0); expected_features.AddBooleanFeature(features::kPageLinkDomain + std::string("chromium.org")); FeatureMap features; ExtractFeatures("host.com", "<html><head><body>" "<a href=\"http://www2.host.com/abc\">link</a>" "<a name=page_anchor></a>" "<a href=\"http://www.chromium.org/\">chromium</a>" "</body></html>", &features); ExpectFeatureMapsAreEqual(features, expected_features); expected_features.Clear(); expected_features.AddRealFeature(features::kPageExternalLinksFreq, 0.25); expected_features.AddRealFeature(features::kPageSecureLinksFreq, 0.25); expected_features.AddBooleanFeature(features::kPageLinkDomain + std::string("chromium.org")); features.Clear(); ResetTest(); ExtractFeatures("host.com", "<html><head><body>" "<a href=\"login\">this is not secure</a>" "<a href=\"http://host.com\">not secure</a>" "<a href=\"http://chromium.org/\">also not secure</a>" "<a href=\"https://www2.host.com/login\"> this secure</a>" "</body></html>", &features); ExpectFeatureMapsAreEqual(features, expected_features); } TEST_F(PhishingDOMFeatureExtractorTest, ScriptAndImageFeatures) { // This test doesn't exercise the extraction timing. EXPECT_CALL(clock_, Now()).WillRepeatedly(Return(base::TimeTicks::Now())); FeatureMap expected_features; expected_features.AddBooleanFeature(features::kPageNumScriptTagsGTOne); FeatureMap features; ExtractFeatures( "host.com", "<html><head><script></script><script></script></head></html>", &features); ExpectFeatureMapsAreEqual(features, expected_features); expected_features.Clear(); expected_features.AddBooleanFeature(features::kPageNumScriptTagsGTOne); expected_features.AddBooleanFeature(features::kPageNumScriptTagsGTSix); expected_features.AddRealFeature(features::kPageImgOtherDomainFreq, 0.5); features.Clear(); ResetTest(); std::string html( "<html><head><script></script><script></script><script></script>" "<script></script><script></script><script></script><script></script>" "</head><body>" "<img src=\"file:///C:/other.png\">" "<img src=\"img/header.png\">" "</body></html>"); ExtractFeatures("host.com", html, &features); ExpectFeatureMapsAreEqual(features, expected_features); } // A page with nested iframes. // html // iframe2 / \ iframe1 // \ iframe3 TEST_F(PhishingDOMFeatureExtractorTest, SubFrames) { // This test doesn't exercise the extraction timing. // Test that features are aggregated across all frames. EXPECT_CALL(clock_, Now()).WillRepeatedly(Return(base::TimeTicks::Now())); const char urlprefix[] = "data:text/html;charset=utf-8,"; base::hash_map<std::string, std::string> url_iframe_map; std::string iframe1_nested_html( "<html><body><input type=password>" "<a href=\"https://host3.com/submit\">link</a>" "<a href=\"relative\">link</a>" "</body></html>"); GURL iframe1_nested_url(urlprefix + iframe1_nested_html); // iframe1_nested is on host1.com. url_iframe_map["https://host3.com/submit"] = "host1.com"; url_iframe_map["relative"] = "host1.com"; std::string iframe1_html( "<html><head><script></script><body>" "<form action=\"http://host3.com/home\"><input type=checkbox></form>" "<form action=\"http://host1.com/submit\"></form>" "<a href=\"http://www.host1.com/reset\">link</a>" "<iframe src=\"" + net::EscapeForHTML(iframe1_nested_url.spec()) + "\"></iframe></head></html>"); GURL iframe1_url(urlprefix + iframe1_html); // iframe1 is on host1.com too. url_iframe_map["http://host3.com/home"] = "host1.com"; url_iframe_map["http://host1.com/submit"] = "host1.com"; url_iframe_map["http://www.host1.com/reset"] = "host1.com"; std::string iframe2_html( "<html><head><script></script><body>" "<img src=\"file:///C:/other.html\">" "</body></html>"); GURL iframe2_url(urlprefix + iframe2_html); // iframe2 is on host2.com url_iframe_map["file:///C:/other.html"] = "host2.com"; std::string html( "<html><body><input type=text>" "<a href=\"info.html\">link</a>" "<iframe src=\"" + net::EscapeForHTML(iframe1_url.spec()) + "\"></iframe><iframe src=\"" + net::EscapeForHTML(iframe2_url.spec()) + "\"></iframe></body></html>"); // The entire html is hosted on host.com url_iframe_map["info.html"] = "host.com"; FeatureMap expected_features; expected_features.AddBooleanFeature(features::kPageHasForms); // Form action domains are compared to the URL of the document they're in, // not the URL of the toplevel page. So http://host1.com/ has two form // actions, one of which is external. expected_features.AddRealFeature(features::kPageActionOtherDomainFreq, 0.5); expected_features.AddBooleanFeature(features::kPageHasTextInputs); expected_features.AddBooleanFeature(features::kPageHasPswdInputs); expected_features.AddBooleanFeature(features::kPageHasCheckInputs); expected_features.AddRealFeature(features::kPageExternalLinksFreq, 0.25); expected_features.AddBooleanFeature(features::kPageLinkDomain + std::string("host3.com")); expected_features.AddRealFeature(features::kPageSecureLinksFreq, 0.25); expected_features.AddBooleanFeature(features::kPageNumScriptTagsGTOne); expected_features.AddRealFeature(features::kPageImgOtherDomainFreq, 1.0); expected_features.AddBooleanFeature(features::kPageActionURL + std::string("http://host1.com/submit")); expected_features.AddBooleanFeature(features::kPageActionURL + std::string("http://host3.com/home")); FeatureMap features; ExtractFeaturesAcrossFrames(html, &features, url_iframe_map); ExpectFeatureMapsAreEqual(features, expected_features); } TEST_F(PhishingDOMFeatureExtractorTest, Continuation) { // For this test, we'll cause the feature extraction to run multiple // iterations by incrementing the clock. // This page has a total of 50 elements. For the external forms feature to // be computed correctly, the extractor has to examine the whole document. // Note: the empty HEAD is important -- WebKit will synthesize a HEAD if // there isn't one present, which can be confusing for the element counts. std::string html = "<html><head></head><body>" "<form action=\"ondomain\"></form>"; for (int i = 0; i < 45; ++i) { html.append("<p>"); } html.append("<form action=\"http://host2.com/\"></form></body></html>"); // Advance the clock 6 ms every 10 elements processed, 10 ms between chunks. // Note that this assumes kClockCheckGranularity = 10 and // kMaxTimePerChunkMs = 10. base::TimeTicks now = base::TimeTicks::Now(); EXPECT_CALL(clock_, Now()) // Time check at the start of extraction. .WillOnce(Return(now)) // Time check at the start of the first chunk of work. .WillOnce(Return(now)) // Time check after the first 10 elements. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(6))) // Time check after the next 10 elements. This is over the chunk // time limit, so a continuation task will be posted. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(12))) // Time check at the start of the second chunk of work. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(22))) // Time check after resuming iteration for the second chunk. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(24))) // Time check after the next 10 elements. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(30))) // Time check after the next 10 elements. This will trigger another // continuation task. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(36))) // Time check at the start of the third chunk of work. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(46))) // Time check after resuming iteration for the third chunk. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(48))) // Time check after the last 10 elements. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(54))) // A final time check for the histograms. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(56))); FeatureMap expected_features; expected_features.AddBooleanFeature(features::kPageHasForms); expected_features.AddRealFeature(features::kPageActionOtherDomainFreq, 0.5); expected_features.AddBooleanFeature(features::kPageActionURL + std::string("http://host.com/ondomain")); expected_features.AddBooleanFeature(features::kPageActionURL + std::string("http://host2.com/")); FeatureMap features; ExtractFeatures("host.com", html, &features); ExpectFeatureMapsAreEqual(features, expected_features); // Make sure none of the mock expectations carry over to the next test. ::testing::Mock::VerifyAndClearExpectations(&clock_); // Now repeat the test with the same page, but advance the clock faster so // that the extraction time exceeds the maximum total time for the feature // extractor. Extraction should fail. Note that this assumes // kMaxTotalTimeMs = 500. EXPECT_CALL(clock_, Now()) // Time check at the start of extraction. .WillOnce(Return(now)) // Time check at the start of the first chunk of work. .WillOnce(Return(now)) // Time check after the first 10 elements. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(300))) // Time check at the start of the second chunk of work. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(350))) // Time check after resuming iteration for the second chunk. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(360))) // Time check after the next 10 elements. This is over the limit. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(600))) // A final time check for the histograms. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(620))); features.Clear(); ResetTest(); ExtractFeatures("host.com", html, &features); EXPECT_FALSE(GetSuccess()); } TEST_F(PhishingDOMFeatureExtractorTest, SubframeRemoval) { // In this test, we'll advance the feature extractor so that it is positioned // inside an iframe, and have it pause due to exceeding the chunk time limit. // Then, prior to continuation, the iframe is removed from the document. // As currently implemented, this should finish extraction from the removed // iframe document. const char urlprefix[] = "data:text/html;charset=utf-8,"; std::string iframe1_html( "<html><body><p><p><p><input type=password></body></html>"); GURL iframe1_url(urlprefix + iframe1_html); base::TimeTicks now = base::TimeTicks::Now(); EXPECT_CALL(clock_, Now()) // Time check at the start of extraction. .WillOnce(Return(now)) // Time check at the start of the first chunk of work. .WillOnce(Return(now)) // Time check after the first 10 elements. Enough time has passed // to stop extraction. Schedule the iframe removal to happen as soon as // the feature extractor returns control to the message loop. .WillOnce(DoAll( Invoke(this, &PhishingDOMFeatureExtractorTest::ScheduleRemoveIframe), Return(now + base::TimeDelta::FromMilliseconds(21)))) // Time check at the start of the second chunk of work. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(25))) // Time check after resuming iteration for the second chunk. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(27))) // A final time check for the histograms. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(33))); FeatureMap expected_features; expected_features.AddBooleanFeature(features::kPageHasForms); expected_features.AddBooleanFeature(features::kPageHasPswdInputs); FeatureMap features; std::string html( "<html><head></head><body>" "<iframe src=\"" + net::EscapeForHTML(iframe1_url.spec()) + "\" id=\"frame1\"></iframe>" "<form></form></body></html>"); ExtractFeatures("host.com", html, &features); ExpectFeatureMapsAreEqual(features, expected_features); } } // namespace safe_browsing
[ "wangpp_os@sari.ac.cn" ]
wangpp_os@sari.ac.cn
c9a3a9bba9e7d94e7af31ae1ce15bc24f54382b0
3f2ad517fc8037b9e6d17cc20aab86deb02c9524
/Source/HostStartup.cpp
f35b647427fad31271687241be10de3836af285c
[]
no_license
georgekrueger/LumaGen
4ceb2233b3cb6cd7fa9453a6bd49a356351eafb7
1cee604c4f57351c7683b840208af0e97b4dda0e
refs/heads/master
2021-01-02T09:27:58.917866
2013-07-14T19:08:41
2013-07-14T19:08:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,102
cpp
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-9 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ #include "JuceHeader.h" #include "MainHostWindow.h" #include "InternalFilters.h" #include "MidiCodePlugin.h" #include "JSFuncs.h" #if ! (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU) #error "If you're building the audio plugin host, you probably want to enable VST and/or AU support" #endif ApplicationCommandManager* commandManager = nullptr; ApplicationProperties* appProperties = nullptr; v8::Persistent<v8::Context> context; //============================================================================== class PluginHostApp : public JUCEApplication { public: //============================================================================== PluginHostApp() { } void initialise (const String& commandLine) { PropertiesFile::Options options; options.applicationName = "Luma"; options.filenameSuffix = "settings"; options.osxLibrarySubFolder = "Preferences"; appProperties = new ApplicationProperties(); appProperties->setStorageParameters (options); commandManager = new ApplicationCommandManager(); AudioPluginFormatManager::getInstance()->addDefaultFormats(); AudioPluginFormatManager::getInstance()->addFormat (new InternalPluginFormat()); AudioPluginFormatManager::getInstance()->addFormat (new GFormatPluginFormat()); // init v8 v8::HandleScope handle_scope; context = CreateV8Context(); if (context.IsEmpty()) { printf("Error creating context\n"); return; } context->Enter(); // end v8 init mainWindow = new MainHostWindow(); //mainWindow->setUsingNativeTitleBar (true); commandManager->registerAllCommandsForTarget (this); commandManager->registerAllCommandsForTarget (mainWindow); mainWindow->menuItemsChanged(); if (commandLine.isNotEmpty() && mainWindow->getGraphEditor() != 0) { #if JUCE_MAC if (! commandLine.trimStart().startsWith ("-")) #endif mainWindow->getGraphEditor()->graph.loadFrom (File::getCurrentWorkingDirectory() .getChildFile (commandLine), true); } } void shutdown() { mainWindow = 0; appProperties->closeFiles(); deleteAndZero (commandManager); deleteAndZero (appProperties); // clean up context context->Exit(); context.Dispose(); v8::V8::Dispose(); } void systemRequestedQuit() { if (mainWindow != 0) mainWindow->tryToQuitApplication(); else JUCEApplication::quit(); } const String getApplicationName() { return "Luma"; } const String getApplicationVersion() { return ProjectInfo::versionString; } bool moreThanOneInstanceAllowed() { return true; } private: ScopedPointer <MainHostWindow> mainWindow; }; // This kicks the whole thing off.. START_JUCE_APPLICATION (PluginHostApp)
[ "georgekrueger@gmail.com" ]
georgekrueger@gmail.com
6557a69feea6802c685211d5a9eb8e9dcc030025
8903cb76cedac12995249e2e613af65365be7cf2
/hiro/windows/keyboard.cpp
150eb2ea34aae9c118b24b91d58fdabfc7821ac1
[ "ISC" ]
permissive
kirwinia/ares-emu-v121
0c1e21e073f291741406cd1ed01acca43acd56d7
722aa227caf943a4a64f1678c1bdd07b38b15caa
refs/heads/main
2023-06-09T15:28:23.665934
2021-06-28T06:10:46
2021-06-28T06:10:46
380,923,321
0
0
ISC
2021-06-28T06:05:04
2021-06-28T06:05:04
null
UTF-8
C++
false
false
3,327
cpp
#if defined(Hiro_Keyboard) namespace hiro { vector<uint16_t> pKeyboard::keycodes; auto pKeyboard::poll() -> vector<bool> { vector<bool> result; for(auto& code : keycodes) result.append(pressed(code)); return result; } auto pKeyboard::pressed(u32 code) -> bool { u8 lo = code >> 0; u8 hi = code >> 8; if(lo && GetAsyncKeyState(lo) & 0x8000) return true; if(hi && GetAsyncKeyState(hi) & 0x8000) return true; return false; } auto pKeyboard::initialize() -> void { auto append = [](u32 lo, u32 hi = 0) { keycodes.append(lo << 0 | hi << 8); }; #define map(name, ...) if(key == name) { append(__VA_ARGS__); continue; } for(auto& key : Keyboard::keys) { #include <hiro/platform/windows/keyboard.hpp> //print("[hiro/windows] warning: unhandled key: ", key, "\n"); append(0); } #undef map } auto pKeyboard::_translate(u32 code, u32 flags) -> s32 { bool numLock = GetKeyState(VK_NUMLOCK); bool capsLock = GetKeyState(VK_CAPITAL); bool shifted = (GetAsyncKeyState(VK_LSHIFT) & 0x8000) || (GetAsyncKeyState(VK_RSHIFT) & 0x8000); bool pressed = GetAsyncKeyState(code) & 0x8000; bool extended = flags & (1 << 24); switch(code) { case VK_OEM_3: return !shifted ? '`' : '~'; case '1': return !shifted ? '1' : '!'; case '2': return !shifted ? '2' : '@'; case '3': return !shifted ? '3' : '#'; case '4': return !shifted ? '4' : '$'; case '5': return !shifted ? '5' : '%'; case '6': return !shifted ? '6' : '^'; case '7': return !shifted ? '7' : '&'; case '8': return !shifted ? '8' : '*'; case '9': return !shifted ? '9' : '('; case '0': return !shifted ? '0' : ')'; case VK_OEM_MINUS: return !shifted ? '-' : '_'; case VK_OEM_PLUS: return !shifted ? '=' : '+'; case VK_BACK: return '\b'; case VK_TAB: return '\t'; case VK_RETURN: return '\n'; case VK_SPACE: return ' '; case VK_OEM_4: return !shifted ? '[' : '{'; case VK_OEM_6: return !shifted ? ']' : '}'; case VK_OEM_5: return !shifted ? '\\' : '|'; case VK_OEM_1: return !shifted ? ';' : ':'; case VK_OEM_7: return !shifted ? '\'' : '\"'; case VK_OEM_COMMA: return !shifted ? ',' : '<'; case VK_OEM_PERIOD: return !shifted ? '.' : '>'; case VK_OEM_2: return !shifted ? '/' : '?'; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': if(capsLock) return !shifted ? code : code + 32; else return !shifted ? code + 32 : code; case VK_DIVIDE: return '/'; case VK_MULTIPLY: return '*'; case VK_SUBTRACT: return '-'; case VK_ADD: return '+'; case VK_DECIMAL: return '.'; case VK_NUMPAD1: return numLock ? '1' : 0; case VK_NUMPAD2: return numLock ? '2' : 0; case VK_NUMPAD3: return numLock ? '3' : 0; case VK_NUMPAD4: return numLock ? '4' : 0; case VK_NUMPAD5: return numLock ? '5' : 0; case VK_NUMPAD6: return numLock ? '6' : 0; case VK_NUMPAD7: return numLock ? '7' : 0; case VK_NUMPAD8: return numLock ? '8' : 0; case VK_NUMPAD9: return numLock ? '9' : 0; case VK_NUMPAD0: return numLock ? '0' : 0; } return 0; } } #endif
[ "ecallaghan@protonmail.com" ]
ecallaghan@protonmail.com
3dc95ec5e101f387e7a29a361b202f30300d06d1
72bb6deb4a8657fc494777847e356c328fe8550d
/algorithms/AlgorithmInitial/AlgorithmInitial/DataStructure6.cpp
e4a6ac73ffc5b26c6c6202cffa4046c0689b935c
[]
no_license
rising-turtle/study
daafeac486e274af47268e9c7d66feacd3476a44
76b414d0a47692f997539b34b356c34a3528f34d
refs/heads/master
2021-12-09T07:23:41.800642
2021-12-02T19:34:44
2021-12-02T19:34:44
90,572,871
2
0
null
null
null
null
UTF-8
C++
false
false
3,616
cpp
#include "preheader.h" void swap(int & a, int& b) { b^=a^= b= a^b; } // 6.1.1 // each time discard the first card, and put the new one to the end void Cards(int n) { queue<int> cards; //cards.resize(n); for(int i=0;i<n;i++) { cards.push(i+1); } int index=0; while(cards.size()>=2) { cout<<" "<<cards.front(); cards.pop(); cards.push(cards.front()); cards.pop(); } cout<<" "<<cards.front()<<endl; } //6.3.1 // falling ball void FallingBall(int Depth, int index) { int N = 1<<Depth; N--; vector<int> bucket; bucket.resize(N); static const int MAX_N = 4096; bitset<MAX_N> switches; switches.reset(); for(int i=0;i<N;i++) { bucket[i] = i+1; } for(int t=1;t<= index; t++) { int index_of_node = 0; while(index_of_node<N) { int tmp_index = index_of_node*2+1; if(switches[index_of_node]) tmp_index++; switches[index_of_node].flip(); if(tmp_index >= N) { break; } else index_of_node = tmp_index; } cout<<" "<<t<<" th at bucket: "<<bucket[index_of_node]<<endl; } } // Actually each ball has its own trajectory // Each Node has the similar behavior void FallingBall2(int Depth,int th) { int N=(1<<Depth) -1; vector<int> bucket; bucket.resize(N); for(int i=0;i<N;i++) bucket[i] = i+1; int k=0; int tmp_th=th; while(k<N) { int tmp_k = k*2+1; if(tmp_th & 0x01) // th is odd { tmp_th = (tmp_th+1)>>1; } else { tmp_k++; tmp_th>>=1; } if(tmp_k>=N) { break; } k = tmp_k; } cout<<" "<<th<<" th ball falls at bucket "<<bucket[k]<<endl; } //6.3.3 rebuild postorder from preorder and midorder // mid: DBACEGF pre: ABCDEFG void obtainPostElement(string& mid,string& pre,string& post) { if(mid.size()==0) return; char tmp_c=mid[0]; for(size_t i=0;i<pre.size();i++) { if(tmp_c ==pre[i]) { post+=tmp_c; // traverse right-subtree if(i+1<mid.size()){ string right_mid(mid,i+1,mid.size()-i-1); string right_pre(pre,i+1,pre.size()-i-1); obtainPostElement(right_mid,right_pre,post); } // traverse left-subtree if(i>=1){ string left_mid(mid,1,i); string left_pre(pre,0,i); obtainPostElement(left_mid,left_pre,post); } break; } } return ; } void RebuildPostOrder(char* mid, char* pre) { string pre_s(pre); string mid_s(mid); // assert(false) -> error assert(pre_s.size()==mid_s.size()); string post_s; obtainPostElement(mid_s,pre_s,post_s); cout<<post_s<<endl; } // 6.4.3 topplogy sort // Input n chars,and m (xi,xj): xi<xj void TopologySort(int n,char* letters, int m,char* front,char* end) { vector<char> stack; map<char,int> degree; // Initialization for(int i=0;i<n;i++) { degree.insert(make_pair(letters[i],0)); } for(int i=0;i<m;i++) { degree[end[i]]++; } for(map<char,int>::iterator it=degree.begin();it!=degree.end();it++) { if(it->second==0) { stack.push_back(it->first); } } // Let's go bitset<10> valid; valid.set(); while(!stack.empty()) { char checked_char=*stack.rbegin(); cout<<" "<<checked_char; stack.pop_back(); for(int i=0;i<m;i++) { if(valid[i] && front[i]==checked_char) { degree[end[i]]--; if(degree[end[i]]==0) { stack.push_back(end[i]); valid[i].flip(); } } } } } //int main() //{ // //Cards(7); // //FallingBall(4,8); // //FallingBall2(4,8); // //RebuildPostOrder("DBACEGF","ABCDEFG"); // TopologySort(5,"ABCDE",5,"AACDB","BCDBE"); // getchar(); // return 0; //}
[ "hxzhang1@ualr.edu" ]
hxzhang1@ualr.edu
6f6e26a62a776a7d2c3de1593c41fa4ed095af35
d0e720d2d52017107cd0455365af81d391c6df61
/stream_sql/uodbc/test_sodbc/test_sodbc.cpp
ba137fe1fd68b9521c00342acd0cb751b0bda168
[]
no_license
tide999/socketpro
9eb683c0184d40e55b8666d4d50c0756906346cd
70c700138e7dba28ea0bc26d21cb3a8c58247887
refs/heads/master
2023-07-26T09:29:25.495292
2021-09-06T19:08:18
2021-09-06T19:08:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,902
cpp
#include "stdafx.h" #include <iostream> #include "../../../include/pexports.h" class CMySocketProServer : public SPA::ServerSide::CSocketProServer { protected: virtual bool OnIsPermitted(USocket_Server_Handle h, const wchar_t* userId, const wchar_t* password, unsigned int serviceId) { assert(DoSPluginAuthentication); //A cheap but quick way to do authentication against a database server by use of ODBC plugin int res = DoSPluginAuthentication(h, userId, password, serviceId, L"dsn=ToMySQL;database=sakila"); switch (res) { case SP_PLUGIN_AUTH_OK: return true; case SP_PLUGIN_AUTH_FAILED: std::cout << "Authentication failed\n"; return false; case SP_PLUGIN_AUTH_INTERNAL_ERROR: std::cout << "Internal error!\n"; return false; case SP_PLUGIN_AUTH_NOT_IMPLEMENTED: std::cout << "Authentication not implemented yet\n"; break; default: assert(false); break; } return false; } virtual bool OnSettingServer(unsigned int listeningPort, unsigned int maxBacklog, bool v6) { DoSPluginAuthentication = nullptr; m_h = SPA::ServerSide::CSocketProServer::DllManager::AddALibrary("sodbc"); if (m_h) { DoSPluginAuthentication = (PDoSPluginAuthentication) GetProcAddress(m_h, "DoSPluginAuthentication"); } return true; } private: HINSTANCE m_h; PDoSPluginAuthentication DoSPluginAuthentication; }; int main(int argc, char* argv[]) { CMySocketProServer server; if (!server.Run(20901)) { int errCode = server.GetErrorCode(); std::cout << "Error code: " << errCode << "\n"; } std::cout << "Press any key to stop the server ......\n"; ::getchar(); }
[ "support@udaparts.com" ]
support@udaparts.com
15dfd99059f85909e2043e4d94741cbcfc9848fb
25180e7cf630d03aab953e9d683ccc48e1bfcc94
/src/Subsystems/LED.cpp
bd7d5ff5ca61dbc5fe4fbcb4f74053ae7ecbbbcf
[]
no_license
EMU4729/FRC-Library-Cpp
8c0b11d227a2c3d0da4beb76fd1d096037787047
4eaeea40c3662f01bd928cf5afa08332162c109e
refs/heads/master
2020-03-14T22:57:40.662823
2018-06-04T09:59:24
2018-06-04T09:59:24
131,833,047
0
0
null
null
null
null
UTF-8
C++
false
false
917
cpp
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "LED.h" #include "../RobotMap.h" LED::LED() : Subsystem("ExampleSubsystem") { led = new CANLight(ledPort); } void LED::green() { led->ShowRGB(0, 255, 0); } void LED::stop() { led->ShowRGB(0, 0, 0); } void LED::InitDefaultCommand() { // Set the default command for a subsystem here. // SetDefaultCommand(new MySpecialCommand()); } // Put methods for controlling this subsystem // here. Call these from Commands.
[ "unswfrc@gmail.com" ]
unswfrc@gmail.com
01e1fd664959ca88c408c9bcbee26e61a83b76f0
3e514adfcfb5a3fa414c88dfbbc7c0b06f6198b6
/src/governance-votedb.cpp
37434cd03036e9139f8ba684fc89e6585e2e4e3a
[ "MIT" ]
permissive
REMIXorg/REMIX
b39c6fcd8eeb87e8c94569acb9ac26ce9f29c40a
4d13226582b528a0d3f78929325854bd66d00d0b
refs/heads/master
2020-04-11T22:52:20.309494
2018-12-17T15:08:18
2018-12-17T15:08:18
162,146,650
0
0
null
null
null
null
UTF-8
C++
false
false
2,628
cpp
// Copyright (c) 2014-2017 The Dash Core developers // Copyright (c) 2017-2018 The Proton Core developers // Copyright (c) 2018 The Bitcoin Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "governance-votedb.h" CGovernanceObjectVoteFile::CGovernanceObjectVoteFile() : nMemoryVotes(0), listVotes(), mapVoteIndex() {} CGovernanceObjectVoteFile::CGovernanceObjectVoteFile(const CGovernanceObjectVoteFile& other) : nMemoryVotes(other.nMemoryVotes), listVotes(other.listVotes), mapVoteIndex() { RebuildIndex(); } void CGovernanceObjectVoteFile::AddVote(const CGovernanceVote& vote) { listVotes.push_front(vote); mapVoteIndex[vote.GetHash()] = listVotes.begin(); ++nMemoryVotes; } bool CGovernanceObjectVoteFile::HasVote(const uint256& nHash) const { vote_m_cit it = mapVoteIndex.find(nHash); if(it == mapVoteIndex.end()) { return false; } return true; } bool CGovernanceObjectVoteFile::GetVote(const uint256& nHash, CGovernanceVote& vote) const { vote_m_cit it = mapVoteIndex.find(nHash); if(it == mapVoteIndex.end()) { return false; } vote = *(it->second); return true; } std::vector<CGovernanceVote> CGovernanceObjectVoteFile::GetVotes() const { std::vector<CGovernanceVote> vecResult; for(vote_l_cit it = listVotes.begin(); it != listVotes.end(); ++it) { vecResult.push_back(*it); } return vecResult; } void CGovernanceObjectVoteFile::RemoveVotesFromMasternode(const CTxIn& vinMasternode) { vote_l_it it = listVotes.begin(); while(it != listVotes.end()) { if(it->GetVinMasternode() == vinMasternode) { --nMemoryVotes; mapVoteIndex.erase(it->GetHash()); listVotes.erase(it++); } else { ++it; } } } CGovernanceObjectVoteFile& CGovernanceObjectVoteFile::operator=(const CGovernanceObjectVoteFile& other) { nMemoryVotes = other.nMemoryVotes; listVotes = other.listVotes; RebuildIndex(); return *this; } void CGovernanceObjectVoteFile::RebuildIndex() { mapVoteIndex.clear(); nMemoryVotes = 0; vote_l_it it = listVotes.begin(); while(it != listVotes.end()) { CGovernanceVote& vote = *it; uint256 nHash = vote.GetHash(); if(mapVoteIndex.find(nHash) == mapVoteIndex.end()) { mapVoteIndex[nHash] = it; ++nMemoryVotes; ++it; } else { listVotes.erase(it++); } } }
[ "REMIXorg@protonmail.com" ]
REMIXorg@protonmail.com
7a8aa14fb3bd13c5e7b2eadf08ee0c2fef91f10a
7bc5b659ddd757cbbe0fc9130f0a874d05c6a7c2
/include/Player.hpp
f5bb47be773f0e12ef1593e9c3387f99a22eb5ae
[]
no_license
BartekMalon/curve
7decf9ee8cd82102c20611f9ab1a151a1d38206b
f3a1d7712596681e92a153cf9ae371d2f5faed2a
refs/heads/master
2022-12-26T14:59:24.323040
2020-10-12T00:56:42
2020-10-12T00:56:42
303,242,276
0
0
null
null
null
null
UTF-8
C++
false
false
2,466
hpp
#ifndef PLAYER_HPP #define PLAYER_HPP #include "GameObject.hpp" #include <SFML/Graphics.hpp> #include <cmath> #include <iostream> #define PI 3.14159265358979323846462338347 namespace thegame { class Powerup : public Object { public: Powerup(std::string name) : Object(name) {} std::string type = "Speedup"; virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const {} virtual void handleKeyInput(sf::Event &keyEvent) {} virtual void update(double dt) {} }; class Player : public Object { friend thegame::ObjectManager; public: Player(std::string name) : Object(name) { setVelocity(sf::Vector2f(1.f, 0.f)); shape.setRadius(10.f); shape.setPointCount(32); shape.setPosition(50, 50); shape.setFillColor(sf::Color::Blue); } void handleKeyInput(sf::Event &eventshape) { auto v = getVelocity(); if (event.type == sf::Event::KeyPressed) { if (event.key.code == sf::Keyboard::Key::Left) { if (rotation > 0) curRot = std::atan2(v.y, v.x); rotation = -0.0004f; } else if (event.key.code == sf::Keyboard::Key::Right) { if (rotation < 0) curRot = std::atan2(v.y, v.x); rotation = 0.0004f; } } else if (event.type == sf::Event::KeyReleased) { // std::min(std::max(curRot, -0.1f), 0.1f); // v.x = std::cos(curRot); // v.y = std::sin(curRot); // { rotation = 0.f; } } } void update(double dt) { sf::Vector2f cp = getPosition(); sf::Vector2f v = getVelocity(); auto mag = std::sqrt((v.x * v.x) + (v.y * v.y)); v.x /= mag; v.y /= mag; curRot std::atan2(v.y, v.x); // curRot += rotatioshapen * (float)dt * 1000.f; std::min(std::max(curRot, -0.1f), 0.1f); v.x = std::cos(curRot); v.y = std::sin(curRot); mag = std::sqrt((v.x * v.x) + (v.y * v.y)) * 1000.f; v.x /= mag; v.y /= mag; v.x *= speed; v.y *= speed; setVelocity(v); setPosition(sf::Vector2f(cp.x + (v.x * dt), cp.y + (v.y * dt))); } void draw(sf::RenderTarget &target, sf::RenderStates states) const override { // states.transform.translate(getPosition()); target.draw(shape, states); } // sf::CircleShape *getShape() const { return &shape; } sf::CircleShape getShape() { return shape; } private: sf::Color colour; sf::CircleShape shape; float speed = 200000.f; float rotation = 0.f; float curRot = 0.f; }; } // namespace thegame #endif
[ "bartlomiejmalon@hotmail.com" ]
bartlomiejmalon@hotmail.com
781d6091465117d9cc986164be7b6e948a987394
e76ddb71ba6074756a592e4e5c8fc3c66af61fab
/app/microphoneStub.cpp
309d71ad49f203dbb48def3e8ae9132fde8c3e5e
[ "MIT" ]
permissive
rubenacevedo3/cpp-RoboDogVoiceController
17943d1caaa8011eba2f07d1afa5a56533b50bb5
9583447574531c18a6346f49de460b52bc97bed4
refs/heads/master
2021-05-08T05:30:07.948810
2017-10-17T23:17:46
2017-10-17T23:17:46
106,491,258
0
0
null
null
null
null
UTF-8
C++
false
false
4,392
cpp
/** *@author Ruben Acevedo *@file microphoneStub.cpp *@brief This is the ".cpp" file for the microphoneStub Class *@copyright [2017] Ruben Acevedo * * This file implements the methods and attributes of the * microphoneStub Class. It is important to note that * this is only the stub of the real microphone Class needed * to present the capabilities of the VoiceController Component. * The real microphone Class will need to be integrated * with the VoiceController component in the future. The assumption * is made that the real microphone Class takes in audio files * and outputs them as strings. */ /** * MIT License * * Copyright 2017 Ruben Acevedo * * 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. © 2017 GitHub, Inc. */ #include <microphoneStub.hpp> #include <stdlib.h> #include <string> #include <vector> //! Class Constructor /** * This code constructs the class. * It initializes the vector of audioSingnals with some "pre-recorded" audio signals which * will be eventually used to simulate that the microphoneStub is picking up random signals * from its environment. * @param nothing * @return nothing */ microphoneStub::microphoneStub() { audioSignals.push_back("I just saw the new StarWars movie."); audioSignals.push_back("Do you want to see my RoboDog walk? Sure why not." " Ok RoboDog mush!"); audioSignals.push_back("I just got my new RoboDog. Look what " "it can do. RoboDog play dead"); audioSignals.push_back("Oh no! RoboDog is going to hit the wall. " "RoboDog turn right!"); audioSignals.push_back("Hola amigo como estas. Wow que padre" " robot tienes. Que hace?"); audioSignals.push_back("Sprechen sie Deutsch?"); audioSignals.push_back("Oh I guess that did not work. Let me " "try this. RoboDog stop."); audioSignals.push_back("RoboDog you are going " "the wrong way. RoboDog turn left."); audioSignals.push_back("I haven't trained him much. All he can " "do is sit. RoboDog sit."); audioSignals.push_back("I can't go I already made plans with Mike."); audioSignals.push_back("Yeah he really does act like a real dog. He can even" " chase his tail. Watch! RoboDog where is your tail?"); audioSignals.push_back("But Mom, I do not want to take out the trash. " "Daniel's parents don't make him do that. I do not care about " "Daniel I care about you! Ugh this house is a prison!"); } //! gets random signals function /** * This function simulates that the microphone is listening * to its environment by randomly outputting different "pre-recorded" * audio signals. *@param nothing *@return a string representing an audio signal */ std::string microphoneStub::randomSignals() { auto r = rand() %audioSignals.size(); return audioSignals[r]; } //! record audio signal function /** * This function records new audio signals and adds it to * audioSignals vector. *@param a constant string reference representing an audio signal *@return nothing */ void microphoneStub::record(const std::string& as) { audioSignals.push_back(as); } //! get the audioSignals vector size function /** * This function returns the audioSignals vector size. *@param nothing *@return an integer representing the audioSignal vector size */ int microphoneStub::getAudioSignalsSize() { return audioSignals.size(); }
[ "raceved3@umd.edu" ]
raceved3@umd.edu
c6d892cc63a3b6840fdc2f7341407079655b6d84
97fde28997b618180cfa5dd979b142fd54dd2105
/core/dep/acelite/ace/Configuration.inl
6611266b4cc19e5e761e8154690de1f0381bea9f
[]
no_license
Refuge89/sunwell-2
5897f4e78c693e791e368761904e79d2b7af20da
f01a89300394065f33eaec799c8779c2cac5c320
refs/heads/master
2020-12-31T05:55:43.496145
2016-02-16T20:46:50
2016-02-16T20:46:50
80,622,543
1
0
null
2017-02-01T13:30:06
2017-02-01T13:30:06
null
UTF-8
C++
false
false
180
inl
// -*- C++ -*- ACE_BEGIN_VERSIONED_NAMESPACE_DECL ACE_INLINE const ACE_TCHAR* ACE_Configuration_ExtId::name (void) { return name_; } ACE_END_VERSIONED_NAMESPACE_DECL
[ "root@wow.playstar.se" ]
root@wow.playstar.se
54469ce43dd99c73ef6c2841ef7bbd5a35f4b66b
9ad40d7fff54f5e4f36ae974e33712a9beb7378e
/kickstart/may2020/candies.cpp
59809840c1a4d4ac16e7bfd8612b1da2766056ea
[]
no_license
vikram-shaw/cpp
7fcac406b003dd717abe43fc5f15ea253b486b1d
8d4367dedef4e48aed649c8174cee74d38be09ea
refs/heads/master
2023-01-31T19:13:04.363704
2020-12-20T05:50:24
2020-12-20T05:50:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
547
cpp
#include<bits/stdc++.h> using namespace std; void solve() { int n,q; cin>>n>>q; vector<int> v(n); for(int& x: v) scanf("%d",&x); int res = 0; while(q--) { char query; int l,r; cin>>query>>l>>r; if(query=='U') { v[l-1] = r; } else { int k=1; int p = 1; for(int i=l-1;i<r;i++) { res += v[i]*p*(k++); if(p==1) p = -1; else p = 1; } } } cout<<res<<endl; } int main() { int t; scanf("%d",&t); for(int i=1;i<=t;i++) { printf("Case #%d: ",i); solve(); } }
[ "vikram.shaw.3382@gmail.com" ]
vikram.shaw.3382@gmail.com
4984293664e21e31f698ba2f4c19e7753e4212c0
ad0fe9f21d55ec64ff72fabf77da92a442463b7e
/core/src/test/resources/CPP/neopz/Analysis/pzsmanal.cpp
35fb57baff3678372a81633844e39798fe84c4a6
[ "MIT" ]
permissive
gems-uff/oceano
91425da8a11aa0268c9b5c1e2db70013f0152bac
a37468dab497c1ffe338bbf06df179bfe27b59d1
refs/heads/master
2020-12-24T19:27:06.468798
2018-11-18T00:20:13
2018-11-18T00:20:13
13,281,731
3
3
MIT
2018-11-18T00:20:13
2013-10-02T20:18:47
Java
UTF-8
C++
false
false
4,121
cpp
/** * \file * @brief Contains implementations of the TPZSubMeshAnalysis methods: implementation of the TPZSubMeshAnalysis class. */ #include "pzsmanal.h" #include "pzsubcmesh.h" #include "pzfmatrix.h" //#include "pztempmat.h" #include "pzstrmatrix.h" #include "pzsolve.h" using namespace std; // Construction/Destruction TPZSubMeshAnalysis::TPZSubMeshAnalysis(TPZSubCompMesh *mesh) : TPZAnalysis(mesh), fReducableStiff(0){ fMesh = mesh; // fReducableStiff = new TPZMatRed<> (); fReferenceSolution.Redim(fCompMesh->NEquations(),1); } TPZSubMeshAnalysis::~TPZSubMeshAnalysis() { } void TPZSubMeshAnalysis::Assemble(){ std::cout << "Assembling the SubCompMesh index " << fMesh->Index() << std::endl; int numeq = fCompMesh->NEquations(); int numinternal = fMesh->NumInternalEquations(); fReferenceSolution.Redim(numeq,1); fRhs.Redim(numeq,1); if(!fReducableStiff) { fReducableStiff = new TPZMatRed<REAL, TPZFMatrix<REAL> > (); } fReducableStiff->Redim(numeq,numinternal); TPZMatRed<REAL, TPZFMatrix<REAL> > *matred = dynamic_cast<TPZMatRed<REAL, TPZFMatrix<REAL> > *> (fReducableStiff.operator->()); if(!fSolver->Matrix()) { fSolver->SetMatrix(fStructMatrix->Create()); } matred->SetMaxNumberRigidBodyModes(fMesh->NumberRigidBodyModes()); // fReducableStiff.SetK00(fSolver->Matrix()); // this will initialize fK00 too matred->SetSolver(dynamic_cast<TPZMatrixSolver<REAL> *>(fSolver->Clone())); // TPZStructMatrix::Assemble(fReducableStiff,fRhs, *fMesh); time_t before = time (NULL); fStructMatrix->Assemble(fReducableStiff,fRhs,fGuiInterface); time_t after = time(NULL); double diff = difftime(after, before); std::cout << __PRETTY_FUNCTION__ << " tempo " << diff << std::endl; } void TPZSubMeshAnalysis::Run(std::ostream &out){ //fReducableStiff.Print("Reducable stiff before assembled"); fReferenceSolution = fSolution; time_t tempo = time(NULL); Assemble(); time_t tempodepois = time(NULL); double elapsedtime = difftime(tempodepois, tempo); std::cout << "Tempo para assemblagem " << elapsedtime << std::endl; if (!fReducableStiff) { DebugStop(); } TPZMatRed<REAL, TPZFMatrix<REAL> > *matred = dynamic_cast<TPZMatRed<REAL, TPZFMatrix<REAL> > *> (fReducableStiff.operator->()); matred->SetF(fRhs); //fReducableStiff.Print("Reducable stiff assembled"); //fBlock->Print("Block structure",out); //fStiffness->Print("Stiffness matrix ",out); //out.flush(); //fRhs->Print("Residual",out); //out.flush(); //fStiffness->Print("Stiffness matrix ",out); //out.flush(); //fRhs->Print("Residual",out); //out.flush(); } void TPZSubMeshAnalysis::CondensedSolution(TPZFMatrix<REAL> &ek, TPZFMatrix<REAL> &ef){ time_t tempo = time(NULL); if (!fReducableStiff) { DebugStop(); } TPZMatRed<REAL, TPZFMatrix<REAL> > *matred = dynamic_cast<TPZMatRed<REAL, TPZFMatrix<REAL> > *> (fReducableStiff.operator->()); ek = matred->K11Red(); ef = matred->F1Red(); //ek.Print("ek condensed"); // cout.flush(); time_t tempodepois = time(NULL); double elapsedtime = difftime(tempodepois, tempo); std::cout << "Tempo para inversao " << elapsedtime << std::endl; } void TPZSubMeshAnalysis::LoadSolution(const TPZFMatrix<REAL> &sol) { // sol.Print("sol"); int numinter = fMesh->NumInternalEquations(); int numeq = fMesh->TPZCompMesh::NEquations(); TPZFMatrix<REAL> soltemp(numeq-numinter,1,0.); // fSolution->Print("Solucao a analise\n"); // fReferenceSolution.Print("Solucao de referencia\n"); // cout.flush(); int i; for(i=0; i<numeq-numinter; i++) { soltemp(i,0) = sol.GetVal(numinter+i,0)-fReferenceSolution(numinter+i,0); } TPZFMatrix<REAL> uglobal(numeq,1,0.); if(fReducableStiff) { TPZMatRed<REAL, TPZFMatrix<REAL> > *matred = dynamic_cast<TPZMatRed<REAL, TPZFMatrix<REAL> > *> (fReducableStiff.operator->()); matred->UGlobal(soltemp,uglobal); // fReferenceSolution.Print("Solucao de referencia\n"); // uglobal.Print("uglobal"); fSolution = fReferenceSolution + uglobal; } TPZAnalysis::LoadSolution(); // cout.flush(); }
[ "leomurta@ic.uff.br" ]
leomurta@ic.uff.br
917700aa0efed3b24e4228f3a627be407d18673a
a568e096593a3ef8ffef97f687d27aab21d6942e
/107.binary-tree-level-order-traversal-ii.cpp
3d6e4d75d8b026c98888f89bc9adeb1ceb80e751
[ "MIT" ]
permissive
pancl1411/leetcode_cpp
95222ddf7c6d3bcd1582644d4290f160cd3a7ff5
aa909cb241bf65b36cc881eefee0c908d2152295
refs/heads/main
2023-05-03T03:21:49.751346
2021-05-22T16:16:56
2021-05-22T16:16:56
309,105,585
2
1
MIT
2020-11-01T14:23:57
2020-11-01T13:47:26
null
UTF-8
C++
false
false
1,715
cpp
/* * @lc app=leetcode id=107 lang=cpp * * [107] Binary Tree Level Order Traversal II */ // @lc code=start /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ #include <vector> class Solution { private: void BFS(std::vector<TreeNode*>& roots, std::vector<std::vector<int>>& answer) { if (roots.empty()) { return; } // std::vector<TreeNode*> next_level; std::vector<int> this_level_val; for (size_t i = 0; i < roots.size(); i++) { this_level_val.push_back(roots[i]->val); if (roots[i]->left != nullptr) { next_level.push_back(roots[i]->left); } if (roots[i]->right != nullptr) { next_level.push_back(roots[i]->right); } } // if (!next_level.empty()) { BFS(next_level, answer); } // answer.push_back(this_level_val); } public: std::vector<std::vector<int>> levelOrderBottom(TreeNode* root) { std::vector<std::vector<int>> answer; // special case if (root == nullptr) { return answer; } // Breadth-first-search std::vector<TreeNode*> next_level; next_level.push_back(root); BFS(next_level, answer); return answer; } }; // @lc code=end
[ "1004907659@qq.com" ]
1004907659@qq.com
85b6a9d1bad1e4f29b4ce44d5cc51effed70ed7c
f28ec0f0c5232ca9b1076313a82e77f2e68c9a65
/abc-144/C-144.cpp
d34c6657d6ae3697aa368f50b94e8746f05a09a7
[]
no_license
aquaEngineer/atcoder
b8dffb5ee292d320e4952878062d59679b7539ae
1fab7f75863d414842bccc0e3e453eff27951fae
refs/heads/master
2022-04-30T13:29:32.879605
2022-04-25T14:09:08
2022-04-25T14:09:08
245,680,211
0
0
null
null
null
null
UTF-8
C++
false
false
892
cpp
#include <iostream> #include <algorithm> #include <math.h> #include <vector> #include <string> #include <queue> #include <map> #include <utility> #include <iomanip> // std::setprecision() using namespace std; using ll = long long; #define rep(i,a,b) for(int i=(a); i<(b); i++) #define YES cout << "YES" << endl; #define NO cout << "NO" << endl; #define yes cout << "Yes" << endl; #define no cout << "No" << endl; ll gcd(ll a, ll b){if (a%b == 0) return(b);else return(gcd(b, a%b));} ll lcm(ll a, ll b){return a * b / gcd(a, b);} /* map<string,int> */ /* 大文字を小文字に変換 tolower*/ /* 小文字を大文字に変換 toupper*/ /* 辞書順 next_permutation(a.begin(),a.end()) */ int main () { ll n; cin >> n; ll mi = n; for(ll i = 1; pow(i,2) <= n; i++) { if (n %i == 0) { mi = min(mi, i + n/i-2); } } cout << mi << endl; }
[ "aqua.server.tech@gmail.com" ]
aqua.server.tech@gmail.com
8e53fc23732bbf2c1f5ad0aab6d2a462792ffe31
7b9508e1b60e53601b93b96369e4806f691e9f58
/Algorithm/백준/알고리즘 중급/분할정복/분할정복/BOJ 2263 트리의 순회.cpp
e293cfba65d560e710f63c8e893307b36eec294e
[]
no_license
wkdehdlr/Doo-it
e522b5227e5c92aa34ec7f2f0de9c8eafbedf38e
4cd7746457c8e1ae34d82e0fae3ae4e820e1a163
refs/heads/master
2023-03-04T02:29:57.283182
2021-02-19T08:22:56
2021-02-19T08:22:56
110,106,422
1
0
null
null
null
null
UTF-8
C++
false
false
613
cpp
#pragma warning(disable : 4996) #include<cstdio> #include<unordered_map> using namespace std; unordered_map<int, int> ma; int inorder[100001]; int postorder[100001]; void solve(int is, int ie, int ps, int pe) { if (is > ie || ps > pe)return; printf("%d ", postorder[pe]); int p = ma[postorder[pe]]; int left = p - is; solve(is, p - 1, ps, ps + left - 1); solve(p + 1, ie, ps+left, pe - 1); } int main() { int N; scanf("%d", &N); for (int i = 0; i < N; ++i) { int temp; scanf("%d", &temp); ma[temp] = i; } for (int i = 0; i < N; ++i) scanf("%d", &postorder[i]); solve(0, N - 1, 0, N - 1); }
[ "wel_789@naver.com" ]
wel_789@naver.com
506a8b7d3180c6d655ed60550271e33281f0c611
24798e814f342e6690109f6f13d787f093a9b53f
/regulator/vertical_regulator.hpp
cafb0c62538fdf923a6c352a035efe9f086b850f
[]
no_license
zinjkov/rc_rov_server
1297af72ff296c85ee6167abbdad9cb0bc350a51
ba09d781c1aad59ba8d0933b1260499ba8be771d
refs/heads/master
2020-03-07T17:19:22.394839
2018-06-15T10:48:12
2018-06-15T10:48:12
127,608,057
0
0
null
null
null
null
UTF-8
C++
false
false
825
hpp
// // Created by zinjkov on 01.04.18. // #ifndef RC_ROV_SERVER_VERTICAL_REGULATOR_HPP #define RC_ROV_SERVER_VERTICAL_REGULATOR_HPP #include "basic_regulator.hpp" namespace rov { class vertical_regulator : public basic_regulator { public: vertical_regulator(); virtual ~vertical_regulator(); void apply(rov_types::rov_hardware_control &thruster, const rov_types::rov_control &rc, const rov_types::rov_telimetry &rt, const regulator_config &config) ; void apply(std::vector<int8_t> &force, const rov_types::rov_control &rc, const rov_types::rov_telimetry &rt, const regulator_config &config) override final {}; }; }; #endif //RC_ROV_SERVER_VERTICAL_REGULATOR_HPP
[ "zinjkov.su@gmail.com" ]
zinjkov.su@gmail.com
690429ddd44540d7357b2f3ce66db2467ef35f88
6e474c50f45556cc153cff61eead76ff987920ec
/source/assimp/port/AndroidJNI/AndroidJNIIOSystem.h
bb52d3065c5fb8ad20d102e5ddc861e82bc6086f
[]
no_license
Failimaily/openFOAMTool
526467d1305d1233623c4c2e7cafea03c401737e
3c5827a64b26460f78a5ff73b0ed665fec5d75d8
refs/heads/main
2023-09-04T13:55:19.154637
2021-11-06T15:15:36
2021-11-06T15:15:36
423,200,826
0
0
null
null
null
null
UTF-8
C++
false
false
3,296
h
/* Open Asset Import Library (assimp) ---------------------------------------------------------------------- Copyright (c) 2006-2021, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------- */ /** @file Android implementation of IOSystem using the standard C file functions. * Aimed to ease the access to android assets */ #if __ANDROID__ and __ANDROID_API__ > 9 and defined(AI_CONFIG_ANDROID_JNI_ASSIMP_MANAGER_SUPPORT) #ifndef AI_ANDROIDJNIIOSYSTEM_H_INC #define AI_ANDROIDJNIIOSYSTEM_H_INC #include <assimp/DefaultIOSystem.h> #include <android/asset_manager.h> #include <android/asset_manager_jni.h> #include <android/native_activity.h> namespace Assimp { // --------------------------------------------------------------------------- /** Android extension to DefaultIOSystem using the standard C file functions */ class ASSIMP_API AndroidJNIIOSystem : public DefaultIOSystem { public: /** Initialize android activity data */ std::string mApkWorkspacePath; AAssetManager* mApkAssetManager; /// Constructor. AndroidJNIIOSystem(ANativeActivity* activity); /// Class constructor with past and asset manager. AndroidJNIIOSystem(const char *internalPath, AAssetManager assetManager); /// Destructor. ~AndroidJNIIOSystem(); /// Tests for the existence of a file at the given path. bool Exists( const char* pFile) const; /// Opens a file at the given path, with given mode IOStream* Open( const char* strFile, const char* strMode); /// Inits Android extractor void AndroidActivityInit(ANativeActivity* activity); /// Extracts android asset bool AndroidExtractAsset(std::string name); }; } //!ns Assimp #endif //AI_ANDROIDJNIIOSYSTEM_H_INC #endif //__ANDROID__ and __ANDROID_API__ > 9 and defined(AI_CONFIG_ANDROID_JNI_ASSIMP_MANAGER_SUPPORT)
[ "dominiquekomes@gmail.com" ]
dominiquekomes@gmail.com
e0840730eea85a99261137a7142c8654fae7a8b1
00b6afadaf5588d9f56723a9a9ab3858b7050bd1
/TreeAnalysis/source/lib/diHiggsTMVATree.cxx
8e0e761babf6da7b0df0cd8747a2823bc3e53e53
[]
no_license
DaniloQuin/Higgs_analysis
ab970102c63799af0220b897c73d59f9b1488be3
e52f098244890b717e51a1cf98aaccd881b813e2
refs/heads/master
2020-03-23T21:20:11.467761
2018-07-24T03:53:24
2018-07-24T03:53:24
142,098,865
0
0
null
null
null
null
UTF-8
C++
false
false
16,151
cxx
// System include(s): #include <iostream> #include <iomanip> #include "string" // Local include(s): #include "diHiggsTMVATree.h" const int thread_out = 1; static const bool v2 = true; static const bool fast = false; diHiggsTMVATree::diHiggsTMVATree(Option option,long N_thread, long threads) { n_thread = N_thread; thread = threads; if (thread == thread_out){ std::cout << std::endl; std::cout << "[diHiggsTMVATree :: diHiggsTMVATree] Generating model option " << option; if ( option_ == nathan_sgn_yybb ) std::cout << ": H->bbyy signal sample" << std::endl; if ( option_ == nathan_bkg_ybbj ) std::cout << ": nathan background sample" << std::endl; if ( option_ == nathan_bkg_yccj ) std::cout << ": nathan background sample" << std::endl; if ( option_ == nathan_bkg_yybb ) std::cout << ": nathan background sample" << std::endl; if ( option_ == nathan_bkg_yycc ) std::cout << ": nathan background sample" << std::endl; if ( option_ == nathan_bkg_yyjj ) std::cout << ": nathan background sample" << std::endl; if ( option_ == nathan_bkg_yyZbb ) std::cout << ": nathan background sample" << std::endl; if ( option_ == nathan_bkg_bbH ) std::cout << ": nathan background sample" << std::endl; if ( option_ == nathan_bkg_ttH ) std::cout << ": nathan background sample" << std::endl; if ( option_ == nathan_bkg_ZH ) std::cout << ": nathan background sample" << std::endl; if ( option_ == nathan_bkg_tt ) std::cout << ": nathan background sample" << std::endl; if ( option_ == nathan_bkg_bbjj ) std::cout << ": nathan background sample" << std::endl; if ( option_ == nathan_bkg_ggh ) std::cout << ": nathan background sample" << std::endl; if ( option_ == nathan_bkg_tty ) std::cout << ": nathan background sample" << std::endl; } option_ = option; } diHiggsTMVATree::~diHiggsTMVATree() { delete tree_in; delete input; delete reader; } void diHiggsTMVATree::initialize(bool nathan) { nathan_analysis = nathan; b1M = 0; b1Pt = 0; b1Eta = 0; b1Phi = 0; b2M = 0; b2Pt = 0; b2Eta = 0; b2Phi = 0; y1Pt = 0; y1Eta = 0; y1Phi = 0; y2Pt = 0; y2Eta = 0; y2Phi = 0; bbM = 0; bbPt = 0; bbEta = 0; bbPhi = 0; bbDr = 0; yyM = 0; yyPt = 0; yyEta = 0; yyPhi = 0; yyDr = 0; BDT_response = 0.0; bb_cosTSBranch = 0; yy_cosTSBranch = 0; bbyy_cosTSBranch = 0; bbyy_m = 0; } void diHiggsTMVATree::addBranches(std::string name,int var_cut) { // TMVA Reader reader = new TMVA::Reader("!V:Silent=True",false); if (var_cut >= 1){reader->AddVariable("b1_m", &b1_m);} else{reader->AddSpectator("b1_m", &b1_m);} if (var_cut >= 2){reader->AddVariable("b1_pt", &b1_pt);} else{reader->AddSpectator("b1_pt", &b1_pt);} if (var_cut >= 3){reader->AddVariable("b1_eta", &b1_eta);} else{reader->AddSpectator("b1_eta", &b1_eta);} if (var_cut >= 4){reader->AddVariable("b1_phi", &b1_phi);} else{reader->AddSpectator("b1_phi", &b1_phi);} if (var_cut >= 5){ reader->AddVariable("b2_m", &b2_m);} else{reader->AddSpectator("b2_m", &b2_m);} if (var_cut >= 6){reader->AddVariable("b2_pt", &b2_pt);} else{reader->AddSpectator("b2_pt", &b2_pt);} if (var_cut >= 7){reader->AddVariable("b2_eta", &b2_eta);} else{reader->AddSpectator("b2_eta", &b2_eta);} if (var_cut >= 8){reader->AddVariable("b2_phi", &b2_phi);} else{reader->AddSpectator("b2_phi", &b2_phi);} if (var_cut >= 9){reader->AddVariable("y1_pt", &y1_pt);} else{reader->AddSpectator("y1_pt", &y1_pt);} if (var_cut >= 10){reader->AddVariable("y1_eta", &y1_eta);} else{reader->AddSpectator("y1_eta", &y1_eta);} if (var_cut >= 11){reader->AddVariable("y1_phi", &y1_phi);} else{reader->AddSpectator("y1_phi", &y1_phi);} if (var_cut >= 12){reader->AddVariable("y2_pt", &y2_pt);} else{reader->AddSpectator("y2_pt", &y2_pt);} if (var_cut >= 13){reader->AddVariable("y2_eta", &y2_eta);} else{reader->AddSpectator("y2_eta", &y2_eta);} if (var_cut >= 14){reader->AddVariable("y2_phi", &y2_phi);} else{reader->AddSpectator("y2_phi", &y2_phi);} if (var_cut >= 15){reader->AddVariable("bb_m", &bb_m);} else{reader->AddSpectator("bb_m", &bb_m);} if (var_cut >= 16){reader->AddVariable("bb_pt", &bb_pt);} else{reader->AddSpectator("bb_pt", &bb_pt);} if (var_cut >= 17){reader->AddVariable("bb_eta", &bb_eta);} else{reader->AddSpectator("bb_eta", &bb_eta);} if (var_cut >= 18){reader->AddVariable("bb_phi", &bb_phi);} else{reader->AddSpectator("bb_phi", &bb_phi);} if (var_cut >= 19){reader->AddVariable("bb_dr", &bb_dr);} else{reader->AddSpectator("bb_dr", &bb_dr);} if (var_cut >= 20){reader->AddSpectator("yy_m", &yy_m);} else{reader->AddSpectator("yy_m", &yy_m);} if (var_cut >= 21){reader->AddVariable("yy_pt", &yy_pt);} else{reader->AddSpectator("yy_pt", &yy_pt);} if (var_cut >= 22){reader->AddVariable("yy_eta", &yy_eta);} else{reader->AddSpectator("yy_eta", &yy_eta);} if (var_cut >= 23){reader->AddVariable("yy_phi", &yy_phi);} else{reader->AddSpectator("yy_phi", &yy_phi);} if (var_cut >= 24){reader->AddVariable("yy_dr", &yy_dr);} else{reader->AddSpectator("yy_dr", &yy_dr);} if (var_cut >= 25){reader->AddVariable("bb_cosTSBranch",&bb_CosTSBranch );} else{reader->AddSpectator("bb_cosTSBranch",&bb_CosTSBranch );} if (var_cut >= 26){reader->AddVariable("yy_cosTSBranch",&yy_CosTSBranch );} else{reader->AddSpectator("yy_cosTSBranch",&yy_CosTSBranch );} if (var_cut >= 27){reader->AddVariable("bbyy_cosTSBranch",&bbyy_CosTSBranch );} else{reader->AddSpectator("bbyy_cosTSBranch",&bbyy_CosTSBranch);} if (var_cut >= 28){reader->AddVariable("bbyy_m",&bbyy_M );} else{reader->AddSpectator("bbyy_m",&bbyy_M);} if (var_cut >= 29){reader->AddVariable("bbyy_pt",&bbyy_Pt);} else{reader->AddSpectator("bbyy_pt",&bbyy_Pt);} reader->AddSpectator("scaledWeight3000fb", &scaledweight3000fb); reader->BookMVA("BDT method", name + "dataset_na/weights/TMVAClassification_BDT.weights.xml"); if ( option_ == nathan_sgn_yybb ) outname = "diHiggs_nathan_sgn_yybb_BDT.root"; if ( option_ == nathan_bkg_ybbj ) outname = "diHiggs_nathan_bkg_ybbj_BDT.root"; if ( option_ == nathan_bkg_yccj ) outname = "diHiggs_nathan_bkg_yccj_BDT.root"; if ( option_ == nathan_bkg_yybb ) outname = "diHiggs_nathan_bkg_yybb_BDT.root"; if ( option_ == nathan_bkg_yycc ) outname = "diHiggs_nathan_bkg_yycc_BDT.root"; if ( option_ == nathan_bkg_yyjj ) outname = "diHiggs_nathan_bkg_yyjj_BDT.root"; if ( option_ == nathan_bkg_yyZbb ) outname = "diHiggs_nathan_bkg_yyZbb_BDT.root"; if ( option_ == nathan_bkg_bbH ) outname = "diHiggs_nathan_bkg_bbH_BDT.root"; if ( option_ == nathan_bkg_ttH ) outname = "diHiggs_nathan_bkg_ttH_BDT.root"; if ( option_ == nathan_bkg_ZH ) outname = "diHiggs_nathan_bkg_ZH_BDT.root"; if ( option_ == nathan_bkg_tt ) outname = "diHiggs_nathan_bkg_tt_BDT.root"; if ( option_ == nathan_bkg_bbjj ) outname = "diHiggs_nathan_bkg_bbjj_BDT.root"; if ( option_ == nathan_bkg_ggh ) outname = "diHiggs_nathan_bkg_ggh_BDT.root"; output = new TFile( name + outname + TString::Itoa(thread,10), "RECREATE"); TString temporal = TString("diHiggs") + std::to_string(option_); tree_out = new TTree(temporal, temporal); tree_out->Branch("b1_m",&b1M); tree_out->Branch("b1_pt",&b1Pt); tree_out->Branch("b1_eta",&b1Eta); tree_out->Branch("b1_phi",&b1Phi); tree_out->Branch("b1_source",&b1Source); tree_out->Branch("b2_m",&b2M); tree_out->Branch("b2_pt",&b2Pt); tree_out->Branch("b2_eta",&b2Eta); tree_out->Branch("b2_phi",&b2Phi); tree_out->Branch("b2_source",&b2Source); tree_out->Branch("y1_pt",&y1Pt); tree_out->Branch("y1_eta",&y1Eta); tree_out->Branch("y1_phi",&y1Phi); tree_out->Branch("y1_source",&y1Source); tree_out->Branch("y2_pt",&y2Pt); tree_out->Branch("y2_eta",&y2Eta); tree_out->Branch("y2_phi",&y2Phi); tree_out->Branch("y2_source",&y2Source); tree_out->Branch("bb_m",&bbM); tree_out->Branch("bb_pt",&bbPt); tree_out->Branch("bb_eta",&bbEta); tree_out->Branch("bb_phi",&bbPhi); tree_out->Branch("bb_dr",&bbDr); tree_out->Branch("yy_m",&yyM); tree_out->Branch("yy_pt",&yyPt); tree_out->Branch("yy_eta",&yyEta); tree_out->Branch("yy_phi",&yyPhi); tree_out->Branch("yy_dr",&yyDr); tree_out->Branch("BDT_response",&BDT_response); tree_out->Branch("finalStateWeight",&finalStateWeight); tree_out->Branch("bb_cosTSBranch",bb_cosTSBranch ); tree_out->Branch("yy_cosTSBranch",yy_cosTSBranch ); tree_out->Branch("bbyy_cosTSBranch",bbyy_cosTSBranch ); tree_out->Branch("bbyy_m",bbyy_m ); tree_out->Branch("bbyy_pt",bbyy_pt); tree_out->Branch("scaledWeight3000fb",&scaledWeight3000fb); if ( option_ == nathan_sgn_yybb ) fname = name + "diHiggs_nathan_sgn_yybb_Tree.root"; if ( option_ == nathan_bkg_ybbj ) fname = name + "diHiggs_nathan_bkg_ybbj_Tree.root"; if ( option_ == nathan_bkg_yccj ) fname = name + "diHiggs_nathan_bkg_yccj_Tree.root"; if ( option_ == nathan_bkg_yybb ) fname = name + "diHiggs_nathan_bkg_yybb_Tree.root"; if ( option_ == nathan_bkg_yycc ) fname = name + "diHiggs_nathan_bkg_yycc_Tree.root"; if ( option_ == nathan_bkg_yyjj ) fname = name + "diHiggs_nathan_bkg_yyjj_Tree.root"; if ( option_ == nathan_bkg_yyZbb ) fname = name + "diHiggs_nathan_bkg_yyZbb_Tree.root"; if ( option_ == nathan_bkg_bbH ) fname = name + "diHiggs_nathan_bkg_bbH_Tree.root"; if ( option_ == nathan_bkg_ttH ) fname = name + "diHiggs_nathan_bkg_ttH_Tree.root"; if ( option_ == nathan_bkg_ZH ) fname = name + "diHiggs_nathan_bkg_ZH_Tree.root"; if ( option_ == nathan_bkg_tt ) fname = name + "diHiggs_nathan_bkg_tt_Tree.root"; if ( option_ == nathan_bkg_bbjj ) fname = name + "diHiggs_nathan_bkg_bbjj_Tree.root"; if ( option_ == nathan_bkg_ggh ) fname = name + "diHiggs_nathan_bkg_ggh_Tree.root"; if ( option_ == nathan_bkg_tty ) fname = name + "diHiggs_nathan_bkg_tty_Tree.root"; if (!gSystem->AccessPathName( fname )) {input = TFile::Open( fname );} if (!input) { std::cout << "ERROR: could not open data file " << fname << std::endl; exit(1); } if (thread == thread_out) { std::cout << "--- TMVAClassificationApp : Using input file: " << input->GetName() << std::endl; if ( option_ == sgn_higgs ) std::cout << "--- Select signal sample" << std::endl; if ( option_ == bkg_bbyy ) std::cout << "--- Select bbyy background sample" << std::endl; if ( option_ == bkg_bbyj ) std::cout << "--- Select bbyj background sample" << std::endl; if ( option_ == bkg_ccyy ) std::cout << "--- Select ccyy background sample" << std::endl; if ( option_ == bkg_jjyy ) std::cout << "--- Select jjyy background sample" << std::endl; if ( option_ == nathan_sgn_yybb ) std::cout << ": Select H->bbyy signal sample" << std::endl; if ( option_ == nathan_bkg_ybbj ) std::cout << ": Select nathan background sample" << std::endl; if ( option_ == nathan_bkg_yccj ) std::cout << ": Select nathan background sample" << std::endl; if ( option_ == nathan_bkg_yybb ) std::cout << ": Select nathan background sample" << std::endl; if ( option_ == nathan_bkg_yycc ) std::cout << ": Select nathan background sample" << std::endl; if ( option_ == nathan_bkg_yyjj ) std::cout << ": Select nathan background sample" << std::endl; if ( option_ == nathan_bkg_yyZbb ) std::cout << ": Select nathan background sample" << std::endl; if ( option_ == nathan_bkg_bbH ) std::cout << ": Select nathan background sample" << std::endl; if ( option_ == nathan_bkg_ttH ) std::cout << ": Select nathan background sample" << std::endl; if ( option_ == nathan_bkg_ZH ) std::cout << ": Select nathan background sample" << std::endl; if ( option_ == nathan_bkg_tt ) std::cout << ": Select nathan background sample" << std::endl; if ( option_ == nathan_bkg_bbjj ) std::cout << ": Select nathan background sample" << std::endl; if ( option_ == nathan_bkg_ggh ) std::cout << ": Select nathan background sample" << std::endl; if ( option_ == nathan_bkg_tty ) std::cout << ": Select nathan background sample" << std::endl; } tree_in = (TTree*)input->Get("diHiggs"); tree_in->SetBranchAddress("b1_m",&b1M); tree_in->SetBranchAddress("b1_pt",&b1Pt); tree_in->SetBranchAddress("b1_eta",&b1Eta); tree_in->SetBranchAddress("b1_phi",&b1Phi); tree_in->SetBranchAddress("b1_source",&b1Source); tree_in->SetBranchAddress("b2_m",&b2M); tree_in->SetBranchAddress("b2_pt",&b2Pt); tree_in->SetBranchAddress("b2_eta",&b2Eta); tree_in->SetBranchAddress("b2_phi",&b2Phi); tree_in->SetBranchAddress("b2_source",&b2Source); tree_in->SetBranchAddress("y1_pt",&y1Pt); tree_in->SetBranchAddress("y1_eta",&y1Eta); tree_in->SetBranchAddress("y1_phi",&y1Phi); tree_in->SetBranchAddress("y1_source",&y1Source); tree_in->SetBranchAddress("y2_pt",&y2Pt); tree_in->SetBranchAddress("y2_eta",&y2Eta); tree_in->SetBranchAddress("y2_phi",&y2Phi); tree_in->SetBranchAddress("y2_source",&y2Source); tree_in->SetBranchAddress("bb_m",&bbM); tree_in->SetBranchAddress("bb_pt",&bbPt); tree_in->SetBranchAddress("bb_eta",&bbEta); tree_in->SetBranchAddress("bb_phi",&bbPhi); tree_in->SetBranchAddress("bb_dr",&bbDr); tree_in->SetBranchAddress("yy_m",&yyM); tree_in->SetBranchAddress("yy_pt",&yyPt); tree_in->SetBranchAddress("yy_eta",&yyEta); tree_in->SetBranchAddress("yy_phi",&yyPhi); tree_in->SetBranchAddress("yy_dr",&yyDr); tree_in->SetBranchAddress("finalStateWeight",&finalStateWeight); tree_in->SetBranchAddress("scaledWeight3000fb",&scaledWeight3000fb); tree_in->SetBranchAddress("bb_cosTSBranch",&bb_cosTSBranch ); tree_in->SetBranchAddress("yy_cosTSBranch",&yy_cosTSBranch ); tree_in->SetBranchAddress("bbyy_cosTSBranch",&bbyy_cosTSBranch ); tree_in->SetBranchAddress("bbyy_m",&bbyy_m ); tree_in->SetBranchAddress("bbyy_pt",&bbyy_pt); } void diHiggsTMVATree::execute() { n_events_ = tree_in->GetEntries(); if (thread == thread_out) { std::cout << "--- Processing: " << n_events_ << " events" << std::endl; show_progress = new boost::progress_display( n_events_/n_thread ); } for (Long64_t ievt=thread*n_events_/n_thread; ievt < (thread+1)*n_events_/n_thread ;ievt++) { if (thread == thread_out){++(*show_progress);} tree_in->GetEntry(ievt); b1_m = (Float_t)b1M; b1_pt = (Float_t)b1Pt; b1_eta = (Float_t)b1Eta; b1_phi = (Float_t)b1Phi; b1_source = (Float_t)b1Source; b2_m = (Float_t)b2M; b2_pt = (Float_t)b2Pt; b2_eta = (Float_t)b2Eta; b2_phi = (Float_t)b2Phi; b2_source = (Float_t)b2Source; y1_pt = (Float_t)y1Pt; y1_eta = (Float_t)y1Eta; y1_phi = (Float_t)y1Phi; y1_source = (Float_t)y1Source; y2_pt = (Float_t)y2Pt; y2_eta = (Float_t)y2Eta; y2_phi = (Float_t)y2Phi; y2_source = (Float_t)y2Source; bb_m = (Float_t)bbM; bb_pt = (Float_t)bbPt; bb_eta = (Float_t)bbEta; bb_phi = (Float_t)bbPhi; bb_dr = (Float_t)bbDr; yy_m = (Float_t)yyM; yy_pt = (Float_t)yyPt; yy_eta = (Float_t)yyEta; yy_phi = (Float_t)yyPhi; yy_dr = (Float_t)yyDr; final_stateWeight = (Float_t)finalStateWeight; scaledWeight3000fb = (Float_t)scaledWeight3000fb; bb_CosTSBranch = (Float_t)bb_cosTSBranch; yy_CosTSBranch = (Float_t)yy_cosTSBranch ; bbyy_CosTSBranch = (Float_t)bbyy_cosTSBranch ; bbyy_M = (Float_t)bbyy_m ; bbyy_Pt = (Float_t)bbyy_pt ; BDT_response = reader->EvaluateMVA("BDT method"); tree_out->Fill(); } if (thread == thread_out) { std::cout << "--- End of event loop: " <<std::endl; std::cout << "[diHiggsTMVATree :: Finalize]" <<std::endl; } output->Write(); output->Close(); }
[ "daquinteros@uc.cl" ]
daquinteros@uc.cl
93879920a59d83d6a4dd18d856cb8f48b76c2eaf
f1e8e085726ae6be6bcfc1faf6ad316f8726bdde
/source/ui/uiSystem.h
de6565bcd68a057035bc0e0b3ca5786ce4ebe3f6
[ "MIT" ]
permissive
TheGreatRambler/ballpusher-io
debf9ca7d02045059cb07e1d9ac2878cdc2282ca
77991d7ce5e0c8cffe5ddd774f4424430a276b91
refs/heads/master
2022-06-16T12:39:56.672537
2020-05-04T18:02:37
2020-05-04T18:02:37
151,259,887
2
1
null
null
null
null
UTF-8
C++
false
false
2,113
h
#include <Urho3D/Core/CoreEvents.h> #include <Urho3D/Core/Object.h> #include <Urho3D/Core/Timer.h> #include <Urho3D/Engine/Application.h> #include <Urho3D/Engine/Console.h> #include <Urho3D/Engine/DebugHud.h> #include <Urho3D/Engine/Engine.h> #include <Urho3D/Engine/EngineDefs.h> #include <Urho3D/Graphics/Camera.h> #include <Urho3D/Graphics/Graphics.h> #include <Urho3D/Graphics/Renderer.h> #include <Urho3D/Graphics/Texture2D.h> #include <Urho3D/IO/FileSystem.h> #include <Urho3D/IO/Log.h> #include <Urho3D/Input/Input.h> #include <Urho3D/Input/InputEvents.h> #include <Urho3D/Resource/ResourceCache.h> #include <Urho3D/Resource/XMLFile.h> #include <Urho3D/Scene/Scene.h> #include <Urho3D/Scene/SceneEvents.h> #include <Urho3D/UI/Cursor.h> #include <Urho3D/UI/Sprite.h> #include <Urho3D/UI/UI.h> #include <RmlUi/Core.h> #include "Urho3DRenderInterface.h" #include "Urho3DSystemInterface.h" class uiSystem { private: // For the UI Urho3DSystemInterface rocketSystemInterface; Urho3DRenderInterface rocketRenderer; Rml::Core::Context* uiContext; Urho3D::Context* uC; Urho3D::Graphics* gSub; Rml::Core::ElementDocument* mainDocument; public: uiSystem(Urho3D::Context* context, Urho3D::Graphics* gS) : rocketSystemInterface(context), rocketRenderer(context) { uC = context; gSub = gS; Rml::Core::SetRenderInterface(&rocketRenderer); Rml::Core::SetSystemInterface(&rocketSystemInterface); Rml::Core::Initialise(); // Get screen width and height int w = gSub->GetWidth(); int h = gSub->GetHeight(); uiContext = Rml::Core::CreateContext("main", Rml::Core::Vector2i(w, h)); // Load fonts (Only regular for now) Rml::Core::FontDatabase::LoadFontFace("AssetsData/fonts/opensans/OpenSans-Regular.ttf"); // Load main menu (May be all menus in future) mainDocument = uiContext->LoadDocument("AssetsData/ui/html/mainMenu.html"); // Show it mainDocument->Show(); } void update() { // Simply update the entire context uiContext->Update(); } void render() { uiContext->Render(); } void shutdown() { uiContext->RemoveReference(); Rml::Core::Shutdown(); } };
[ "aehart684351@gmail.com" ]
aehart684351@gmail.com
621a1505969783d75f8765d6108457b1d8a538e7
51f6e63555b4fda6a620fb42952c5c1fa6eac706
/chrome/browser/chromeos/tpm_firmware_update_unittest.cc
6060bc2f742a3eed7450940f06ad87fd3720e6fe
[ "BSD-3-Clause" ]
permissive
heanglightman/chromium
6f74026b428317a28cbb1226d20d1116ed54dd2b
f561f3e0174135fcc555aad31f4adb845977b8bd
refs/heads/master
2023-02-25T08:18:13.731198
2019-03-25T16:19:12
2019-03-25T16:19:12
177,623,917
1
0
NOASSERTION
2019-03-25T16:27:22
2019-03-25T16:27:22
null
UTF-8
C++
false
false
14,014
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/tpm_firmware_update.h" #include <utility> #include "base/bind.h" #include "base/callback.h" #include "base/files/file_util.h" #include "base/files/important_file_writer.h" #include "base/files/scoped_temp_dir.h" #include "base/path_service.h" #include "base/test/scoped_feature_list.h" #include "base/test/scoped_path_override.h" #include "base/test/scoped_task_environment.h" #include "base/values.h" #include "chrome/browser/chromeos/settings/scoped_cros_settings_test_helper.h" #include "chrome/browser/chromeos/settings/stub_install_attributes.h" #include "chrome/common/chrome_features.h" #include "chrome/common/chrome_paths.h" #include "chromeos/settings/cros_settings_names.h" #include "chromeos/system/fake_statistics_provider.h" #include "components/policy/proto/chrome_device_policy.pb.h" #include "testing/gtest/include/gtest/gtest.h" namespace chromeos { namespace tpm_firmware_update { TEST(TPMFirmwareUpdateTest, DecodeSettingsProto) { enterprise_management::TPMFirmwareUpdateSettingsProto settings; settings.set_allow_user_initiated_powerwash(true); settings.set_allow_user_initiated_preserve_device_state(true); settings.set_auto_update_mode( enterprise_management:: TPMFirmwareUpdateSettingsProto_AutoUpdateMode_USER_ACKNOWLEDGMENT); auto dict = DecodeSettingsProto(settings); ASSERT_TRUE(dict); bool value = false; EXPECT_TRUE(dict->GetBoolean("allow-user-initiated-powerwash", &value)); EXPECT_TRUE(value); EXPECT_TRUE( dict->GetBoolean("allow-user-initiated-preserve-device-state", &value)); EXPECT_TRUE(value); int update_mode_value = 0; EXPECT_TRUE(dict->GetInteger("auto-update-mode", &update_mode_value)); EXPECT_EQ(2, update_mode_value); } class TPMFirmwareUpdateTest : public testing::Test { public: enum class Availability { kPending, kUnavailable, kUnavailableROCAVulnerable, kAvailable, }; TPMFirmwareUpdateTest() = default; void SetUp() override { feature_list_ = std::make_unique<base::test::ScopedFeatureList>(); feature_list_->InitAndEnableFeature(features::kTPMFirmwareUpdate); ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); base::FilePath update_location_path = temp_dir_.GetPath().AppendASCII("tpm_firmware_update_location"); path_override_location_ = std::make_unique<base::ScopedPathOverride>( chrome::FILE_CHROME_OS_TPM_FIRMWARE_UPDATE_LOCATION, update_location_path, update_location_path.IsAbsolute(), false); base::FilePath srk_vulnerable_roca_path = temp_dir_.GetPath().AppendASCII( "tpm_firmware_update_srk_vulnerable_roca"); path_override_srk_vulnerable_roca_ = std::make_unique<base::ScopedPathOverride>( chrome::FILE_CHROME_OS_TPM_FIRMWARE_UPDATE_SRK_VULNERABLE_ROCA, srk_vulnerable_roca_path, srk_vulnerable_roca_path.IsAbsolute(), false); SetUpdateAvailability(Availability::kAvailable); } void SetUpdateAvailability(Availability availability) { base::FilePath srk_vulnerable_roca_path; ASSERT_TRUE(base::PathService::Get( chrome::FILE_CHROME_OS_TPM_FIRMWARE_UPDATE_SRK_VULNERABLE_ROCA, &srk_vulnerable_roca_path)); switch (availability) { case Availability::kPending: case Availability::kUnavailable: base::DeleteFile(srk_vulnerable_roca_path, false); break; case Availability::kAvailable: case Availability::kUnavailableROCAVulnerable: ASSERT_TRUE(base::ImportantFileWriter::WriteFileAtomically( srk_vulnerable_roca_path, "")); break; } base::FilePath update_location_path; ASSERT_TRUE(base::PathService::Get( chrome::FILE_CHROME_OS_TPM_FIRMWARE_UPDATE_LOCATION, &update_location_path)); switch (availability) { case Availability::kPending: base::DeleteFile(update_location_path, false); break; case Availability::kUnavailable: case Availability::kUnavailableROCAVulnerable: ASSERT_TRUE(base::ImportantFileWriter::WriteFileAtomically( update_location_path, "")); break; case Availability::kAvailable: const char kUpdatePath[] = "/lib/firmware/tpm/firmware.bin"; ASSERT_TRUE(base::ImportantFileWriter::WriteFileAtomically( update_location_path, kUpdatePath)); break; } } std::unique_ptr<base::test::ScopedFeatureList> feature_list_; base::ScopedTempDir temp_dir_; std::unique_ptr<base::ScopedPathOverride> path_override_location_; std::unique_ptr<base::ScopedPathOverride> path_override_srk_vulnerable_roca_; base::test::ScopedTaskEnvironment scoped_task_environment_{ base::test::ScopedTaskEnvironment::MainThreadType::MOCK_TIME}; ScopedCrosSettingsTestHelper cros_settings_test_helper_; chromeos::system::ScopedFakeStatisticsProvider statistics_provider_; }; class TPMFirmwareUpdateModesTest : public TPMFirmwareUpdateTest { public: TPMFirmwareUpdateModesTest() = default; void SetUp() override { TPMFirmwareUpdateTest::SetUp(); callback_ = base::BindOnce(&TPMFirmwareUpdateModesTest::RecordResponse, base::Unretained(this)); } void RecordResponse(const std::set<Mode>& modes) { callback_received_ = true; callback_modes_ = modes; } const std::set<Mode> kAllModes{Mode::kPowerwash, Mode::kPreserveDeviceState}; bool callback_received_ = false; std::set<Mode> callback_modes_; base::OnceCallback<void(const std::set<Mode>&)> callback_; }; TEST_F(TPMFirmwareUpdateModesTest, FeatureDisabled) { feature_list_.reset(); feature_list_ = std::make_unique<base::test::ScopedFeatureList>(); feature_list_->InitAndDisableFeature(features::kTPMFirmwareUpdate); GetAvailableUpdateModes(std::move(callback_), base::TimeDelta()); EXPECT_TRUE(callback_received_); EXPECT_TRUE(callback_modes_.empty()); } TEST_F(TPMFirmwareUpdateModesTest, FRERequired) { statistics_provider_.SetMachineStatistic(system::kCheckEnrollmentKey, "1"); GetAvailableUpdateModes(std::move(callback_), base::TimeDelta()); EXPECT_TRUE(callback_received_); EXPECT_TRUE(callback_modes_.empty()); } TEST_F(TPMFirmwareUpdateModesTest, Pending) { SetUpdateAvailability(Availability::kPending); GetAvailableUpdateModes(std::move(callback_), base::TimeDelta()); scoped_task_environment_.RunUntilIdle(); EXPECT_TRUE(callback_received_); EXPECT_TRUE(callback_modes_.empty()); } TEST_F(TPMFirmwareUpdateModesTest, Available) { GetAvailableUpdateModes(std::move(callback_), base::TimeDelta()); scoped_task_environment_.RunUntilIdle(); EXPECT_TRUE(callback_received_); EXPECT_EQ(kAllModes, callback_modes_); } TEST_F(TPMFirmwareUpdateModesTest, AvailableAfterWaiting) { SetUpdateAvailability(Availability::kPending); GetAvailableUpdateModes(std::move(callback_), base::TimeDelta::FromSeconds(5)); scoped_task_environment_.RunUntilIdle(); EXPECT_FALSE(callback_received_); // When testing that file appearance triggers the callback, we can't rely on // a single execution of ScopedTaskEnvironment::RunUntilIdle(). This is // because ScopedTaskEnvironment doesn't know about file system events that // haven't fired and propagated to a task scheduler thread yet so may return // early before the file system event is received. An event is expected here // though, so keep spinning the loop until the callback is received. This // isn't ideal, but better than flakiness due to file system events racing // with a single invocation of RunUntilIdle(). SetUpdateAvailability(Availability::kAvailable); while (!callback_received_) { scoped_task_environment_.RunUntilIdle(); } EXPECT_EQ(kAllModes, callback_modes_); // Trigger timeout and validate there are no further callbacks or crashes. callback_received_ = false; scoped_task_environment_.FastForwardBy(base::TimeDelta::FromSeconds(5)); scoped_task_environment_.RunUntilIdle(); EXPECT_FALSE(callback_received_); } TEST_F(TPMFirmwareUpdateModesTest, NoUpdateVulnerableSRK) { SetUpdateAvailability(Availability::kUnavailableROCAVulnerable); GetAvailableUpdateModes(std::move(callback_), base::TimeDelta()); scoped_task_environment_.RunUntilIdle(); EXPECT_TRUE(callback_received_); EXPECT_EQ(std::set<Mode>{Mode::kCleanup}, callback_modes_); } TEST_F(TPMFirmwareUpdateModesTest, NoUpdateNonVulnerableSRK) { SetUpdateAvailability(Availability::kUnavailable); GetAvailableUpdateModes(std::move(callback_), base::TimeDelta()); scoped_task_environment_.RunUntilIdle(); EXPECT_TRUE(callback_received_); EXPECT_EQ(std::set<Mode>(), callback_modes_); } TEST_F(TPMFirmwareUpdateModesTest, Timeout) { SetUpdateAvailability(Availability::kPending); GetAvailableUpdateModes(std::move(callback_), base::TimeDelta::FromSeconds(5)); scoped_task_environment_.RunUntilIdle(); EXPECT_FALSE(callback_received_); scoped_task_environment_.FastForwardBy(base::TimeDelta::FromSeconds(5)); scoped_task_environment_.RunUntilIdle(); EXPECT_TRUE(callback_received_); EXPECT_TRUE(callback_modes_.empty()); } class TPMFirmwareUpdateModesEnterpriseTest : public TPMFirmwareUpdateModesTest { public: void SetUp() override { TPMFirmwareUpdateModesTest::SetUp(); cros_settings_test_helper_.ReplaceDeviceSettingsProviderWithStub(); cros_settings_test_helper_.InstallAttributes()->SetCloudManaged( "example.com", "fake-device-id"); } void SetPolicy(const std::set<Mode>& modes) { base::DictionaryValue dict; dict.SetKey(kSettingsKeyAllowPowerwash, base::Value(modes.count(Mode::kPowerwash) > 0)); dict.SetKey(kSettingsKeyAllowPreserveDeviceState, base::Value(modes.count(Mode::kPreserveDeviceState) > 0)); cros_settings_test_helper_.Set(kTPMFirmwareUpdateSettings, dict); } }; TEST_F(TPMFirmwareUpdateModesEnterpriseTest, DeviceSettingPending) { SetPolicy(kAllModes); cros_settings_test_helper_.SetTrustedStatus( CrosSettingsProvider::TEMPORARILY_UNTRUSTED); GetAvailableUpdateModes(std::move(callback_), base::TimeDelta()); scoped_task_environment_.RunUntilIdle(); EXPECT_FALSE(callback_received_); cros_settings_test_helper_.SetTrustedStatus(CrosSettingsProvider::TRUSTED); scoped_task_environment_.RunUntilIdle(); EXPECT_TRUE(callback_received_); EXPECT_EQ(kAllModes, callback_modes_); } TEST_F(TPMFirmwareUpdateModesEnterpriseTest, DeviceSettingUntrusted) { cros_settings_test_helper_.SetTrustedStatus( CrosSettingsProvider::PERMANENTLY_UNTRUSTED); GetAvailableUpdateModes(std::move(callback_), base::TimeDelta()); scoped_task_environment_.RunUntilIdle(); EXPECT_TRUE(callback_received_); EXPECT_TRUE(callback_modes_.empty()); } TEST_F(TPMFirmwareUpdateModesEnterpriseTest, DeviceSettingNotSet) { GetAvailableUpdateModes(std::move(callback_), base::TimeDelta()); scoped_task_environment_.RunUntilIdle(); EXPECT_TRUE(callback_received_); EXPECT_TRUE(callback_modes_.empty()); } TEST_F(TPMFirmwareUpdateModesEnterpriseTest, DeviceSettingDisallowed) { SetPolicy({}); GetAvailableUpdateModes(std::move(callback_), base::TimeDelta()); scoped_task_environment_.RunUntilIdle(); EXPECT_TRUE(callback_received_); EXPECT_TRUE(callback_modes_.empty()); } TEST_F(TPMFirmwareUpdateModesEnterpriseTest, DeviceSettingPowerwashAllowed) { SetPolicy({Mode::kPowerwash}); GetAvailableUpdateModes(std::move(callback_), base::TimeDelta()); scoped_task_environment_.RunUntilIdle(); EXPECT_TRUE(callback_received_); EXPECT_EQ(std::set<Mode>({Mode::kPowerwash}), callback_modes_); } TEST_F(TPMFirmwareUpdateModesEnterpriseTest, DeviceSettingPreserveDeviceStateAllowed) { SetPolicy({Mode::kPreserveDeviceState}); GetAvailableUpdateModes(std::move(callback_), base::TimeDelta()); scoped_task_environment_.RunUntilIdle(); EXPECT_TRUE(callback_received_); EXPECT_EQ(std::set<Mode>({Mode::kPreserveDeviceState}), callback_modes_); } TEST_F(TPMFirmwareUpdateModesEnterpriseTest, VulnerableSRK) { SetUpdateAvailability(Availability::kUnavailableROCAVulnerable); SetPolicy({Mode::kPreserveDeviceState}); GetAvailableUpdateModes(std::move(callback_), base::TimeDelta()); scoped_task_environment_.RunUntilIdle(); EXPECT_TRUE(callback_received_); EXPECT_EQ(std::set<Mode>({Mode::kCleanup}), callback_modes_); } class TPMFirmwareAutoUpdateTest : public TPMFirmwareUpdateTest { public: TPMFirmwareAutoUpdateTest() = default; void SetUp() override { TPMFirmwareUpdateTest::SetUp(); callback_ = base::BindOnce(&TPMFirmwareAutoUpdateTest::RecordResponse, base::Unretained(this)); } void RecordResponse(bool update_available) { callback_received_ = true; update_available_ = update_available; } bool callback_received_ = false; bool update_available_; base::OnceCallback<void(bool)> callback_; }; TEST_F(TPMFirmwareAutoUpdateTest, AutoUpdateAvaiable) { UpdateAvailable(std::move(callback_), base::TimeDelta()); scoped_task_environment_.RunUntilIdle(); EXPECT_TRUE(callback_received_); EXPECT_TRUE(update_available_); } TEST_F(TPMFirmwareAutoUpdateTest, VulnerableSRKNoStatePreservingUpdate) { SetUpdateAvailability(Availability::kUnavailableROCAVulnerable); UpdateAvailable(std::move(callback_), base::TimeDelta()); scoped_task_environment_.RunUntilIdle(); EXPECT_TRUE(callback_received_); EXPECT_FALSE(update_available_); } TEST_F(TPMFirmwareAutoUpdateTest, NoUpdate) { SetUpdateAvailability(Availability::kUnavailable); UpdateAvailable(std::move(callback_), base::TimeDelta()); scoped_task_environment_.RunUntilIdle(); EXPECT_TRUE(callback_received_); EXPECT_FALSE(update_available_); } } // namespace tpm_firmware_update } // namespace chromeos
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
b269d5f64957ffae8999be25aae96497286958ea
6514b5a137e260db7c2d2d9da7c93c4f56ec108e
/llvm/src/lib/CSE231/BranchFolding.cpp
77202fd9f407578707449dd4d43c1442da0bfed9
[]
no_license
ananducsd/llvm-final
d5bb2716c758df694418a177c01d0e6d5a66a690
fcda136b95f56d1049152efa25124d0a065bf6f3
refs/heads/master
2021-01-10T13:48:56.200623
2015-12-11T07:52:17
2015-12-11T07:52:17
47,582,155
0
1
null
null
null
null
UTF-8
C++
false
false
2,975
cpp
#define DEBUG_TYPE "BranchFoldingPass" #include <map> #include "ConstantPropagation.cpp" #include "llvm/Transforms/Utils/BasicBlockUtils.h" //NOTE : this algorithm //opt -load $LLVMLIB/CSE231.so -ConstPass -BranchFoldingPass < $BENCHMARKS/gcd/gcd.bc > temp.instrumented.bc using namespace llvm; using namespace constprop; namespace { static IRBuilder<> builder(getGlobalContext()); struct BranchFoldingPass : public ModulePass { static char ID; // Pass identification, replacement for typeid //iterate through all instructions, fill map. BranchFoldingPass() : ModulePass(ID) { //errs() << "Branch Folding Module Created" << "\n"; } bool runOnModule(Module &M){ //create the worklist object Worklist<EdgeFact, FlowFunctions, Lattice>* wl = new Worklist<EdgeFact, FlowFunctions, Lattice>(); wl->init(M); wl->run(); //M.dump(); //wl->printTop(); //wl->printBottom(); //For each BBNode<EdgeFact> for(map<int, BBNode<EdgeFact>*>::iterator it = wl->bbMap.begin(); it != wl->bbMap.end(); it++) { BBNode<EdgeFact> * BBN = it->second; Node<EdgeFact> * N = BBN->nodes.back(); if(N->I->getOpcode() == Instruction::Br) { //get the terminating instruction BranchInst * B = dyn_cast<BranchInst>(N->I); //make sure the branch is conditional if(B->isConditional()) { //use the worklist results to replace input if available Value *temp = N->I->getOperand(0); //check if the operand is linked to an instruction //NOTE: if it is already a constant like true or false, it will just skip this. Instruction * cond = dyn_cast<Instruction>(temp); if(cond && N->e->data->count(temp) == 1 ){ Fact *c = N->e->data->find(cond)->second; if(c->possibleValues.size() == 1){ set<Value *>::iterator itl = c->possibleValues.begin(); Value * result = *itl; BasicBlock::iterator ii(cond); ReplaceInstWithValue(cond->getParent()->getInstList(), ii, result); } } //check for if it is true or false (0, or non-zero...) if(isa<ConstantInt>(B->getCondition())){ ConstantInt * CI = dyn_cast<ConstantInt>(B->getCondition()); //check false: if(CI->isZero()){ //swap successors B->swapSuccessors(); } //get the good black (always taken). BranchInst* New = BranchInst::Create(B->getSuccessor(0)); //replace this branching instruction with an unconditional one ReplaceInstWithInst(B, New); } } } } M.dump(); return false; } }; } char BranchFoldingPass::ID = 0; static RegisterPass<BranchFoldingPass> X("BranchFoldingPass", "Branch Folding Pass",false,false);
[ "a3anand@ucsd.edu" ]
a3anand@ucsd.edu
9ab1d712a7581c9fdf76d2f8917546f00670f996
5436a18ae8e523fc7c6b6adb0577b5a37d0ea751
/src/include/hinatacore/bsdf.h
97bd5f84424e8bc8bb08e3a1e81a03317d1c521e
[]
no_license
hi2p-perim/hinatarender
aeeb1cc901d67644b0abd0ca57b499316bbc2a1a
a03609c5d5772ae7ca7f812055bf048ab8b55df9
refs/heads/master
2021-04-09T17:20:21.253135
2013-08-23T23:52:26
2013-08-23T23:52:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,248
h
#ifndef __HINATA_CORE_BSDF_H__ #define __HINATA_CORE_BSDF_H__ #include "common.h" #include "math.h" HINATA_NAMESPACE_BEGIN /*! BSDF sample. Samples needed for BSDF sampling. */ struct BSDFSample { Vec2d u; double uComponent; }; /*! BSDF record. IO structure for BSDF. */ struct BSDFRecord { int type; //<! Requested BSDF type flag int sampledType; //<! Sampled BSDF type double adjoint; //<! Adjoint BSDF Vec3d wi; //<! Input direction in local coordinates Vec3d wo; //<! Output direction in local coordinates }; ///! BSDF types. enum BSDFType { // Primitive BSDF types DiffuseReflection = 1<<0, DiffuseTransmission = 1<<1, DeltaReflection = 1<<2, DeltaTransmission = 1<<3, GlossyReflection = 1<<4, GlossyTransmission = 1<<5, // Useful flags Diffuse = DiffuseReflection | DiffuseTransmission, Delta = DeltaReflection | DeltaTransmission, Glossy = GlossyReflection | GlossyTransmission, All = Diffuse | Delta | Glossy, Reflection = DiffuseReflection | DeltaReflection | GlossyReflection, Transmission = DiffuseTransmission | DeltaTransmission | GlossyTransmission, }; class Intersection; class BSDF { public: BSDF() {} virtual ~BSDF() {} private: BSDF(const BSDF&); BSDF(BSDF&&); void operator=(const BSDF&); void operator=(BSDF&&); public: /*! Get BSDF type. \return BSDF type. */ virtual BSDFType Type() = 0; /*! Evaluate BSDF. Evaluate f(wi, wo) * cos(theta). */ virtual Vec3d Evaluate(BSDFRecord& record, Intersection& isect) = 0; /*! Sample and evaluate BSDF. Sample wo and evalueate f(wi, wo) * cos(theta) / p(wo). */ virtual Vec3d SampleAndEvaluate(BSDFRecord& record, BSDFSample& sample, double& pdf, Intersection& isect) = 0; /*! Evaluate PDF. Evaluate PDF in solid angle measure. */ virtual double Pdf(BSDFRecord& record) = 0; protected: // Useful operation on local shading coordinates double CosTheta(const Vec3d& v); double SinTheta2(const Vec3d& v); double TanTheta(const Vec3d& v); Vec3d Reflect(const Vec3d& wi); Vec3d Refract(const Vec3d& wi, double eta, double cosThetaT); double ShadingNormalCorrectionFactor(BSDFRecord& record, Intersection& isect); }; HINATA_NAMESPACE_END #endif // __HINATA_CORE_BSDF_H__
[ "hi2p.perim@gmail.com" ]
hi2p.perim@gmail.com
1d6b4b65bafa3afa39ca479626051278e9605ac2
0f99d48ef29b0f5682b928e6c1972fb9e0c31fe0
/test/floor.cpp
5664cb5154080530038268409dfbbe9bfd2e8aba
[]
no_license
MayaPosch/BMaC
d438a6d631ab1d62c0af82c059b68a5ee73ca649
8d65b38e19a32ce761cfec20c9aa17577403e60b
refs/heads/master
2023-02-08T02:27:21.234107
2023-02-02T21:24:09
2023-02-02T21:24:09
114,949,973
105
15
null
2022-09-05T11:10:27
2017-12-21T01:53:25
C++
UTF-8
C++
false
false
947
cpp
/* floor.cpp - Floor class. Revision 0 Notes: - 2018/09/18, Maya Posch */ #include "floor.h" #include "utility.h" #include <string> #include <iostream> // --- CONSTRUCTOR --- Floor::Floor(uint32_t level, Config &config) { // For each floor, create the room instances defined for it. std::string floor_cat = "Floor_" + std::to_string(level); std::string roomsStr = config.getValue<std::string>(floor_cat + ".rooms", std::string()); // Extract the room IDs. std::vector<std::string> room_ids; split_string(roomsStr, ',', room_ids); int room_count = room_ids.size(); // Create the rooms for this floor. if (room_count > 0) { for (int i = 0; i < room_count; ++i) { try { Room room(std::stoi(room_ids.at(i)), config); rooms.push_back(std::move(room)); } catch(std::invalid_argument &e) { std::cerr << "stoi() conversion failed for: " << room_ids.at(i) << std::endl; continue; } } } }
[ "maya@nyanko.ws" ]
maya@nyanko.ws
e50fc673654af56512b8419c345f4ef57984afb5
646c6dd9ade69cc6ed8f91d784be7f3719d70891
/src/defconbots22.cpp
408f26afef2a1a528f96241b6d7ab51e17c786f4
[]
no_license
ryanshoff/defconbots22
5bb43a34858e73442fc8bcf338c0af0a2bce418d
e688703b6845d0f2417ab33693a139f3b291255d
refs/heads/master
2021-01-21T12:23:20.148221
2014-08-07T06:54:43
2014-08-07T06:54:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,937
cpp
#define IMAGEVIEWER #define TRACKVIEWER #undef SERIAL #undef NOVIEWER #include <iostream> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/openni_grabber.h> #include <SerialStream.h> #ifndef NOVIEWER #include <pcl/visualization/pcl_visualizer.h> #endif #include <pcl/io/openni_camera/openni_driver.h> #include <pcl/io/pcd_io.h> #include <pcl/console/parse.h> #include <pcl/sample_consensus/method_types.h> #include <pcl/sample_consensus/model_types.h> #include <pcl/segmentation/sac_segmentation.h> #include <pcl/segmentation/extract_clusters.h> #include <pcl/filters/extract_indices.h> #include <pcl/filters/passthrough.h> #include <pcl/kdtree/kdtree.h> #include <defconbots22.h> #include <pcl/common/time.h> #include <pcl/common/centroid.h> #include <pcl/common/impl/angles.hpp> #include <pcl/conversions.h> #include <pcl/visualization/image_viewer.h> #include <opencv2/core/core.hpp> class DefconBots22 { public: typedef pcl::PointCloud<pcl::PointXYZRGBA> Cloud; typedef typename Cloud::Ptr CloudPtr; typedef typename Cloud::ConstPtr CloudConstPtr; #ifndef NOVIEWER void viewerOneOff (pcl::visualization::PCLVisualizer& viewer) { pcl::PointXYZ origin(0.0, 0.0, 0.0); pcl::PointCloud<pcl::PointXYZRGBA> boundingbox; pcl::PointXYZRGBA point; viewer.addText3D("DefconBots", origin, .1); point.x = MIN_X_DEPTH; point.y = MIN_Y_DEPTH; point.z = MIN_Z_DEPTH; point.r = 255; point.g = 255; point.b = 255; boundingbox.points.push_back(point); point.x = MAX_X_DEPTH; boundingbox.points.push_back(point); point.y = MAX_Y_DEPTH; boundingbox.points.push_back(point); point.x = MIN_X_DEPTH; boundingbox.points.push_back(point); point.z = MAX_Z_DEPTH; point.y = MIN_Y_DEPTH; boundingbox.points.push_back(point); point.x = MAX_X_DEPTH; boundingbox.points.push_back(point); point.y = MAX_Y_DEPTH; boundingbox.points.push_back(point); point.x = MIN_X_DEPTH; boundingbox.points.push_back(point); viewer.addLine(boundingbox[0],boundingbox[1], "1", 0); viewer.addLine(boundingbox[1],boundingbox[2], "2", 0); viewer.addLine(boundingbox[2],boundingbox[3], "3", 0); viewer.addLine(boundingbox[3],boundingbox[0], "4", 0); viewer.addLine(boundingbox[4],boundingbox[5], "5", 0); viewer.addLine(boundingbox[5],boundingbox[6], "6", 0); viewer.addLine(boundingbox[6],boundingbox[7], "7", 0); viewer.addLine(boundingbox[7],boundingbox[4], "8", 0); viewer.addLine(boundingbox[0],boundingbox[4], "9", 0); viewer.addLine(boundingbox[1],boundingbox[5], "10", 0); viewer.addLine(boundingbox[2],boundingbox[6], "11", 0); viewer.addLine(boundingbox[3],boundingbox[7], "12", 0); viewer.initCameraParameters(); viewer.resetCameraViewpoint(); } #endif DefconBots22 (const std::string& device_id = "", const std::string& filename = "" ) : #ifndef NOVIEWER viewer ("defconbots22"), #endif device_id_ (device_id) , filename_ (filename) { passx.setFilterFieldName("x"); passx.setFilterLimits(MIN_X_DEPTH, MAX_X_DEPTH); passy.setFilterFieldName("y"); passy.setFilterLimits(MIN_Y_DEPTH, MAX_Y_DEPTH); passz.setFilterFieldName("z"); passz.setFilterLimits(MIN_Z_DEPTH, MAX_Z_DEPTH); ec.setClusterTolerance (0.02); // 2cm ec.setMinClusterSize (50); ec.setMaxClusterSize (25000); #ifndef NOVIEWER viewer.registerKeyboardCallback(&DefconBots22::keyboard_callback, *this , 0); #endif saveCloud = false; toggleView = 0; filesSaved = 0; #ifdef IMAGEVIEWER height = 0; width = 0; #endif openserial(); bzero(rgb_track,sizeof (char) * TRACKSIZE*TRACKSIZE*3); } ~DefconBots22() { }; void openserial() { #ifdef SERIAL using namespace LibSerial ; serial_port.Open( SERIAL_PORT_DEVICE ) ; if ( ! serial_port.good() ) { std::cerr << "Error: Could not open serial port " << SERIAL_PORT_DEVICE << std::endl ; exit(1) ; } // // Set the baud rate of the serial port. // serial_port.SetBaudRate( SerialStreamBuf::BAUD_57600 ) ; if ( ! serial_port.good() ) { std::cerr << "Error: Could not set the baud rate." << std::endl ; exit(1) ; } // // Set the number of data bits. // serial_port.SetCharSize( SerialStreamBuf::CHAR_SIZE_8 ) ; if ( ! serial_port.good() ) { std::cerr << "Error: Could not set the character size." << std::endl ; exit(1) ; } // // Disable parity. // serial_port.SetParity( SerialStreamBuf::PARITY_NONE ) ; if ( ! serial_port.good() ) { std::cerr << "Error: Could not disable the parity." << std::endl ; exit(1) ; } // // Set the number of stop bits. // serial_port.SetNumOfStopBits( 1 ) ; if ( ! serial_port.good() ) { std::cerr << "Error: Could not set the number of stop bits." << std::endl ; exit(1) ; } // // Turn on hardware flow control. // serial_port.SetFlowControl( SerialStreamBuf::FLOW_CONTROL_NONE ) ; if ( ! serial_port.good() ) { std::cerr << "Error: Could not use hardware flow control." << std::endl ; exit(1) ; } // // Do not skip whitespace characters while reading from the // serial port. // // serial_port.unsetf( std::ios_base::skipws ) ; #endif } void keyboard_callback (const pcl::visualization::KeyboardEvent& event, void *) { if (event.keyUp ()) { switch (event.getKeyCode()) { case 's': case 'S': saveCloud = true; // save pcd file break; case 't': case 'T': ++toggleView %= 2; break; case 'c': case 'C': bzero(rgb_track,sizeof (char) * TRACKSIZE*TRACKSIZE*3); break; } } } #ifdef IMAGEVIEWER void image_cb_ (const boost::shared_ptr<openni_wrapper::Image> &image) { boost::mutex::scoped_lock lock (mtx2_); height = image->getHeight(); width = image->getWidth(); cv::Mat frameBGR=cv::Mat(image->getHeight(),image->getWidth(),CV_8UC3); image->fillRGB(frameBGR.cols,frameBGR.rows,frameBGR.data,frameBGR.step); //-- 3. Apply the classifier to the frame if( !frameBGR.empty() ) { for(int j=0; j<height; j++) { for(int i=0; i<width; i++) { rgb_buffer[(j*width + i)*3+0] = frameBGR.at<cv::Vec3b>(j,i)[0]; // B rgb_buffer[(j*width + i)*3+1] = frameBGR.at<cv::Vec3b>(j,i)[1]; // G rgb_buffer[(j*width + i)*3+2] = frameBGR.at<cv::Vec3b>(j,i)[2]; // R //cout << (j*width + i)*3+0 << "," << (j*width + i)*3+1 << "," << (j*width + i)*3+2 << "," << std::endl; } } } else { //cout << " --(!) No captured frame -- Break!" << endl; } } #endif void cloud_cb_ (const CloudConstPtr& cloud) { static unsigned count = 0; static double last = pcl::getTime(); double now = pcl::getTime(); if(++count == FRAMES_PER_SEC) { set (cloud); last = now; count = 0; } } void set (const CloudConstPtr& cloud) { //lock while we set our cloud; boost::mutex::scoped_lock lock (mtx_); cloud_ = cloud; } CloudPtr get () { //lock while we swap our cloud and reset it. boost::mutex::scoped_lock lock (mtx_); CloudPtr temp_cloud (new Cloud); CloudPtr temp_cloud2 (new Cloud); CloudPtr temp_cloud3 (new Cloud); CloudPtr temp_cloud4 (new Cloud); CloudPtr temp_cloud5 (new Cloud); CloudConstPtr empty_cloud; Eigen::Vector3f pointercenter (0.0f,0.1f,0.0f); Eigen::Vector3f pointervector (0.0f,0.0f,0.0f); cout << "===============================\n" "======Start of frame===========\n" "===============================\n"; cout << "cloud size orig: " << cloud_->size() << endl; passx.setInputCloud (cloud_); passx.filter (*temp_cloud); passy.setInputCloud (temp_cloud); passy.filter (*temp_cloud2); passz.setInputCloud (temp_cloud2); passz.filter (*temp_cloud3); cout << "cloud size post filter: " << temp_cloud3->size() << endl; centroid_vector.clear(); if(temp_cloud3->size() > 0) { pcl::search::KdTree<pcl::PointXYZRGBA>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZRGBA>); std::vector<pcl::PointIndices> cluster_indices; tree->setInputCloud (temp_cloud3); ec.setSearchMethod (tree); ec.setInputCloud (temp_cloud3); ec.extract (cluster_indices); cout << "number of clusters " << cluster_indices.size() << endl; unsigned int count = 0; for (std::vector<pcl::PointIndices>::const_iterator it = cluster_indices.begin (); it != cluster_indices.end (); ++it) { count++; cout << "centroid " << count << endl; Eigen::VectorXf centroid(8); centroid.setZero(); const std::vector<int> indices = (*it).indices; for(size_t i = 0; i < indices.size(); i++) { centroid[0] += (*temp_cloud3)[indices[i]].x; centroid[1] += (*temp_cloud3)[indices[i]].y; centroid[2] += (*temp_cloud3)[indices[i]].z; centroid[3] += (*temp_cloud3)[indices[i]].r; centroid[4] += (*temp_cloud3)[indices[i]].g; centroid[5] += (*temp_cloud3)[indices[i]].b; } centroid /= indices.size(); Eigen::Vector3f centroid3f; centroid3f[0] = centroid[0]; centroid3f[1] = centroid[1]; centroid3f[2] = centroid[2]; pointervector = pointercenter - centroid3f; float theta = pcl::rad2deg(atan(centroid[0]/centroid[2])); unsigned int thetapwm = theta * 10 + 1200; float phi = pcl::rad2deg(atan(-centroid[1]/centroid[2])); unsigned int phipwm = phi * 10 + 1340; float thetapointer = pcl::rad2deg(atan(pointervector[0]/pointervector[2])); float phipointer = pcl::rad2deg(atan(-pointervector[1]/pointervector[2])); centroid[6] = phipwm; centroid[7] = thetapwm; unsigned int x = centroid[0]*100 + TRACKSIZE/2; unsigned int z = TRACKSIZE - centroid[2]*100; rgb_track[(z*TRACKSIZE + x)*3+0] = 255; // R rgb_track[(z*TRACKSIZE + x+1)*3+0] = 255; // R rgb_track[((z+1)*TRACKSIZE + x)*3+0] = 255; // R rgb_track[((z+1)*TRACKSIZE + x+1)*3+0] = 255; // R cout << centroid << endl; cout << "distance from laser to centroid " << pointervector.norm() << " meters." << endl; cout << "theta angle " << theta << " degrees. phi angle " << phi << " degrees." << endl; cout << "theta pointer angle " << thetapointer << " degrees. phi angle " << phipointer << " degrees." << endl; cout << phipwm << "," << thetapwm << ",10" << endl; centroid_vector.push_back(centroid); } } // need mutex here centroid_vector_.swap(centroid_vector); if (saveCloud) { std::stringstream stream, stream1; std::string filename; stream << "inputCloud" << filesSaved << ".pcd"; filename = stream.str(); if (pcl::io::savePCDFile(filename, *cloud_, true) == 0) { filesSaved++; cout << "Saved " << filename << "." << endl; } else PCL_ERROR("Problem saving %s.\n", filename.c_str()); stream1 << "inputCloud" << filesSaved << ".pcd"; filename = stream1.str(); if (pcl::io::savePCDFile(filename, *temp_cloud5, true) == 0) { filesSaved++; cout << "Saved " << filename << "." << endl; } else PCL_ERROR("Problem saving %s.\n", filename.c_str()); saveCloud = false; } empty_cloud.swap(cloud_); // set cloud_ to null if(toggleView == 1) return (temp_cloud); // return zcloud else return (temp_cloud3); // return xyzcloud } void run () { CloudPtr filecloud; pcl::Grabber* interface; if(filename_.empty()) { interface = new pcl::OpenNIGrabber (device_id_); boost::function<void (const CloudConstPtr&)> f = boost::bind (&DefconBots22::cloud_cb_, this, _1); boost::signals2::connection c = interface->registerCallback (f); #ifdef IMAGEVIEWER boost::function<void (const boost::shared_ptr<openni_wrapper::Image>&)> g = boost::bind (&DefconBots22::image_cb_, this, _1); boost::signals2::connection d = interface->registerCallback (g); #endif interface->start (); } else { pcd_cloud.reset (new pcl::PCLPointCloud2); if(pcd.read (filename_, *pcd_cloud, origin, orientation, version) < 0) cout << "file read failed" << endl; filecloud.reset (new Cloud); pcl::fromPCLPointCloud2(*pcd_cloud, *filecloud); cloud_ = filecloud; } #ifdef NOVIEWER if(!filename_.empty()) get(); else while(TRUE) { if (cloud_) get(); boost::this_thread::sleep (boost::posix_time::microseconds (10000)); } #else viewerOneOff(viewer); pcl::PointCloud<pcl::PointXYZRGBA>::Ptr emptycloud (new pcl::PointCloud<pcl::PointXYZRGBA>); pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGBA> rgb(emptycloud); viewer.addPointCloud<pcl::PointXYZRGBA>(emptycloud, rgb, "kinect cloud"); unsigned int count = 0; while ( !viewer.wasStopped () ) { if (cloud_) { //the call to get() sets the cloud_ to null; viewer.updatePointCloud(get (), "kinect cloud"); #ifdef SERIAL if(!centroid_vector_.empty()) serial_port << (unsigned int) (centroid_vector_[0])[6] << "," << (unsigned int) (centroid_vector_[0])[7] << ",10" << endl; #endif viewer.spinOnce(); count++; if(count%2) { //cout << "1000,1000,10" << endl; //serial_port << "1000,1000,10" << endl; } } #ifdef IMAGEVIEWER if(!imageviewer.wasStopped()) { if(width) { updateImage(); imageviewer.spinOnce(); } } #endif #ifdef TRACKVIEWER if(!imageviewertrack.wasStopped()) { imageviewertrack.showRGBImage(rgb_track,TRACKSIZE,TRACKSIZE); imageviewertrack.spinOnce(); } #endif boost::this_thread::sleep (boost::posix_time::microseconds (10000)); if(!filename_.empty()) viewer.spinOnce(); } #endif if(filename_.empty()) { interface->stop (); } } #ifdef IMAGEVIEWER void updateImage() { boost::mutex::scoped_lock lock (mtx2_); imageviewer.showRGBImage(rgb_buffer,width,height); width = 0; } #endif #ifndef NOVIEWER pcl::visualization::PCLVisualizer viewer; #endif #ifdef IMAGEVIEWER pcl::visualization::ImageViewer imageviewer; unsigned char rgb_buffer[sizeof (char) * 640*480*3]; unsigned int height; unsigned int width; #endif #ifdef TRACKVIEWER pcl::visualization::ImageViewer imageviewertrack; #endif unsigned char rgb_track[sizeof (char) * TRACKSIZE*TRACKSIZE*3]; pcl::PassThrough<pcl::PointXYZRGBA> passx; pcl::PassThrough<pcl::PointXYZRGBA> passy; pcl::PassThrough<pcl::PointXYZRGBA> passz; pcl::EuclideanClusterExtraction<pcl::PointXYZRGBA> ec; LibSerial::SerialStream serial_port; pcl::PCDReader pcd; Eigen::Vector4f origin; Eigen::Quaternionf orientation; int version; pcl::PCLPointCloud2::Ptr pcd_cloud; std::vector<Eigen::VectorXf> centroid_vector_; std::vector<Eigen::VectorXf> centroid_vector; std::string device_id_; std::string filename_; boost::mutex mtx_; boost::mutex mtx2_; CloudConstPtr cloud_; bool saveCloud; unsigned int toggleView; unsigned int filesSaved; }; void usage (char ** argv) { std::cout << "usage: " << argv[0] << " <-device device_id> <-file filename.pcd>\n\n"; openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance (); if (driver.getNumberDevices () > 0) { for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices (); ++deviceIdx) { cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName (deviceIdx) << ", product: " << driver.getProductName (deviceIdx) << ", connected: " << driver.getBus (deviceIdx) << " @ " << driver.getAddress (deviceIdx) << ", serial number: \'" << driver.getSerialNumber (deviceIdx) << "\'" << endl; cout << "device_id may be #1, #2, ... for the first second etc device in the list or" << endl << " bus@address for the device connected to a specific usb-bus / address combination (works only in Linux) or" << endl << " <serial-number> (only in Linux and for devices which provide serial numbers)" << endl; } } else cout << "No devices connected." << endl; } int main (int argc, char ** argv) { std::string filename; std::string device; if ( pcl::console::find_switch(argc, argv, "--help") || pcl::console::find_switch(argc, argv, "-h")) { usage (argv); return 1; } //double threshold = 0.05; //pcl::console::parse_argument (argc, argv, "-thresh", threshold); pcl::console::parse_argument (argc, argv, "-file", filename); if(filename.empty() == FALSE) cout << "filename: " << filename << endl; pcl::console::parse_argument (argc, argv, "-device", device); if(device.empty() == TRUE) device += "#1"; openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance (); if (driver.getNumberDevices () == 0 && filename.empty()) { cout << "No devices connected. No filename." << endl; return 1; } DefconBots22 v (device, filename); v.run (); return (0); }
[ "ryanshoff@gmail.com" ]
ryanshoff@gmail.com
63231e0b40a8580b017415905d13d078632460f2
19eb22e5e3e3578d5798285b925803cdcf125deb
/SDEngine/Source/SDEngine/Shader/GeometryBuffer.h
3495d4932f661e6e6f1e568de1e230855834176c
[]
no_license
2047241149/SDEngine
b17fb90feaeaa1d1b9d44d992f5b2326bd06d460
44ff1e1afdf192136b6f1b96d3e95544e5a7d941
refs/heads/master
2022-03-01T16:01:03.351937
2022-02-19T15:21:20
2022-02-19T15:21:20
129,990,360
62
21
null
2018-09-25T16:27:58
2018-04-18T02:13:04
C++
UTF-8
C++
false
false
1,406
h
#pragma once #ifndef _GEOMETRY_BUFFER_H #define _GEOMETRY_BUFFER_H #include "CoreMinimal.h" enum GBufferType { Diffuse, Pos, Normal, SpecularRoughMetal, Depth, }; const int BUFFER_COUNT = 4; //1- diffuse //2- pos //3- normal //4- specular-rough-metal //另外加一个depthBuffer class GeometryBuffer { private: //G_Buffer ID3D11Texture2D* mRenderTargetTextureArray[BUFFER_COUNT]; ID3D11RenderTargetView* mRenderTargetViewArray[BUFFER_COUNT]; ID3D11ShaderResourceView* mGBufferSRV[BUFFER_COUNT]; //DepthBuffer ID3D11Texture2D* mDepthStencilTexture; ID3D11DepthStencilView* mDepthStencilView; ID3D11ShaderResourceView* mDepthBufferSRV; D3D11_VIEWPORT md3dViewport; int TextureWidth, TextureHeight; //RandomRT ID3D11Texture2D* mRandomTexture; ID3D11ShaderResourceView* mRandomSRV; public: GeometryBuffer(int TextureWidth, int TexureHeight, float ScreenDepth, float ScreenNear); ~GeometryBuffer(); bool Initialize(int TextureWidth, int TexureHeight, float ScreenDepth, float ScreenNear); void ShutDown(); void SetRenderTarget(XMFLOAT3 backColor); void SetDepthTarget(); void ClearDepthBuffer(); void ClearGBuffer(XMFLOAT3 backColor); void ClearRenderTarget(XMFLOAT3 backColor); ID3D11ShaderResourceView* GetGBufferSRV(GBufferType gBufferType); ID3D11ShaderResourceView* GetRandomRTSRV(); ID3D11DepthStencilView* GetDSV(); }; #endif // !_RENDER_3D_MODEL_TO_TEXTURE_H
[ "2047241149@qq.com" ]
2047241149@qq.com
f64f390a00908c652c8354d8097be20bb9d450d2
07bd6d166bfe69f62559d51476ac724c380f932b
/src/cmake-build-debug/devel/include/webots_ros/field_get_count.h
4262f8ce0ee48172d474717b459aebac6e9a4b76
[]
no_license
Dangko/webots_differential_car
0efa45e1d729a14839e6e318da64c7f8398edd17
188fe93c2fb8d2e681b617df78b93dcdf52e09a9
refs/heads/master
2023-06-02T16:40:58.472884
2021-06-14T09:19:58
2021-06-14T09:19:58
376,771,194
1
0
null
null
null
null
UTF-8
C++
false
false
2,840
h
// Generated by gencpp from file webots_ros/field_get_count.msg // DO NOT EDIT! #ifndef WEBOTS_ROS_MESSAGE_FIELD_GET_COUNT_H #define WEBOTS_ROS_MESSAGE_FIELD_GET_COUNT_H #include <ros/service_traits.h> #include <webots_ros/field_get_countRequest.h> #include <webots_ros/field_get_countResponse.h> namespace webots_ros { struct field_get_count { typedef field_get_countRequest Request; typedef field_get_countResponse Response; Request request; Response response; typedef Request RequestType; typedef Response ResponseType; }; // struct field_get_count } // namespace webots_ros namespace ros { namespace service_traits { template<> struct MD5Sum< ::webots_ros::field_get_count > { static const char* value() { return "3e2de6f1a76fa011e87122941131671e"; } static const char* value(const ::webots_ros::field_get_count&) { return value(); } }; template<> struct DataType< ::webots_ros::field_get_count > { static const char* value() { return "webots_ros/field_get_count"; } static const char* value(const ::webots_ros::field_get_count&) { return value(); } }; // service_traits::MD5Sum< ::webots_ros::field_get_countRequest> should match // service_traits::MD5Sum< ::webots_ros::field_get_count > template<> struct MD5Sum< ::webots_ros::field_get_countRequest> { static const char* value() { return MD5Sum< ::webots_ros::field_get_count >::value(); } static const char* value(const ::webots_ros::field_get_countRequest&) { return value(); } }; // service_traits::DataType< ::webots_ros::field_get_countRequest> should match // service_traits::DataType< ::webots_ros::field_get_count > template<> struct DataType< ::webots_ros::field_get_countRequest> { static const char* value() { return DataType< ::webots_ros::field_get_count >::value(); } static const char* value(const ::webots_ros::field_get_countRequest&) { return value(); } }; // service_traits::MD5Sum< ::webots_ros::field_get_countResponse> should match // service_traits::MD5Sum< ::webots_ros::field_get_count > template<> struct MD5Sum< ::webots_ros::field_get_countResponse> { static const char* value() { return MD5Sum< ::webots_ros::field_get_count >::value(); } static const char* value(const ::webots_ros::field_get_countResponse&) { return value(); } }; // service_traits::DataType< ::webots_ros::field_get_countResponse> should match // service_traits::DataType< ::webots_ros::field_get_count > template<> struct DataType< ::webots_ros::field_get_countResponse> { static const char* value() { return DataType< ::webots_ros::field_get_count >::value(); } static const char* value(const ::webots_ros::field_get_countResponse&) { return value(); } }; } // namespace service_traits } // namespace ros #endif // WEBOTS_ROS_MESSAGE_FIELD_GET_COUNT_H
[ "1477055603@qq.com" ]
1477055603@qq.com
58d2328e701312b27463882c7c3086559cfc8597
9ba7c9b0fcccd00813c858d0a24332f99034749a
/src/MkNode.cpp
9895332d379f97184e7c025de82a3a1f792c163a
[]
no_license
jjzhang166/QtLiteNote
ef31152443dae08a0011369efb96e95ff5f5b032
37e5b29cb8ff89ffc3ba72713f11cdd77bf9ab86
refs/heads/master
2021-06-22T05:12:46.497484
2016-11-25T10:32:36
2016-11-25T10:32:36
100,249,079
1
0
null
null
null
null
UTF-8
C++
false
false
14,191
cpp
#include "MkNodePri.h" #include <stdio.h> #include <regex> #include <algorithm> #include <functional> std::string ltrim(const std::string &str) { if (str.empty()) { return str; } size_t index = str.find_first_not_of(" \n\r\t"); if (index >= 0 && index < str.length()) { return str.substr(index); } return str; } std::string rtrim(const std::string &str) { size_t index = str.find_last_not_of(" \n\r\t"); //TODO: return str; } std::string HtmlTagFilter(const std::string &str) { std::string dst = str; // & -> &amp; // < -> &lt; // > -> &gt; // " -> &quot; std::regex reg1("&"); dst = std::regex_replace(dst, reg1, "&amp;"); std::regex reg2("<"); dst = std::regex_replace(dst, reg2, "&lt;"); std::regex reg3(">"); dst = std::regex_replace(dst, reg3, "&gt;"); std::regex reg4("\""); dst = std::regex_replace(dst, reg4, "&quot;"); return dst; } std::string HtmlImageFilter(const std::string &str, const std::string &file_dir) { std::regex pat("!\\[\\]\\((.*)\\)"); std::smatch match; if (std::regex_search(str, match, pat)) { std::string s(match[1]); //printf("%s\n", s.c_str()); char img[1024]; sprintf(img, "<img src=\"file:///%s/%s\"/>", file_dir.c_str(), s.c_str()); return img; } return str; } AnchorNode::AnchorNode() : m_level(0) { } void AnchorNode::AppendCh(AnchorNode* node) { m_children.push_back(node); } MkNode::MkNode() { } MkNode::~MkNode() { } void MkNode::ToString(std::stringstream &stream) { } AnchorNode* MkNode::CreateAnchor(int id) { return NULL; } void MkNode::appendCh(MkNodePtr ch) { m_chNodes.push_back(ch); } HeadNode::HeadNode(int level, const std::string &text) : m_headLevel(level), m_headText(text) { } void HeadNode::ToString(std::stringstream &stream) { char str[1024]; sprintf(str, "<a id=\"%s\"></a>", m_headID.c_str()); stream << str; stream << "<h" << m_headLevel <<">"; stream << m_headText; stream << "</h" << m_headLevel << ">"; } AnchorNode* HeadNode::CreateAnchor(int id) { char str[1024]; sprintf(str, "md_%d", id); m_headID = std::string(str); AnchorNode* a = new AnchorNode; a->m_level = m_headLevel; a->m_anchorID = m_headID; a->m_name = m_headText; return a; } void UlNode::ToString(std::stringstream &stream) { stream << "<ul>"; for (int i = 0; i < m_chNodes.size(); ++i) { m_chNodes[i]->ToString(stream); } stream << "</ul>"; stream << "\n"; } void OlNode::ToString(std::stringstream &stream) { stream << "<ol>"; for (int i = 0; i < m_chNodes.size(); ++i) { m_chNodes[i]->ToString(stream); } stream << "</ol>"; stream << "\n"; } LiNode::LiNode(MkNodePtr txtNode) { m_chNodes.push_back(txtNode); } void LiNode::ToString(std::stringstream &stream) { stream << "<li>"; for (int i = 0; i < m_chNodes.size(); ++i) { m_chNodes[i]->ToString(stream); } stream << "</li>"; } void CodeNode::ToString(std::stringstream &stream) { stream << "<pre><code>"; for (int i = 0; i < m_codeText.size(); ++i) { stream << HtmlTagFilter(m_codeText[i]); stream << "<br/>"; } stream << "</pre></code>"; } void CodeNode::AppendCode(const std::string &text) { m_codeText.push_back(text); } TextNode::TextNode(const std::string &text, const std::string &file_dir) : m_text(text), m_file_dir(file_dir) { } void TextNode::ToString(std::stringstream &stream) { std::string text = HtmlTagFilter(m_text); text = HtmlImageFilter(text, m_file_dir); stream << text; stream << "<br/>"; } //////////////////////////////////////////// MkContent::MkContent(const std::string &file_dir) : m_file_dir(file_dir) { } void MkContent::AppendTop(MkNodePtr node) { m_tops.push_back(node); } void MkContent::AppendLi(MkNodePtr li) { m_tops.back()->appendCh(li); } void MkContent::LiAppendCodeNode(MkNodePtr codeNode) { m_tops.back()->m_chNodes.back()->appendCh(codeNode); } void MkContent::LiAppendCodeContent(const std::string &text) { MkNodePtr ptr = m_tops.back()->m_chNodes.back()->m_chNodes.back(); CodeNode *code = (CodeNode*)ptr.get(); code->AppendCode(text); } void MkContent::LiAppendText(const std::string &text) { MkNodePtr ptr = m_tops.back()->m_chNodes.back(); MkNode *p = ptr.get(); LiNode *li = (LiNode*)p; MkNodePtr txtNode(new TextNode(text, m_file_dir)); li->appendCh(txtNode); } void MkContent::AppendCodeContent(const std::string &text) { MkNodePtr ptr = m_tops.back(); CodeNode *code = (CodeNode*)ptr.get(); code->AppendCode(text); } void MkContent::ToString(std::stringstream &stream) { for (int i = 0; i < m_tops.size(); ++i) { m_tops[i]->ToString(stream); } } AnchorNode* MkContent::CreateMkLevel() { std::vector<AnchorNode*> heads; int headID = 0; for (int i = 0; i < m_tops.size(); ++i) { AnchorNode* a = m_tops[i]->CreateAnchor(headID); if (a) { heads.push_back(a); ++headID; } } AnchorNode* n = CreateTree(heads); return n; } AnchorNode* MkContent::CreateTree(std::vector<AnchorNode*> &heads) { std::vector<AnchorNode*> cc; cc.resize(7, NULL); cc[0] = new AnchorNode; for (int i = 0; i < heads.size(); ++i) { int level = heads[i]->m_level; AnchorNode *an; int ii = level - 1; while (ii >= 0) { if (cc[ii]) { an = cc[ii]; break; } --ii; } an->AppendCh(heads[i]); cc[level] = heads[i]; for (int ii = level+1; ii < 7; ++ii) { cc[ii] = NULL; } } return cc[0]; } ////////////////////////////////////////////// // MkSyntax MkSyntax::MkSyntax(std::vector<std::string> &lines, const std::string &file_dir) : m_lines(lines), m_file_dir(file_dir), m_content(file_dir) { } void MkSyntax::Analyse() { int stat = 0; int i = -1; while (1) { ++i; //printf("lineNum: %d\n", i); if (m_lines.size() == i) break; bool haveAct = false; if (stat == 0) { haveAct = ActionTop(i, stat); } else if (stat == 1) { ActionUl(i, stat); haveAct = true; } else if (stat == 2) { ActionOl(i, stat); haveAct = true; } else if (stat == 3) { if (IsCodeLine(i)) { stat = 0; } else { m_content.AppendCodeContent(m_lines[i]); } haveAct = true; } else if (stat == 13) { ActionUlCode(i, stat); haveAct = true; } else if (stat == 23) { ActionOlCode(i, stat); haveAct = true; } if (!haveAct) { const std::string &line = m_lines[i]; if (line.length() > 0) { MkNodePtr txtNode(new TextNode(line, m_file_dir)); m_content.AppendTop(txtNode); } } } } AnchorNode* MkSyntax::GetMkContent() { return m_content.CreateMkLevel(); } void MkSyntax::ToString(std::stringstream &stream) { m_content.ToString(stream); } bool MkSyntax::ActionTop(int i, int &stat) { std::pair<int, std::string> head = GetHeadLevel(i); int headLevel = head.first; std::string text = head.second; if (headLevel >= 1 && headLevel <= 6 && !text.empty()) { MkNodePtr headNode(new HeadNode(headLevel, text)); m_content.AppendTop(headNode); return true; } std::pair<bool, std::string> r = GetUlItem(i); bool isUl = r.first; text = r.second; if (isUl) { MkNodePtr ul(new UlNode()); MkNodePtr txtNode(new TextNode(text, m_file_dir)); MkNodePtr li(new LiNode(txtNode)); ul->appendCh(li); m_content.AppendTop(ul); stat = 1; return true; } r = GetOlItem(i); bool isOl = r.first; text = r.second; if (isOl) { MkNodePtr ol(new OlNode); MkNodePtr txtNode(new TextNode(text, m_file_dir)); MkNodePtr li(new LiNode(txtNode)); ol->appendCh(li); m_content.AppendTop(ol); stat = 2; return true; } if (IsCodeLine(i)) { MkNodePtr code(new CodeNode); m_content.AppendTop(code); stat = 3; return true; } return false; } void MkSyntax::ActionUl(int &i, int &stat) { std::pair<bool, std::string> r = GetUlItem(i); bool isUl = r.first; std::string &text = r.second; if (isUl) { MkNodePtr txtNode(new TextNode(text, m_file_dir)); MkNodePtr li(new LiNode(txtNode)); m_content.AppendLi(li); return; } if (IsTabCodeLine(i)) { MkNodePtr code(new CodeNode); m_content.LiAppendCodeNode(code); stat = 13; return; } r = GetTabStart(i); bool isTab = r.first; if (isTab) { m_content.LiAppendText(text); } else { stat = 0; --i; } } void MkSyntax::ActionOl(int &i, int &stat) { std::pair<bool, std::string> r = GetOlItem(i); if (r.first) { MkNodePtr txtNode(new TextNode(r.second, m_file_dir)); MkNodePtr li(new LiNode(txtNode)); m_content.AppendLi(li); return; } if (IsTabCodeLine(i)) { MkNodePtr code(new CodeNode); m_content.LiAppendCodeNode(code); stat = 23; return; } r = GetTabStart(i); bool isTab = r.first; if (isTab) { m_content.LiAppendText(r.second); } else { stat = 0; --i; } } void MkSyntax::ActionUlCode(int &i, int &stat) { if (IsTabCodeLine(i)) { stat = 1; return; } if (m_lines[i].empty()) { m_content.LiAppendCodeContent(" "); return; } std::pair<bool, std::string> r = GetTabStart(i); if (r.first) { m_content.LiAppendCodeContent(r.second); } else { stat = 1; --i; } } void MkSyntax::ActionOlCode(int &i, int &stat) { if (IsTabCodeLine(i)) { stat = 2; return; } if (m_lines[i].empty()) { m_content.LiAppendCodeContent(" "); return; } std::pair<bool, std::string> r = GetTabStart(i); bool isTab = r.first; std::string &text = r.second; if (isTab) { m_content.LiAppendCodeContent(text); } else { stat = 2; --i; } } std::pair<int, std::string> MkSyntax::GetHeadLevel(int i) { std::string &line = m_lines[i]; std::regex pat("^#+"); std::smatch match; if (std::regex_search(line, match, pat)) { std::ssub_match suf = match.suffix(); std::ssub_match pre = match.prefix(); std::string h(pre.first, suf.first); std::string after(suf.first, suf.second); after = ltrim(after); return std::make_pair(h.size(), after); } return std::make_pair(0, ""); } std::pair<bool, std::string> MkSyntax::GetUlItem(int i) { return SplitStartItem(i, "^\\* "); } std::pair<bool, std::string> MkSyntax::GetOlItem(int i) { return SplitStartItem(i, "^[0-9]+\\. "); } std::pair<bool, std::string> MkSyntax::SplitStartItem(int i, std::string pat) { std::string &line = m_lines[i]; std::regex reg(pat); std::smatch match; if (std::regex_search(line, match, reg)) { std::ssub_match suf = match.suffix(); std::string after(suf.first, suf.second); after = ltrim(after); return std::make_pair(true, after); } return std::make_pair(false, ""); } std::pair<bool, std::string> MkSyntax::GetTabStart(int i) { std::string &line = m_lines[i]; if (line.size() >= 2 && line[0] == '\t') { return std::make_pair(true, line.substr(1)); } if (line.size() >= 5 && line.substr(0, 4) == " ") { return std::make_pair(true, line.substr(4)); } return std::make_pair(false, ""); } bool MkSyntax::IsCodeLine(int i) { std::string &line = m_lines[i]; if (line == "```") { return true; } return false; } bool MkSyntax::IsTabCodeLine(int i) { std::string &line = m_lines[i]; if (line.size() == 4) { if (line[0] == '\t' && line.substr(1, 3) == "```") { return true; } } if (line.size() == 7) { if (line.substr(0, 4) == " " && line.substr(4, 3) == "```") { return true; } } return false; } const char *css_templ = "<html>" "<head>" " <meta http-equiv=\"content-type\" content=\"text/html;charset=UTF-8\">" " <style type=\"text/css\">" " body { color: #444444; font-size:%dpt; line-height:1.4; word-wrap: break-word; font-family: DejaVu Sans Mono, \\5FAE\\8F6F\\96C5\\9ED1; }" " h1, h2, h3, h4 { color: #111111; font-weight: bold; margin-top:3pt;margin-bottom:3pt;}" " h1 { font-size: %dpt; border-bottom: 1pt solid; color: #D6615C; }" " h2 { font-size: %dpt; font-weight: bold; color: #2F517B; }" " h3 { font-size: %dpt; font-style: italic; }" " h4 { font-size: %dpt; font-style: italic; }" " h5 { font-size: %dpt; font-style: italic; }" " h6 { font-size: %dpt; font-style: italic; }" " a { color: #0099ff; margin: 0; padding: 0; vertical-align: baseline; }" " a:link, a:visited { text-decoration: none; }" " a:hover { text-decoration: underline; }" " br {display:inline;}" " pre { padding: 4pt; max-width: 100%%white-space; line-height: 1.5; font-size: %dpt; border: 1pt solid #ddd; background-color: #f7f7f7; }" " code { font-family: DejaVu Sans Mono, \\5FAE\\8F6F\\96C5\\9ED1; line-height: 1.5; font-size: %dpt; background-color: #f7f7f7; }" " td, th { border: 1pt solid #ccc; padding: 5pt; }" " aside { display: block; float: right; width: 100%%; }" " blockquote { border-left: .5em solid #40AA53; padding: 0 2em; margin-left: 0; max-width: 100%%; }" " blockquote cite { font-size: %dpt; line-height: 1.5; color: #bfbfbf; }" " blockquote p { color: #666; max-width: 100%%; }" " table { border-spacing: 0; border: 1pt; solid #ccc; }" " </style>" "</head>" "<body><p/>"; // %d std::pair<std::string, AnchorNode*> SyntaxMk(std::vector<std::string> &lines, const std::string &file_dir, int font_size) { size_t len = strlen(css_templ); char *str = new char[len+1024]; int len2 = strlen(str); int diff = 1; sprintf(str, css_templ, font_size, font_size+diff*5, font_size+diff*4, font_size+diff*3, font_size+diff*2, font_size+diff, font_size, font_size-diff, font_size-diff, font_size-diff); MkSyntax syn(lines, file_dir); syn.Analyse(); AnchorNode *node = syn.GetMkContent(); std::stringstream stream; stream << str; delete [] str; syn.ToString(stream); stream << "</body></html>"; return std::make_pair(stream.str(), node); } void ReleaseAnchorNode(AnchorNode *node) { if (node) { for (int i = 0; i < node->m_children.size(); ++i) { ReleaseAnchorNode(node->m_children[i]); } delete node; } }
[ "327340773@qq.com" ]
327340773@qq.com
c75c3f9de2a5e18cbed162f090418cd2fd3269eb
7e6e45fc43fcfaf3a7ac84197a6629ea0215a138
/15649.cpp
01488131713614518abc8fd52a2af06e6387ad73
[]
no_license
calm-lab/online-judge
cb2719c010480c833caa169977db9e19d091236f
92da8776fec4d7835f9b6e6eb0b034c63709b356
refs/heads/master
2023-06-09T09:03:31.080759
2021-06-29T06:52:55
2021-06-29T06:52:55
371,567,818
1
0
null
null
null
null
UTF-8
C++
false
false
1,286
cpp
#include <iostream> using namespace std; bool c[10];//중복을 처리할 배열.true: 고른 숫자, false: 고르지 않은 숫자 int a[10];//고른 수열을 저장할 배열 void go(int index, int n, int m){ if(index == m){//인덱스와 m이 같다라는 의미는 0부터 index-1까지 이미 앞에서 수열이 만들어졌으므로 for(int i = 0; i < m; i++){ //답을 출력한다 cout << a[i]; if(i != m - 1) cout << ' ';//수열을 공백으로 구분하기 위함 } cout << '\n'; return; } for (int i = 1; i <= n; i++){//1부터 N까지 자연수이므로... if (c[i]) continue;//c[i]가 true라면 이미 그 값은 사용한 것이므로 다음 루프를 진행 c[i] = true; //i숫자를 선택할 것이므로 c[i]를 true로 수정. a[index] = i;//선택한 숫자를 a[index]에 저장한다. go(index + 1, n, m);//재귀함수. index를 하나씩 올려 다음 저장할 수를 찾는다. c[i] = false; //이 부분을 반드시 해주어야 함. 선택을 안한 상태로 다시 다음 i를 처음부터 수열을 만들어야 하기 때문 } } int main(){ int m,n; cin >> n >> m; go(0, n, m);//index를 0부터 시작한다 return 0; }
[ "opmina72@naver.com" ]
opmina72@naver.com
1491baa7632b964435da9bb6b0f67f99f2857667
394374ca6a617ff5e152bd9eb249531c57eb70a8
/ZOJ/3499.cpp
b8024c4c30809be499464f523bb1b9983695da5b
[]
no_license
WzDTj/Keep-Coding
83330b761a3ff0673ec53e7d7b85259073040ae6
5fd6d997cfc8a36494ef6d39ac012c93b71c7d56
refs/heads/master
2021-01-10T14:35:06.546100
2017-03-30T15:18:24
2017-03-30T15:18:24
46,961,963
0
0
null
null
null
null
UTF-8
C++
false
false
600
cpp
#include <cstdio> #include <cstdlib> int cmp(const void *a, const void *b) { return ((*(double *) a - *(double *) b > 0) ? 1 : -1); } int main() { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); #endif const int MAX_LENGTH = 500; double number[MAX_LENGTH]; int t, n; scanf("%d", &t); while (t -- && scanf("%d", &n)) { for (int i = 0; i < n; ++i) scanf("%lf", &number[i]); qsort(number, n, sizeof(double), cmp); if (n%2) printf("%.3lf\n", number[n/2]); else printf("%.3lf\n", (number[n/2-1]+number[n/2])/2); } return 0; }
[ "j.dantong@gmail.com" ]
j.dantong@gmail.com
f517c35ceef45eade97018e05ee9b1d0d5ea1485
49ca92c13ad17c5aea082cc9c60e632bc85cf6d4
/SRC/UI/AniEditDM_UI.h
f58dabc6be2b6ccf40fa96f439c486aa2416300b
[ "Apache-2.0" ]
permissive
simba518/AniEditor
8677db3d26a9b383870f414c45b489ea3498ea6c
50f1af36ecc3fdca01fbd65468e2aecca521cbef
refs/heads/master
2016-09-05T14:43:02.870927
2014-08-22T07:17:53
2014-08-22T07:17:53
12,777,605
0
1
null
null
null
null
UTF-8
C++
false
false
3,239
h
#ifndef _ANIEDITDM_UI_H_ #define _ANIEDITDM_UI_H_ #include <QObject> #include <QtGui/QMainWindow> #include <FileDialog.h> #include "AniEditDM.h" using namespace QGLVEXT; namespace ANI_EDIT_UI{ #define ANIEDITDM_SAVE(functionName) \ const string fname = file_dialog->save(); \ if(fname.size() >0){ \ file_dialog->warning(data_model!=NULL&&data_model->functionName(fname)); \ } #define ANIEDITDM_LOAD(functionName) \ const string fname = file_dialog->load(); \ if(fname.size() >0){ \ file_dialog->warning(data_model!=NULL&&data_model->functionName(fname)); \ emit update(); \ } class AniEditDM_UI:public QObject{ Q_OBJECT public: AniEditDM_UI(QMainWindow *main_win, pAniEditDM data_model): data_model(data_model){ this->file_dialog = pFileDialog(new FileDialog(main_win)); } public slots: void toggleWarp(){ if(data_model){ data_model->useWarp( !(data_model->isUseWarp()) ); emit update(); } } void interpolate(){ file_dialog->warning(data_model != NULL && data_model->interpolate()); } void toggleInterpolate(){ if (data_model) data_model->toggleInterpolate(); } void removeAllPosCon(){ if (data_model) data_model->removeAllPosCon(); } void clearAdditionalAni(){ if (data_model) data_model->clearAdditionalAni(); } void saveParitalCon()const{ANIEDITDM_SAVE(saveParitalCon);} void saveOutputVolMeshesVTK()const{ANIEDITDM_SAVE(saveOutputVolMeshesVTK);} void saveOutputObjMeshesVTK()const{ANIEDITDM_SAVE(saveOutputObjMeshesVTK);} void saveAdditionalAniObjMeshesVTK()const{ANIEDITDM_SAVE(saveAdditionalAniObjMeshesVTK);} void saveAdditionalAniObjMeshes()const{ANIEDITDM_SAVE(saveAdditionalAniObjMeshes);} void saveOutputMeshes()const{ANIEDITDM_SAVE(saveOutputMeshes);} void saveInputMeshes()const{ANIEDITDM_SAVE(saveInputMeshes);} void saveCurrentOutputMesh()const{ANIEDITDM_SAVE(saveCurrentOutputMesh);} void saveCurrentInputMesh()const{ANIEDITDM_SAVE(saveCurrentInputMesh);} void saveCurrentOutputVolMesh(){ANIEDITDM_SAVE(saveCurrentOutputVolMesh);} void saveVolFullU()const{ANIEDITDM_SAVE(saveVolFullU);} void saveCurrentReducedEdits()const{ANIEDITDM_SAVE(saveCurrentReducedEdits);} void saveAllReducedEdits()const{ANIEDITDM_SAVE(saveAllReducedEdits);} void saveCurrentVolFullU()const{ANIEDITDM_SAVE(saveCurrentVolFullU);} void saveSceneSequence()const{ANIEDITDM_SAVE(saveSceneSequence);} void saveSceneSequenceVTK()const{ANIEDITDM_SAVE(saveSceneSequenceVTK);} void savePartialConBalls()const{ANIEDITDM_SAVE(savePartialConBalls);} void loadParitalCon(){ANIEDITDM_LOAD(loadParitalCon);} void loadConPath(){ANIEDITDM_LOAD(loadConPath);} void loadCurrentReducedEdits(){ANIEDITDM_LOAD(loadCurrentReducedEdits);} void loadAllReducedEdits(){ANIEDITDM_LOAD(loadAllReducedEdits);} void loadAnimation(){ANIEDITDM_LOAD(loadAnimation);} void printEigenValues()const{ if (data_model && data_model->getInterpolator()){ data_model->getInterpolator()->print("eigenvalues"); } } signals: void update(); private: pAniEditDM data_model; pFileDialog file_dialog; }; typedef boost::shared_ptr<AniEditDM_UI> pAniEditDM_UI; }//end of namespace #endif /*_ANIEDITDM_UI_H_*/
[ "=" ]
=
22b11086521f2ff3eb7a64f86e7cf3304243a962
2574df7ba3d4659fc7db3184d14d4dead7678f91
/ListeGOD.h
5895a1b9fab6bc0bf6accc3e81366218714e2f19
[]
no_license
BodySplash/bomberman
a761448eb5e65091e794a70cd9d3cf7cbbef7f54
423bf66c66d448557fb5fb4128f00957b4a9d419
refs/heads/master
2021-01-10T19:00:33.077294
2012-02-20T10:20:31
2012-02-20T10:20:31
3,492,703
1
0
null
null
null
null
UTF-8
C++
false
false
88
h
#pragma once class CListeGOD { public: CListeGOD(void); ~CListeGOD(void); };
[ "bodysplash@gmail.com" ]
bodysplash@gmail.com
997f889d03eec92182cf5e54f4221aa32443a478
8422912ae3866de3f8792b68f38d90fff40815d3
/tests/benchmarks/mmff-energy/mmffenergybenchmark.cpp
e58e824eb1803efec4c7056a8f75041301b1cf20
[ "BSD-3-Clause" ]
permissive
smrhh42/chemkit
7bf1e6d302cf5d04812d1772d0f847b6578e8c5c
94a9680042fb9d5381d52ef96ac6e13cd985a463
refs/heads/master
2021-01-18T13:32:38.822079
2012-04-02T01:30:39
2012-04-02T01:30:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,937
cpp
/****************************************************************************** ** ** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com> ** All rights reserved. ** ** This file is a part of the chemkit project. For more information ** see <http://www.chemkit.org>. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** * Neither the name of the chemkit project nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ******************************************************************************/ #include "mmffenergybenchmark.h" #include <chemkit/molecule.h> #include <chemkit/forcefield.h> #include <chemkit/moleculefile.h> const std::string dataPath = "../../data/"; void MmffEnergyBenchmark::benchmark() { // load test file chemkit::MoleculeFile file(dataPath + "MMFF94_hypervalent.mol2"); bool ok = file.read(); if(!ok) qDebug() << file.errorString().c_str(); QVERIFY(ok); // total energy of all 753 molecules double totalEnergy = 0; QBENCHMARK_ONCE { chemkit::ForceField *forceField = chemkit::ForceField::create("mmff"); foreach(const boost::shared_ptr<chemkit::Molecule> &molecule, file.molecules()){ QVERIFY(forceField); forceField->setMolecule(molecule.get()); forceField->setup(); //QVERIFY(forceField->isSetup()); totalEnergy += forceField->energy(); } delete forceField; } // expected total energy = 5228.05954 QCOMPARE(qRound(totalEnergy), 5228); } QTEST_APPLESS_MAIN(MmffEnergyBenchmark)
[ "kyle.r.lutz@gmail.com" ]
kyle.r.lutz@gmail.com
ae9eba990bc669b9462fc848b1ca780060868b18
5ba58b1c3816f6779d46e60ee7fb9f0de827074c
/中序遍历递归.cpp
626cb3e2aece45103670237b9450d1024ea99223
[]
no_license
yunruowu/LeetCode
9a3b3d4ce7c4c6a428995dce0ff94205b39bf80c
217884f33c0a3f8414583583cb4293886a0a577f
refs/heads/master
2020-12-01T01:58:34.236588
2020-09-28T07:20:18
2020-09-28T07:20:18
230,535,728
2
0
null
null
null
null
UTF-8
C++
false
false
1,239
cpp
/** * Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; */ #include <iostream> #include <vector> #include <stack> #include <string> #include <stdlib.h> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: vector<int> inorderTraversal(TreeNode *root) { vector<int> ans; stack<TreeNode*> st; if(root==NULL){ return ans; } st.push(root); int tag = 0; while(!st.empty()){ while(st.top()->left!=NULL&&tag==0){ st.push(st.top()->left); } if(st.top()->right!=NULL){ TreeNode* croot = st.top(); st.pop(); ans.push_back(croot->val); st.push (croot->right); tag=0; }else{ TreeNode* croot = st.top(); st.pop(); ans.push_back(croot->val); tag =1; } } return ans; } };
[ "mcdxwan@outlook.com" ]
mcdxwan@outlook.com
3144b95d81b463d81505fbc8473cd48a5de39474
a202b62726204f62141ea0de4cdd29edf94281da
/demo/ios/Pods/hippy/core/base/macros.h
932050ef268e1a091914904c5b3c4f038a6bf286
[ "Apache-2.0", "MIT" ]
permissive
hippy-contrib/hippy-react-ui
8145dd7d5fbdc9352e479f3ea1efbcc48cc90415
e3446b75a098b6f200a2c56f32078ab3b83e0e28
refs/heads/master
2023-03-23T20:16:41.113313
2020-04-23T13:59:05
2020-04-23T13:59:05
258,219,692
8
0
MIT
2021-03-12T12:31:10
2020-04-23T13:46:26
JavaScript
UTF-8
C++
false
false
1,489
h
/* * * Tencent is pleased to support the open source community by making * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * 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 CORE_BASE_MACROS_H_ #define CORE_BASE_MACROS_H_ #include <stddef.h> // Suppress UNUSED warnings #define HIPPY_USE(expr) \ do { \ (void)(expr); \ } while (0) // Calculate size of array #define arraysize(array) (sizeof(ArraySizeHelper(array))) template <typename T, size_t N> char (&ArraySizeHelper(T (&array)[N]))[N]; // Suppress copy #define DISALLOW_COPY_AND_ASSIGN(Type) \ Type(const Type&) = delete; \ Type& operator=(const Type&) = delete // Enable move and suppress copy #define MOVE_ONLY(Type) \ Type(Type&&) noexcept = default; \ Type& operator=(Type&&) noexcept = default; \ DISALLOW_COPY_AND_ASSIGN(Type) #endif // CORE_BASE_MACROS_H_
[ "kiddxu@tencent.com" ]
kiddxu@tencent.com
000f4a4cef683e0427f7511b11a0f15e8a5c6ae1
7ff34a99d91f13b345a93296e20b0b45140024fc
/Поехали/Klad.h
cc997988f9dfa591a047a5c45c0d762821b85967
[]
no_license
Kirilcha/PROC
e95f8e2a51121bf3c0da91e4daee26676548f0be
215acaeceef2b9d4ffc40e3e3f7f38bdf07f59c8
refs/heads/master
2021-05-05T11:10:47.617090
2018-03-06T17:23:32
2018-03-06T17:23:32
118,119,202
0
0
null
2018-02-27T14:29:36
2018-01-19T11:49:59
C++
UTF-8
C++
false
false
253
h
#ifndef _Klad_ #define _Klad_ #include "Aforizm.h" #include "Posl_Pogov.h" #include <string> struct Kladez { enum key { AFORIZM, POSL_P, ZAGADKI }; key key; int kol; std::string fraza; union { Aforizm afor; Poslovica_P poslov; }; }; #endif
[ "33288427+Kirilcha@users.noreply.github.com" ]
33288427+Kirilcha@users.noreply.github.com
294bae035e0a3cabed420a22cfc8d759bac18487
f8af03d378ad26359517d8d1de429d210bc9b441
/src/unit-test/common/main.cc
0e7d9f5b2fc95b859d704968c084d1b56c3c1301
[]
no_license
bud-adamas/ccraft
6a4c85669093d634b7d1e99353b5086e4d91539a
2bc3eba607592f3f84f61f68069b25b5d26258b9
refs/heads/master
2021-06-21T03:15:06.819028
2017-09-03T12:35:03
2017-09-03T12:35:03
101,495,568
0
0
null
2017-08-26T15:44:43
2017-08-26T15:44:43
null
UTF-8
C++
false
false
1,248
cc
/** * This work copyright Chao Sun(qq:296449610) and licensed under * a Creative Commons Attribution 3.0 Unported License(https://creativecommons.org/licenses/by/3.0/). */ #include <string> #include <gtest/gtest.h> #include "../../common/hash-algorithms.h" #include "../../common/common-def.h" #include "../../common/common-utils.h" using namespace ccraft::common; int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); ccraft::common::initialize(); return RUN_ALL_TESTS(); } TEST(CommonTest, HashTest) { std::string key = "hashtest"; uint32_t hashcode1; MurmurHash3_x86_32(key.c_str(), (int) (key.length()), 22, &hashcode1); EXPECT_GT(hashcode1, uint32_t(0)); uint32_t hashcode2; MurmurHash3_x86_32(key.c_str(), (int) (key.length()), 22, &hashcode2); EXPECT_EQ(hashcode1, hashcode2); } TEST(CommonTest, ClockTest) { auto curTime = CommonUtils::GetCurrentTime(); EXPECT_NE(curTime.sec, -1); } TEST(CommonTest, SpinLockTest) { spin_lock_t l = UNLOCKED; SpinLock sl(&l, false); EXPECT_EQ(sl.TryLock(), true); SpinLock sl2(&l, false); EXPECT_EQ(sl2.TryLock(), false); sl.Unlock(); SpinLock sl3(&l, false); EXPECT_EQ(sl3.TryLock(), true); }
[ "sunchao7" ]
sunchao7
6fc380221cf80f3b200012b21d047c2ea59586b6
fb22e1687613aceff4d4d3a2c041cf2446d18c2f
/VAttemperServer/DDSDebug/include/RTPS/ParticipantAgent.h
9a42637ccecf225b525223467a938100f4d4778d
[]
no_license
gh2510/QtWorkSpace
5fc8173b8cf19557bb0ad90ff377270ebc3685c9
4c9a477b43ad8749771c7ffcc73794427ffbfa34
refs/heads/master
2021-01-19T18:29:32.161505
2017-08-23T13:46:01
2017-08-23T13:46:01
101,142,041
0
0
null
null
null
null
GB18030
C++
false
false
2,065
h
/************************************************************ ** 文件名:ParticipantAgent.h ** Copyright (c) 2011-2012 中国船舶工业系统工程研究院 ** 创建人:杨猛<635584332@qq.com> ** 日 期:2011-01-11 ** 修改人:无 ** 日 期:无 ** 描 述:ParticipantAgent头文件 ** 版 本:Version 0.1 **---------------------------------------------------------- ************************************************************/ #ifndef _DDS_ParticipantAGENT_H_INCLUDED_ #define _DDS_ParticipantAGENT_H_INCLUDED_ #include "dds/Agent.h" #include "rtps/ParticipantDataReader.h" #include "rtps/ParticipantDataWriter.h" class DataWriter; class DataReader; class DomainParticipant; class Topic; class DataWriterListener; class DataReaderListener; class Publisher; class Subscriber; class ParticipantAgent : public Agent { public: ParticipantAgent(DomainParticipant *pDomainParticipant, string strName) : Agent(pDomainParticipant, strName) { } virtual ~ParticipantAgent() {} DataWriter *CreateDataWriter(Topic* pTopic, const _DATA_WRITER_QOS *pQos, DataWriterListener* pListener, _STATUS_MASK Mask, Publisher* pPublisher, unsigned long ulCacheLength) { DataWriter *pNewDataWriter = new ParticipantDataWriter(pTopic, pQos, pListener, Mask, pPublisher, ulCacheLength); return pNewDataWriter; } DataReader *CreateDataReader(TopicDescription* pTopic, const _DATA_READER_QOS *pQos, DataReaderListener* pListener, _STATUS_MASK Mask, Subscriber* pSubscriber, unsigned long ulCacheLength) { DataReader *pNewDataReader = new ParticipantDataReader(pTopic, pQos, pListener, Mask, pSubscriber, ulCacheLength); return pNewDataReader; } }; #endif
[ "gh2510@163.com" ]
gh2510@163.com
de0b7b2b24ad4ae10f88b2eb508078fb33569cfe
4d9c741a31edae00908e781b3cd9f033037a38a2
/geeksforgeeks/1278.cpp
05b5cef3cbda10bd6f06f9623b52bf14a65a9104
[]
no_license
LavishKothari/MyAllCodes---Lavish
eebff25b762748e715122b383630b456f41bd17c
73786bb44531b06c63a94048f4c0f9c8982dc36e
refs/heads/master
2020-04-06T10:01:37.207045
2019-04-15T18:50:27
2019-04-15T18:50:27
20,599,188
0
0
null
null
null
null
UTF-8
C++
false
false
2,894
cpp
/* problem link : http://www.practice.geeksforgeeks.org/problem-page.php?pid=1278 */ #include <bits/stdc++.h> using namespace std; vector<string>result; void printall(string current,int start,vector< vector<int> >&graph,string &s) { if(start==graph.size()-1) result.push_back(current.substr(0,current.size()-1)); else for(int i=0;i<graph[start].size();i++) printall(current+s.substr(start+1,graph[start][i]-start)+" ",graph[start][i],graph,s); } void printAllPossible(string &s,set<string>&dict) { vector< vector<int> >table(s.size(),vector<int>()); for(int i=0;i<s.size();i++) { if(/*table[i].size()==0 && */dict.find(s.substr(0,i+1))!=dict.end()) table[i].push_back(-1); if(table[i].size()!=0) for(int j=i+1;j<s.size();j++) if(dict.find(s.substr(i+1,j-i))!=dict.end()) table[j].push_back(i); } if(table[s.size()-1].size()==0) { cout<<"Empty"<<endl; return; } // constructing the complement of the graph. vector< vector<int> >graph(s.size(),vector<int>()); vector<int> start; for(int i=0;i<s.size();i++) for(int j=0;j<table[i].size();j++) if(table[i][j]!=-1) graph[table[i][j]].push_back(i); else start.push_back(i); for(int i=0;i<start.size();i++) printall(s.substr(0,start[i]+1)+" ",start[i],graph,s); sort(result.begin(),result.end()); for(int i=0;i<result.size();i++) cout <<"("<<result[i]<<")"; cout<<endl; } int main() { int t; scanf("%d",&t); while(t--) { result.erase(result.begin(),result.end()); int n; scanf("%d",&n); set<string>dict; for(int i=0;i<n;i++) { string temp; cin>>temp; dict.insert(temp); } string str; cin>>str; printAllPossible(str,dict); } return 0; } /* Input: 9 x i like man go mango easy mangoeasy likemangoeasyx ilikemangoeasyx Output: (i like man go easy x) (i like mango easy x) (i like mangoeasy x) (i likemangoeasyx) ///////////////////////////////////////////// Input: 4 qscdx mowfr qscdxmowfr jy qscdxmowfrqscdxmowfrqscdxmowfrmowfrqscdxmowfr Output: (in one single line) (qscdx mowfr qscdx mowfr qscdx mowfr mowfr qscdx mowfr) (qscdx mowfr qscdx mowfr qscdx mowfr mowfr qscdxmowfr) (qscdx mowfr qscdx mowfr qscdxmowfr mowfr qscdx mowfr) (qscdx mowfr qscdx mowfr qscdxmowfr mowfr qscdxmowfr) (qscdx mowfr qscdxmowfr qscdx mowfr mowfr qscdx mowfr) (qscdx mowfr qscdxmowfr qscdx mowfr mowfr qscdxmowfr) (qscdx mowfr qscdxmowfr qscdxmowfr mowfr qscdx mowfr) (qscdx mowfr qscdxmowfr qscdxmowfr mowfr qscdxmowfr) (qscdxmowfr qscdx mowfr qscdx mowfr mowfr qscdx mowfr) (qscdxmowfr qscdx mowfr qscdx mowfr mowfr qscdxmowfr) (qscdxmowfr qscdx mowfr qscdxmowfr mowfr qscdx mowfr) (qscdxmowfr qscdx mowfr qscdxmowfr mowfr qscdxmowfr) (qscdxmowfr qscdxmowfr qscdx mowfr mowfr qscdx mowfr) (qscdxmowfr qscdxmowfr qscdx mowfr mowfr qscdxmowfr) (qscdxmowfr qscdxmowfr qscdxmowfr mowfr qscdx mowfr) (qscdxmowfr qscdxmowfr qscdxmowfr mowfr qscdxmowfr) */
[ "lavishkothari004@gmail.com" ]
lavishkothari004@gmail.com
45de2a454a85b9074a477bc3627305631e03aa9d
1dbf007249acad6038d2aaa1751cbde7e7842c53
/gaussdbforopengauss/include/huaweicloud/gaussdbforopengauss/v3/model/CreateDbUserResponse.h
b00e0911196e6808a0f4b68c06d7f1384f59f00e
[]
permissive
huaweicloud/huaweicloud-sdk-cpp-v3
24fc8d93c922598376bdb7d009e12378dff5dd20
71674f4afbb0cd5950f880ec516cfabcde71afe4
refs/heads/master
2023-08-04T19:37:47.187698
2023-08-03T08:25:43
2023-08-03T08:25:43
324,328,641
11
10
Apache-2.0
2021-06-24T07:25:26
2020-12-25T09:11:43
C++
UTF-8
C++
false
false
1,218
h
#ifndef HUAWEICLOUD_SDK_GAUSSDBFOROPENGAUSS_V3_MODEL_CreateDbUserResponse_H_ #define HUAWEICLOUD_SDK_GAUSSDBFOROPENGAUSS_V3_MODEL_CreateDbUserResponse_H_ #include <huaweicloud/gaussdbforopengauss/v3/GaussDBforopenGaussExport.h> #include <huaweicloud/core/utils/ModelBase.h> #include <huaweicloud/core/http/HttpResponse.h> namespace HuaweiCloud { namespace Sdk { namespace Gaussdbforopengauss { namespace V3 { namespace Model { using namespace HuaweiCloud::Sdk::Core::Utils; using namespace HuaweiCloud::Sdk::Core::Http; /// <summary> /// Response Object /// </summary> class HUAWEICLOUD_GAUSSDBFOROPENGAUSS_V3_EXPORT CreateDbUserResponse : public ModelBase, public HttpResponse { public: CreateDbUserResponse(); virtual ~CreateDbUserResponse(); ///////////////////////////////////////////// /// ModelBase overrides void validate() override; web::json::value toJson() const override; bool fromJson(const web::json::value& json) override; ///////////////////////////////////////////// /// CreateDbUserResponse members protected: #ifdef RTTR_FLAG RTTR_ENABLE() #endif }; } } } } } #endif // HUAWEICLOUD_SDK_GAUSSDBFOROPENGAUSS_V3_MODEL_CreateDbUserResponse_H_
[ "hwcloudsdk@huawei.com" ]
hwcloudsdk@huawei.com
72be63c8a7bbf08023692417e160fe5200bd8e51
e96a0bc65d1e015881030f3f94e2145bb2b163ea
/ABC/c56/b.cpp
92bd1484cc8d192fb181bc0939137b7c5014a7d6
[]
no_license
TimTam725/Atcoder
85a8d2f1961da9ed873312e90bd357f46eb2892b
067dcb03e6ad2f311f0b4de911fae273cee5113c
refs/heads/main
2023-06-06T02:06:34.833164
2021-06-20T06:22:01
2021-06-20T06:22:01
378,565,753
0
0
null
null
null
null
UTF-8
C++
false
false
672
cpp
#include<bits/stdc++.h> #include<iomanip> using namespace std; typedef long long ll; typedef long l; typedef pair<int,int> P; #define rep(i,n) for(int i=0;i<n;i++) #define fs first #define sc second #define pb push_back #define mp make_pair #define eb emplace_back #define ALL(A) A.begin(),A.end() const double PI=3.141592653589; const int INF=1000000001; const ll LMAX=1000000000000001; ll gcd(ll a,ll b){if(a<b)swap(a,b);while((a%b)!=0){a=b;b=a%b;}return b;} int dx[]={-1,0,1,0}; int dy[]={0,1,0,-1}; int main(){ int w,a,b; cin>>w>>a>>b; if(a>b) swap(a,b); if(a+w>=b) cout<<0<<endl; else cout<<b-(a+w)<<endl; return 0; }
[ "root@DESKTOP-PJOIK5S.localdomain" ]
root@DESKTOP-PJOIK5S.localdomain
6fcac296ce4d09a7f97ed02efc397405b0bcc92c
be947ec7af6d1039dbc2a829862876b71ebf597c
/CXHibernate/CXHibernate.h
665d9bc1a32df9db6ea367306b04b132098c3de7
[]
no_license
pengge/CXHibernate
b398975d9fa84b581217dfa781b21107a11fa2a1
6eeb0b0d3604e673a4ef0d830dbfa09b2f8d3706
refs/heads/master
2020-06-12T11:48:13.192014
2018-08-07T14:07:30
2018-08-07T14:07:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,305
h
//////////////////////////////////////////////////////////////////////// // // File: CXHibernate.h // // Copyright (c) 1998-2018 ir. W.E. Huisman // All rights reserved // // 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. // // Last Revision: 17-06-2018 // Version number: 0.9.0 // #pragma once #include "CXObjectFactory.h" #include "CXStaticInitialization.h" #include <vector> #include <map> #define HIBERNATE_VERSION "1.0.0" #define HIBERNATE_DATE "07-08-2018" #define CXH_LOG_NOTHING 0 // Logging is OFF #define CXH_LOG_ERRORS 1 // Only error logging #define CXH_LOG_ACTIONS 2 // Log standard actions #define CXH_LOG_DEBUG 3 // Log as much as possible #define CXH_LOG_SQL 6 // Log all SQL actions #define CXH_LOG_MAX 6 // Maximum log level // ORM Mapping strategy classes -> tables typedef enum _map_strategy { Strategy_standalone // No sub/super classes. 1 table = 1 class ,Strategy_one_table // 1 table for super + all sub-classes ,Strategy_sub_table // 1 table for super + 1 table per sub-class ,Strategy_classtable // 1 table for subclass + all its supers } MapStrategy; #define HIBERNATE_CONFIG_FILE "hibernate.cfg.xml" // Maximum number of classes that can be initialized // by the object factories. De- or increase at your own leisure. const unsigned int MAX_CLASSES = 1000; class CXSession; using MapSessions = std::map<CString,CXSession*>; using MapCreate = std::map<CString,CreateCXO>; class CXHibernate { public: CXHibernate(); ~CXHibernate(); // FUNCTIONS // Log a message to the hibernate logfile void Log(int p_level, bool p_format, const char* p_text, ...); // Loading and saving the general configuration XML CXSession* LoadConfiguration(CString p_sessionKey, CString p_configFile = ""); bool SaveConfiguration(CXSession* p_session, CString p_configFile = ""); // Getting a (possibly existing) session CXSession* GetSession(CString p_sessionKey = ""); // Create a new Hibernate session CXSession* CreateSession(CString p_sessionKey = "",CString p_configFile = ""); // Adding a externally created session (but we now own it). You **MUST** supply a session key void AddSession(CXSession* p_session, CString p_sessionKey); // Removing a session void RemoveSession(CXSession* p_session); // Flushing all data to the database and closing all sessions void CloseAllSessions(); // Register a create function for a class name void RegisterCreateCXO(CString p_name, CreateCXO p_create); // Find a create function for a class name CreateCXO FindCreateCXO(CString p_name); // SETTERS // Setting a hibernate mapping strategy bool SetStrategy(MapStrategy p_strategy); // Setting a default catalog for the execution time void SetDefaultCatalog(CString p_catalog); // Setting a default database schema for the execution time void SetDefaultSchema(CString p_schema); // Toolset: incomplete model void SetIncomplete(bool p_incomplete); // Setting a default configuration file (can be called once!) void SetConfiguration(CString p_configFile); // GETTERS MapStrategy GetStrategy(); CString GetDefaultCatalog(); CString GetDefaultSchema(); int GetLogLevel(); LogAnalysis* GetLogAnalysis(); CString GetConfiguration(); int GetNewMutation(); private: // Translate strategy names MapStrategy StringToMapStrategy(CString p_strategy); CString MapStrategyToString(MapStrategy p_strategy); // Create an opaque session key CString CreateSessionKey(); // Start and stop our logging void StartLogging(CString p_logfile, int p_level); void CloseLogfile(); // Relational-Object-Mapping strategy MapStrategy m_strategy { Strategy_standalone }; // Mapping to all open sessions MapSessions m_sessions; // Mapping with all create object functions MapCreate m_createCXO; // Configuration file CString m_configFile; // Current session key int m_key { 1 }; // Current transaction long m_mutation { 0 }; // Logging for Hibernate int m_loglevel { CXH_LOG_NOTHING }; LogAnalysis* m_logfile { nullptr }; // DEFAULTS CString m_default_catalog; // Default catalog CString m_default_schema; // Default schema of all tables // Incomplete mode: Only for tools and partly running models bool m_incomplete { false }; // Multi-threaded session lock CRITICAL_SECTION m_lock; }; // Singleton pointer to the library extern CXHibernate hibernate; // Selecting the right library to link with automatically // So we do not need to worry about which library to use in the linker settings #if defined _M_IX86 #define CXH_PLATFORM "x86" #else #define CXH_PLATFORM "x64" #endif #if defined _DEBUG #define CXH_CONFIGURATION "D" #else #define CXH_CONFIGURATION "R" #endif #ifndef CXH_COMPONENTS_NOAUTOLINK #pragma comment(lib,"CXHibernate_" CXH_PLATFORM CXH_CONFIGURATION ".lib") #pragma message("Automatically linking with CXHibernate_" CXH_PLATFORM CXH_CONFIGURATION ".lib") #endif
[ "edwig.huisman@hetnet.nl" ]
edwig.huisman@hetnet.nl
7f23d480c5bc02f4b5533b88138dca18e7181bdc
a6ef0926a77cdbca6140fce580564fe5c8bff131
/qt_dlib_dnn2/dnnface/dnn_base/vectorstream.h
01b8ee71f1633aa832ef9394ca1a155003687e22
[]
no_license
yjwudi/digiKam-Test
4220e2d85afef0d95627c160a7edc1dcf48a7b35
8f6a16f9ce47f12c69484a8ec8408050f03837c4
refs/heads/master
2021-06-24T02:58:50.240169
2017-07-26T12:12:25
2017-07-26T12:12:25
95,617,175
0
0
null
null
null
null
UTF-8
C++
false
false
3,913
h
// Copyright (C) 2012 Davis E. King (davis@dlib.net) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_VECTORStREAM_Hh_ #define DLIB_VECTORStREAM_Hh_ //#include "vectorstream_abstract.h" #include <cstring> #include <iostream> #include <streambuf> #include <vector> #include <cstdio> #include "algs.h" #ifdef _MSC_VER // Disable the warning about inheriting from std::iostream 'via dominance' since this warning is a warning about // visual studio conforming to the standard and is ignorable. See http://connect.microsoft.com/VisualStudio/feedback/details/733720/inheriting-from-std-fstream-produces-c4250-warning // for further details if interested. #pragma warning(disable : 4250) #endif // _MSC_VER //namespace dlib //{ class vectorstream : public std::iostream { class vector_streambuf : public std::streambuf { typedef std::vector<char>::size_type size_type; size_type read_pos; // buffer[read_pos] == next byte to read from buffer public: std::vector<char>& buffer; vector_streambuf( std::vector<char>& buffer_ ) : read_pos(0), buffer(buffer_) {} void seekg(size_type pos) { read_pos = pos; } // ------------------------ OUTPUT FUNCTIONS ------------------------ int_type overflow ( int_type c) { if (c != EOF) buffer.push_back(static_cast<char>(c)); return c; } std::streamsize xsputn ( const char* s, std::streamsize num) { buffer.insert(buffer.end(), s, s+num); return num; } // ------------------------ INPUT FUNCTIONS ------------------------ int_type underflow( ) { if (read_pos < buffer.size()) return static_cast<unsigned char>(buffer[read_pos]); else return EOF; } int_type uflow( ) { if (read_pos < buffer.size()) return static_cast<unsigned char>(buffer[read_pos++]); else return EOF; } int_type pbackfail( int_type c ) { // if they are trying to push back a character that they didn't read last // that is an error const unsigned long prev = read_pos-1; if (c != EOF && prev < buffer.size() && c != static_cast<unsigned char>(buffer[prev])) { return EOF; } read_pos = prev; return 1; } std::streamsize xsgetn ( char* s, std::streamsize n ) { if (read_pos < buffer.size()) { const size_type num = std::min<size_type>(n, buffer.size()-read_pos); std::memcpy(s, &buffer[read_pos], num); read_pos += num; return num; } return 0; } }; public: vectorstream ( std::vector<char>& buffer ) : std::iostream(&buf), buf(buffer) {} std::istream& seekg ( std::streampos pos ) { buf.seekg(pos); return *this; } private: vector_streambuf buf; }; //} #endif // DLIB_VECTORStREAM_Hh_
[ "18706819589@163.com" ]
18706819589@163.com
92c7ea2f01dfdc3143c5f24a5aacaae2eff4987f
5005357207b2ef59b5245a6f772e2ede6b8669ed
/KolkoIKrzyzyk/Cell.h
d12568d9630b4f5ba366f2391b8cc343d2510861
[ "MIT" ]
permissive
Ariello05/tictactoe
b175c3bdcbbe80bd7fdfa698f3097371e3edeb0e
0df0620465ee543215fcba046fb10a6ff2b6d60c
refs/heads/master
2020-04-11T00:26:58.249406
2019-12-21T19:35:38
2019-12-21T19:35:38
161,386,854
0
0
null
null
null
null
UTF-8
C++
false
false
348
h
#pragma once #include "Field.h" #include "Board.h" class Cell :public Field { public: Cell(sf::Vector2f position, sf::Vector2f size); ~Cell(); virtual void draw(sf::RenderWindow & window); virtual void click(sf::Vector2f position, Board & board); private: sf::RectangleShape rect; sf::RectangleShape lines[2]; sf::CircleShape circle; };
[ "heriu@wp.pl" ]
heriu@wp.pl
282aca33c1031844c4fbd3164a70b29a6ce84c5f
9d7a8d3e8d5df680c32fa70c73ef7c2820986187
/.history/D05/ex01/Form_20210309132020.cpp
978bf5102120221783767ad10d3154e592246ee9
[]
no_license
asleonova/cpp
dc2d606e361ffdfa2013953f68bd0da4530f34bc
adfaecc238cdb63053b34b106869d3185204d73a
refs/heads/master
2023-04-06T19:27:21.725162
2021-04-13T19:18:00
2021-04-13T19:18:00
337,834,070
0
0
null
null
null
null
UTF-8
C++
false
false
2,538
cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Form.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbliss <dbliss@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/09 12:10:26 by dbliss #+# #+# */ /* Updated: 2021/03/09 13:20:20 by dbliss ### ########.fr */ /* */ /* ************************************************************************** */ #include "Form.hpp" /* ** ------------------------------- CONSTRUCTOR -------------------------------- */ Form::Form(std::string name, unsigned int sign_grade, unsigned int exec_grade) : _name(name), _sign_grade(sign_grade), _exec_grade(exec_grade) { this->_signed = false; } Form::Form(const Form & src) : _name(src._name), _sign_grade(src._sign_grade), _exec_grade(src._exec_grade) { this->_signed = src._signed; } /* ** -------------------------------- DESTRUCTOR -------------------------------- */ Form::~Form() { } /* ** --------------------------------- OVERLOAD --------------------------------- */ Form & Form::operator=( Form const & rhs ) { (void)rhs; return *this; } std::ostream & operator<<( std::ostream & o, Form const & i ) { o << "Name: " << i.getName() << std::endl; o << "Sign Grade: " << i.getSignGrade() << std::endl; o << "Executable Grade: " << i.getExecGrade() << std::endl; o << "If Signed or not: " << i.getIfSigned() << std::endl; return o; } /* ** --------------------------------- METHODS ---------------------------------- */ void Form::beSigned(Bureaucrat & target) { if(target.getGrade() < 150) this->_signed = true; else throw Form::GradeTooLowException(); } /* ** --------------------------------- ACCESSOR --------------------------------- */ std::string Form::getName() const { return this->_name; } int Form::getSignGrade() const { return this->_sign_grade; } int Form::getExecGrade() const { return this->_exec_grade; } bool Form::getIfSigned() const { return this->_signed; } /* ************************************************************************** */
[ "dbliss@oa-d1.msk.21-school.ru" ]
dbliss@oa-d1.msk.21-school.ru
fbe62cdcbe79c49798577e5be0a5b2b7c0b019c4
bcf138c82fcba9acc7d7ce4d3a92618b06ebe7c7
/rdr2/0xDF8822C55EDDA65B.cpp
61d3cacaa7a305435f9d404beff76abc7d87698b
[]
no_license
DeepWolf413/additional-native-data
aded47e042f0feb30057e753910e0884c44121a0
e015b2500b52065252ffbe3c53865fe3cdd3e06c
refs/heads/main
2023-07-10T00:19:54.416083
2021-08-12T16:00:12
2021-08-12T16:00:12
395,340,507
1
0
null
null
null
null
UTF-8
C++
false
false
325
cpp
// laramie1.ysc @ L16454 void func_109(var uParam0) { func_370(uParam0, 7); func_371(); func_103(uParam0, 128); func_372(64, ""); if (!func_173(Global_1898437)) { PLAYER::START_PLAYER_TELEPORT(PLAYER::PLAYER_ID(), -2589.576f, 466.1188f, 145.0443f, 208.263f, true, true, true, false); func_373(0, 0); } }
[ "jesper15fuji@live.dk" ]
jesper15fuji@live.dk
3606de284af7b6762ea0a9c9ca26d7374d62094c
cfe39f93225e50c89ea3b0aded35ccb00c4294a6
/webcore_bindings/derived/JSSpeechSynthesisEvent.h
65c25c347324361f21393fcbf35a372e2443c129
[ "BSD-3-Clause" ]
permissive
Web5design/webkit.js
4d589121d5fdb29d807bd99d387be5f256b81b91
050d44f34d2bac3df01be2ee33c3545e5c1ce715
refs/heads/master
2020-12-03T07:58:21.250807
2014-02-16T23:19:47
2014-02-16T23:19:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,440
h
/* This file is part of the WebKit open source project. This file has been generated by generate-bindings.pl. DO NOT MODIFY! This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef JSSpeechSynthesisEvent_h #define JSSpeechSynthesisEvent_h #if ENABLE(SPEECH_SYNTHESIS) #include "JSDOMBinding.h" #include "JSEvent.h" #include "SpeechSynthesisEvent.h" #include <runtime/JSObject.h> namespace WebCore { class JSSpeechSynthesisEvent : public JSEvent { public: typedef JSEvent Base; static JSSpeechSynthesisEvent* create(JSC::Structure* structure, JSDOMGlobalObject* globalObject, PassRefPtr<SpeechSynthesisEvent> impl) { JSSpeechSynthesisEvent* ptr = new (NotNull, JSC::allocateCell<JSSpeechSynthesisEvent>(globalObject->vm().heap)) JSSpeechSynthesisEvent(structure, globalObject, impl); ptr->finishCreation(globalObject->vm()); return ptr; } static JSC::JSObject* createPrototype(JSC::VM&, JSC::JSGlobalObject*); static bool getOwnPropertySlot(JSC::JSObject*, JSC::ExecState*, JSC::PropertyName, JSC::PropertySlot&); DECLARE_INFO; static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype) { return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info()); } static JSC::JSValue getConstructor(JSC::VM&, JSC::JSGlobalObject*); SpeechSynthesisEvent& impl() const { return static_cast<SpeechSynthesisEvent&>(Base::impl()); } protected: JSSpeechSynthesisEvent(JSC::Structure*, JSDOMGlobalObject*, PassRefPtr<SpeechSynthesisEvent>); void finishCreation(JSC::VM&); static const unsigned StructureFlags = JSC::OverridesGetOwnPropertySlot | JSC::InterceptsGetOwnPropertySlotByIndexEvenWhenLengthIsNotZero | Base::StructureFlags; }; class JSSpeechSynthesisEventPrototype : public JSC::JSNonFinalObject { public: typedef JSC::JSNonFinalObject Base; static JSC::JSObject* self(JSC::VM&, JSC::JSGlobalObject*); static JSSpeechSynthesisEventPrototype* create(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::Structure* structure) { JSSpeechSynthesisEventPrototype* ptr = new (NotNull, JSC::allocateCell<JSSpeechSynthesisEventPrototype>(vm.heap)) JSSpeechSynthesisEventPrototype(vm, globalObject, structure); ptr->finishCreation(vm); return ptr; } DECLARE_INFO; static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype) { return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info()); } private: JSSpeechSynthesisEventPrototype(JSC::VM& vm, JSC::JSGlobalObject*, JSC::Structure* structure) : JSC::JSNonFinalObject(vm, structure) { } protected: static const unsigned StructureFlags = Base::StructureFlags; }; class JSSpeechSynthesisEventConstructor : public DOMConstructorObject { private: JSSpeechSynthesisEventConstructor(JSC::Structure*, JSDOMGlobalObject*); void finishCreation(JSC::VM&, JSDOMGlobalObject*); public: typedef DOMConstructorObject Base; static JSSpeechSynthesisEventConstructor* create(JSC::VM& vm, JSC::Structure* structure, JSDOMGlobalObject* globalObject) { JSSpeechSynthesisEventConstructor* ptr = new (NotNull, JSC::allocateCell<JSSpeechSynthesisEventConstructor>(vm.heap)) JSSpeechSynthesisEventConstructor(structure, globalObject); ptr->finishCreation(vm, globalObject); return ptr; } static bool getOwnPropertySlot(JSC::JSObject*, JSC::ExecState*, JSC::PropertyName, JSC::PropertySlot&); DECLARE_INFO; static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype) { return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info()); } protected: static const unsigned StructureFlags = JSC::OverridesGetOwnPropertySlot | JSC::ImplementsHasInstance | DOMConstructorObject::StructureFlags; }; // Attributes JSC::EncodedJSValue jsSpeechSynthesisEventCharIndex(JSC::ExecState*, JSC::EncodedJSValue, JSC::EncodedJSValue, JSC::PropertyName); JSC::EncodedJSValue jsSpeechSynthesisEventElapsedTime(JSC::ExecState*, JSC::EncodedJSValue, JSC::EncodedJSValue, JSC::PropertyName); JSC::EncodedJSValue jsSpeechSynthesisEventName(JSC::ExecState*, JSC::EncodedJSValue, JSC::EncodedJSValue, JSC::PropertyName); JSC::EncodedJSValue jsSpeechSynthesisEventConstructor(JSC::ExecState*, JSC::EncodedJSValue, JSC::EncodedJSValue, JSC::PropertyName); } // namespace WebCore #endif // ENABLE(SPEECH_SYNTHESIS) #endif
[ "trevor.linton@gmail.com" ]
trevor.linton@gmail.com
a59ca8fade046f1f24b68575d9cb050ddaceeb89
917bc29195834b7c4f6775658e32033851b34196
/include/ns/Blackboard.h
ca0aa84a19c92130600843c7c1690c4f89312c13
[ "MIT" ]
permissive
xzrunner/nserializer
ebc31f44b564a7c91dc352b8ddf98a23b36dbf86
44c252703a53c5970b8d9f2b608d56830601055e
refs/heads/master
2021-01-24T02:13:51.857108
2020-11-02T23:15:17
2020-11-02T23:15:17
122,839,761
0
0
null
null
null
null
UTF-8
C++
false
false
355
h
#pragma once #include <cu/cu_macro.h> #include <functional> namespace ns { class Blackboard { public: void SetGenNodeIdFunc(std::function<uint32_t()> func) { m_gen_node_id_func = func; } uint32_t GenNodeId() const; private: std::function<uint32_t()> m_gen_node_id_func = nullptr; CU_SINGLETON_DECLARATION(Blackboard); }; // Blackboard }
[ "zhuguang@ejoy.com" ]
zhuguang@ejoy.com
8c9c24647e5a2d829cae292ad902c58aab41c865
2a5215bcf8816f2de3ca02aee0d053cdaf219a6d
/Day 0.cpp
e5679787f7e3ba6f83603e6149d7d71f092ee57f
[]
no_license
kasaikarthik/30-days-of-code
f12c209fbea8915b502e203646efdf5704807f4a
b0276c680cac2bf7b6bc4bb8aaed8f1a8552e9cc
refs/heads/master
2020-11-30T04:16:07.339275
2020-02-04T11:12:14
2020-02-04T11:12:14
230,299,993
0
0
null
null
null
null
UTF-8
C++
false
false
154
cpp
int main() { string input_string; getline(cin, input_string); cout << "Hello, World." << endl; cout << input_string; return 0; }
[ "kasaikarthik@gmail.com" ]
kasaikarthik@gmail.com
d2ffbfcb1314ed872d238fc7005d5b669c7477f8
e98e505de1a1a3542189125ef4bdde147f9c77cd
/components/ntp_snippets/remote/remote_suggestions_provider_impl.cc
eba4dda04ebb8442ea1d740120c4d246b4542079
[ "BSD-3-Clause" ]
permissive
jesonlay/chromium
b98fca219ab71d230df9a758252058a18e075a06
292532fedbb55d68a83b46c106fd04849a47571d
refs/heads/master
2022-12-16T15:25:13.723395
2017-03-20T14:36:34
2017-03-20T15:37:49
158,929,892
0
0
NOASSERTION
2018-11-24T11:32:20
2018-11-24T11:32:19
null
UTF-8
C++
false
false
47,452
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/ntp_snippets/remote/remote_suggestions_provider_impl.h" #include <algorithm> #include <iterator> #include <utility> #include "base/bind.h" #include "base/command_line.h" #include "base/location.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/sparse_histogram.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/default_clock.h" #include "base/time/time.h" #include "base/values.h" #include "components/data_use_measurement/core/data_use_user_data.h" #include "components/image_fetcher/image_decoder.h" #include "components/image_fetcher/image_fetcher.h" #include "components/ntp_snippets/category_rankers/category_ranker.h" #include "components/ntp_snippets/pref_names.h" #include "components/ntp_snippets/remote/remote_suggestions_database.h" #include "components/ntp_snippets/remote/remote_suggestions_scheduler.h" #include "components/ntp_snippets/switches.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/strings/grit/components_strings.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/image/image.h" namespace ntp_snippets { namespace { // Number of suggestions requested to the server. Consider replacing sparse UMA // histograms with COUNTS() if this number increases beyond 50. const int kMaxSuggestionCount = 10; // Number of archived suggestions we keep around in memory. const int kMaxArchivedSuggestionCount = 200; // Keys for storing CategoryContent info in prefs. const char kCategoryContentId[] = "id"; const char kCategoryContentTitle[] = "title"; const char kCategoryContentProvidedByServer[] = "provided_by_server"; const char kCategoryContentAllowFetchingMore[] = "allow_fetching_more"; template <typename SuggestionPtrContainer> std::unique_ptr<std::vector<std::string>> GetSuggestionIDVector( const SuggestionPtrContainer& suggestions) { auto result = base::MakeUnique<std::vector<std::string>>(); for (const auto& suggestion : suggestions) { result->push_back(suggestion->id()); } return result; } bool HasIntersection(const std::vector<std::string>& a, const std::set<std::string>& b) { for (const std::string& item : a) { if (base::ContainsValue(b, item)) { return true; } } return false; } void EraseByPrimaryID(RemoteSuggestion::PtrVector* suggestions, const std::vector<std::string>& ids) { std::set<std::string> ids_lookup(ids.begin(), ids.end()); base::EraseIf( *suggestions, [&ids_lookup](const std::unique_ptr<RemoteSuggestion>& suggestion) { return base::ContainsValue(ids_lookup, suggestion->id()); }); } void EraseMatchingSuggestions( RemoteSuggestion::PtrVector* suggestions, const RemoteSuggestion::PtrVector& compare_against) { std::set<std::string> compare_against_ids; for (const std::unique_ptr<RemoteSuggestion>& suggestion : compare_against) { const std::vector<std::string>& suggestion_ids = suggestion->GetAllIDs(); compare_against_ids.insert(suggestion_ids.begin(), suggestion_ids.end()); } base::EraseIf( *suggestions, [&compare_against_ids]( const std::unique_ptr<RemoteSuggestion>& suggestion) { return HasIntersection(suggestion->GetAllIDs(), compare_against_ids); }); } void RemoveNullPointers(RemoteSuggestion::PtrVector* suggestions) { base::EraseIf(*suggestions, [](const std::unique_ptr<RemoteSuggestion>& suggestion) { return !suggestion; }); } void RemoveIncompleteSuggestions(RemoteSuggestion::PtrVector* suggestions) { if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kAddIncompleteSnippets)) { return; } int num_suggestions = suggestions->size(); // Remove suggestions that do not have all the info we need to display it to // the user. base::EraseIf(*suggestions, [](const std::unique_ptr<RemoteSuggestion>& suggestion) { return !suggestion->is_complete(); }); int num_suggestions_removed = num_suggestions - suggestions->size(); UMA_HISTOGRAM_BOOLEAN("NewTabPage.Snippets.IncompleteSnippetsAfterFetch", num_suggestions_removed > 0); if (num_suggestions_removed > 0) { UMA_HISTOGRAM_SPARSE_SLOWLY("NewTabPage.Snippets.NumIncompleteSnippets", num_suggestions_removed); } } std::vector<ContentSuggestion> ConvertToContentSuggestions( Category category, const RemoteSuggestion::PtrVector& suggestions) { std::vector<ContentSuggestion> result; for (const std::unique_ptr<RemoteSuggestion>& suggestion : suggestions) { // TODO(sfiera): if a suggestion is not going to be displayed, move it // directly to content.dismissed on fetch. Otherwise, we might prune // other suggestions to get down to kMaxSuggestionCount, only to hide one of // the incomplete ones we kept. if (!suggestion->is_complete()) { continue; } result.emplace_back(suggestion->ToContentSuggestion(category)); } return result; } void CallWithEmptyResults(const FetchDoneCallback& callback, const Status& status) { if (callback.is_null()) { return; } callback.Run(status, std::vector<ContentSuggestion>()); } } // namespace CachedImageFetcher::CachedImageFetcher( std::unique_ptr<image_fetcher::ImageFetcher> image_fetcher, PrefService* pref_service, RemoteSuggestionsDatabase* database) : image_fetcher_(std::move(image_fetcher)), database_(database), thumbnail_requests_throttler_( pref_service, RequestThrottler::RequestType::CONTENT_SUGGESTION_THUMBNAIL) { // |image_fetcher_| can be null in tests. if (image_fetcher_) { image_fetcher_->SetImageFetcherDelegate(this); image_fetcher_->SetDataUseServiceName( data_use_measurement::DataUseUserData::NTP_SNIPPETS_THUMBNAILS); } } CachedImageFetcher::~CachedImageFetcher() {} void CachedImageFetcher::FetchSuggestionImage( const ContentSuggestion::ID& suggestion_id, const GURL& url, const ImageFetchedCallback& callback) { database_->LoadImage( suggestion_id.id_within_category(), base::Bind(&CachedImageFetcher::OnImageFetchedFromDatabase, base::Unretained(this), callback, suggestion_id, url)); } // This function gets only called for caching the image data received from the // network. The actual decoding is done in OnImageDecodedFromDatabase(). void CachedImageFetcher::OnImageDataFetched( const std::string& id_within_category, const std::string& image_data) { if (image_data.empty()) { return; } database_->SaveImage(id_within_category, image_data); } void CachedImageFetcher::OnImageDecodingDone( const ImageFetchedCallback& callback, const std::string& id_within_category, const gfx::Image& image, const image_fetcher::RequestMetadata& metadata) { callback.Run(image); } void CachedImageFetcher::OnImageFetchedFromDatabase( const ImageFetchedCallback& callback, const ContentSuggestion::ID& suggestion_id, const GURL& url, std::string data) { // SnippetImageCallback requires by-value. // The image decoder is null in tests. if (image_fetcher_->GetImageDecoder() && !data.empty()) { image_fetcher_->GetImageDecoder()->DecodeImage( data, // We're not dealing with multi-frame images. /*desired_image_frame_size=*/gfx::Size(), base::Bind(&CachedImageFetcher::OnImageDecodedFromDatabase, base::Unretained(this), callback, suggestion_id, url)); return; } // Fetching from the DB failed; start a network fetch. FetchImageFromNetwork(suggestion_id, url, callback); } void CachedImageFetcher::OnImageDecodedFromDatabase( const ImageFetchedCallback& callback, const ContentSuggestion::ID& suggestion_id, const GURL& url, const gfx::Image& image) { if (!image.IsEmpty()) { callback.Run(image); return; } // If decoding the image failed, delete the DB entry. database_->DeleteImage(suggestion_id.id_within_category()); FetchImageFromNetwork(suggestion_id, url, callback); } void CachedImageFetcher::FetchImageFromNetwork( const ContentSuggestion::ID& suggestion_id, const GURL& url, const ImageFetchedCallback& callback) { if (url.is_empty() || !thumbnail_requests_throttler_.DemandQuotaForRequest( /*interactive_request=*/true)) { // Return an empty image. Directly, this is never synchronous with the // original FetchSuggestionImage() call - an asynchronous database query has // happened in the meantime. callback.Run(gfx::Image()); return; } image_fetcher_->StartOrQueueNetworkRequest( suggestion_id.id_within_category(), url, base::Bind(&CachedImageFetcher::OnImageDecodingDone, base::Unretained(this), callback)); } RemoteSuggestionsProviderImpl::RemoteSuggestionsProviderImpl( Observer* observer, PrefService* pref_service, const std::string& application_language_code, CategoryRanker* category_ranker, std::unique_ptr<RemoteSuggestionsFetcher> suggestions_fetcher, std::unique_ptr<image_fetcher::ImageFetcher> image_fetcher, std::unique_ptr<RemoteSuggestionsDatabase> database, std::unique_ptr<RemoteSuggestionsStatusService> status_service) : RemoteSuggestionsProvider(observer), state_(State::NOT_INITED), pref_service_(pref_service), articles_category_( Category::FromKnownCategory(KnownCategories::ARTICLES)), application_language_code_(application_language_code), category_ranker_(category_ranker), suggestions_fetcher_(std::move(suggestions_fetcher)), database_(std::move(database)), image_fetcher_(std::move(image_fetcher), pref_service, database_.get()), status_service_(std::move(status_service)), fetch_when_ready_(false), fetch_when_ready_interactive_(false), fetch_when_ready_callback_(nullptr), remote_suggestions_scheduler_(nullptr), clear_history_dependent_state_when_initialized_(false), clock_(base::MakeUnique<base::DefaultClock>()) { RestoreCategoriesFromPrefs(); // The articles category always exists. Add it if we didn't get it from prefs. // TODO(treib): Rethink this. category_contents_.insert( std::make_pair(articles_category_, CategoryContent(BuildArticleCategoryInfo(base::nullopt)))); // Tell the observer about all the categories. for (const auto& entry : category_contents_) { observer->OnCategoryStatusChanged(this, entry.first, entry.second.status); } if (database_->IsErrorState()) { EnterState(State::ERROR_OCCURRED); UpdateAllCategoryStatus(CategoryStatus::LOADING_ERROR); return; } database_->SetErrorCallback(base::Bind( &RemoteSuggestionsProviderImpl::OnDatabaseError, base::Unretained(this))); // We transition to other states while finalizing the initialization, when the // database is done loading. database_load_start_ = base::TimeTicks::Now(); database_->LoadSnippets( base::Bind(&RemoteSuggestionsProviderImpl::OnDatabaseLoaded, base::Unretained(this))); } RemoteSuggestionsProviderImpl::~RemoteSuggestionsProviderImpl() = default; // static void RemoteSuggestionsProviderImpl::RegisterProfilePrefs( PrefRegistrySimple* registry) { registry->RegisterListPref(prefs::kRemoteSuggestionCategories); registry->RegisterInt64Pref(prefs::kLastSuccessfulBackgroundFetchTime, 0); RemoteSuggestionsStatusService::RegisterProfilePrefs(registry); } void RemoteSuggestionsProviderImpl::SetRemoteSuggestionsScheduler( RemoteSuggestionsScheduler* scheduler) { remote_suggestions_scheduler_ = scheduler; // Call the observer right away if we've reached any final state. NotifyStateChanged(); } void RemoteSuggestionsProviderImpl::ReloadSuggestions() { FetchSuggestions(/*interactive_request=*/true, /*callback=*/nullptr); } void RemoteSuggestionsProviderImpl::RefetchInTheBackground( std::unique_ptr<FetchStatusCallback> callback) { FetchSuggestions(/*interactive_request=*/false, std::move(callback)); } const RemoteSuggestionsFetcher* RemoteSuggestionsProviderImpl::suggestions_fetcher_for_debugging() const { return suggestions_fetcher_.get(); } void RemoteSuggestionsProviderImpl::FetchSuggestions( bool interactive_request, std::unique_ptr<FetchStatusCallback> callback) { if (!ready()) { fetch_when_ready_ = true; fetch_when_ready_interactive_ = interactive_request; fetch_when_ready_callback_ = std::move(callback); return; } MarkEmptyCategoriesAsLoading(); RequestParams params = BuildFetchParams(); params.interactive_request = interactive_request; suggestions_fetcher_->FetchSnippets( params, base::BindOnce(&RemoteSuggestionsProviderImpl::OnFetchFinished, base::Unretained(this), std::move(callback), interactive_request)); } void RemoteSuggestionsProviderImpl::Fetch( const Category& category, const std::set<std::string>& known_suggestion_ids, const FetchDoneCallback& callback) { if (!ready()) { CallWithEmptyResults(callback, Status(StatusCode::TEMPORARY_ERROR, "RemoteSuggestionsProvider is not ready!")); return; } RequestParams params = BuildFetchParams(); params.excluded_ids.insert(known_suggestion_ids.begin(), known_suggestion_ids.end()); params.interactive_request = true; params.exclusive_category = category; suggestions_fetcher_->FetchSnippets( params, base::BindOnce(&RemoteSuggestionsProviderImpl::OnFetchMoreFinished, base::Unretained(this), callback)); } // Builds default fetcher params. RequestParams RemoteSuggestionsProviderImpl::BuildFetchParams() const { RequestParams result; result.language_code = application_language_code_; result.count_to_fetch = kMaxSuggestionCount; for (const auto& map_entry : category_contents_) { const CategoryContent& content = map_entry.second; for (const auto& dismissed_suggestion : content.dismissed) { result.excluded_ids.insert(dismissed_suggestion->id()); } } return result; } void RemoteSuggestionsProviderImpl::MarkEmptyCategoriesAsLoading() { for (const auto& item : category_contents_) { Category category = item.first; const CategoryContent& content = item.second; if (content.suggestions.empty()) { UpdateCategoryStatus(category, CategoryStatus::AVAILABLE_LOADING); } } } CategoryStatus RemoteSuggestionsProviderImpl::GetCategoryStatus( Category category) { auto content_it = category_contents_.find(category); DCHECK(content_it != category_contents_.end()); return content_it->second.status; } CategoryInfo RemoteSuggestionsProviderImpl::GetCategoryInfo(Category category) { auto content_it = category_contents_.find(category); DCHECK(content_it != category_contents_.end()); return content_it->second.info; } void RemoteSuggestionsProviderImpl::DismissSuggestion( const ContentSuggestion::ID& suggestion_id) { if (!ready()) { return; } auto content_it = category_contents_.find(suggestion_id.category()); DCHECK(content_it != category_contents_.end()); CategoryContent* content = &content_it->second; DismissSuggestionFromCategoryContent(content, suggestion_id.id_within_category()); } void RemoteSuggestionsProviderImpl::ClearHistory( base::Time begin, base::Time end, const base::Callback<bool(const GURL& url)>& filter) { // Both time range and the filter are ignored and all suggestions are removed, // because it is not known which history entries were used for the suggestions // personalization. ClearHistoryDependentState(); } void RemoteSuggestionsProviderImpl::ClearCachedSuggestions(Category category) { if (!initialized()) { return; } auto content_it = category_contents_.find(category); if (content_it == category_contents_.end()) { return; } CategoryContent* content = &content_it->second; // TODO(tschumann): We do the unnecessary checks for .empty() in many places // before calling database methods. Change the RemoteSuggestionsDatabase to // return early for those and remove the many if statements in this file. if (!content->suggestions.empty()) { database_->DeleteSnippets(GetSuggestionIDVector(content->suggestions)); database_->DeleteImages(GetSuggestionIDVector(content->suggestions)); content->suggestions.clear(); } if (!content->archived.empty()) { database_->DeleteSnippets(GetSuggestionIDVector(content->archived)); database_->DeleteImages(GetSuggestionIDVector(content->archived)); content->archived.clear(); } } void RemoteSuggestionsProviderImpl::OnSignInStateChanged() { // Make sure the status service is registered and we already initialised its // start state. if (!initialized()) { return; } status_service_->OnSignInStateChanged(); } void RemoteSuggestionsProviderImpl::GetDismissedSuggestionsForDebugging( Category category, const DismissedSuggestionsCallback& callback) { auto content_it = category_contents_.find(category); DCHECK(content_it != category_contents_.end()); callback.Run( ConvertToContentSuggestions(category, content_it->second.dismissed)); } void RemoteSuggestionsProviderImpl::ClearDismissedSuggestionsForDebugging( Category category) { auto content_it = category_contents_.find(category); DCHECK(content_it != category_contents_.end()); CategoryContent* content = &content_it->second; if (!initialized()) { return; } if (content->dismissed.empty()) { return; } database_->DeleteSnippets(GetSuggestionIDVector(content->dismissed)); // The image got already deleted when the suggestion was dismissed. content->dismissed.clear(); } // static int RemoteSuggestionsProviderImpl::GetMaxSuggestionCountForTesting() { return kMaxSuggestionCount; } //////////////////////////////////////////////////////////////////////////////// // Private methods GURL RemoteSuggestionsProviderImpl::FindSuggestionImageUrl( const ContentSuggestion::ID& suggestion_id) const { DCHECK(base::ContainsKey(category_contents_, suggestion_id.category())); const CategoryContent& content = category_contents_.at(suggestion_id.category()); const RemoteSuggestion* suggestion = content.FindSuggestion(suggestion_id.id_within_category()); if (!suggestion) { return GURL(); } return suggestion->salient_image_url(); } void RemoteSuggestionsProviderImpl::OnDatabaseLoaded( RemoteSuggestion::PtrVector suggestions) { if (state_ == State::ERROR_OCCURRED) { return; } DCHECK(state_ == State::NOT_INITED); DCHECK(base::ContainsKey(category_contents_, articles_category_)); base::TimeDelta database_load_time = base::TimeTicks::Now() - database_load_start_; UMA_HISTOGRAM_MEDIUM_TIMES("NewTabPage.Snippets.DatabaseLoadTime", database_load_time); RemoteSuggestion::PtrVector to_delete; for (std::unique_ptr<RemoteSuggestion>& suggestion : suggestions) { Category suggestion_category = Category::FromRemoteCategory(suggestion->remote_category_id()); auto content_it = category_contents_.find(suggestion_category); // We should already know about the category. if (content_it == category_contents_.end()) { DLOG(WARNING) << "Loaded a suggestion for unknown category " << suggestion_category << " from the DB; deleting"; to_delete.emplace_back(std::move(suggestion)); continue; } CategoryContent* content = &content_it->second; if (suggestion->is_dismissed()) { content->dismissed.emplace_back(std::move(suggestion)); } else { content->suggestions.emplace_back(std::move(suggestion)); } } if (!to_delete.empty()) { database_->DeleteSnippets(GetSuggestionIDVector(to_delete)); database_->DeleteImages(GetSuggestionIDVector(to_delete)); } // Sort the suggestions in each category. // TODO(treib): Persist the actual order in the DB somehow? crbug.com/654409 for (auto& entry : category_contents_) { CategoryContent* content = &entry.second; std::sort(content->suggestions.begin(), content->suggestions.end(), [](const std::unique_ptr<RemoteSuggestion>& lhs, const std::unique_ptr<RemoteSuggestion>& rhs) { return lhs->score() > rhs->score(); }); } // TODO(tschumann): If I move ClearExpiredDismissedSuggestions() to the // beginning of the function, it essentially does nothing but tests are still // green. Fix this! ClearExpiredDismissedSuggestions(); ClearOrphanedImages(); FinishInitialization(); } void RemoteSuggestionsProviderImpl::OnDatabaseError() { EnterState(State::ERROR_OCCURRED); UpdateAllCategoryStatus(CategoryStatus::LOADING_ERROR); } void RemoteSuggestionsProviderImpl::OnFetchMoreFinished( const FetchDoneCallback& fetching_callback, Status status, RemoteSuggestionsFetcher::OptionalFetchedCategories fetched_categories) { if (!fetched_categories) { DCHECK(!status.IsSuccess()); CallWithEmptyResults(fetching_callback, status); return; } if (fetched_categories->size() != 1u) { LOG(DFATAL) << "Requested one exclusive category but received " << fetched_categories->size() << " categories."; CallWithEmptyResults(fetching_callback, Status(StatusCode::PERMANENT_ERROR, "RemoteSuggestionsProvider received more " "categories than requested.")); return; } auto& fetched_category = (*fetched_categories)[0]; Category category = fetched_category.category; CategoryContent* existing_content = UpdateCategoryInfo(category, fetched_category.info); SanitizeReceivedSuggestions(existing_content->dismissed, &fetched_category.suggestions); // We compute the result now before modifying |fetched_category.suggestions|. // However, we wait with notifying the caller until the end of the method when // all state is updated. std::vector<ContentSuggestion> result = ConvertToContentSuggestions(category, fetched_category.suggestions); // Fill up the newly fetched suggestions with existing ones, store them, and // notify observers about new data. while (fetched_category.suggestions.size() < static_cast<size_t>(kMaxSuggestionCount) && !existing_content->suggestions.empty()) { fetched_category.suggestions.emplace( fetched_category.suggestions.begin(), std::move(existing_content->suggestions.back())); existing_content->suggestions.pop_back(); } std::vector<std::string> to_dismiss = *GetSuggestionIDVector(existing_content->suggestions); for (const auto& id : to_dismiss) { DismissSuggestionFromCategoryContent(existing_content, id); } DCHECK(existing_content->suggestions.empty()); IntegrateSuggestions(existing_content, std::move(fetched_category.suggestions)); // TODO(tschumann): We should properly honor the existing category state, // e.g. to make sure we don't serve results after the sign-out. Revisit this: // Should Nuke also cancel outstanding requests, or do we want to check the // status? UpdateCategoryStatus(category, CategoryStatus::AVAILABLE); // Notify callers and observers. fetching_callback.Run(Status::Success(), std::move(result)); NotifyNewSuggestions(category, *existing_content); } void RemoteSuggestionsProviderImpl::OnFetchFinished( std::unique_ptr<FetchStatusCallback> callback, bool interactive_request, Status status, RemoteSuggestionsFetcher::OptionalFetchedCategories fetched_categories) { if (!ready()) { // TODO(tschumann): What happens if this was a user-triggered, interactive // request? Is the UI waiting indefinitely now? return; } // Record the fetch time of a successfull background fetch. if (!interactive_request && status.IsSuccess()) { pref_service_->SetInt64(prefs::kLastSuccessfulBackgroundFetchTime, clock_->Now().ToInternalValue()); } // Mark all categories as not provided by the server in the latest fetch. The // ones we got will be marked again below. for (auto& item : category_contents_) { CategoryContent* content = &item.second; content->included_in_last_server_response = false; } // Clear up expired dismissed suggestions before we use them to filter new // ones. ClearExpiredDismissedSuggestions(); // If suggestions were fetched successfully, update our |category_contents_| // from // each category provided by the server. if (fetched_categories) { // TODO(treib): Reorder |category_contents_| to match the order we received // from the server. crbug.com/653816 for (RemoteSuggestionsFetcher::FetchedCategory& fetched_category : *fetched_categories) { // TODO(tschumann): Remove this histogram once we only talk to the content // suggestions cloud backend. if (fetched_category.category == articles_category_) { UMA_HISTOGRAM_SPARSE_SLOWLY( "NewTabPage.Snippets.NumArticlesFetched", std::min(fetched_category.suggestions.size(), static_cast<size_t>(kMaxSuggestionCount + 1))); } category_ranker_->AppendCategoryIfNecessary(fetched_category.category); CategoryContent* content = UpdateCategoryInfo(fetched_category.category, fetched_category.info); content->included_in_last_server_response = true; SanitizeReceivedSuggestions(content->dismissed, &fetched_category.suggestions); IntegrateSuggestions(content, std::move(fetched_category.suggestions)); } } // TODO(tschumann): The suggestions fetcher needs to signal errors so that we // know why we received no data. If an error occured, none of the following // should take place. // We might have gotten new categories (or updated the titles of existing // ones), so update the pref. StoreCategoriesToPrefs(); for (const auto& item : category_contents_) { Category category = item.first; UpdateCategoryStatus(category, CategoryStatus::AVAILABLE); // TODO(sfiera): notify only when a category changed above. NotifyNewSuggestions(category, item.second); } // TODO(sfiera): equivalent metrics for non-articles. auto content_it = category_contents_.find(articles_category_); DCHECK(content_it != category_contents_.end()); const CategoryContent& content = content_it->second; UMA_HISTOGRAM_SPARSE_SLOWLY("NewTabPage.Snippets.NumArticles", content.suggestions.size()); if (content.suggestions.empty() && !content.dismissed.empty()) { UMA_HISTOGRAM_COUNTS("NewTabPage.Snippets.NumArticlesZeroDueToDiscarded", content.dismissed.size()); } if (callback) { callback->Run(status); } } void RemoteSuggestionsProviderImpl::ArchiveSuggestions( CategoryContent* content, RemoteSuggestion::PtrVector* to_archive) { // Archive previous suggestions - move them at the beginning of the list. content->archived.insert(content->archived.begin(), std::make_move_iterator(to_archive->begin()), std::make_move_iterator(to_archive->end())); to_archive->clear(); // If there are more archived suggestions than we want to keep, delete the // oldest ones by their fetch time (which are always in the back). if (content->archived.size() > kMaxArchivedSuggestionCount) { RemoteSuggestion::PtrVector to_delete( std::make_move_iterator(content->archived.begin() + kMaxArchivedSuggestionCount), std::make_move_iterator(content->archived.end())); content->archived.resize(kMaxArchivedSuggestionCount); database_->DeleteImages(GetSuggestionIDVector(to_delete)); } } void RemoteSuggestionsProviderImpl::SanitizeReceivedSuggestions( const RemoteSuggestion::PtrVector& dismissed, RemoteSuggestion::PtrVector* suggestions) { DCHECK(ready()); EraseMatchingSuggestions(suggestions, dismissed); RemoveIncompleteSuggestions(suggestions); } void RemoteSuggestionsProviderImpl::IntegrateSuggestions( CategoryContent* content, RemoteSuggestion::PtrVector new_suggestions) { DCHECK(ready()); // Do not touch the current set of suggestions if the newly fetched one is // empty. // TODO(tschumann): This should go. If we get empty results we should update // accordingly and remove the old one (only of course if this was not received // through a fetch-more). if (new_suggestions.empty()) { return; } // It's entirely possible that the newly fetched suggestions contain articles // that have been present before. // We need to make sure to only delete and archive suggestions that don't // appear with the same ID in the new suggestions (it's fine for additional // IDs though). EraseByPrimaryID(&content->suggestions, *GetSuggestionIDVector(new_suggestions)); // Do not delete the thumbnail images as they are still handy on open NTPs. database_->DeleteSnippets(GetSuggestionIDVector(content->suggestions)); // Note, that ArchiveSuggestions will clear |content->suggestions|. ArchiveSuggestions(content, &content->suggestions); database_->SaveSnippets(new_suggestions); content->suggestions = std::move(new_suggestions); } void RemoteSuggestionsProviderImpl::DismissSuggestionFromCategoryContent( CategoryContent* content, const std::string& id_within_category) { auto it = std::find_if(content->suggestions.begin(), content->suggestions.end(), [&id_within_category]( const std::unique_ptr<RemoteSuggestion>& suggestion) { return suggestion->id() == id_within_category; }); if (it == content->suggestions.end()) { return; } (*it)->set_dismissed(true); database_->SaveSnippet(**it); content->dismissed.push_back(std::move(*it)); content->suggestions.erase(it); } void RemoteSuggestionsProviderImpl::ClearExpiredDismissedSuggestions() { std::vector<Category> categories_to_erase; const base::Time now = base::Time::Now(); for (auto& item : category_contents_) { Category category = item.first; CategoryContent* content = &item.second; RemoteSuggestion::PtrVector to_delete; // Move expired dismissed suggestions over into |to_delete|. for (std::unique_ptr<RemoteSuggestion>& suggestion : content->dismissed) { if (suggestion->expiry_date() <= now) { to_delete.emplace_back(std::move(suggestion)); } } RemoveNullPointers(&content->dismissed); // Delete the images. database_->DeleteImages(GetSuggestionIDVector(to_delete)); // Delete the removed article suggestions from the DB. database_->DeleteSnippets(GetSuggestionIDVector(to_delete)); if (content->suggestions.empty() && content->dismissed.empty() && category != articles_category_ && !content->included_in_last_server_response) { categories_to_erase.push_back(category); } } for (Category category : categories_to_erase) { UpdateCategoryStatus(category, CategoryStatus::NOT_PROVIDED); category_contents_.erase(category); } StoreCategoriesToPrefs(); } void RemoteSuggestionsProviderImpl::ClearOrphanedImages() { auto alive_suggestions = base::MakeUnique<std::set<std::string>>(); for (const auto& entry : category_contents_) { const CategoryContent& content = entry.second; for (const auto& suggestion_ptr : content.suggestions) { alive_suggestions->insert(suggestion_ptr->id()); } for (const auto& suggestion_ptr : content.dismissed) { alive_suggestions->insert(suggestion_ptr->id()); } } database_->GarbageCollectImages(std::move(alive_suggestions)); } void RemoteSuggestionsProviderImpl::ClearHistoryDependentState() { if (!initialized()) { clear_history_dependent_state_when_initialized_ = true; return; } NukeAllSuggestions(); if (remote_suggestions_scheduler_) { remote_suggestions_scheduler_->OnHistoryCleared(); } } void RemoteSuggestionsProviderImpl::ClearSuggestions() { DCHECK(initialized()); NukeAllSuggestions(); if (remote_suggestions_scheduler_) { remote_suggestions_scheduler_->OnSuggestionsCleared(); } } void RemoteSuggestionsProviderImpl::NukeAllSuggestions() { for (const auto& item : category_contents_) { Category category = item.first; const CategoryContent& content = item.second; ClearCachedSuggestions(category); // Update listeners about the new (empty) state. if (IsCategoryStatusAvailable(content.status)) { NotifyNewSuggestions(category, content); } // TODO(tschumann): We should not call debug code from production code. ClearDismissedSuggestionsForDebugging(category); } StoreCategoriesToPrefs(); } void RemoteSuggestionsProviderImpl::FetchSuggestionImage( const ContentSuggestion::ID& suggestion_id, const ImageFetchedCallback& callback) { if (!base::ContainsKey(category_contents_, suggestion_id.category())) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, gfx::Image())); return; } GURL image_url = FindSuggestionImageUrl(suggestion_id); if (image_url.is_empty()) { // As we don't know the corresponding suggestion anymore, we don't expect to // find it in the database (and also can't fetch it remotely). Cut the // lookup short and return directly. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, gfx::Image())); return; } image_fetcher_.FetchSuggestionImage(suggestion_id, image_url, callback); } void RemoteSuggestionsProviderImpl::EnterStateReady() { if (clear_history_dependent_state_when_initialized_) { clear_history_dependent_state_when_initialized_ = false; ClearHistoryDependentState(); } auto article_category_it = category_contents_.find(articles_category_); DCHECK(article_category_it != category_contents_.end()); if (fetch_when_ready_) { FetchSuggestions(fetch_when_ready_interactive_, std::move(fetch_when_ready_callback_)); fetch_when_ready_ = false; } for (const auto& item : category_contents_) { Category category = item.first; const CategoryContent& content = item.second; // FetchSuggestions has set the status to |AVAILABLE_LOADING| if relevant, // otherwise we transition to |AVAILABLE| here. if (content.status != CategoryStatus::AVAILABLE_LOADING) { UpdateCategoryStatus(category, CategoryStatus::AVAILABLE); } } } void RemoteSuggestionsProviderImpl::EnterStateDisabled() { ClearSuggestions(); } void RemoteSuggestionsProviderImpl::EnterStateError() { status_service_.reset(); } void RemoteSuggestionsProviderImpl::FinishInitialization() { if (clear_history_dependent_state_when_initialized_) { // We clear here in addition to EnterStateReady, so that it happens even if // we enter the DISABLED state below. clear_history_dependent_state_when_initialized_ = false; ClearHistoryDependentState(); } // Note: Initializing the status service will run the callback right away with // the current state. status_service_->Init(base::Bind( &RemoteSuggestionsProviderImpl::OnStatusChanged, base::Unretained(this))); // Always notify here even if we got nothing from the database, because we // don't know how long the fetch will take or if it will even complete. for (const auto& item : category_contents_) { Category category = item.first; const CategoryContent& content = item.second; // Note: We might be in a non-available status here, e.g. DISABLED due to // enterprise policy. if (IsCategoryStatusAvailable(content.status)) { NotifyNewSuggestions(category, content); } } } void RemoteSuggestionsProviderImpl::OnStatusChanged( RemoteSuggestionsStatus old_status, RemoteSuggestionsStatus new_status) { switch (new_status) { case RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN: if (old_status == RemoteSuggestionsStatus::ENABLED_AND_SIGNED_OUT) { DCHECK(state_ == State::READY); // Clear nonpersonalized suggestions (and notify the scheduler there are // no suggestions). ClearSuggestions(); } else { // Do not change the status. That will be done in EnterStateReady(). EnterState(State::READY); } break; case RemoteSuggestionsStatus::ENABLED_AND_SIGNED_OUT: if (old_status == RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN) { DCHECK(state_ == State::READY); // Clear personalized suggestions (and notify the scheduler there are // no suggestions). ClearSuggestions(); } else { // Do not change the status. That will be done in EnterStateReady(). EnterState(State::READY); } break; case RemoteSuggestionsStatus::EXPLICITLY_DISABLED: EnterState(State::DISABLED); UpdateAllCategoryStatus(CategoryStatus::CATEGORY_EXPLICITLY_DISABLED); break; } } void RemoteSuggestionsProviderImpl::EnterState(State state) { if (state == state_) { return; } UMA_HISTOGRAM_ENUMERATION("NewTabPage.Snippets.EnteredState", static_cast<int>(state), static_cast<int>(State::COUNT)); switch (state) { case State::NOT_INITED: // Initial state, it should not be possible to get back there. NOTREACHED(); break; case State::READY: DCHECK(state_ == State::NOT_INITED || state_ == State::DISABLED); DVLOG(1) << "Entering state: READY"; state_ = State::READY; NotifyStateChanged(); EnterStateReady(); break; case State::DISABLED: DCHECK(state_ == State::NOT_INITED || state_ == State::READY); DVLOG(1) << "Entering state: DISABLED"; // TODO(jkrcal): Fix the fragility of the following code. Currently, it is // important that we first change the state and notify the scheduler (as // it will update its state) and only at last we EnterStateDisabled() // which clears suggestions. Clearing suggestions namely notifies the // scheduler to fetch them again, which is ignored because the scheduler // is disabled. crbug/695447 state_ = State::DISABLED; NotifyStateChanged(); EnterStateDisabled(); break; case State::ERROR_OCCURRED: DVLOG(1) << "Entering state: ERROR_OCCURRED"; state_ = State::ERROR_OCCURRED; NotifyStateChanged(); EnterStateError(); break; case State::COUNT: NOTREACHED(); break; } } void RemoteSuggestionsProviderImpl::NotifyStateChanged() { if (!remote_suggestions_scheduler_) { return; } switch (state_) { case State::NOT_INITED: // Initial state, not sure yet whether active or not. break; case State::READY: remote_suggestions_scheduler_->OnProviderActivated(); break; case State::DISABLED: remote_suggestions_scheduler_->OnProviderDeactivated(); break; case State::ERROR_OCCURRED: remote_suggestions_scheduler_->OnProviderDeactivated(); break; case State::COUNT: NOTREACHED(); break; } } void RemoteSuggestionsProviderImpl::NotifyNewSuggestions( Category category, const CategoryContent& content) { DCHECK(IsCategoryStatusAvailable(content.status)); std::vector<ContentSuggestion> result = ConvertToContentSuggestions(category, content.suggestions); DVLOG(1) << "NotifyNewSuggestions(): " << result.size() << " items in category " << category; observer()->OnNewSuggestions(this, category, std::move(result)); } void RemoteSuggestionsProviderImpl::UpdateCategoryStatus( Category category, CategoryStatus status) { auto content_it = category_contents_.find(category); DCHECK(content_it != category_contents_.end()); CategoryContent& content = content_it->second; if (status == content.status) { return; } DVLOG(1) << "UpdateCategoryStatus(): " << category.id() << ": " << static_cast<int>(content.status) << " -> " << static_cast<int>(status); content.status = status; observer()->OnCategoryStatusChanged(this, category, content.status); } void RemoteSuggestionsProviderImpl::UpdateAllCategoryStatus( CategoryStatus status) { for (const auto& category : category_contents_) { UpdateCategoryStatus(category.first, status); } } namespace { template <typename T> typename T::const_iterator FindSuggestionInContainer( const T& container, const std::string& id_within_category) { return std::find_if(container.begin(), container.end(), [&id_within_category]( const std::unique_ptr<RemoteSuggestion>& suggestion) { return suggestion->id() == id_within_category; }); } } // namespace const RemoteSuggestion* RemoteSuggestionsProviderImpl::CategoryContent::FindSuggestion( const std::string& id_within_category) const { // Search for the suggestion in current and archived suggestions. auto it = FindSuggestionInContainer(suggestions, id_within_category); if (it != suggestions.end()) { return it->get(); } auto archived_it = FindSuggestionInContainer(archived, id_within_category); if (archived_it != archived.end()) { return archived_it->get(); } auto dismissed_it = FindSuggestionInContainer(dismissed, id_within_category); if (dismissed_it != dismissed.end()) { return dismissed_it->get(); } return nullptr; } RemoteSuggestionsProviderImpl::CategoryContent* RemoteSuggestionsProviderImpl::UpdateCategoryInfo(Category category, const CategoryInfo& info) { auto content_it = category_contents_.find(category); if (content_it == category_contents_.end()) { content_it = category_contents_ .insert(std::make_pair(category, CategoryContent(info))) .first; } else { content_it->second.info = info; } return &content_it->second; } void RemoteSuggestionsProviderImpl::RestoreCategoriesFromPrefs() { // This must only be called at startup, before there are any categories. DCHECK(category_contents_.empty()); const base::ListValue* list = pref_service_->GetList(prefs::kRemoteSuggestionCategories); for (const std::unique_ptr<base::Value>& entry : *list) { const base::DictionaryValue* dict = nullptr; if (!entry->GetAsDictionary(&dict)) { DLOG(WARNING) << "Invalid category pref value: " << *entry; continue; } int id = 0; if (!dict->GetInteger(kCategoryContentId, &id)) { DLOG(WARNING) << "Invalid category pref value, missing '" << kCategoryContentId << "': " << *entry; continue; } base::string16 title; if (!dict->GetString(kCategoryContentTitle, &title)) { DLOG(WARNING) << "Invalid category pref value, missing '" << kCategoryContentTitle << "': " << *entry; continue; } bool included_in_last_server_response = false; if (!dict->GetBoolean(kCategoryContentProvidedByServer, &included_in_last_server_response)) { DLOG(WARNING) << "Invalid category pref value, missing '" << kCategoryContentProvidedByServer << "': " << *entry; continue; } bool allow_fetching_more_results = false; // This wasn't always around, so it's okay if it's missing. dict->GetBoolean(kCategoryContentAllowFetchingMore, &allow_fetching_more_results); Category category = Category::FromIDValue(id); // The ranker may not persist the order of remote categories. category_ranker_->AppendCategoryIfNecessary(category); // TODO(tschumann): The following has a bad smell that category // serialization / deserialization should not be done inside this // class. We should move that into a central place that also knows how to // parse data we received from remote backends. CategoryInfo info = category == articles_category_ ? BuildArticleCategoryInfo(title) : BuildRemoteCategoryInfo(title, allow_fetching_more_results); CategoryContent* content = UpdateCategoryInfo(category, info); content->included_in_last_server_response = included_in_last_server_response; } } void RemoteSuggestionsProviderImpl::StoreCategoriesToPrefs() { // Collect all the CategoryContents. std::vector<std::pair<Category, const CategoryContent*>> to_store; for (const auto& entry : category_contents_) { to_store.emplace_back(entry.first, &entry.second); } // The ranker may not persist the order, thus, it is stored by the provider. std::sort(to_store.begin(), to_store.end(), [this](const std::pair<Category, const CategoryContent*>& left, const std::pair<Category, const CategoryContent*>& right) { return category_ranker_->Compare(left.first, right.first); }); // Convert the relevant info into a base::ListValue for storage. base::ListValue list; for (const auto& entry : to_store) { const Category& category = entry.first; const CategoryContent& content = *entry.second; auto dict = base::MakeUnique<base::DictionaryValue>(); dict->SetInteger(kCategoryContentId, category.id()); // TODO(tschumann): Persist other properties of the CategoryInfo. dict->SetString(kCategoryContentTitle, content.info.title()); dict->SetBoolean(kCategoryContentProvidedByServer, content.included_in_last_server_response); bool has_fetch_action = content.info.additional_action() == ContentSuggestionsAdditionalAction::FETCH; dict->SetBoolean(kCategoryContentAllowFetchingMore, has_fetch_action); list.Append(std::move(dict)); } // Finally, store the result in the pref service. pref_service_->Set(prefs::kRemoteSuggestionCategories, list); } RemoteSuggestionsProviderImpl::CategoryContent::CategoryContent( const CategoryInfo& info) : info(info) {} RemoteSuggestionsProviderImpl::CategoryContent::CategoryContent( CategoryContent&&) = default; RemoteSuggestionsProviderImpl::CategoryContent::~CategoryContent() = default; RemoteSuggestionsProviderImpl::CategoryContent& RemoteSuggestionsProviderImpl::CategoryContent::operator=(CategoryContent&&) = default; } // namespace ntp_snippets
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
b68a1a8f30611453a584b845dfc47c5a5d0ada9e
375b9785b16c0a64beb58aac0c2c605b2197d566
/riscv-sim/src/PeriodicTimeout.cpp
1ad629ca0b955041e7daef0e5a4662260aaa360f
[]
no_license
linwj130013/riscv-console
51a67f6ee53f36ebe369ac5459aa931e297aef6f
2110e388e34320f09a81a26891cbdeab12c548cc
refs/heads/main
2023-02-18T09:48:08.845556
2021-01-19T19:02:29
2021-01-19T19:02:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,578
cpp
#include "PeriodicTimeout.h" #include <cstdint> /* int CTimeout::SecondsUntilDeadline(struct timeval deadline){ struct timeval CurrentTime; gettimeofday(&CurrentTime, nullptr); return ((deadline.tv_sec * 1000 + deadline.tv_usec / 1000) - (CurrentTime.tv_sec * 1000 + CurrentTime.tv_usec / 1000)) / 1000; }; int CTimeout::MiliSecondsUntilDeadline(struct timeval deadline){ struct timeval CurrentTime; gettimeofday(&CurrentTime, nullptr); return ((deadline.tv_sec * 1000 + deadline.tv_usec / 1000) - (CurrentTime.tv_sec * 1000 + CurrentTime.tv_usec / 1000)); }; */ CPeriodicTimeout::CPeriodicTimeout(int periodms){ gettimeofday(&DNextExpectedTimeout, nullptr); if(0 >= periodms){ DTimeoutInterval = 1000; } else{ DTimeoutInterval = periodms; } } int CPeriodicTimeout::MiliSecondsUntilDeadline(){ struct timeval CurrentTime; int64_t TimeDelta; gettimeofday(&CurrentTime, nullptr); TimeDelta = (DNextExpectedTimeout.tv_sec * 1000 + DNextExpectedTimeout.tv_usec / 1000) - (CurrentTime.tv_sec * 1000 + CurrentTime.tv_usec / 1000); while(0 >= TimeDelta){ DNextExpectedTimeout.tv_usec += DTimeoutInterval * 1000; if(1000000 <= DNextExpectedTimeout.tv_usec){ DNextExpectedTimeout.tv_usec %= 1000000; DNextExpectedTimeout.tv_sec++; } TimeDelta = (DNextExpectedTimeout.tv_sec * 1000 + DNextExpectedTimeout.tv_usec / 1000) - (CurrentTime.tv_sec * 1000 + CurrentTime.tv_usec / 1000); } return TimeDelta; }
[ "cjnitta@gmail.com" ]
cjnitta@gmail.com
0098a2071bfd262e9c3c0c7f72d3ef07c72ca0e1
713870ba408d1b56d8d2b377b1caba918915a70d
/queue/queue.h
86cd78a1f5f1cfb7918a737cc2880e85364ca6b6
[]
no_license
berkerdemirel/data-structures
70fb99354a1a49c1028d81467fa1df608dd6b319
0b9dcdabb2b27d766feac07f52e313ae6977b4a4
refs/heads/master
2021-07-20T01:29:04.226272
2020-08-04T12:25:14
2020-08-04T12:25:14
201,508,413
2
0
null
null
null
null
UTF-8
C++
false
false
408
h
#pragma once #include <iostream> template <class T> struct queueNode { T val; queueNode* next; queueNode(T v = T(), queueNode* n= NULL): val(v), next(n){} }; template <class T> class queue { private: queueNode<T> * front; queueNode<T> * rear; int currentSize; public: queue(); void enqueue(T val); void dequeue(); T getFront(); int getSize(); bool isEmpty(); ~queue(); }; #include "queue.cpp"
[ "berkerdemirel@sabanciuniv.edu" ]
berkerdemirel@sabanciuniv.edu
b44763de55dad5d2d2465116f1de48f19f19bdb9
b9e46960a43d2a735f9170b97852d097c743f142
/src/helpers.cc
d97cb2188decca7cb45a27a1fae050c46e616f88
[ "MIT" ]
permissive
tunamako/cs426-shell
9151ec70d298ccdb2ef2d3b10567457b6a0035f9
b9b17bccc2fd4e9f2d4e03b2268cf7d7e1ebd2f6
refs/heads/master
2021-08-11T13:38:54.959523
2017-11-13T20:17:58
2017-11-13T20:17:58
108,306,895
0
0
null
2017-10-26T01:21:21
2017-10-25T18:06:40
C++
UTF-8
C++
false
false
2,109
cc
#include "helpers.h" #include <sstream> using namespace std; void ErrorCheckExit(bool condition, string message) { if(condition) { perror(message.c_str()); exit(1); } } void ErrorCheck(bool condition, string message) { if(condition) perror(message.c_str()); } //Some info on stringstreams from //https://stackoverflow.com/questions/11719538/how-to-use-stringstream-to-separate-comma-separated-strings vector<string> splitStr(string aString, char delimiter) { vector<string> ret; stringstream ss(aString); string temp; while (getline(ss, temp, delimiter)) ret.push_back(temp); return ret; } string getEnv(string varname) { extern char **environ; int i = 0; char *next = environ[i]; while(next){ if(string(next).substr(0,varname.size()) == varname) return string(next).substr(varname.size() + 1, strlen(next)); next = environ[i++]; } return ""; } string getPwd() { char temp[4096]; ErrorCheckExit(getcwd(temp, 4096) == NULL, "getcwd"); return string(temp); } char **convertVector(vector<string> &aVector) { char **ret = new char*[aVector.size()]; for(uint i = 0; i < aVector.size(); i++) { int strsize = aVector[i].size(); char *temp = strdup(aVector[i].c_str()); ret[i] = new char[strsize]; strncpy(ret[i], temp, strsize); ret[i][strsize] = 0; } ret[aVector.size()] = NULL; return ret; } string findBin(string cmd) { struct stat buf; if(stat(cmd.c_str(), &buf) == 0) return cmd; string executable; vector<string> pathdirs = splitStr(getEnv("PATH"),':'); for(auto dir : pathdirs) { executable = dir + "/" + cmd; if(stat(executable.c_str(), &buf) == 0) return executable; } return ""; } //Getting the index of the iterator on return is from: //https://stackoverflow.com/questions/24997910/get-index-in-vector-from-reverse-iterator int getLastPositionOf(vector<string> &input, string delims) { vector<string>::reverse_iterator iter = input.rbegin(); while(iter != input.rend()) { for(auto op : delims) { string temp(1, op); if(*iter == temp) return distance(input.begin(), iter.base()) - 1; } *iter++; } return -1; }
[ "inedibledelicacies@gmail.com" ]
inedibledelicacies@gmail.com
352ad87dc44b5689ecb0615591c65dfdb14cfca3
0d2deffa50a1596fbc5c4b04b7235932c0f6a695
/src/qt/rpcconsole.cpp
f4be39dd95b27a8b75735b7296304c121b58a19a
[ "MIT" ]
permissive
cjcoingit/cjcoingitrepo
031cf3f3abdb07cfcfc5aa5d6d93916ff58e2b1a
edbf67c2bfd9050862334f32f9a1922c684857b2
refs/heads/master
2021-01-18T23:34:52.463067
2017-04-10T18:28:41
2017-04-10T18:28:41
87,119,204
1
2
null
null
null
null
UTF-8
C++
false
false
14,607
cpp
#include "rpcconsole.h" #include "ui_rpcconsole.h" #include "clientmodel.h" #include "bitcoinrpc.h" #include "guiutil.h" #include <QTime> #include <QTimer> #include <QThread> #include <QTextEdit> #include <QKeyEvent> #include <QUrl> #include <QScrollBar> #include <openssl/crypto.h> // TODO: make it possible to filter out categories (esp debug messages when implemented) // TODO: receive errors and debug messages through ClientModel const int CONSOLE_SCROLLBACK = 50; const int CONSOLE_HISTORY = 50; const QSize ICON_SIZE(24, 24); const struct { const char *url; const char *source; } ICON_MAPPING[] = { {"cmd-request", ":/icons/tx_input"}, {"cmd-reply", ":/icons/tx_output"}, {"cmd-error", ":/icons/tx_output"}, {"misc", ":/icons/tx_inout"}, {NULL, NULL} }; /* Object for executing console RPC commands in a separate thread. */ class RPCExecutor: public QObject { Q_OBJECT public slots: void start(); void request(const QString &command); signals: void reply(int category, const QString &command); }; #include "rpcconsole.moc" void RPCExecutor::start() { // Nothing to do } /** * Split shell command line into a list of arguments. Aims to emulate \c bash and friends. * * - Arguments are delimited with whitespace * - Extra whitespace at the beginning and end and between arguments will be ignored * - Text can be "double" or 'single' quoted * - The backslash \c \ is used as escape character * - Outside quotes, any character can be escaped * - Within double quotes, only escape \c " and backslashes before a \c " or another backslash * - Within single quotes, no escaping is possible and no special interpretation takes place * * @param[out] args Parsed arguments will be appended to this list * @param[in] strCommand Command line to split */ bool parseCommandLine(std::vector<std::string> &args, const std::string &strCommand) { enum CmdParseState { STATE_EATING_SPACES, STATE_ARGUMENT, STATE_SINGLEQUOTED, STATE_DOUBLEQUOTED, STATE_ESCAPE_OUTER, STATE_ESCAPE_DOUBLEQUOTED } state = STATE_EATING_SPACES; std::string curarg; foreach(char ch, strCommand) { switch(state) { case STATE_ARGUMENT: // In or after argument case STATE_EATING_SPACES: // Handle runs of whitespace switch(ch) { case '"': state = STATE_DOUBLEQUOTED; break; case '\'': state = STATE_SINGLEQUOTED; break; case '\\': state = STATE_ESCAPE_OUTER; break; case ' ': case '\n': case '\t': if(state == STATE_ARGUMENT) // Space ends argument { args.push_back(curarg); curarg.clear(); } state = STATE_EATING_SPACES; break; default: curarg += ch; state = STATE_ARGUMENT; } break; case STATE_SINGLEQUOTED: // Single-quoted string switch(ch) { case '\'': state = STATE_ARGUMENT; break; default: curarg += ch; } break; case STATE_DOUBLEQUOTED: // Double-quoted string switch(ch) { case '"': state = STATE_ARGUMENT; break; case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break; default: curarg += ch; } break; case STATE_ESCAPE_OUTER: // '\' outside quotes curarg += ch; state = STATE_ARGUMENT; break; case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself curarg += ch; state = STATE_DOUBLEQUOTED; break; } } switch(state) // final state { case STATE_EATING_SPACES: return true; case STATE_ARGUMENT: args.push_back(curarg); return true; default: // ERROR to end in one of the other states return false; } } void RPCExecutor::request(const QString &command) { std::vector<std::string> args; if(!parseCommandLine(args, command.toStdString())) { emit reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \"")); return; } if(args.empty()) return; // Nothing to do try { std::string strPrint; // Convert argument list to JSON objects in method-dependent way, // and pass it along with the method name to the dispatcher. json_spirit::Value result = tableRPC.execute( args[0], RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end()))); // Format result reply if (result.type() == json_spirit::null_type) strPrint = ""; else if (result.type() == json_spirit::str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint)); } catch (json_spirit::Object& objError) { try // Nice formatting for standard-format error { int code = find_value(objError, "code").get_int(); std::string message = find_value(objError, "message").get_str(); emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")"); } catch(std::runtime_error &) // raised when converting to invalid type, i.e. missing code or message { // Show raw JSON object emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false))); } } catch (std::exception& e) { emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what())); } } RPCConsole::RPCConsole(QWidget *parent) : QDialog(parent), ui(new Ui::RPCConsole), historyPtr(0) { ui->setupUi(this); #ifndef Q_OS_MAC ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export")); ui->showCLOptionsButton->setIcon(QIcon(":/icons/options")); #endif // Install event filter for up and down arrow ui->lineEdit->installEventFilter(this); ui->messagesWidget->installEventFilter(this); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // set OpenSSL version label ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION)); startExecutor(); clear(); } RPCConsole::~RPCConsole() { emit stopExecutor(); delete ui; } bool RPCConsole::eventFilter(QObject* obj, QEvent *event) { if(event->type() == QEvent::KeyPress) // Special key handling { QKeyEvent *keyevt = static_cast<QKeyEvent*>(event); int key = keyevt->key(); Qt::KeyboardModifiers mod = keyevt->modifiers(); switch(key) { case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break; case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break; case Qt::Key_PageUp: /* pass paging keys to messages widget */ case Qt::Key_PageDown: if(obj == ui->lineEdit) { QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt)); return true; } break; default: // Typing in messages widget brings focus to line edit, and redirects key there // Exclude most combinations and keys that emit no text, except paste shortcuts if(obj == ui->messagesWidget && ( (!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) || ((mod & Qt::ControlModifier) && key == Qt::Key_V) || ((mod & Qt::ShiftModifier) && key == Qt::Key_Insert))) { ui->lineEdit->setFocus(); QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt)); return true; } } } return QDialog::eventFilter(obj, event); } void RPCConsole::setClientModel(ClientModel *model) { this->clientModel = model; if(model) { // Subscribe to information, replies, messages, errors connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); connect(model, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int))); // Provide initial values ui->clientVersion->setText(model->formatFullVersion()); ui->clientName->setText(model->clientName()); ui->buildDate->setText(model->formatBuildDate()); ui->startupTime->setText(model->formatClientStartupTime()); setNumConnections(model->getNumConnections()); ui->isTestNet->setChecked(model->isTestNet()); setNumBlocks(model->getNumBlocks(), model->getNumBlocksOfPeers()); } } static QString categoryClass(int category) { switch(category) { case RPCConsole::CMD_REQUEST: return "cmd-request"; break; case RPCConsole::CMD_REPLY: return "cmd-reply"; break; case RPCConsole::CMD_ERROR: return "cmd-error"; break; default: return "misc"; } } void RPCConsole::clear() { ui->messagesWidget->clear(); ui->lineEdit->clear(); ui->lineEdit->setFocus(); // Add smoothly scaled icon images. // (when using width/height on an img, Qt uses nearest instead of linear interpolation) for(int i=0; ICON_MAPPING[i].url; ++i) { ui->messagesWidget->document()->addResource( QTextDocument::ImageResource, QUrl(ICON_MAPPING[i].url), QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); } // Set default style sheet ui->messagesWidget->document()->setDefaultStyleSheet( "table { }" "td.time { color: #808080; padding-top: 3px; } " "td.message { font-family: Monospace; font-size: 12px; } " "td.cmd-request { color: #093d76; } " "td.cmd-error { color: red; } " "b { color: #093d76; } " ); message(CMD_REPLY, (tr("Welcome to the Cryptojournal RPC console.") + "<br>" + tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" + tr("Type <b>help</b> for an overview of available commands.")), true); } void RPCConsole::message(int category, const QString &message, bool html) { QTime time = QTime::currentTime(); QString timeString = time.toString(); QString out; out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>"; out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>"; out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">"; if(html) out += message; else out += GUIUtil::HtmlEscape(message, true); out += "</td></tr></table>"; ui->messagesWidget->append(out); } void RPCConsole::setNumConnections(int count) { ui->numberOfConnections->setText(QString::number(count)); } void RPCConsole::setNumBlocks(int count, int countOfPeers) { ui->numberOfBlocks->setText(QString::number(count)); ui->totalBlocks->setText(QString::number(countOfPeers)); if(clientModel) { // If there is no current number available display N/A instead of 0, which can't ever be true ui->totalBlocks->setText(clientModel->getNumBlocksOfPeers() == 0 ? tr("N/A") : QString::number(clientModel->getNumBlocksOfPeers())); ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString()); } } void RPCConsole::on_lineEdit_returnPressed() { QString cmd = ui->lineEdit->text(); ui->lineEdit->clear(); if(!cmd.isEmpty()) { message(CMD_REQUEST, cmd); emit cmdRequest(cmd); // Truncate history from current position history.erase(history.begin() + historyPtr, history.end()); // Append command to history history.append(cmd); // Enforce maximum history size while(history.size() > CONSOLE_HISTORY) history.removeFirst(); // Set pointer to end of history historyPtr = history.size(); // Scroll console view to end scrollToEnd(); } } void RPCConsole::browseHistory(int offset) { historyPtr += offset; if(historyPtr < 0) historyPtr = 0; if(historyPtr > history.size()) historyPtr = history.size(); QString cmd; if(historyPtr < history.size()) cmd = history.at(historyPtr); ui->lineEdit->setText(cmd); } void RPCConsole::startExecutor() { QThread* thread = new QThread; RPCExecutor *executor = new RPCExecutor(); executor->moveToThread(thread); // Notify executor when thread started (in executor thread) connect(thread, SIGNAL(started()), executor, SLOT(start())); // Replies from executor object must go to this object connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString))); // Requests from this object must go to executor connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString))); // On stopExecutor signal // - queue executor for deletion (in execution thread) // - quit the Qt event loop in the execution thread connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit())); // Queue the thread for deletion (in this thread) when it is finished connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); // Default implementation of QThread::run() simply spins up an event loop in the thread, // which is what we want. thread->start(); } void RPCConsole::on_tabWidget_currentChanged(int index) { if(ui->tabWidget->widget(index) == ui->tab_console) { ui->lineEdit->setFocus(); } } void RPCConsole::on_openDebugLogfileButton_clicked() { GUIUtil::openDebugLogfile(); } void RPCConsole::scrollToEnd() { QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar(); scrollbar->setValue(scrollbar->maximum()); } void RPCConsole::on_showCLOptionsButton_clicked() { GUIUtil::HelpMessageBox help; help.exec(); } void RPCConsole::showTab_Debug() { ui->tabWidget->setCurrentIndex(1); this->show(); }
[ "cryptojournalcoin@gmail.com" ]
cryptojournalcoin@gmail.com
55bc2f3ec4af350954b06b24a9924ea6de4ffd84
e0387cf8f45d3e2b7ea3788b299f195a621708a8
/Source/Sable/Core/Bank/Library.cpp
be2c984cd6513b36a15b555f60daa2836ffd85f5
[]
no_license
ClementVidal/sable.sable
eea0e822d90739269e35bed20805a2789b5fbc81
0ec2cd03867a4673472c1bc7b071a3f16b55fb1b
refs/heads/master
2021-01-13T01:28:54.070144
2013-10-15T15:21:49
2013-10-15T15:21:49
39,085,785
0
0
null
null
null
null
UTF-8
C++
false
false
2,859
cpp
#include <Sable\Core\Bank\Library.h> IMPLEMENT_MANAGED_CLASS1( Sable, CBankLibrary, CPersistentArchive ) using namespace Sable; CBankLibrary::CBankLibrary( ) { m_NextFreeId = 0; m_CurrentBank = NULL; m_IsStoring = FALSE; } CBankLibrary::~CBankLibrary() { } Int64 CBankLibrary::GetIDFromObject( CManagedObject* obj ) const { UInt32 addr = (UInt32) obj; if( m_ObjectToID.HasItem( obj ) ) return m_ObjectToID.GetItem( obj ); return -1; } CManagedObject* CBankLibrary::GetObjectFromID( Int64 id ) const { if( m_IDToObject.HasItem( id ) ) return m_IDToObject.GetItem( id ); return NULL; } Void CBankLibrary::AddObject( CManagedObject* obj, Int64 id ) { DebugAssert( obj ); DebugAssert( m_ObjectToID.HasItem( obj ) == FALSE ); m_ObjectToID.AddItem( obj, id ); m_IDToObject.AddItem( id, obj ); Int64 bankId = id; bankId >>= 32; CBank* b = FindBank( (HashValue)bankId ); if( b ) m_CurrentBank = b; m_CurrentBank->GetArchive().AddObjectWithoutLibraryLookup( obj, id ); } Int64 CBankLibrary::AcquirePointerID( CManagedObject* obj ) { DebugAssert( m_ObjectToID.HasItem( obj ) == FALSE ); Int64 i = -1; CBank* b = FindBank( obj ); if( b ) m_CurrentBank = b; DebugAssert( m_CurrentBank ); Int64 msb = m_CurrentBank->GetId(); Int64 lsb = m_NextFreeId; i = msb; i <<= 32; i |= lsb; m_NextFreeId++; return i; } CBank* CBankLibrary::FindBank( HashValue bankId ) const { BankTable::Iterator it; ForEachItem( it, m_BankTable ) { if( (*it)->GetId() == bankId ) return (*it); } return NULL; } CBank* CBankLibrary::FindBank( CManagedObject* obj ) const { BankTable::Iterator it; ForEachItem( it, m_BankTable ) { if( (*it)->HasObject( obj ) ) return (*it); } return NULL; } CBank* CBankLibrary::GetBank( String name ) const { BankTable::Iterator it; ForEachItem( it, m_BankTable ) { if( StringCompare( (*it)->GetName(), name ) == 0 ) return *it; } return NULL; } Bool CBankLibrary::Save() { BankTable::Iterator it; m_IsStoring = TRUE; ForEachItem( it, m_BankTable ) { (*it)->Open( nAccesMode_Write ); } ForEachItem( it, m_BankTable ) { (*it)->Save( ); } return TRUE; } Bool CBankLibrary::Load() { BankTable::Iterator it; m_IsStoring = FALSE; ForEachItem( it, m_BankTable ) { if( !(*it)->Open( nAccesMode_Read ) ) return FALSE; } ForEachItem( it, m_BankTable ) { (*it)->Load( ); } return TRUE; } /** Add a new bank to this library. TODO: Check if a bank with the given path is not already loaded */ Bool CBankLibrary::AddBank( const CFilePath& path ) { CBank* b = NEWOBJ( CBank, () ); b->SetFilePath( path ); b->SetLibrary( this ); m_BankTable.AddItemAtEnd( b ); return TRUE; }
[ "clement.vidal@lam.fr" ]
clement.vidal@lam.fr
2be5550dd140d59e3e44d8861d3fa728b407575e
aba5baef6d4680e668671e811e0cb4496f0f9140
/dask_em/tokenizer/qgramtokenizer.cpp
eb0bccda6e0d44b01346589032948f92ce621dcf
[]
no_license
kvpradap/dask_em
76cd491db87940359c64f9fc0a87be50914d6d02
727c68c6ac7c31b86b641bc9844c3594ca11f2fc
refs/heads/master
2021-01-16T18:26:40.033433
2017-08-14T23:20:47
2017-08-14T23:20:47
100,081,260
0
0
null
null
null
null
UTF-8
C++
false
true
162,256
cpp
/* Generated by Cython 0.25.2 */ #define PY_SSIZE_T_CLEAN #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. #elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03020000) #error Cython requires Python 2.6+ or Python 3.2+. #else #define CYTHON_ABI "0_25_2" #include <stddef.h> #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall #endif #ifndef __cdecl #define __cdecl #endif #ifndef __fastcall #define __fastcall #endif #endif #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif #ifndef HAVE_LONG_LONG #if PY_VERSION_HEX >= 0x03030000 || (PY_MAJOR_VERSION == 2 && PY_VERSION_HEX >= 0x02070000) #define HAVE_LONG_LONG #endif #endif #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif #ifndef Py_HUGE_VAL #define Py_HUGE_VAL HUGE_VAL #endif #ifdef PYPY_VERSION #define CYTHON_COMPILING_IN_PYPY 1 #define CYTHON_COMPILING_IN_PYSTON 0 #define CYTHON_COMPILING_IN_CPYTHON 0 #undef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 0 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #undef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 0 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #undef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 1 #undef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 0 #undef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 0 #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #elif defined(PYSTON_VERSION) #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_PYSTON 1 #define CYTHON_COMPILING_IN_CPYTHON 0 #ifndef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 1 #endif #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #ifndef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 1 #endif #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #ifndef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 0 #endif #ifndef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 1 #endif #ifndef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 1 #endif #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #else #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_PYSTON 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #ifndef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 1 #endif #if PY_MAJOR_VERSION < 3 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #elif !defined(CYTHON_USE_ASYNC_SLOTS) #define CYTHON_USE_ASYNC_SLOTS 1 #endif #if PY_VERSION_HEX < 0x02070000 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #elif !defined(CYTHON_USE_PYLONG_INTERNALS) #define CYTHON_USE_PYLONG_INTERNALS 1 #endif #ifndef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 1 #endif #ifndef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 1 #endif #if PY_VERSION_HEX < 0x030300F0 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #elif !defined(CYTHON_USE_UNICODE_WRITER) #define CYTHON_USE_UNICODE_WRITER 1 #endif #ifndef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 0 #endif #ifndef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 1 #endif #ifndef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 1 #endif #ifndef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 1 #endif #ifndef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 1 #endif #endif #if !defined(CYTHON_FAST_PYCCALL) #define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) #endif #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #undef SHIFT #undef BASE #undef MASK #endif #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) #define Py_OptimizeFlag 0 #endif #define __PYX_BUILD_PY_SSIZE_T "n" #define CYTHON_FORMAT_SSIZE_T "z" #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyType_Type #endif #ifndef Py_TPFLAGS_CHECKTYPES #define Py_TPFLAGS_CHECKTYPES 0 #endif #ifndef Py_TPFLAGS_HAVE_INDEX #define Py_TPFLAGS_HAVE_INDEX 0 #endif #ifndef Py_TPFLAGS_HAVE_NEWBUFFER #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif #ifndef Py_TPFLAGS_HAVE_FINALIZE #define Py_TPFLAGS_HAVE_FINALIZE 0 #endif #ifndef METH_FASTCALL #define METH_FASTCALL 0x80 typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames); #else #define __Pyx_PyCFunctionFast _PyCFunctionFast #endif #if CYTHON_FAST_PYCCALL #define __Pyx_PyFastCFunction_Check(func)\ ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST))))) #else #define __Pyx_PyFastCFunction_Check(func) 0 #endif #if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ 0 : _PyUnicode_Ready((PyObject *)(op))) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch) #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) #else #define CYTHON_PEP393_ENABLED 0 #define PyUnicode_1BYTE_KIND 1 #define PyUnicode_2BYTE_KIND 2 #define PyUnicode_4BYTE_KIND 4 #define __Pyx_PyUnicode_READY(op) (0) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111) #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch) #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) #endif #if CYTHON_COMPILING_IN_PYPY #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) #else #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check) #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format) #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) #define PyObject_Malloc(s) PyMem_Malloc(s) #define PyObject_Free(p) PyMem_Free(p) #define PyObject_Realloc(p) PyMem_Realloc(p) #endif #if CYTHON_COMPILING_IN_PYSTON #define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co) #define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno) #else #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) #endif #define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) #define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) #else #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) #endif #if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) #define PyObject_ASCII(o) PyObject_Repr(o) #endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject #define PyString_Type PyUnicode_Type #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) #else #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) #endif #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) #define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type #define PyInt_Check(op) PyLong_Check(op) #define PyInt_CheckExact(op) PyLong_CheckExact(op) #define PyInt_FromString PyLong_FromString #define PyInt_FromUnicode PyLong_FromUnicode #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSize_t PyLong_FromSize_t #define PyInt_FromSsize_t PyLong_FromSsize_t #define PyInt_AsLong PyLong_AsLong #define PyInt_AS_LONG PyLong_AS_LONG #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #define PyNumber_Int PyNumber_Long #endif #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif #if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY #ifndef PyUnicode_InternFromString #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) #endif #endif #if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong #else #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #else #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) #endif #if CYTHON_USE_ASYNC_SLOTS #if PY_VERSION_HEX >= 0x030500B1 #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) #else typedef struct { unaryfunc am_await; unaryfunc am_aiter; unaryfunc am_anext; } __Pyx_PyAsyncMethodsStruct; #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) #endif #else #define __Pyx_PyType_AsAsync(obj) NULL #endif #ifndef CYTHON_RESTRICT #if defined(__GNUC__) #define CYTHON_RESTRICT __restrict__ #elif defined(_MSC_VER) && _MSC_VER >= 1400 #define CYTHON_RESTRICT __restrict #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_RESTRICT restrict #else #define CYTHON_RESTRICT #endif #endif #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif # elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif #ifndef CYTHON_MAYBE_UNUSED_VAR # if defined(__cplusplus) template<class T> void CYTHON_MAYBE_UNUSED_VAR( const T& ) { } # else # define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x) # endif #endif #ifndef CYTHON_NCP_UNUSED # if CYTHON_COMPILING_IN_CPYTHON # define CYTHON_NCP_UNUSED # else # define CYTHON_NCP_UNUSED CYTHON_UNUSED # endif #endif #define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) #ifndef __cplusplus #error "Cython files generated with the C++ option must be compiled with a C++ compiler." #endif #ifndef CYTHON_INLINE #if defined(__clang__) #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) #else #define CYTHON_INLINE inline #endif #endif template<typename T> void __Pyx_call_destructor(T& x) { x.~T(); } template<typename T> class __Pyx_FakeReference { public: __Pyx_FakeReference() : ptr(NULL) { } __Pyx_FakeReference(const T& ref) : ptr(const_cast<T*>(&ref)) { } T *operator->() { return ptr; } T *operator&() { return ptr; } operator T&() { return *ptr; } template<typename U> bool operator ==(U other) { return *ptr == other; } template<typename U> bool operator !=(U other) { return *ptr != other; } private: T *ptr; }; #if defined(WIN32) || defined(MS_WINDOWS) #define _USE_MATH_DEFINES #endif #include <math.h> #ifdef NAN #define __PYX_NAN() ((float) NAN) #else static CYTHON_INLINE float __PYX_NAN() { float value; memset(&value, 0xFF, sizeof(value)); return value; } #endif #if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) #define __Pyx_truncl trunc #else #define __Pyx_truncl truncl #endif #define __PYX_ERR(f_index, lineno, Ln_error) \ { \ __pyx_filename = __pyx_f[f_index]; __pyx_lineno = lineno; __pyx_clineno = __LINE__; goto Ln_error; \ } #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) #else #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) #endif #ifndef __PYX_EXTERN_C #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #endif #define __PYX_HAVE__dask_em__tokenizer__qgramtokenizer #define __PYX_HAVE_API__dask_em__tokenizer__qgramtokenizer #include <string.h> #include <string> #include "ios" #include "new" #include "stdexcept" #include "typeinfo" #include <vector> #include <utility> #include <set> #include <map> #ifdef _OPENMP #include <omp.h> #endif /* _OPENMP */ #ifdef PYREX_WITHOUT_ASSERTIONS #define CYTHON_WITHOUT_ASSERTIONS #endif typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; #define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 #define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 #define __PYX_DEFAULT_STRING_ENCODING "" #define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString #define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #define __Pyx_uchar_cast(c) ((unsigned char)c) #define __Pyx_long_cast(x) ((long)x) #define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ (sizeof(type) < sizeof(Py_ssize_t)) ||\ (sizeof(type) > sizeof(Py_ssize_t) &&\ likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX) &&\ (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ v == (type)PY_SSIZE_T_MIN))) ||\ (sizeof(type) == sizeof(Py_ssize_t) &&\ (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX))) ) #if defined (__cplusplus) && __cplusplus >= 201103L #include <cstdlib> #define __Pyx_sst_abs(value) std::abs(value) #elif SIZEOF_INT >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) abs(value) #elif SIZEOF_LONG >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) labs(value) #elif defined (_MSC_VER) && defined (_M_X64) #define __Pyx_sst_abs(value) _abs64(value) #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define __Pyx_sst_abs(value) llabs(value) #elif defined (__GNUC__) #define __Pyx_sst_abs(value) __builtin_llabs(value) #else #define __Pyx_sst_abs(value) ((value<0) ? -value : value) #endif static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); #define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) #define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) #define __Pyx_PyBytes_FromString PyBytes_FromString #define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); #if PY_MAJOR_VERSION < 3 #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #else #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize #endif #define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) #define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) #define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) #define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) #define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) #if PY_MAJOR_VERSION < 3 static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { const Py_UNICODE *u_end = u; while (*u_end++) ; return (size_t)(u_end - u - 1); } #else #define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen #endif #define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) #define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode #define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) #define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); #if CYTHON_ASSUME_SAFE_MACROS #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) #else #define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) #endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) #else #define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) #endif #define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x)) #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII static int __Pyx_sys_getdefaultencoding_not_ascii; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys; PyObject* default_encoding = NULL; PyObject* ascii_chars_u = NULL; PyObject* ascii_chars_b = NULL; const char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); if (!default_encoding_c) goto bad; if (strcmp(default_encoding_c, "ascii") == 0) { __Pyx_sys_getdefaultencoding_not_ascii = 0; } else { char ascii_chars[128]; int c; for (c = 0; c < 128; c++) { ascii_chars[c] = c; } __Pyx_sys_getdefaultencoding_not_ascii = 1; ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); if (!ascii_chars_u) goto bad; ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { PyErr_Format( PyExc_ValueError, "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", default_encoding_c); goto bad; } Py_DECREF(ascii_chars_u); Py_DECREF(ascii_chars_b); } Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); Py_XDECREF(ascii_chars_u); Py_XDECREF(ascii_chars_b); return -1; } #endif #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) #else #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT static char* __PYX_DEFAULT_STRING_ENCODING; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys; PyObject* default_encoding = NULL; char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); if (!default_encoding_c) goto bad; __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); return -1; } #endif #endif /* Test for GCC > 2.95 */ #if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #else /* !__GNUC__ or GCC < 2.95 */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ static PyObject *__pyx_m; static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; static PyObject *__pyx_empty_unicode; static int __pyx_lineno; static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; static const char *__pyx_f[] = { "dask_em/tokenizer/qgramtokenizer.pyx", "stringsource", }; /*--- Type declarations ---*/ struct __pyx_obj_7dask_em_9tokenizer_9tokenizer_Tokenizer; struct __pyx_obj_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer; /* "dask_em/tokenizer/tokenizer.pxd":6 * from libcpp.set cimport set as oset * * cdef class Tokenizer: # <<<<<<<<<<<<<< * cdef vector[string] ctokenize(self, string s) nogil * */ struct __pyx_obj_7dask_em_9tokenizer_9tokenizer_Tokenizer { PyObject_HEAD struct __pyx_vtabstruct_7dask_em_9tokenizer_9tokenizer_Tokenizer *__pyx_vtab; }; /* "dask_em/tokenizer/qgramtokenizer.pxd":8 * from dask_em.tokenizer.tokenizer cimport Tokenizer * * cdef class QgramTokenizer(Tokenizer): # <<<<<<<<<<<<<< * cdef int qval * cdef char prefix_pad, suffix_pad */ struct __pyx_obj_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer { struct __pyx_obj_7dask_em_9tokenizer_9tokenizer_Tokenizer __pyx_base; int qval; char prefix_pad; char suffix_pad; bool padding; bool return_set; }; /* "dask_em/tokenizer/tokenizer.pxd":6 * from libcpp.set cimport set as oset * * cdef class Tokenizer: # <<<<<<<<<<<<<< * cdef vector[string] ctokenize(self, string s) nogil * */ struct __pyx_vtabstruct_7dask_em_9tokenizer_9tokenizer_Tokenizer { std::vector<std::string> (*ctokenize)(struct __pyx_obj_7dask_em_9tokenizer_9tokenizer_Tokenizer *, std::string); }; static struct __pyx_vtabstruct_7dask_em_9tokenizer_9tokenizer_Tokenizer *__pyx_vtabptr_7dask_em_9tokenizer_9tokenizer_Tokenizer; /* "dask_em/tokenizer/qgramtokenizer.pyx":1 * cdef class QgramTokenizer(Tokenizer): # <<<<<<<<<<<<<< * def __init__(self, int qval=2, bool padding=True, char prefix_pad='#', char suffix_pad='$', bool return_set=False): * self.qval = qval */ struct __pyx_vtabstruct_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer { struct __pyx_vtabstruct_7dask_em_9tokenizer_9tokenizer_Tokenizer __pyx_base; }; static struct __pyx_vtabstruct_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer *__pyx_vtabptr_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer; /* --- Runtime support code (head) --- */ /* Refnanny.proto */ #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); void (*DECREF)(void*, PyObject*, int); void (*GOTREF)(void*, PyObject*, int); void (*GIVEREF)(void*, PyObject*, int); void* (*SetupContext)(const char*, int, const char*); void (*FinishContext)(void**); } __Pyx_RefNannyAPIStruct; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; #ifdef WITH_THREAD #define __Pyx_RefNannySetupContext(name, acquire_gil)\ if (acquire_gil) {\ PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ PyGILState_Release(__pyx_gilstate_save);\ } else {\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ } #else #define __Pyx_RefNannySetupContext(name, acquire_gil)\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) #endif #define __Pyx_RefNannyFinishContext()\ __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) #define __Pyx_GOTREF(r) #define __Pyx_GIVEREF(r) #define __Pyx_XINCREF(r) Py_XINCREF(r) #define __Pyx_XDECREF(r) Py_XDECREF(r) #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif #define __Pyx_XDECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; __Pyx_XDECREF(tmp);\ } while (0) #define __Pyx_DECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; __Pyx_DECREF(tmp);\ } while (0) #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) /* PyObjectGetAttrStr.proto */ #if CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { PyTypeObject* tp = Py_TYPE(obj); if (likely(tp->tp_getattro)) return tp->tp_getattro(obj, attr_name); #if PY_MAJOR_VERSION < 3 if (likely(tp->tp_getattr)) return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); #endif return PyObject_GetAttr(obj, attr_name); } #else #define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) #endif /* GetBuiltinName.proto */ static PyObject *__Pyx_GetBuiltinName(PyObject *name); /* RaiseDoubleKeywords.proto */ static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /* ParseKeywords.proto */ static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ const char* function_name); /* RaiseArgTupleInvalid.proto */ static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /* ForceInitThreads.proto */ #ifndef __PYX_FORCE_INIT_THREADS #define __PYX_FORCE_INIT_THREADS 0 #endif /* PyThreadStateGet.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; #define __Pyx_PyThreadState_assign __pyx_tstate = PyThreadState_GET(); #else #define __Pyx_PyThreadState_declare #define __Pyx_PyThreadState_assign #endif /* PyErrFetchRestore.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) #define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #else #define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) #define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) #endif /* WriteUnraisableException.proto */ static void __Pyx_WriteUnraisable(const char *name, int clineno, int lineno, const char *filename, int full_traceback, int nogil); /* ListCompAppend.proto */ #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { PyListObject* L = (PyListObject*) list; Py_ssize_t len = Py_SIZE(list); if (likely(L->allocated > len)) { Py_INCREF(x); PyList_SET_ITEM(list, len, x); Py_SIZE(list) = len+1; return 0; } return PyList_Append(list, x); } #else #define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) #endif /* CallNextTpDealloc.proto */ static void __Pyx_call_next_tp_dealloc(PyObject* obj, destructor current_tp_dealloc); /* GetVTable.proto */ static void* __Pyx_GetVtable(PyObject *dict); /* SetVTable.proto */ static int __Pyx_SetVtable(PyObject *dict, void *vtable); /* CodeObjectCache.proto */ typedef struct { PyCodeObject* code_object; int code_line; } __Pyx_CodeObjectCacheEntry; struct __Pyx_CodeObjectCache { int count; int max_count; __Pyx_CodeObjectCacheEntry* entries; }; static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); static PyCodeObject *__pyx_find_code_object(int code_line); static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); /* AddTraceback.proto */ static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename); /* CppExceptionConversion.proto */ #ifndef __Pyx_CppExn2PyErr #include <new> #include <typeinfo> #include <stdexcept> #include <ios> static void __Pyx_CppExn2PyErr() { try { if (PyErr_Occurred()) ; // let the latest Python exn pass through and ignore the current one else throw; } catch (const std::bad_alloc& exn) { PyErr_SetString(PyExc_MemoryError, exn.what()); } catch (const std::bad_cast& exn) { PyErr_SetString(PyExc_TypeError, exn.what()); } catch (const std::bad_typeid& exn) { PyErr_SetString(PyExc_TypeError, exn.what()); } catch (const std::domain_error& exn) { PyErr_SetString(PyExc_ValueError, exn.what()); } catch (const std::invalid_argument& exn) { PyErr_SetString(PyExc_ValueError, exn.what()); } catch (const std::ios_base::failure& exn) { PyErr_SetString(PyExc_IOError, exn.what()); } catch (const std::out_of_range& exn) { PyErr_SetString(PyExc_IndexError, exn.what()); } catch (const std::overflow_error& exn) { PyErr_SetString(PyExc_OverflowError, exn.what()); } catch (const std::range_error& exn) { PyErr_SetString(PyExc_ArithmeticError, exn.what()); } catch (const std::underflow_error& exn) { PyErr_SetString(PyExc_ArithmeticError, exn.what()); } catch (const std::exception& exn) { PyErr_SetString(PyExc_RuntimeError, exn.what()); } catch (...) { PyErr_SetString(PyExc_RuntimeError, "Unknown exception"); } } #endif /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_int(unsigned int value); /* CIntFromPy.proto */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); /* CIntFromPy.proto */ static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *); /* CIntFromPy.proto */ static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *); /* CIntFromPy.proto */ static CYTHON_INLINE size_t __Pyx_PyInt_As_size_t(PyObject *); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); /* CIntFromPy.proto */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); /* CheckBinaryVersion.proto */ static int __Pyx_check_binary_version(void); /* PyIdentifierFromString.proto */ #if !defined(__Pyx_PyIdentifier_FromString) #if PY_MAJOR_VERSION < 3 #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) #else #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) #endif #endif /* ModuleImport.proto */ static PyObject *__Pyx_ImportModule(const char *name); /* TypeImport.proto */ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /* InitStrings.proto */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); static std::vector<std::string> __pyx_f_7dask_em_9tokenizer_14qgramtokenizer_14QgramTokenizer_ctokenize(struct __pyx_obj_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer *__pyx_v_self, std::string const &__pyx_v_istring); /* proto*/ /* Module declarations from 'libc.string' */ /* Module declarations from 'libcpp.string' */ /* Module declarations from 'libcpp.vector' */ /* Module declarations from 'libcpp.utility' */ /* Module declarations from 'libcpp.set' */ /* Module declarations from 'libcpp.map' */ /* Module declarations from 'libcpp' */ /* Module declarations from 'dask_em.tokenizer.tokenizer' */ static PyTypeObject *__pyx_ptype_7dask_em_9tokenizer_9tokenizer_Tokenizer = 0; /* Module declarations from 'dask_em.tokenizer.qgramtokenizer' */ static PyTypeObject *__pyx_ptype_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer = 0; static std::string __pyx_convert_string_from_py_std__in_string(PyObject *); /*proto*/ static CYTHON_INLINE PyObject *__pyx_convert_PyObject_string_to_py_std__in_string(std::string const &); /*proto*/ static CYTHON_INLINE PyObject *__pyx_convert_PyUnicode_string_to_py_std__in_string(std::string const &); /*proto*/ static CYTHON_INLINE PyObject *__pyx_convert_PyStr_string_to_py_std__in_string(std::string const &); /*proto*/ static CYTHON_INLINE PyObject *__pyx_convert_PyBytes_string_to_py_std__in_string(std::string const &); /*proto*/ static CYTHON_INLINE PyObject *__pyx_convert_PyByteArray_string_to_py_std__in_string(std::string const &); /*proto*/ static PyObject *__pyx_convert_vector_to_py_std_3a__3a_string(const std::vector<std::string> &); /*proto*/ #define __Pyx_MODULE_NAME "dask_em.tokenizer.qgramtokenizer" int __pyx_module_is_main_dask_em__tokenizer__qgramtokenizer = 0; /* Implementation of 'dask_em.tokenizer.qgramtokenizer' */ static PyObject *__pyx_builtin_xrange; static PyObject *__pyx_builtin_range; static const char __pyx_k_main[] = "__main__"; static const char __pyx_k_qval[] = "qval"; static const char __pyx_k_test[] = "__test__"; static const char __pyx_k_range[] = "range"; static const char __pyx_k_xrange[] = "xrange"; static const char __pyx_k_padding[] = "padding"; static const char __pyx_k_prefix_pad[] = "prefix_pad"; static const char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; static const char __pyx_k_return_set[] = "return_set"; static const char __pyx_k_suffix_pad[] = "suffix_pad"; static PyObject *__pyx_n_s_main; static PyObject *__pyx_n_s_padding; static PyObject *__pyx_n_s_prefix_pad; static PyObject *__pyx_n_s_pyx_vtable; static PyObject *__pyx_n_s_qval; static PyObject *__pyx_n_s_range; static PyObject *__pyx_n_s_return_set; static PyObject *__pyx_n_s_suffix_pad; static PyObject *__pyx_n_s_test; static PyObject *__pyx_n_s_xrange; static int __pyx_pf_7dask_em_9tokenizer_14qgramtokenizer_14QgramTokenizer___init__(struct __pyx_obj_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer *__pyx_v_self, int __pyx_v_qval, bool __pyx_v_padding, char __pyx_v_prefix_pad, char __pyx_v_suffix_pad, bool __pyx_v_return_set); /* proto */ static PyObject *__pyx_pf_7dask_em_9tokenizer_14qgramtokenizer_14QgramTokenizer_2tokenize(struct __pyx_obj_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer *__pyx_v_self, std::string __pyx_v_istring); /* proto */ static PyObject *__pyx_tp_new_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ /* "dask_em/tokenizer/qgramtokenizer.pyx":2 * cdef class QgramTokenizer(Tokenizer): * def __init__(self, int qval=2, bool padding=True, char prefix_pad='#', char suffix_pad='$', bool return_set=False): # <<<<<<<<<<<<<< * self.qval = qval * self.padding = padding */ /* Python wrapper */ static int __pyx_pw_7dask_em_9tokenizer_14qgramtokenizer_14QgramTokenizer_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static int __pyx_pw_7dask_em_9tokenizer_14qgramtokenizer_14QgramTokenizer_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { int __pyx_v_qval; bool __pyx_v_padding; char __pyx_v_prefix_pad; char __pyx_v_suffix_pad; bool __pyx_v_return_set; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_qval,&__pyx_n_s_padding,&__pyx_n_s_prefix_pad,&__pyx_n_s_suffix_pad,&__pyx_n_s_return_set,0}; PyObject* values[5] = {0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_qval); if (value) { values[0] = value; kw_args--; } } case 1: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_padding); if (value) { values[1] = value; kw_args--; } } case 2: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_prefix_pad); if (value) { values[2] = value; kw_args--; } } case 3: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_suffix_pad); if (value) { values[3] = value; kw_args--; } } case 4: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_return_set); if (value) { values[4] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) __PYX_ERR(0, 2, __pyx_L3_error) } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } } if (values[0]) { __pyx_v_qval = __Pyx_PyInt_As_int(values[0]); if (unlikely((__pyx_v_qval == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2, __pyx_L3_error) } else { __pyx_v_qval = ((int)2); } if (values[1]) { __pyx_v_padding = __Pyx_PyObject_IsTrue(values[1]); if (unlikely((__pyx_v_padding == ((bool)-1)) && PyErr_Occurred())) __PYX_ERR(0, 2, __pyx_L3_error) } else { __pyx_v_padding = ((bool)1); } if (values[2]) { __pyx_v_prefix_pad = __Pyx_PyInt_As_char(values[2]); if (unlikely((__pyx_v_prefix_pad == (char)-1) && PyErr_Occurred())) __PYX_ERR(0, 2, __pyx_L3_error) } else { __pyx_v_prefix_pad = ((char)'#'); } if (values[3]) { __pyx_v_suffix_pad = __Pyx_PyInt_As_char(values[3]); if (unlikely((__pyx_v_suffix_pad == (char)-1) && PyErr_Occurred())) __PYX_ERR(0, 2, __pyx_L3_error) } else { __pyx_v_suffix_pad = ((char)'$'); } if (values[4]) { __pyx_v_return_set = __Pyx_PyObject_IsTrue(values[4]); if (unlikely((__pyx_v_return_set == ((bool)-1)) && PyErr_Occurred())) __PYX_ERR(0, 2, __pyx_L3_error) } else { __pyx_v_return_set = ((bool)0); } } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("__init__", 0, 0, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 2, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("dask_em.tokenizer.qgramtokenizer.QgramTokenizer.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_7dask_em_9tokenizer_14qgramtokenizer_14QgramTokenizer___init__(((struct __pyx_obj_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer *)__pyx_v_self), __pyx_v_qval, __pyx_v_padding, __pyx_v_prefix_pad, __pyx_v_suffix_pad, __pyx_v_return_set); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_7dask_em_9tokenizer_14qgramtokenizer_14QgramTokenizer___init__(struct __pyx_obj_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer *__pyx_v_self, int __pyx_v_qval, bool __pyx_v_padding, char __pyx_v_prefix_pad, char __pyx_v_suffix_pad, bool __pyx_v_return_set) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__init__", 0); /* "dask_em/tokenizer/qgramtokenizer.pyx":3 * cdef class QgramTokenizer(Tokenizer): * def __init__(self, int qval=2, bool padding=True, char prefix_pad='#', char suffix_pad='$', bool return_set=False): * self.qval = qval # <<<<<<<<<<<<<< * self.padding = padding * self.prefix_pad = prefix_pad */ __pyx_v_self->qval = __pyx_v_qval; /* "dask_em/tokenizer/qgramtokenizer.pyx":4 * def __init__(self, int qval=2, bool padding=True, char prefix_pad='#', char suffix_pad='$', bool return_set=False): * self.qval = qval * self.padding = padding # <<<<<<<<<<<<<< * self.prefix_pad = prefix_pad * self.suffix_pad = suffix_pad */ __pyx_v_self->padding = __pyx_v_padding; /* "dask_em/tokenizer/qgramtokenizer.pyx":5 * self.qval = qval * self.padding = padding * self.prefix_pad = prefix_pad # <<<<<<<<<<<<<< * self.suffix_pad = suffix_pad * self.return_set = return_set */ __pyx_v_self->prefix_pad = __pyx_v_prefix_pad; /* "dask_em/tokenizer/qgramtokenizer.pyx":6 * self.padding = padding * self.prefix_pad = prefix_pad * self.suffix_pad = suffix_pad # <<<<<<<<<<<<<< * self.return_set = return_set * */ __pyx_v_self->suffix_pad = __pyx_v_suffix_pad; /* "dask_em/tokenizer/qgramtokenizer.pyx":7 * self.prefix_pad = prefix_pad * self.suffix_pad = suffix_pad * self.return_set = return_set # <<<<<<<<<<<<<< * * cdef vector[string] ctokenize(self, const string& istring) nogil: */ __pyx_v_self->return_set = __pyx_v_return_set; /* "dask_em/tokenizer/qgramtokenizer.pyx":2 * cdef class QgramTokenizer(Tokenizer): * def __init__(self, int qval=2, bool padding=True, char prefix_pad='#', char suffix_pad='$', bool return_set=False): # <<<<<<<<<<<<<< * self.qval = qval * self.padding = padding */ /* function exit code */ __pyx_r = 0; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "dask_em/tokenizer/qgramtokenizer.pyx":9 * self.return_set = return_set * * cdef vector[string] ctokenize(self, const string& istring) nogil: # <<<<<<<<<<<<<< * cdef string inp_str = istring * cdef oset[string] tokens */ static std::vector<std::string> __pyx_f_7dask_em_9tokenizer_14qgramtokenizer_14QgramTokenizer_ctokenize(struct __pyx_obj_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer *__pyx_v_self, std::string const &__pyx_v_istring) { std::string __pyx_v_inp_str; std::set<std::string> __pyx_v_tokens; std::vector<std::string> __pyx_v_out_tokens; unsigned int __pyx_v_i; unsigned int __pyx_v_n; std::string __pyx_v_s; std::vector<std::string> __pyx_r; int __pyx_t_1; std::string __pyx_t_2; std::string __pyx_t_3; unsigned int __pyx_t_4; unsigned int __pyx_t_5; std::set<std::string> ::iterator __pyx_t_6; /* "dask_em/tokenizer/qgramtokenizer.pyx":10 * * cdef vector[string] ctokenize(self, const string& istring) nogil: * cdef string inp_str = istring # <<<<<<<<<<<<<< * cdef oset[string] tokens * cdef vector[string] out_tokens */ __pyx_v_inp_str = __pyx_v_istring; /* "dask_em/tokenizer/qgramtokenizer.pyx":14 * cdef vector[string] out_tokens * * if self.padding: # <<<<<<<<<<<<<< * inp_str = string(self.qval - 1, self.prefix_pad) + inp_str + string(self.qval - 1, self.suffix_pad) * cdef unsigned int i, n = inp_str.length() - self.qval + 1 */ __pyx_t_1 = (__pyx_v_self->padding != 0); if (__pyx_t_1) { /* "dask_em/tokenizer/qgramtokenizer.pyx":15 * * if self.padding: * inp_str = string(self.qval - 1, self.prefix_pad) + inp_str + string(self.qval - 1, self.suffix_pad) # <<<<<<<<<<<<<< * cdef unsigned int i, n = inp_str.length() - self.qval + 1 * if self.return_set: */ try { __pyx_t_2 = std::string((__pyx_v_self->qval - 1), __pyx_v_self->prefix_pad); } catch(...) { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_CppExn2PyErr(); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif __PYX_ERR(0, 15, __pyx_L1_error) } try { __pyx_t_3 = std::string((__pyx_v_self->qval - 1), __pyx_v_self->suffix_pad); } catch(...) { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_CppExn2PyErr(); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif __PYX_ERR(0, 15, __pyx_L1_error) } __pyx_v_inp_str = ((__pyx_t_2 + __pyx_v_inp_str) + __pyx_t_3); /* "dask_em/tokenizer/qgramtokenizer.pyx":14 * cdef vector[string] out_tokens * * if self.padding: # <<<<<<<<<<<<<< * inp_str = string(self.qval - 1, self.prefix_pad) + inp_str + string(self.qval - 1, self.suffix_pad) * cdef unsigned int i, n = inp_str.length() - self.qval + 1 */ } /* "dask_em/tokenizer/qgramtokenizer.pyx":16 * if self.padding: * inp_str = string(self.qval - 1, self.prefix_pad) + inp_str + string(self.qval - 1, self.suffix_pad) * cdef unsigned int i, n = inp_str.length() - self.qval + 1 # <<<<<<<<<<<<<< * if self.return_set: * for i in xrange(n): */ __pyx_v_n = ((__pyx_v_inp_str.length() - __pyx_v_self->qval) + 1); /* "dask_em/tokenizer/qgramtokenizer.pyx":17 * inp_str = string(self.qval - 1, self.prefix_pad) + inp_str + string(self.qval - 1, self.suffix_pad) * cdef unsigned int i, n = inp_str.length() - self.qval + 1 * if self.return_set: # <<<<<<<<<<<<<< * for i in xrange(n): * tokens.insert(inp_str.substr(i, self.qval)) */ __pyx_t_1 = (__pyx_v_self->return_set != 0); if (__pyx_t_1) { /* "dask_em/tokenizer/qgramtokenizer.pyx":18 * cdef unsigned int i, n = inp_str.length() - self.qval + 1 * if self.return_set: * for i in xrange(n): # <<<<<<<<<<<<<< * tokens.insert(inp_str.substr(i, self.qval)) * for s in tokens: */ __pyx_t_4 = __pyx_v_n; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "dask_em/tokenizer/qgramtokenizer.pyx":19 * if self.return_set: * for i in xrange(n): * tokens.insert(inp_str.substr(i, self.qval)) # <<<<<<<<<<<<<< * for s in tokens: * out_tokens.push_back(s) */ try { __pyx_v_tokens.insert(__pyx_v_inp_str.substr(__pyx_v_i, __pyx_v_self->qval)); } catch(...) { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_CppExn2PyErr(); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif __PYX_ERR(0, 19, __pyx_L1_error) } } /* "dask_em/tokenizer/qgramtokenizer.pyx":20 * for i in xrange(n): * tokens.insert(inp_str.substr(i, self.qval)) * for s in tokens: # <<<<<<<<<<<<<< * out_tokens.push_back(s) * else: */ __pyx_t_6 = __pyx_v_tokens.begin(); for (;;) { if (!(__pyx_t_6 != __pyx_v_tokens.end())) break; __pyx_t_3 = *__pyx_t_6; ++__pyx_t_6; __pyx_v_s = __pyx_t_3; /* "dask_em/tokenizer/qgramtokenizer.pyx":21 * tokens.insert(inp_str.substr(i, self.qval)) * for s in tokens: * out_tokens.push_back(s) # <<<<<<<<<<<<<< * else: * for i in xrange(n): */ try { __pyx_v_out_tokens.push_back(__pyx_v_s); } catch(...) { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_CppExn2PyErr(); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif __PYX_ERR(0, 21, __pyx_L1_error) } /* "dask_em/tokenizer/qgramtokenizer.pyx":20 * for i in xrange(n): * tokens.insert(inp_str.substr(i, self.qval)) * for s in tokens: # <<<<<<<<<<<<<< * out_tokens.push_back(s) * else: */ } /* "dask_em/tokenizer/qgramtokenizer.pyx":17 * inp_str = string(self.qval - 1, self.prefix_pad) + inp_str + string(self.qval - 1, self.suffix_pad) * cdef unsigned int i, n = inp_str.length() - self.qval + 1 * if self.return_set: # <<<<<<<<<<<<<< * for i in xrange(n): * tokens.insert(inp_str.substr(i, self.qval)) */ goto __pyx_L4; } /* "dask_em/tokenizer/qgramtokenizer.pyx":23 * out_tokens.push_back(s) * else: * for i in xrange(n): # <<<<<<<<<<<<<< * out_tokens.push_back(inp_str.substr(i, self.qval)) * return out_tokens */ /*else*/ { __pyx_t_4 = __pyx_v_n; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "dask_em/tokenizer/qgramtokenizer.pyx":24 * else: * for i in xrange(n): * out_tokens.push_back(inp_str.substr(i, self.qval)) # <<<<<<<<<<<<<< * return out_tokens * */ try { __pyx_v_out_tokens.push_back(__pyx_v_inp_str.substr(__pyx_v_i, __pyx_v_self->qval)); } catch(...) { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_CppExn2PyErr(); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif __PYX_ERR(0, 24, __pyx_L1_error) } } } __pyx_L4:; /* "dask_em/tokenizer/qgramtokenizer.pyx":25 * for i in xrange(n): * out_tokens.push_back(inp_str.substr(i, self.qval)) * return out_tokens # <<<<<<<<<<<<<< * * def tokenize(self, const string& istring): */ __pyx_r = __pyx_v_out_tokens; goto __pyx_L0; /* "dask_em/tokenizer/qgramtokenizer.pyx":9 * self.return_set = return_set * * cdef vector[string] ctokenize(self, const string& istring) nogil: # <<<<<<<<<<<<<< * cdef string inp_str = istring * cdef oset[string] tokens */ /* function exit code */ __pyx_L1_error:; __Pyx_WriteUnraisable("dask_em.tokenizer.qgramtokenizer.QgramTokenizer.ctokenize", __pyx_clineno, __pyx_lineno, __pyx_filename, 0, 1); __pyx_L0:; return __pyx_r; } /* "dask_em/tokenizer/qgramtokenizer.pyx":27 * return out_tokens * * def tokenize(self, const string& istring): # <<<<<<<<<<<<<< * return self.ctokenize(istring) */ /* Python wrapper */ static PyObject *__pyx_pw_7dask_em_9tokenizer_14qgramtokenizer_14QgramTokenizer_3tokenize(PyObject *__pyx_v_self, PyObject *__pyx_arg_istring); /*proto*/ static PyObject *__pyx_pw_7dask_em_9tokenizer_14qgramtokenizer_14QgramTokenizer_3tokenize(PyObject *__pyx_v_self, PyObject *__pyx_arg_istring) { std::string __pyx_v_istring; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("tokenize (wrapper)", 0); assert(__pyx_arg_istring); { __pyx_v_istring = __pyx_convert_string_from_py_std__in_string(__pyx_arg_istring); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 27, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; __Pyx_AddTraceback("dask_em.tokenizer.qgramtokenizer.QgramTokenizer.tokenize", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_7dask_em_9tokenizer_14qgramtokenizer_14QgramTokenizer_2tokenize(((struct __pyx_obj_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer *)__pyx_v_self), ((std::string)__pyx_v_istring)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_7dask_em_9tokenizer_14qgramtokenizer_14QgramTokenizer_2tokenize(struct __pyx_obj_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer *__pyx_v_self, std::string __pyx_v_istring) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("tokenize", 0); /* "dask_em/tokenizer/qgramtokenizer.pyx":28 * * def tokenize(self, const string& istring): * return self.ctokenize(istring) # <<<<<<<<<<<<<< */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __pyx_convert_vector_to_py_std_3a__3a_string(((struct __pyx_vtabstruct_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base.ctokenize(((struct __pyx_obj_7dask_em_9tokenizer_9tokenizer_Tokenizer *)__pyx_v_self), __pyx_v_istring)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 28, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "dask_em/tokenizer/qgramtokenizer.pyx":27 * return out_tokens * * def tokenize(self, const string& istring): # <<<<<<<<<<<<<< * return self.ctokenize(istring) */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("dask_em.tokenizer.qgramtokenizer.QgramTokenizer.tokenize", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "string.from_py":13 * * @cname("__pyx_convert_string_from_py_std__in_string") * cdef string __pyx_convert_string_from_py_std__in_string(object o) except *: # <<<<<<<<<<<<<< * cdef Py_ssize_t length * cdef char* data = __Pyx_PyObject_AsStringAndSize(o, &length) */ static std::string __pyx_convert_string_from_py_std__in_string(PyObject *__pyx_v_o) { Py_ssize_t __pyx_v_length; char *__pyx_v_data; std::string __pyx_r; __Pyx_RefNannyDeclarations char *__pyx_t_1; __Pyx_RefNannySetupContext("__pyx_convert_string_from_py_std__in_string", 0); /* "string.from_py":15 * cdef string __pyx_convert_string_from_py_std__in_string(object o) except *: * cdef Py_ssize_t length * cdef char* data = __Pyx_PyObject_AsStringAndSize(o, &length) # <<<<<<<<<<<<<< * return string(data, length) * */ __pyx_t_1 = __Pyx_PyObject_AsStringAndSize(__pyx_v_o, (&__pyx_v_length)); if (unlikely(__pyx_t_1 == NULL)) __PYX_ERR(1, 15, __pyx_L1_error) __pyx_v_data = __pyx_t_1; /* "string.from_py":16 * cdef Py_ssize_t length * cdef char* data = __Pyx_PyObject_AsStringAndSize(o, &length) * return string(data, length) # <<<<<<<<<<<<<< * * */ __pyx_r = std::string(__pyx_v_data, __pyx_v_length); goto __pyx_L0; /* "string.from_py":13 * * @cname("__pyx_convert_string_from_py_std__in_string") * cdef string __pyx_convert_string_from_py_std__in_string(object o) except *: # <<<<<<<<<<<<<< * cdef Py_ssize_t length * cdef char* data = __Pyx_PyObject_AsStringAndSize(o, &length) */ /* function exit code */ __pyx_L1_error:; __Pyx_AddTraceback("string.from_py.__pyx_convert_string_from_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "string.to_py":31 * * @cname("__pyx_convert_PyObject_string_to_py_std__in_string") * cdef inline object __pyx_convert_PyObject_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< * return __Pyx_PyObject_FromStringAndSize(s.data(), s.size()) * cdef extern from *: */ static CYTHON_INLINE PyObject *__pyx_convert_PyObject_string_to_py_std__in_string(std::string const &__pyx_v_s) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__pyx_convert_PyObject_string_to_py_std__in_string", 0); /* "string.to_py":32 * @cname("__pyx_convert_PyObject_string_to_py_std__in_string") * cdef inline object __pyx_convert_PyObject_string_to_py_std__in_string(const string& s): * return __Pyx_PyObject_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< * cdef extern from *: * cdef object __Pyx_PyUnicode_FromStringAndSize(char*, size_t) */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyObject_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 32, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "string.to_py":31 * * @cname("__pyx_convert_PyObject_string_to_py_std__in_string") * cdef inline object __pyx_convert_PyObject_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< * return __Pyx_PyObject_FromStringAndSize(s.data(), s.size()) * cdef extern from *: */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("string.to_py.__pyx_convert_PyObject_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "string.to_py":37 * * @cname("__pyx_convert_PyUnicode_string_to_py_std__in_string") * cdef inline object __pyx_convert_PyUnicode_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< * return __Pyx_PyUnicode_FromStringAndSize(s.data(), s.size()) * cdef extern from *: */ static CYTHON_INLINE PyObject *__pyx_convert_PyUnicode_string_to_py_std__in_string(std::string const &__pyx_v_s) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__pyx_convert_PyUnicode_string_to_py_std__in_string", 0); /* "string.to_py":38 * @cname("__pyx_convert_PyUnicode_string_to_py_std__in_string") * cdef inline object __pyx_convert_PyUnicode_string_to_py_std__in_string(const string& s): * return __Pyx_PyUnicode_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< * cdef extern from *: * cdef object __Pyx_PyStr_FromStringAndSize(char*, size_t) */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyUnicode_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 38, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "string.to_py":37 * * @cname("__pyx_convert_PyUnicode_string_to_py_std__in_string") * cdef inline object __pyx_convert_PyUnicode_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< * return __Pyx_PyUnicode_FromStringAndSize(s.data(), s.size()) * cdef extern from *: */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("string.to_py.__pyx_convert_PyUnicode_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "string.to_py":43 * * @cname("__pyx_convert_PyStr_string_to_py_std__in_string") * cdef inline object __pyx_convert_PyStr_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< * return __Pyx_PyStr_FromStringAndSize(s.data(), s.size()) * cdef extern from *: */ static CYTHON_INLINE PyObject *__pyx_convert_PyStr_string_to_py_std__in_string(std::string const &__pyx_v_s) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__pyx_convert_PyStr_string_to_py_std__in_string", 0); /* "string.to_py":44 * @cname("__pyx_convert_PyStr_string_to_py_std__in_string") * cdef inline object __pyx_convert_PyStr_string_to_py_std__in_string(const string& s): * return __Pyx_PyStr_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< * cdef extern from *: * cdef object __Pyx_PyBytes_FromStringAndSize(char*, size_t) */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyStr_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 44, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "string.to_py":43 * * @cname("__pyx_convert_PyStr_string_to_py_std__in_string") * cdef inline object __pyx_convert_PyStr_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< * return __Pyx_PyStr_FromStringAndSize(s.data(), s.size()) * cdef extern from *: */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("string.to_py.__pyx_convert_PyStr_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "string.to_py":49 * * @cname("__pyx_convert_PyBytes_string_to_py_std__in_string") * cdef inline object __pyx_convert_PyBytes_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< * return __Pyx_PyBytes_FromStringAndSize(s.data(), s.size()) * cdef extern from *: */ static CYTHON_INLINE PyObject *__pyx_convert_PyBytes_string_to_py_std__in_string(std::string const &__pyx_v_s) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__pyx_convert_PyBytes_string_to_py_std__in_string", 0); /* "string.to_py":50 * @cname("__pyx_convert_PyBytes_string_to_py_std__in_string") * cdef inline object __pyx_convert_PyBytes_string_to_py_std__in_string(const string& s): * return __Pyx_PyBytes_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< * cdef extern from *: * cdef object __Pyx_PyByteArray_FromStringAndSize(char*, size_t) */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 50, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "string.to_py":49 * * @cname("__pyx_convert_PyBytes_string_to_py_std__in_string") * cdef inline object __pyx_convert_PyBytes_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< * return __Pyx_PyBytes_FromStringAndSize(s.data(), s.size()) * cdef extern from *: */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("string.to_py.__pyx_convert_PyBytes_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "string.to_py":55 * * @cname("__pyx_convert_PyByteArray_string_to_py_std__in_string") * cdef inline object __pyx_convert_PyByteArray_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< * return __Pyx_PyByteArray_FromStringAndSize(s.data(), s.size()) * */ static CYTHON_INLINE PyObject *__pyx_convert_PyByteArray_string_to_py_std__in_string(std::string const &__pyx_v_s) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__pyx_convert_PyByteArray_string_to_py_std__in_string", 0); /* "string.to_py":56 * @cname("__pyx_convert_PyByteArray_string_to_py_std__in_string") * cdef inline object __pyx_convert_PyByteArray_string_to_py_std__in_string(const string& s): * return __Pyx_PyByteArray_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyByteArray_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 56, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "string.to_py":55 * * @cname("__pyx_convert_PyByteArray_string_to_py_std__in_string") * cdef inline object __pyx_convert_PyByteArray_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< * return __Pyx_PyByteArray_FromStringAndSize(s.data(), s.size()) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("string.to_py.__pyx_convert_PyByteArray_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "vector.to_py":67 * * @cname("__pyx_convert_vector_to_py_std_3a__3a_string") * cdef object __pyx_convert_vector_to_py_std_3a__3a_string(vector[X]& v): # <<<<<<<<<<<<<< * return [X_to_py(v[i]) for i in range(v.size())] * */ static PyObject *__pyx_convert_vector_to_py_std_3a__3a_string(const std::vector<std::string> &__pyx_v_v) { size_t __pyx_v_i; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; size_t __pyx_t_2; size_t __pyx_t_3; PyObject *__pyx_t_4 = NULL; __Pyx_RefNannySetupContext("__pyx_convert_vector_to_py_std_3a__3a_string", 0); /* "vector.to_py":68 * @cname("__pyx_convert_vector_to_py_std_3a__3a_string") * cdef object __pyx_convert_vector_to_py_std_3a__3a_string(vector[X]& v): * return [X_to_py(v[i]) for i in range(v.size())] # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 68, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __pyx_v_v.size(); for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; __pyx_t_4 = __pyx_convert_PyObject_string_to_py_std__in_string((__pyx_v_v[__pyx_v_i])); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 68, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_4))) __PYX_ERR(1, 68, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; } __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "vector.to_py":67 * * @cname("__pyx_convert_vector_to_py_std_3a__3a_string") * cdef object __pyx_convert_vector_to_py_std_3a__3a_string(vector[X]& v): # <<<<<<<<<<<<<< * return [X_to_py(v[i]) for i in range(v.size())] * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("vector.to_py.__pyx_convert_vector_to_py_std_3a__3a_string", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static struct __pyx_vtabstruct_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer __pyx_vtable_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer; static PyObject *__pyx_tp_new_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer(PyTypeObject *t, PyObject *a, PyObject *k) { struct __pyx_obj_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer *p; PyObject *o = __pyx_ptype_7dask_em_9tokenizer_9tokenizer_Tokenizer->tp_new(t, a, k); if (unlikely(!o)) return 0; p = ((struct __pyx_obj_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer *)o); p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7dask_em_9tokenizer_9tokenizer_Tokenizer*)__pyx_vtabptr_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer; return o; } static void __pyx_tp_dealloc_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer(PyObject *o) { #if PY_VERSION_HEX >= 0x030400a1 if (unlikely(Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif if (likely(__pyx_ptype_7dask_em_9tokenizer_9tokenizer_Tokenizer)) __pyx_ptype_7dask_em_9tokenizer_9tokenizer_Tokenizer->tp_dealloc(o); else __Pyx_call_next_tp_dealloc(o, __pyx_tp_dealloc_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer); } static PyMethodDef __pyx_methods_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer[] = { {"tokenize", (PyCFunction)__pyx_pw_7dask_em_9tokenizer_14qgramtokenizer_14QgramTokenizer_3tokenize, METH_O, 0}, {0, 0, 0, 0} }; static PyTypeObject __pyx_type_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer = { PyVarObject_HEAD_INIT(0, 0) "dask_em.tokenizer.qgramtokenizer.QgramTokenizer", /*tp_name*/ sizeof(struct __pyx_obj_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #endif 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ __pyx_pw_7dask_em_9tokenizer_14qgramtokenizer_14QgramTokenizer_1__init__, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif }; static PyMethodDef __pyx_methods[] = { {0, 0, 0, 0} }; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef __pyx_moduledef = { #if PY_VERSION_HEX < 0x03020000 { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, #else PyModuleDef_HEAD_INIT, #endif "qgramtokenizer", 0, /* m_doc */ -1, /* m_size */ __pyx_methods /* m_methods */, NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL /* m_free */ }; #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, {&__pyx_n_s_padding, __pyx_k_padding, sizeof(__pyx_k_padding), 0, 0, 1, 1}, {&__pyx_n_s_prefix_pad, __pyx_k_prefix_pad, sizeof(__pyx_k_prefix_pad), 0, 0, 1, 1}, {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, {&__pyx_n_s_qval, __pyx_k_qval, sizeof(__pyx_k_qval), 0, 0, 1, 1}, {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, {&__pyx_n_s_return_set, __pyx_k_return_set, sizeof(__pyx_k_return_set), 0, 0, 1, 1}, {&__pyx_n_s_suffix_pad, __pyx_k_suffix_pad, sizeof(__pyx_k_suffix_pad), 0, 0, 1, 1}, {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, {&__pyx_n_s_xrange, __pyx_k_xrange, sizeof(__pyx_k_xrange), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { #if PY_MAJOR_VERSION >= 3 __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_xrange) __PYX_ERR(0, 18, __pyx_L1_error) #else __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s_xrange); if (!__pyx_builtin_xrange) __PYX_ERR(0, 18, __pyx_L1_error) #endif __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(1, 68, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_InitGlobals(void) { if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error); return 0; __pyx_L1_error:; return -1; } #if PY_MAJOR_VERSION < 3 PyMODINIT_FUNC initqgramtokenizer(void); /*proto*/ PyMODINIT_FUNC initqgramtokenizer(void) #else PyMODINIT_FUNC PyInit_qgramtokenizer(void); /*proto*/ PyMODINIT_FUNC PyInit_qgramtokenizer(void) #endif { PyObject *__pyx_t_1 = NULL; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); if (!__Pyx_RefNanny) { PyErr_Clear(); __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); if (!__Pyx_RefNanny) Py_FatalError("failed to import 'refnanny' module"); } #endif __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_qgramtokenizer(void)", 0); if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) #ifdef __Pyx_CyFunction_USED if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_FusedFunction_USED if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Coroutine_USED if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Generator_USED if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_StopAsyncIteration_USED if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS #ifdef WITH_THREAD /* Python build with threading support? */ PyEval_InitThreads(); #endif #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 __pyx_m = Py_InitModule4("qgramtokenizer", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) Py_INCREF(__pyx_d); __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) #if CYTHON_COMPILING_IN_PYPY Py_INCREF(__pyx_b); #endif if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error); /*--- Initialize various global constants etc. ---*/ if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif if (__pyx_module_is_main_dask_em__tokenizer__qgramtokenizer) { if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) } #if PY_MAJOR_VERSION >= 3 { PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) if (!PyDict_GetItemString(modules, "dask_em.tokenizer.qgramtokenizer")) { if (unlikely(PyDict_SetItemString(modules, "dask_em.tokenizer.qgramtokenizer", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) } } #endif /*--- Builtin init code ---*/ if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Constants init code ---*/ if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Global init code ---*/ /*--- Variable export code ---*/ /*--- Function export code ---*/ /*--- Type init code ---*/ __pyx_ptype_7dask_em_9tokenizer_9tokenizer_Tokenizer = __Pyx_ImportType("dask_em.tokenizer.tokenizer", "Tokenizer", sizeof(struct __pyx_obj_7dask_em_9tokenizer_9tokenizer_Tokenizer), 1); if (unlikely(!__pyx_ptype_7dask_em_9tokenizer_9tokenizer_Tokenizer)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_vtabptr_7dask_em_9tokenizer_9tokenizer_Tokenizer = (struct __pyx_vtabstruct_7dask_em_9tokenizer_9tokenizer_Tokenizer*)__Pyx_GetVtable(__pyx_ptype_7dask_em_9tokenizer_9tokenizer_Tokenizer->tp_dict); if (unlikely(!__pyx_vtabptr_7dask_em_9tokenizer_9tokenizer_Tokenizer)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_vtabptr_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer = &__pyx_vtable_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer; __pyx_vtable_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer.__pyx_base = *__pyx_vtabptr_7dask_em_9tokenizer_9tokenizer_Tokenizer; __pyx_vtable_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer.__pyx_base.ctokenize = (std::vector<std::string> (*)(struct __pyx_obj_7dask_em_9tokenizer_9tokenizer_Tokenizer *, std::string))__pyx_f_7dask_em_9tokenizer_14qgramtokenizer_14QgramTokenizer_ctokenize; __pyx_type_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer.tp_base = __pyx_ptype_7dask_em_9tokenizer_9tokenizer_Tokenizer; if (PyType_Ready(&__pyx_type_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer) < 0) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_type_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer.tp_print = 0; if (__Pyx_SetVtable(__pyx_type_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer.tp_dict, __pyx_vtabptr_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer) < 0) __PYX_ERR(0, 1, __pyx_L1_error) if (PyObject_SetAttrString(__pyx_m, "QgramTokenizer", (PyObject *)&__pyx_type_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer) < 0) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_ptype_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer = &__pyx_type_7dask_em_9tokenizer_14qgramtokenizer_QgramTokenizer; /*--- Type import code ---*/ /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /* "dask_em/tokenizer/qgramtokenizer.pyx":1 * cdef class QgramTokenizer(Tokenizer): # <<<<<<<<<<<<<< * def __init__(self, int qval=2, bool padding=True, char prefix_pad='#', char suffix_pad='$', bool return_set=False): * self.qval = qval */ __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "vector.to_py":67 * * @cname("__pyx_convert_vector_to_py_std_3a__3a_string") * cdef object __pyx_convert_vector_to_py_std_3a__3a_string(vector[X]& v): # <<<<<<<<<<<<<< * return [X_to_py(v[i]) for i in range(v.size())] * */ /*--- Wrapped vars code ---*/ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); if (__pyx_m) { if (__pyx_d) { __Pyx_AddTraceback("init dask_em.tokenizer.qgramtokenizer", __pyx_clineno, __pyx_lineno, __pyx_filename); } Py_DECREF(__pyx_m); __pyx_m = 0; } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init dask_em.tokenizer.qgramtokenizer"); } __pyx_L0:; __Pyx_RefNannyFinishContext(); #if PY_MAJOR_VERSION < 3 return; #else return __pyx_m; #endif } /* --- Runtime support code --- */ /* Refnanny */ #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; void *r = NULL; m = PyImport_ImportModule((char *)modname); if (!m) goto end; p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); if (!p) goto end; r = PyLong_AsVoidPtr(p); end: Py_XDECREF(p); Py_XDECREF(m); return (__Pyx_RefNannyAPIStruct *)r; } #endif /* GetBuiltinName */ static PyObject *__Pyx_GetBuiltinName(PyObject *name) { PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); if (unlikely(!result)) { PyErr_Format(PyExc_NameError, #if PY_MAJOR_VERSION >= 3 "name '%U' is not defined", name); #else "name '%.200s' is not defined", PyString_AS_STRING(name)); #endif } return result; } /* RaiseDoubleKeywords */ static void __Pyx_RaiseDoubleKeywordsError( const char* func_name, PyObject* kw_name) { PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION >= 3 "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, PyString_AsString(kw_name)); #endif } /* ParseKeywords */ static int __Pyx_ParseOptionalKeywords( PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name) { PyObject *key = 0, *value = 0; Py_ssize_t pos = 0; PyObject*** name; PyObject*** first_kw_arg = argnames + num_pos_args; while (PyDict_Next(kwds, &pos, &key, &value)) { name = first_kw_arg; while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; continue; } name = first_kw_arg; #if PY_MAJOR_VERSION < 3 if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { while (*name) { if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) && _PyString_Eq(**name, key)) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { if ((**argname == key) || ( (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) && _PyString_Eq(**argname, key))) { goto arg_passed_twice; } argname++; } } } else #endif if (likely(PyUnicode_Check(key))) { while (*name) { int cmp = (**name == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : #endif PyUnicode_Compare(**name, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { int cmp = (**argname == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : #endif PyUnicode_Compare(**argname, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) goto arg_passed_twice; argname++; } } } else goto invalid_keyword_type; if (kwds2) { if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; } else { goto invalid_keyword; } } return 0; arg_passed_twice: __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, "%.200s() keywords must be strings", function_name); goto bad; invalid_keyword: PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION < 3 "%.200s() got an unexpected keyword argument '%.200s'", function_name, PyString_AsString(key)); #else "%s() got an unexpected keyword argument '%U'", function_name, key); #endif bad: return -1; } /* RaiseArgTupleInvalid */ static void __Pyx_RaiseArgtupleInvalid( const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found) { Py_ssize_t num_expected; const char *more_or_less; if (num_found < num_min) { num_expected = num_min; more_or_less = "at least"; } else { num_expected = num_max; more_or_less = "at most"; } if (exact) { more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } /* PyErrFetchRestore */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; tstate->curexc_type = type; tstate->curexc_value = value; tstate->curexc_traceback = tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); } static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; } #endif /* WriteUnraisableException */ static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename, int full_traceback, CYTHON_UNUSED int nogil) { PyObject *old_exc, *old_val, *old_tb; PyObject *ctx; __Pyx_PyThreadState_declare #ifdef WITH_THREAD PyGILState_STATE state; if (nogil) state = PyGILState_Ensure(); #ifdef _MSC_VER else state = (PyGILState_STATE)-1; #endif #endif __Pyx_PyThreadState_assign __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); if (full_traceback) { Py_XINCREF(old_exc); Py_XINCREF(old_val); Py_XINCREF(old_tb); __Pyx_ErrRestore(old_exc, old_val, old_tb); PyErr_PrintEx(1); } #if PY_MAJOR_VERSION < 3 ctx = PyString_FromString(name); #else ctx = PyUnicode_FromString(name); #endif __Pyx_ErrRestore(old_exc, old_val, old_tb); if (!ctx) { PyErr_WriteUnraisable(Py_None); } else { PyErr_WriteUnraisable(ctx); Py_DECREF(ctx); } #ifdef WITH_THREAD if (nogil) PyGILState_Release(state); #endif } /* CallNextTpDealloc */ static void __Pyx_call_next_tp_dealloc(PyObject* obj, destructor current_tp_dealloc) { PyTypeObject* type = Py_TYPE(obj); while (type && type->tp_dealloc != current_tp_dealloc) type = type->tp_base; while (type && type->tp_dealloc == current_tp_dealloc) type = type->tp_base; if (type) type->tp_dealloc(obj); } /* GetVTable */ static void* __Pyx_GetVtable(PyObject *dict) { void* ptr; PyObject *ob = PyObject_GetItem(dict, __pyx_n_s_pyx_vtable); if (!ob) goto bad; #if PY_VERSION_HEX >= 0x02070000 ptr = PyCapsule_GetPointer(ob, 0); #else ptr = PyCObject_AsVoidPtr(ob); #endif if (!ptr && !PyErr_Occurred()) PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type"); Py_DECREF(ob); return ptr; bad: Py_XDECREF(ob); return NULL; } /* SetVTable */ static int __Pyx_SetVtable(PyObject *dict, void *vtable) { #if PY_VERSION_HEX >= 0x02070000 PyObject *ob = PyCapsule_New(vtable, 0, 0); #else PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); #endif if (!ob) goto bad; if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) goto bad; Py_DECREF(ob); return 0; bad: Py_XDECREF(ob); return -1; } /* CodeObjectCache */ static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { int start = 0, mid = 0, end = count - 1; if (end >= 0 && code_line > entries[end].code_line) { return count; } while (start < end) { mid = start + (end - start) / 2; if (code_line < entries[mid].code_line) { end = mid; } else if (code_line > entries[mid].code_line) { start = mid + 1; } else { return mid; } } if (code_line <= entries[mid].code_line) { return mid; } else { return mid + 1; } } static PyCodeObject *__pyx_find_code_object(int code_line) { PyCodeObject* code_object; int pos; if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { return NULL; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { return NULL; } code_object = __pyx_code_cache.entries[pos].code_object; Py_INCREF(code_object); return code_object; } static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { int pos, i; __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; if (unlikely(!code_line)) { return; } if (unlikely(!entries)) { entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); if (likely(entries)) { __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = 64; __pyx_code_cache.count = 1; entries[0].code_line = code_line; entries[0].code_object = code_object; Py_INCREF(code_object); } return; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { PyCodeObject* tmp = entries[pos].code_object; entries[pos].code_object = code_object; Py_DECREF(tmp); return; } if (__pyx_code_cache.count == __pyx_code_cache.max_count) { int new_max = __pyx_code_cache.max_count + 64; entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( __pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry)); if (unlikely(!entries)) { return; } __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = new_max; } for (i=__pyx_code_cache.count; i>pos; i--) { entries[i] = entries[i-1]; } entries[pos].code_line = code_line; entries[pos].code_object = code_object; __pyx_code_cache.count++; Py_INCREF(code_object); } /* AddTraceback */ #include "compile.h" #include "frameobject.h" #include "traceback.h" static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; #if PY_MAJOR_VERSION < 3 py_srcfile = PyString_FromString(filename); #else py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; if (c_line) { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #endif } else { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromString(funcname); #else py_funcname = PyUnicode_FromString(funcname); #endif } if (!py_funcname) goto bad; py_code = __Pyx_PyCode_New( 0, 0, 0, 0, 0, __pyx_empty_bytes, /*PyObject *code,*/ __pyx_empty_tuple, /*PyObject *consts,*/ __pyx_empty_tuple, /*PyObject *names,*/ __pyx_empty_tuple, /*PyObject *varnames,*/ __pyx_empty_tuple, /*PyObject *freevars,*/ __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ py_line, __pyx_empty_bytes /*PyObject *lnotab*/ ); Py_DECREF(py_srcfile); Py_DECREF(py_funcname); return py_code; bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); return NULL; } static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyFrameObject *py_frame = 0; py_code = __pyx_find_code_object(c_line ? c_line : py_line); if (!py_code) { py_code = __Pyx_CreateCodeObjectForTraceback( funcname, c_line, py_line, filename); if (!py_code) goto bad; __pyx_insert_code_object(c_line ? c_line : py_line, py_code); } py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ __pyx_d, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; __Pyx_PyFrame_SetLineNumber(py_frame, py_line); PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_code); Py_XDECREF(py_frame); } /* CIntFromPyVerify */ #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) #define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) #define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ {\ func_type value = func_value;\ if (sizeof(target_type) < sizeof(func_type)) {\ if (unlikely(value != (func_type) (target_type) value)) {\ func_type zero = 0;\ if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ return (target_type) -1;\ if (is_unsigned && unlikely(value < zero))\ goto raise_neg_overflow;\ else\ goto raise_overflow;\ }\ }\ return (target_type) value;\ } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_int(unsigned int value) { const unsigned int neg_one = (unsigned int) -1, const_zero = (unsigned int) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(unsigned int) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(unsigned int) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(unsigned int) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(unsigned int) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(unsigned int) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(unsigned int), little, !is_unsigned); } } /* CIntFromPy */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { const int neg_one = (int) -1, const_zero = (int) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(int) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (int) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (int) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(int) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) case -2: if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -3: if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -4: if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; } #endif if (sizeof(int) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else int val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (int) -1; } } else { int val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (int) -1; val = __Pyx_PyInt_As_int(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to int"); return (int) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to int"); return (int) -1; } /* CIntFromPy */ static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *x) { const char neg_one = (char) -1, const_zero = (char) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(char) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(char, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (char) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (char) 0; case 1: __PYX_VERIFY_RETURN_INT(char, digit, digits[0]) case 2: if (8 * sizeof(char) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) >= 2 * PyLong_SHIFT) { return (char) (((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); } } break; case 3: if (8 * sizeof(char) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) >= 3 * PyLong_SHIFT) { return (char) (((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); } } break; case 4: if (8 * sizeof(char) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) >= 4 * PyLong_SHIFT) { return (char) (((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (char) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(char) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(char, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(char) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(char, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (char) 0; case -1: __PYX_VERIFY_RETURN_INT(char, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(char, digit, +digits[0]) case -2: if (8 * sizeof(char) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { return (char) (((char)-1)*(((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case 2: if (8 * sizeof(char) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { return (char) ((((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case -3: if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { return (char) (((char)-1)*(((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case 3: if (8 * sizeof(char) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { return (char) ((((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case -4: if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 4 * PyLong_SHIFT) { return (char) (((char)-1)*(((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case 4: if (8 * sizeof(char) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 4 * PyLong_SHIFT) { return (char) ((((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; } #endif if (sizeof(char) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(char, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(char) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(char, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else char val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (char) -1; } } else { char val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (char) -1; val = __Pyx_PyInt_As_char(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to char"); return (char) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to char"); return (char) -1; } /* CIntFromPy */ static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *x) { const unsigned int neg_one = (unsigned int) -1, const_zero = (unsigned int) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(unsigned int) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(unsigned int, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (unsigned int) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (unsigned int) 0; case 1: __PYX_VERIFY_RETURN_INT(unsigned int, digit, digits[0]) case 2: if (8 * sizeof(unsigned int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) >= 2 * PyLong_SHIFT) { return (unsigned int) (((((unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0])); } } break; case 3: if (8 * sizeof(unsigned int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) >= 3 * PyLong_SHIFT) { return (unsigned int) (((((((unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0])); } } break; case 4: if (8 * sizeof(unsigned int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) >= 4 * PyLong_SHIFT) { return (unsigned int) (((((((((unsigned int)digits[3]) << PyLong_SHIFT) | (unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (unsigned int) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(unsigned int) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(unsigned int, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(unsigned int) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(unsigned int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (unsigned int) 0; case -1: __PYX_VERIFY_RETURN_INT(unsigned int, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(unsigned int, digit, +digits[0]) case -2: if (8 * sizeof(unsigned int) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 2 * PyLong_SHIFT) { return (unsigned int) (((unsigned int)-1)*(((((unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; case 2: if (8 * sizeof(unsigned int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 2 * PyLong_SHIFT) { return (unsigned int) ((((((unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; case -3: if (8 * sizeof(unsigned int) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 3 * PyLong_SHIFT) { return (unsigned int) (((unsigned int)-1)*(((((((unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; case 3: if (8 * sizeof(unsigned int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 3 * PyLong_SHIFT) { return (unsigned int) ((((((((unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; case -4: if (8 * sizeof(unsigned int) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 4 * PyLong_SHIFT) { return (unsigned int) (((unsigned int)-1)*(((((((((unsigned int)digits[3]) << PyLong_SHIFT) | (unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; case 4: if (8 * sizeof(unsigned int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 4 * PyLong_SHIFT) { return (unsigned int) ((((((((((unsigned int)digits[3]) << PyLong_SHIFT) | (unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; } #endif if (sizeof(unsigned int) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(unsigned int, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(unsigned int) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(unsigned int, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else unsigned int val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (unsigned int) -1; } } else { unsigned int val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (unsigned int) -1; val = __Pyx_PyInt_As_unsigned_int(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to unsigned int"); return (unsigned int) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned int"); return (unsigned int) -1; } /* CIntFromPy */ static CYTHON_INLINE size_t __Pyx_PyInt_As_size_t(PyObject *x) { const size_t neg_one = (size_t) -1, const_zero = (size_t) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(size_t) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(size_t, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (size_t) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (size_t) 0; case 1: __PYX_VERIFY_RETURN_INT(size_t, digit, digits[0]) case 2: if (8 * sizeof(size_t) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) >= 2 * PyLong_SHIFT) { return (size_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } } break; case 3: if (8 * sizeof(size_t) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) >= 3 * PyLong_SHIFT) { return (size_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } } break; case 4: if (8 * sizeof(size_t) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) >= 4 * PyLong_SHIFT) { return (size_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (size_t) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(size_t) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(size_t, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(size_t) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(size_t, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (size_t) 0; case -1: __PYX_VERIFY_RETURN_INT(size_t, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(size_t, digit, +digits[0]) case -2: if (8 * sizeof(size_t) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) - 1 > 2 * PyLong_SHIFT) { return (size_t) (((size_t)-1)*(((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); } } break; case 2: if (8 * sizeof(size_t) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) - 1 > 2 * PyLong_SHIFT) { return (size_t) ((((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); } } break; case -3: if (8 * sizeof(size_t) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) - 1 > 3 * PyLong_SHIFT) { return (size_t) (((size_t)-1)*(((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); } } break; case 3: if (8 * sizeof(size_t) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) - 1 > 3 * PyLong_SHIFT) { return (size_t) ((((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); } } break; case -4: if (8 * sizeof(size_t) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) - 1 > 4 * PyLong_SHIFT) { return (size_t) (((size_t)-1)*(((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); } } break; case 4: if (8 * sizeof(size_t) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) - 1 > 4 * PyLong_SHIFT) { return (size_t) ((((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); } } break; } #endif if (sizeof(size_t) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(size_t, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(size_t) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(size_t, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else size_t val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (size_t) -1; } } else { size_t val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (size_t) -1; val = __Pyx_PyInt_As_size_t(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to size_t"); return (size_t) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to size_t"); return (size_t) -1; } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { const long neg_one = (long) -1, const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(long) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(long) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(long) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(long), little, !is_unsigned); } } /* CIntFromPy */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { const long neg_one = (long) -1, const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(long) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (long) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (long) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(long) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) case -2: if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -3: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -4: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; } #endif if (sizeof(long) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else long val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (long) -1; } } else { long val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (long) -1; val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to long"); return (long) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); return (long) -1; } /* CheckBinaryVersion */ static int __Pyx_check_binary_version(void) { char ctversion[4], rtversion[4]; PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { char message[200]; PyOS_snprintf(message, sizeof(message), "compiletime version %s of module '%.100s' " "does not match runtime version %s", ctversion, __Pyx_MODULE_NAME, rtversion); return PyErr_WarnEx(NULL, message, 1); } return 0; } /* ModuleImport */ #ifndef __PYX_HAVE_RT_ImportModule #define __PYX_HAVE_RT_ImportModule static PyObject *__Pyx_ImportModule(const char *name) { PyObject *py_name = 0; PyObject *py_module = 0; py_name = __Pyx_PyIdentifier_FromString(name); if (!py_name) goto bad; py_module = PyImport_Import(py_name); Py_DECREF(py_name); return py_module; bad: Py_XDECREF(py_name); return 0; } #endif /* TypeImport */ #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict) { PyObject *py_module = 0; PyObject *result = 0; PyObject *py_name = 0; char warning[200]; Py_ssize_t basicsize; #ifdef Py_LIMITED_API PyObject *py_basicsize; #endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; py_name = __Pyx_PyIdentifier_FromString(class_name); if (!py_name) goto bad; result = PyObject_GetAttr(py_module, py_name); Py_DECREF(py_name); py_name = 0; Py_DECREF(py_module); py_module = 0; if (!result) goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, "%.200s.%.200s is not a type object", module_name, class_name); goto bad; } #ifndef Py_LIMITED_API basicsize = ((PyTypeObject *)result)->tp_basicsize; #else py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); if (!py_basicsize) goto bad; basicsize = PyLong_AsSsize_t(py_basicsize); Py_DECREF(py_basicsize); py_basicsize = 0; if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) goto bad; #endif if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility. Expected %zd, got %zd", module_name, class_name, basicsize, size); if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; } else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, "%.200s.%.200s has the wrong size, try recompiling. Expected %zd, got %zd", module_name, class_name, basicsize, size); goto bad; } return (PyTypeObject *)result; bad: Py_XDECREF(py_module); Py_XDECREF(result); return NULL; } #endif /* InitStrings */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { #if PY_MAJOR_VERSION < 3 if (t->is_unicode) { *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); } else if (t->intern) { *t->p = PyString_InternFromString(t->s); } else { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); } #else if (t->is_unicode | t->is_str) { if (t->intern) { *t->p = PyUnicode_InternFromString(t->s); } else if (t->encoding) { *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); } else { *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); } } else { *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); } #endif if (!*t->p) return -1; ++t; } return 0; } static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); } static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { Py_ssize_t ignore; return __Pyx_PyObject_AsStringAndSize(o, &ignore); } static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { #if CYTHON_COMPILING_IN_CPYTHON && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) if ( #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII __Pyx_sys_getdefaultencoding_not_ascii && #endif PyUnicode_Check(o)) { #if PY_VERSION_HEX < 0x03030000 char* defenc_c; PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); if (!defenc) return NULL; defenc_c = PyBytes_AS_STRING(defenc); #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII { char* end = defenc_c + PyBytes_GET_SIZE(defenc); char* c; for (c = defenc_c; c < end; c++) { if ((unsigned char) (*c) >= 128) { PyUnicode_AsASCIIString(o); return NULL; } } } #endif *length = PyBytes_GET_SIZE(defenc); return defenc_c; #else if (__Pyx_PyUnicode_READY(o) == -1) return NULL; #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII if (PyUnicode_IS_ASCII(o)) { *length = PyUnicode_GET_LENGTH(o); return PyUnicode_AsUTF8(o); } else { PyUnicode_AsASCIIString(o); return NULL; } #else return PyUnicode_AsUTF8AndSize(o, length); #endif #endif } else #endif #if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) if (PyByteArray_Check(o)) { *length = PyByteArray_GET_SIZE(o); return PyByteArray_AS_STRING(o); } else #endif { char* result; int r = PyBytes_AsStringAndSize(o, &result, length); if (unlikely(r < 0)) { return NULL; } else { return result; } } } static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { #if CYTHON_USE_TYPE_SLOTS PyNumberMethods *m; #endif const char *name = NULL; PyObject *res = NULL; #if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return __Pyx_NewRef(x); #if CYTHON_USE_TYPE_SLOTS m = Py_TYPE(x)->tp_as_number; #if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); } else if (m && m->nb_long) { name = "long"; res = PyNumber_Long(x); } #else if (m && m->nb_int) { name = "int"; res = PyNumber_Long(x); } #endif #else res = PyNumber_Int(x); #endif if (res) { #if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, "__%.4s__ returned non-%.4s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; } } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "an integer is required"); } return res; } static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject *x; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(b))) { if (sizeof(Py_ssize_t) >= sizeof(long)) return PyInt_AS_LONG(b); else return PyInt_AsSsize_t(x); } #endif if (likely(PyLong_CheckExact(b))) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)b)->ob_digit; const Py_ssize_t size = Py_SIZE(b); if (likely(__Pyx_sst_abs(size) <= 1)) { ival = likely(size) ? digits[0] : 0; if (size == -1) ival = -ival; return ival; } else { switch (size) { case 2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; } } #endif return PyLong_AsSsize_t(b); } x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { return PyInt_FromSize_t(ival); } #endif /* Py_PYTHON_H */
[ "pradap@cs.wisc.edu" ]
pradap@cs.wisc.edu
fc3e0e16dac590bb8524bf8bd66d7da47ca75776
1b7bc0c8810624c79e1dade01bb63177058f1a28
/Voltron/Source/UnitTests/DataStructures/Trees/SuffixTrie_tests.cpp
16374322e559f3766849a4c9d6f1f274860d0a93
[ "MIT" ]
permissive
ernestyalumni/HrdwCCppCUDA
61f123359fb585f279a32a19ba64dfdb60a4f66f
ad067fd4e605c230ea87bdc36cc38341e681a1e0
refs/heads/master
2023-07-21T06:00:51.881770
2023-04-26T13:58:57
2023-04-26T13:58:57
109,069,731
3
0
null
null
null
null
UTF-8
C++
false
false
3,032
cpp
#include "DataStructures/Trees/SuffixTrie.h" #include <boost/test/unit_test.hpp> using namespace DataStructures::Trees::Tries::SuffixTries; BOOST_AUTO_TEST_SUITE(DataStructures) BOOST_AUTO_TEST_SUITE(Trees) BOOST_AUTO_TEST_SUITE(Tries) BOOST_AUTO_TEST_SUITE(SuffixTrie_tests) BOOST_AUTO_TEST_SUITE(ExpertIO_tests) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ BOOST_AUTO_TEST_CASE(SuffixTrieConstructsWithString) { ExpertIO::SuffixTrie st {"babc"}; BOOST_TEST(true); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ BOOST_AUTO_TEST_CASE(ContainsFindsSubstringForSuffixTrie) { { ExpertIO::SuffixTrie st {"babc"}; BOOST_TEST(st.contains("abc")); } { ExpertIO::SuffixTrie st {"test"}; BOOST_TEST(st.contains("t")); BOOST_TEST(st.contains("st")); BOOST_TEST(st.contains("est")); BOOST_TEST(st.contains("test")); BOOST_TEST(!st.contains("tes")); } { ExpertIO::SuffixTrie st {"invisible"}; BOOST_TEST(st.contains("e")); BOOST_TEST(st.contains("le")); BOOST_TEST(st.contains("ble")); BOOST_TEST(st.contains("ible")); BOOST_TEST(st.contains("sible")); BOOST_TEST(st.contains("isible")); BOOST_TEST(st.contains("visible")); BOOST_TEST(st.contains("nvisible")); BOOST_TEST(st.contains("invisible")); BOOST_TEST(!st.contains("nvisibl")); } { ExpertIO::SuffixTrie st {"1234556789"}; BOOST_TEST(st.contains("9")); BOOST_TEST(st.contains("89")); BOOST_TEST(st.contains("789")); BOOST_TEST(st.contains("6789")); BOOST_TEST(st.contains("56789")); BOOST_TEST(!st.contains("456789")); BOOST_TEST(!st.contains("3456789")); BOOST_TEST(!st.contains("23456789")); BOOST_TEST(!st.contains("123456789")); BOOST_TEST(!st.contains("45567")); } { ExpertIO::SuffixTrie st {"testtest"}; BOOST_TEST(st.contains("t")); BOOST_TEST(st.contains("st")); BOOST_TEST(st.contains("est")); BOOST_TEST(st.contains("test")); BOOST_TEST(st.contains("ttest")); BOOST_TEST(st.contains("sttest")); BOOST_TEST(st.contains("esttest")); BOOST_TEST(st.contains("testtest")); BOOST_TEST(!st.contains("tt")); } { ExpertIO::SuffixTrie st {"ttttttttt"}; BOOST_TEST(st.contains("t")); BOOST_TEST(st.contains("tt")); BOOST_TEST(st.contains("ttt")); BOOST_TEST(st.contains("tttt")); BOOST_TEST(st.contains("ttttt")); BOOST_TEST(st.contains("tttttt")); BOOST_TEST(st.contains("ttttttt")); BOOST_TEST(st.contains("tttttttt")); BOOST_TEST(st.contains("ttttttttt")); BOOST_TEST(!st.contains("vvv")); } } BOOST_AUTO_TEST_SUITE_END() // ExpertIO_tests BOOST_AUTO_TEST_SUITE_END() // SuffixTrie_tests BOOST_AUTO_TEST_SUITE_END() // Tries BOOST_AUTO_TEST_SUITE_END() // Trees BOOST_AUTO_TEST_SUITE_END() // DataStructures
[ "ernestyalumni@gmail.com" ]
ernestyalumni@gmail.com
457e5a00286a2e33c212329c3cc4c2a6d3666f28
bf46ead26b9550c92c1f4cb81ff0bb553471ce8f
/src/test/scriptnum_tests.cpp
cd3279003fd7488a3794f396f9d5a73dfcb5f87f
[ "MIT" ]
permissive
HondaisCoin/hondaiscoinmn
afeadfa0a34c6b5aafb2f5f89f7d1b36a77a2ee3
5b159940ee12ff8886ef21498dfddffb4ac76b1a
refs/heads/master
2020-08-29T03:44:24.444315
2019-10-27T20:59:52
2019-10-27T20:59:52
217,913,441
1
1
null
null
null
null
UTF-8
C++
false
false
7,466
cpp
// Copyright (c) 2012-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "scriptnum10.h" #include "script/script.h" #include "test/test_hondaiscoinmn.h" #include <boost/test/unit_test.hpp> #include <limits.h> #include <stdint.h> BOOST_FIXTURE_TEST_SUITE(scriptnum_tests, BasicTestingSetup) static const int64_t values[] = \ { 0, 1, CHAR_MIN, CHAR_MAX, UCHAR_MAX, SHRT_MIN, USHRT_MAX, INT_MIN, INT_MAX, UINT_MAX, LONG_MIN, LONG_MAX }; static const int64_t offsets[] = { 1, 0x79, 0x80, 0x81, 0xFF, 0x7FFF, 0x8000, 0xFFFF, 0x10000}; static bool verify(const CScriptNum10& bignum, const CScriptNum& scriptnum) { return bignum.getvch() == scriptnum.getvch() && bignum.getint() == scriptnum.getint(); } static void CheckCreateVch(const int64_t& num) { CScriptNum10 bignum(num); CScriptNum scriptnum(num); BOOST_CHECK(verify(bignum, scriptnum)); std::vector<unsigned char> vch = bignum.getvch(); CScriptNum10 bignum2(bignum.getvch(), false); vch = scriptnum.getvch(); CScriptNum scriptnum2(scriptnum.getvch(), false); BOOST_CHECK(verify(bignum2, scriptnum2)); CScriptNum10 bignum3(scriptnum2.getvch(), false); CScriptNum scriptnum3(bignum2.getvch(), false); BOOST_CHECK(verify(bignum3, scriptnum3)); } static void CheckCreateInt(const int64_t& num) { CScriptNum10 bignum(num); CScriptNum scriptnum(num); BOOST_CHECK(verify(bignum, scriptnum)); BOOST_CHECK(verify(CScriptNum10(bignum.getint()), CScriptNum(scriptnum.getint()))); BOOST_CHECK(verify(CScriptNum10(scriptnum.getint()), CScriptNum(bignum.getint()))); BOOST_CHECK(verify(CScriptNum10(CScriptNum10(scriptnum.getint()).getint()), CScriptNum(CScriptNum(bignum.getint()).getint()))); } static void CheckAdd(const int64_t& num1, const int64_t& num2) { const CScriptNum10 bignum1(num1); const CScriptNum10 bignum2(num2); const CScriptNum scriptnum1(num1); const CScriptNum scriptnum2(num2); CScriptNum10 bignum3(num1); CScriptNum10 bignum4(num1); CScriptNum scriptnum3(num1); CScriptNum scriptnum4(num1); // int64_t overflow is undefined. bool invalid = (((num2 > 0) && (num1 > (std::numeric_limits<int64_t>::max() - num2))) || ((num2 < 0) && (num1 < (std::numeric_limits<int64_t>::min() - num2)))); if (!invalid) { BOOST_CHECK(verify(bignum1 + bignum2, scriptnum1 + scriptnum2)); BOOST_CHECK(verify(bignum1 + bignum2, scriptnum1 + num2)); BOOST_CHECK(verify(bignum1 + bignum2, scriptnum2 + num1)); } } static void CheckNegate(const int64_t& num) { const CScriptNum10 bignum(num); const CScriptNum scriptnum(num); // -INT64_MIN is undefined if (num != std::numeric_limits<int64_t>::min()) BOOST_CHECK(verify(-bignum, -scriptnum)); } static void CheckSubtract(const int64_t& num1, const int64_t& num2) { const CScriptNum10 bignum1(num1); const CScriptNum10 bignum2(num2); const CScriptNum scriptnum1(num1); const CScriptNum scriptnum2(num2); bool invalid = false; // int64_t overflow is undefined. invalid = ((num2 > 0 && num1 < std::numeric_limits<int64_t>::min() + num2) || (num2 < 0 && num1 > std::numeric_limits<int64_t>::max() + num2)); if (!invalid) { BOOST_CHECK(verify(bignum1 - bignum2, scriptnum1 - scriptnum2)); BOOST_CHECK(verify(bignum1 - bignum2, scriptnum1 - num2)); } invalid = ((num1 > 0 && num2 < std::numeric_limits<int64_t>::min() + num1) || (num1 < 0 && num2 > std::numeric_limits<int64_t>::max() + num1)); if (!invalid) { BOOST_CHECK(verify(bignum2 - bignum1, scriptnum2 - scriptnum1)); BOOST_CHECK(verify(bignum2 - bignum1, scriptnum2 - num1)); } } static void CheckCompare(const int64_t& num1, const int64_t& num2) { const CScriptNum10 bignum1(num1); const CScriptNum10 bignum2(num2); const CScriptNum scriptnum1(num1); const CScriptNum scriptnum2(num2); BOOST_CHECK((bignum1 == bignum1) == (scriptnum1 == scriptnum1)); BOOST_CHECK((bignum1 != bignum1) == (scriptnum1 != scriptnum1)); BOOST_CHECK((bignum1 < bignum1) == (scriptnum1 < scriptnum1)); BOOST_CHECK((bignum1 > bignum1) == (scriptnum1 > scriptnum1)); BOOST_CHECK((bignum1 >= bignum1) == (scriptnum1 >= scriptnum1)); BOOST_CHECK((bignum1 <= bignum1) == (scriptnum1 <= scriptnum1)); BOOST_CHECK((bignum1 == bignum1) == (scriptnum1 == num1)); BOOST_CHECK((bignum1 != bignum1) == (scriptnum1 != num1)); BOOST_CHECK((bignum1 < bignum1) == (scriptnum1 < num1)); BOOST_CHECK((bignum1 > bignum1) == (scriptnum1 > num1)); BOOST_CHECK((bignum1 >= bignum1) == (scriptnum1 >= num1)); BOOST_CHECK((bignum1 <= bignum1) == (scriptnum1 <= num1)); BOOST_CHECK((bignum1 == bignum2) == (scriptnum1 == scriptnum2)); BOOST_CHECK((bignum1 != bignum2) == (scriptnum1 != scriptnum2)); BOOST_CHECK((bignum1 < bignum2) == (scriptnum1 < scriptnum2)); BOOST_CHECK((bignum1 > bignum2) == (scriptnum1 > scriptnum2)); BOOST_CHECK((bignum1 >= bignum2) == (scriptnum1 >= scriptnum2)); BOOST_CHECK((bignum1 <= bignum2) == (scriptnum1 <= scriptnum2)); BOOST_CHECK((bignum1 == bignum2) == (scriptnum1 == num2)); BOOST_CHECK((bignum1 != bignum2) == (scriptnum1 != num2)); BOOST_CHECK((bignum1 < bignum2) == (scriptnum1 < num2)); BOOST_CHECK((bignum1 > bignum2) == (scriptnum1 > num2)); BOOST_CHECK((bignum1 >= bignum2) == (scriptnum1 >= num2)); BOOST_CHECK((bignum1 <= bignum2) == (scriptnum1 <= num2)); } static void RunCreate(const int64_t& num) { CheckCreateInt(num); CScriptNum scriptnum(num); if (scriptnum.getvch().size() <= CScriptNum::nDefaultMaxNumSize) CheckCreateVch(num); else { BOOST_CHECK_THROW (CheckCreateVch(num), scriptnum10_error); } } static void RunOperators(const int64_t& num1, const int64_t& num2) { CheckAdd(num1, num2); CheckSubtract(num1, num2); CheckNegate(num1); CheckCompare(num1, num2); } BOOST_AUTO_TEST_CASE(creation) { for(size_t i = 0; i < sizeof(values) / sizeof(values[0]); ++i) { for(size_t j = 0; j < sizeof(offsets) / sizeof(offsets[0]); ++j) { RunCreate(values[i]); RunCreate(values[i] + offsets[j]); RunCreate(values[i] - offsets[j]); } } } BOOST_AUTO_TEST_CASE(operators) { for(size_t i = 0; i < sizeof(values) / sizeof(values[0]); ++i) { for(size_t j = 0; j < sizeof(offsets) / sizeof(offsets[0]); ++j) { RunOperators(values[i], values[i]); RunOperators(values[i], -values[i]); RunOperators(values[i], values[j]); RunOperators(values[i], -values[j]); RunOperators(values[i] + values[j], values[j]); RunOperators(values[i] + values[j], -values[j]); RunOperators(values[i] - values[j], values[j]); RunOperators(values[i] - values[j], -values[j]); RunOperators(values[i] + values[j], values[i] + values[j]); RunOperators(values[i] + values[j], values[i] - values[j]); RunOperators(values[i] - values[j], values[i] + values[j]); RunOperators(values[i] - values[j], values[i] - values[j]); } } } BOOST_AUTO_TEST_SUITE_END()
[ "you@example.com" ]
you@example.com
a275a727e51948d50ec6e498e17f1d3c6ff32e27
adfa317ce1bae691174309d7b361950b07ba5ca8
/src/ParabolicBoxDomainPdeSystemModifier.hpp
c5936c4cc42c0830729301123c5f50fca2692740
[]
no_license
CJohnsonMathSys/ChemChaste
34a121a14a0e62dbb61e735a0c9bb5581652c403
ca9308628948baf758b7a864b0269c6e6bf29325
refs/heads/main
2023-02-22T20:21:50.778557
2021-01-27T12:34:00
2021-01-27T12:34:00
307,725,542
0
0
null
null
null
null
UTF-8
C++
false
false
11,982
hpp
#ifndef PARABOLICBOXDOMAINPDESYSTEMMODIFIER_HPP_ #define PARABOLICBOXDOMAINPDESYSTEMMODIFIER_HPP_ #include "InhomogenousParabolicPdeForCoupledOdeSystem_templated.hpp" #include "AbstractBoxDomainPdeSystemModifier.hpp" #include "AbstractPdeSystemModifier.hpp" #include "BoundaryConditionsContainer.hpp" #include "AbstractIvpOdeSolver.hpp" #include "AbstractOdeSystemForCoupledPdeSystem.hpp" #include "InhomogenousCoupledPdeOdeCoupledCellSolver.hpp" #include "AbstractOdeSystemForCoupledPdeSystem.hpp" #include "InhomogenousCoupledPdeOdeSolver_templated.hpp" #include "ChemicalDomainFieldForCellCoupling.hpp" template<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM> class ParabolicBoxDomainPdeSystemModifier : public AbstractBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM> { protected: bool mConditionsInterpolated = false; public: ParabolicBoxDomainPdeSystemModifier(ChemicalDomainFieldForCellCoupling<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>* p_domain_field, boost::shared_ptr<ChasteCuboid<SPACE_DIM> > pMeshCuboid=boost::shared_ptr<ChasteCuboid<SPACE_DIM> >(), double stepSize=1.0, Vec solution=nullptr); /** * Destructor. */ virtual ~ParabolicBoxDomainPdeSystemModifier(); /** * Overridden UpdateAtEndOfTimeStep() method. * * Specifies what to do in the simulation at the end of each time step. * * @param rCellPopulation reference to the cell population */ virtual void UpdateAtEndOfTimeStep(AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>& rCellPopulation); /** * Overridden SetupSolve() method. * * Specifies what to do in the simulation before the start of the time loop. * * @param rCellPopulation reference to the cell population * @param outputDirectory the output directory, relative to where Chaste output is stored */ virtual void SetupSolve(AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>& rCellPopulation, std::string outputDirectory); /** * Helper method to construct the boundary conditions container for the PDE. * * @param rCellPopulation reference to the cell population * * @return the full boundary conditions container */ virtual boost::shared_ptr<BoundaryConditionsContainer<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM> > ConstructBoundaryConditionsContainer(AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>& rCellPopulation); /** * Helper method to initialise the PDE solution using the CellData. * * Here we assume a homogeneous initial consition. * * @param rCellPopulation reference to the cell population */ void SetupInitialSolutionVector(AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>& rCellPopulation); /** * Overridden OutputSimulationModifierParameters() method. * Output any simulation modifier parameters to file. * * @param rParamsFile the file stream to which the parameters are output */ void OutputSimulationModifierParameters(out_stream& rParamsFile); void SetPdeDimension(unsigned pdeDim); unsigned GetPdeDimension(); //void SetNodalInitialConditions(std::vector<double> init_nodal_conditions); //std::vector<double> GetNodalInitialConditions(); //void SetCellInitialConditions(std::vector<double> init_cell_conditions); //std::vector<double> GetCellInitialConditions(); }; template<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM> ParabolicBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::ParabolicBoxDomainPdeSystemModifier( ChemicalDomainFieldForCellCoupling<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>* p_domain_field, boost::shared_ptr<ChasteCuboid<SPACE_DIM> > pMeshCuboid, double stepSize, Vec solution) : AbstractBoxDomainPdeSystemModifier<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>(p_domain_field, pMeshCuboid, stepSize, solution) { } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM> ParabolicBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::~ParabolicBoxDomainPdeSystemModifier() { } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM> void ParabolicBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::UpdateAtEndOfTimeStep(AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>& rCellPopulation) { //std::cout<<"ParabolicBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::UpdateAtEndOfTimeStep - start"<<std::endl; // Set up boundary conditions, comes from the rCellPopulation rather than the constructor boost::shared_ptr<BoundaryConditionsContainer<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM> > p_bcc = ConstructBoundaryConditionsContainer(rCellPopulation); this->UpdateCellPdeElementMap(rCellPopulation); // When using a PDE mesh which doesn't coincide with the cells, we must set up the source terms before solving the PDE. // Pass in already updated CellPdeElementMap to speed up finding cells. // this line shoudl be fine for the pOdeSystem this->SetUpSourceTermsForAveragedSourcePde(this->mpFeMesh, &this->mCellPdeElementMap); InhomogenousCoupledPdeOdeCoupledCellSolver<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM> solver( this->mpFeMesh, this->mpCoupledDomainField->ReturnSharedPtrPdeSystem().get(), this->mpCoupledDomainField->ReturnSharedPtrBoundaryConditionsContainer().get(), rCellPopulation, this->mpCoupledDomainField->GetNodalOdeSystems(), this->mpCoupledDomainField->GetNodalOdeSolvers(), mConditionsInterpolated ); ///\todo Investigate more than one PDE time step per spatial step SimulationTime* p_simulation_time = SimulationTime::Instance(); double current_time = p_simulation_time->GetTime(); double dt = p_simulation_time->GetTimeStep(); // solver is calling the LinearParabolicSystemWithCOupledOdeSystemSolver solver.SetTimes(current_time,current_time + dt); solver.SetTimeStep(dt); // Use previous solution as the initial condition Vec previous_solution = this->mSolution; solver.SetInitialCondition(previous_solution); // Note that the linear solver creates a vector, so we have to keep a handle on the old one // in order to destroy it this->mSolution = solver.Solve(); PetscTools::Destroy(previous_solution); this->UpdateCellData(rCellPopulation); mConditionsInterpolated = true; //std::cout<<"ParabolicBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::UpdateAtEndOfTimeStep - end"<<std::endl; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM> void ParabolicBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::SetupSolve(AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>& rCellPopulation, std::string outputDirectory) { //std::cout<<"ParabolicBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM>::SetupSolve - start"<<std::endl; AbstractBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::SetupSolve(rCellPopulation,outputDirectory); // Copy the cell data to mSolution (this is the initial condition) SetupInitialSolutionVector(rCellPopulation); // Output the initial conditions on FeMesh this->UpdateAtEndOfOutputTimeStep(rCellPopulation); //std::cout<<"ParabolicBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM>::SetupSolve - end"<<std::endl; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM> // why does this take in a cell population? if() is true, shrinks the box onto the tissue (cellpopulation) here makes no difference boost::shared_ptr<BoundaryConditionsContainer<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM> > ParabolicBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::ConstructBoundaryConditionsContainer(AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>& rCellPopulation) { boost::shared_ptr<BoundaryConditionsContainer<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM> > p_bcc(new BoundaryConditionsContainer<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>(false)); // false implies not to delete previous conditions but there shouldn't be any if (!this->mSetBcsOnBoxBoundary) { EXCEPTION("Boundary conditions cannot yet be set on the cell population boundary for a ParabolicBoxDomainPdeSystemModifier"); } else // Apply BC at boundary nodes of box domain FE mesh { p_bcc = this->mpCoupledDomainField -> ReturnSharedPtrBoundaryConditionsContainer();//ChemicalDomainFieldForCellCoupling<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::ReturnSharedPtrBoundaryConditionsContainer(); } return p_bcc; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM> void ParabolicBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::SetupInitialSolutionVector(AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>& rCellPopulation) { // set up the initial conditions for the pde mesh // set up cell initial conditions for (typename AbstractCellPopulation<SPACE_DIM>::Iterator cell_iter = rCellPopulation.Begin(); cell_iter != rCellPopulation.End(); ++cell_iter) { CellPropertyCollection& prop_collection = cell_iter->rGetCellPropertyCollection(); if (prop_collection.HasProperty<ChemicalCellProperty>()) { // the cell has it's own concentration vector that may be related to the domain boost::shared_ptr<ChemicalCellProperty> property = boost::static_pointer_cast<ChemicalCellProperty>(prop_collection.GetPropertiesType<ChemicalCellProperty>().GetProperty()); std::vector<std::string> cell_species_names = property -> GetStateVariableRegister() -> GetStateVariableRegisterVector(); for(unsigned name_index=0; name_index<cell_species_names.size();name_index++) { cell_iter->GetCellData()->SetItem(cell_species_names[name_index], property -> GetCellConcentrationByIndex(name_index)); } } else { // assume zero concentration in cell, set up for all species in the PROBLEM_DIM, that is species diffusing through the domain std::vector<double> initial_conditions(PROBLEM_DIM,0.0); std::vector<std::string> domain_species_names = this->mpCoupledDomainField -> GetDomainStateVariableRegister() -> GetStateVariableRegisterVector(); for(unsigned name_index=0; name_index<domain_species_names.size();name_index++) { cell_iter->GetCellData()->SetItem(domain_species_names[name_index], 0.0); } } } // set pde serialised nodal initial conditions from domain layer // Initialise mSolution this->mSolution = PetscTools::CreateVec(this->mpCoupledDomainField -> GetInitialNodeConditions()); } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM> void ParabolicBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::OutputSimulationModifierParameters(out_stream& rParamsFile) { // No parameters to output, so just call method on direct parent class AbstractBoxDomainPdeSystemModifier<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::OutputSimulationModifierParameters(rParamsFile); } #endif /*PARABOLICBOXDOMAINPDESYSTEMMODIFIER_HPP_*/
[ "c.johnson.6@warwick.ac.uk" ]
c.johnson.6@warwick.ac.uk
89b1e9f84bbbeee65c0d182132d672fabd94f080
ad2bf55f50be16c3e2bdd3e49fef5f570224f371
/Basic/Mang/Mang 1 chieu/300. Tim phan tu lon nhat va nho nhat.cpp
5fda716af0cf9de5767d25a2af4c7ecd51cad8f1
[]
no_license
GibOreh/CodeC
31f1b79b6f5c741fecc0031f508b7b96eafc1844
b45fd8ae9ae6e720c9c5dfc07c23c52f2f85c5d5
refs/heads/master
2022-11-24T09:55:50.111087
2020-08-02T05:54:31
2020-08-02T05:54:31
284,399,863
0
0
null
null
null
null
UTF-8
C++
false
false
367
cpp
#include <stdio.h> void in(int x[],int n){ for(int i=0 ; i<n ; i++){ scanf("%d",&x[i]); } } void check(int x[],int n){ int max=x[0],min=x[0]; for(int i=0 ; i<n ; i++){ if(max < x[i]) max = x[i]; if(min > x[i]) min = x[i]; } printf("%d ",max); printf("%d",min); } int main(){ int x[20],n; scanf("%d",&n); in(x,n); check(x,n); return 0; }
[ "vuonghung2308@gmail.com" ]
vuonghung2308@gmail.com
65c05019b2ef2a8c16c944fe535336989506409f
63876d01ccee25cec402431e02f0f24f06b4b3a4
/ch01_getting_started/exe/ex_01_04.cc
d2348704d43073e63e495c59e0cdac557dd26389
[]
no_license
christyjohn/cpp_primer
af6f89d06f5048e05d703cf7cc10ffc98c362ac0
f3352520fde9bf3094a48653e9513964ee100cb5
refs/heads/master
2021-04-21T11:46:57.263207
2020-03-31T14:06:15
2020-03-31T14:06:15
249,777,134
0
0
null
null
null
null
UTF-8
C++
false
false
257
cc
#include <iostream> int main() { int v1 = 0, v2 = 0; std::cout << "Enter two numbers" << std::endl; std::cin >> v1 >> v2; std::cout << "The produt of " << v1 << " and " << v2 << " is " << v1 * v2 << std::endl; return 0; }
[ "christyjohn.crz@gmail.com" ]
christyjohn.crz@gmail.com
4d38f056a8b3a3d7a3c2f21e593e1314449967b4
1b7616e325dbf6c2f591b34a35246d37c078dbbf
/scanner.cpp
9f9df36eb6beb7267cb813667bd1813570ab541f
[]
no_license
SefikMehmedovic/CS4280-P4
cd0fd7773d2ac0e5afe17a77e5e1a1e8dfff3d44
2c16ad1b48e7a0045468c64861c2caf3fd25de1d
refs/heads/master
2020-04-13T01:10:33.878061
2018-12-23T06:05:50
2018-12-23T06:05:50
162,866,429
0
1
null
null
null
null
UTF-8
C++
false
false
5,483
cpp
//scanner.cpp #include <string> #include <cctype> #include <cstddef> #include <iostream> #include <cstdlib> #include "scanner.h" #include "token.h" using namespace std; //From token.h int token_index; int current_index; int line_index; vector <string> file_string; static int comment_flag; //function to read in from file input void read_file(istream &in) { populate_operator_map(); populate_keyword_map(); string input_line; current_index = 0; Token token; int counter = 0; //get line until EOF while (getline(in, input_line)) { current_index = 0; filter(input_line); if (input_line.length() > 0) { file_string.push_back(input_line); counter++; } } } int filter(string &input_string) { if (current_index >= input_string.length()) return 0; string filtered_string; char current_ch; const char SPACE = ' '; char prev_ch = ' '; //go through each char for (int counter = current_index; counter < input_string.length(); counter++) { current_ch = input_string.at(counter); if (counter > 0) prev_ch = input_string.at(counter - 1); if (current_ch == COMMENT_DELIM) { filtered_string.push_back(SPACE); comment_flag = !comment_flag; } else if (!comment_flag) { //check for space if (isspace(current_ch)) { if (!isspace(prev_ch)) filtered_string.push_back(current_ch); } else if (is_valid_ch(current_ch) == -1) { //check for char cout << "Error: \'" << current_ch << "\' is not a valid character.\n"; exit(EXIT_FAILURE); } else { filtered_string.push_back(current_ch); } } current_index++; } string whitespaces = " \t\f\v\n\r"; size_t trailing_whitespace_index = filtered_string.find_last_not_of(whitespaces); if (trailing_whitespace_index != string::npos) { filtered_string.erase(trailing_whitespace_index + 1); } else { bool all_spaces_flag = true; for (int i = 0; i < filtered_string.length(); i++) { if (filtered_string.at(i) != SPACE) { all_spaces_flag = false; break; } } if (all_spaces_flag) filtered_string.assign(""); } input_string.assign(filtered_string); return current_index; } //check if the input is not an operator or digit or char int is_valid_ch(char ch) { if (!is_operator(ch) && !isdigit(ch) & !isalpha(ch)) return -1; else return 0; } //get current line string get_string() { return file_string[line_index]; } //---------------------------------------------------- int scanner(Token &token) { string input_string = get_string(); if (token_index == input_string.length()) { line_index++; token_index = 0; if (line_index < file_string.size()) input_string = file_string[line_index]; else { token.desc = "EOF"; token.ID = EOFtk; token.line_number = (line_index - 1); return 1; } } token.line_number = (line_index + 1); int current_state = 0; int next_state; int next_col; string token_desc; char next_char; const char SPACE = ' '; while (token_index <= input_string.length()) { if (token_index < input_string.length()) next_char = input_string.at(token_index); else next_char = SPACE; next_col = get_column(next_char); next_state = FSA_TABLE[current_state][next_col]; if (next_state < 0) { current_state = 0; error_output(next_state, input_string); cout << input_string.substr(0, token_index + 1) << "\n"; cout << string(token_index, SPACE) << "^\n"; token_index++; exit(EXIT_FAILURE); } else if (next_state > FINAL_STATES) { token.desc = token_desc; switch (next_state) { case IDENTIFIER_FINAL_STATE: if (is_keyword(token) != -1) { token.ID = KEYWORDtk; token.desc.assign(token_desc); } else { token.ID = ID_tk; token.desc.assign("ID_tk " + token_desc); } break; case INTEGER_FINAL_STATE: token.ID = INT_tk; token.desc.assign("INT_tk " + token_desc); break; case OPERATOR_FINAL_STATE: token.ID = OPtk; get_operator(token); token.desc.assign(token_desc); break; } return 0; } current_state = next_state; token_index++; if (!isspace(next_char)) token_desc.push_back(next_char); } return -1; } //-------------------------------------------------- //get the column with the input int get_column(char ch) { if (isalpha(ch)) { //check if input is lower case if (islower(ch)) return 0; //return 0 for lower else return 1; //return 1 for upper } else if (isdigit(ch)) return 2; //return 2 for digit else if (isspace(ch)) return 3; //return 3 for space else if (is_operator(ch)) return 5; //return 5 for operatort= else return -1; //does not exisit } //output error void error_output(int state, string input_string) { cout << "Scanner error: Line " << line_index << ": "; //print error if (state == ERROR_STATE_UPPERCASE) { cout << "All tokens must be lower case \n"; } else if (state == ERROR_STATE_INTEGER) { cout << "All integer tokens must only be numbers\n"; } }
[ "sefikm10@gmail.com" ]
sefikm10@gmail.com
59c5ebae2773555ae6170eceae8d79bef74bb0e9
0a4afb613c12e5a06702f28f922fc03461bebb47
/Classes/BroadphaseTestLayer.cpp
2bbef8ae741f3cfcb27a2b7aad2224ad9295eae5
[]
no_license
zhangw358/2DPhysicsEngine
7f363de698a6e5cd9f9b7851d84f2559df725d8f
f31ea27699646fd16f11349e5e37c8309e026129
refs/heads/master
2021-01-10T01:45:39.985322
2016-04-03T05:20:38
2016-04-03T05:20:38
55,300,168
0
0
null
null
null
null
UTF-8
C++
false
false
7,801
cpp
// // BroadphaseTestLayer.cpp // PhysicsProj // // Created by 张唯 on 16/3/29. // // #include "VisibleRect.h" #include "cocos-ext.h" #include "StartScene.h" #include "BroadphaseTestLayer.h" USING_NS_CC; using extension::CCPhysicsSprite; enum { kTagParentNode = 1, }; BroadphaseTestLayer::BroadphaseTestLayer() : m_pSpriteTexture(NULL) , m_pWorld(NULL) , m_counter(0) , m_pListener(NULL) { } BroadphaseTestLayer::~BroadphaseTestLayer() { CC_SAFE_DELETE(m_pWorld); CC_SAFE_DELETE(m_pListener); } void BroadphaseTestLayer::onEnter() { CCLayer::onEnter(); } void BroadphaseTestLayer::initPhysics() { m_pWorld = new MyWorld(); m_pListener = new MyContactListenerImpl3(); m_pWorld->setContactListener(m_pListener); MyBody *body = m_pWorld->createBody(); MyEdgeShape shape1; shape1.setPosition(MyVec2(VisibleRect::leftTop().x,VisibleRect::leftTop().y-1), MyVec2(VisibleRect::leftBottom().x,VisibleRect::leftBottom().y+1)); body->createShape(&shape1); MyBody *body2 = m_pWorld->createBody(); MyEdgeShape shape2; shape2.setPosition(MyVec2(VisibleRect::leftBottom().x+1,VisibleRect::leftBottom().y), MyVec2(VisibleRect::rightBottom().x-1,VisibleRect::rightBottom().y)); body2->createShape(&shape2); MyBody *body3 = m_pWorld->createBody(); MyEdgeShape shape3; shape3.setPosition(MyVec2(VisibleRect::leftTop().x+1,VisibleRect::leftTop().y), MyVec2(VisibleRect::rightTop().x-1,VisibleRect::rightTop().y)); body3->createShape(&shape3); MyBody *body4 = m_pWorld->createBody(); MyEdgeShape shape4; shape4.setPosition(MyVec2(VisibleRect::rightBottom().x,VisibleRect::rightBottom().y+1), MyVec2(VisibleRect::rightTop().x,VisibleRect::rightTop().y-1)); body4->createShape(&shape4); } // on "init" you need to initialize your instance bool BroadphaseTestLayer::init() { ////////////////////////////// // 1. super init first bool bRet = CCLayer::init(); if ( bRet ) { CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize(); CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object CCMenuItemImage *pCloseItem = CCMenuItemImage::create( "CloseNormal.png", "CloseSelected.png", this, menu_selector(BroadphaseTestLayer::menuCloseCallback)); pCloseItem->setPosition(ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width/2 , origin.y + pCloseItem->getContentSize().height/2)); // create menu, it's an autorelease object CCMenu* pMenu = CCMenu::create(pCloseItem, NULL); pMenu->setPosition(CCPointZero); this->addChild(pMenu, 1); ///////////////////////////// // 3. add your codes below... setTouchEnabled( true ); setAccelerometerEnabled( true ); // init physics this->initPhysics(); // create reset button this->createResetButton(); //Set up sprite // Use batch node. Faster CCSpriteBatchNode *parent = CCSpriteBatchNode::create("Images/blocks.png", 100); m_pSpriteTexture = parent->getTexture(); addChild(parent, 0, kTagParentNode); for (int i = 1; i < 22; i++) { for (int j = 1; j < 13; j++) { addNewSpriteAtPosition(CCPoint(i * 43, j * 43)); } } scheduleUpdate(); } return bRet; } void BroadphaseTestLayer::createResetButton() { CCMenuItemImage *reset = CCMenuItemImage::create("Images/r1.png", "Images/r2.png", this, menu_selector(BroadphaseTestLayer::reset)); CCMenu *menu = CCMenu::create(reset, NULL); menu->setPosition(ccp(VisibleRect::bottom().x, VisibleRect::bottom().y + 30)); this->addChild(menu, -1); } void BroadphaseTestLayer::reset(CCObject* sender) { CCDirector::sharedDirector()->replaceScene(StartScene::create()); } void BroadphaseTestLayer::draw() { // // IMPORTANT: // This is only for debug purposes // It is recommend to disable it // CCLayer::draw(); ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position ); kmGLPushMatrix(); //world->DrawDebugData(); kmGLPopMatrix(); } void BroadphaseTestLayer::addNewSpriteAtPosition(CCPoint p) { CCLOG("Add sprite %0.2f x %02.f",p.x,p.y); MyBody *body = m_pWorld->createBody(); CCPhysicsSprite *sprite = NULL; MyCircleShape shape; shape.setRadius(12.0f); body->createShape(&shape); body->setPosition(MyVec2(p.x, p.y)); body->setAngularVelocity(0.05f); if (m_counter > 250) { body->setLinearVelocity(MyVec2(2.0f, -1.0f)); } m_counter++; sprite = CCPhysicsSprite::create("Images/r2.png", CCRectMake(0,0,49,48)); sprite->setScale(0.5); addChild(sprite); body->setPosition(MyVec2(p.x, p.y)); sprite->setMyBody(body); body->setUserData((void*)sprite); } void BroadphaseTestLayer::update(float dt) { //It is recommended that a fixed time step is used with Box2D for stability //of the simulation, however, we are using a variable time step here. //You need to make an informed choice, the following URL is useful //http://gafferongames.com/game-physics/fix-your-timestep/ //int velocityIterations = 8; int positionIterations = 3; // Instruct the world to perform a single step of simulation. It is // generally best to keep the time step and iterations fixed. m_pWorld->step(positionIterations); } void BroadphaseTestLayer::ccTouchesEnded(CCSet* touches, CCEvent* event) { //Add a new body/atlas sprite at the touched location CCSetIterator it; CCTouch* touch; for( it = touches->begin(); it != touches->end(); it++) { touch = (CCTouch*)(*it); if(!touch) break; CCPoint location = touch->getLocation(); addNewSpriteAtPosition( location ); } } void BroadphaseTestLayer::menuCloseCallback(CCObject* pSender) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert"); #else CCDirector::sharedDirector()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif #endif } ///ContactListener void MyContactListenerImpl3::BeginContact(MyContact* contact) { if (contact) { MyBody* bodya = contact->getBodyA(); MyBody* bodyb = contact->getBodyB(); //if (bodya->getShapeInfo()->getType() == bodyb->getShapeInfo()->getType()) { //bodya->setValid(false); //bodyb->setValid(false); } } } void MyContactListenerImpl3::EndContact(MyContact* contact) { MyBody* bodya = contact->getBodyA(); MyBody* bodyb = contact->getBodyB(); CCPhysicsSprite* spriteA = (CCPhysicsSprite*)bodya->getUserData(); CCPhysicsSprite* spriteB = (CCPhysicsSprite*)bodyb->getUserData(); if (spriteA) { //spriteA->setColor(ccc3(255, 255, 255)); } if (spriteB) { //spriteB->setColor(ccc3(255, 255, 255)); } }
[ "zhangw358@qq.com" ]
zhangw358@qq.com
92eb660652ef629ec7b1172c832e03a55f013971
45fc787fe73d9a64b6757da1abfa1237acfa34de
/arduino/illuminate_led/illuminate_led.ino
c454cb06facc0f29d81d20a5451983f588ef2b3c
[]
no_license
keiji/adk-handson
eff7b9e81d9d63dec663e70a4c1cbce080f20832
b701ae5c8ed0719302605ae47330751393a49a1d
refs/heads/master
2016-08-06T17:11:56.252620
2013-01-18T23:39:43
2013-01-18T23:41:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
245
ino
#define PIN_LED 13 void setup() { Serial.begin(115200); pinMode(PIN_LED, OUTPUT); } int light = 0; int p = 1; void loop() { light += p; if (light == 0 || light == 255) { p *= -1; } delay(10); analogWrite(PIN_LED, light); }
[ "keiji_ariyama@c-lis.co.jp" ]
keiji_ariyama@c-lis.co.jp
49807796d63581e6a2d97fe635a8cf72098b75f6
e4f59a3b3a7eda4d1bc00050d76fc8bce1cf093f
/code/Spikes/timer_example_alex/timer_example_alex.ino
663a0dae2b0fd6f1b643a82a1e88d137e1e45ea8
[]
no_license
AlexanderNahr/arduino_team_PMES_WS2016
03ed37906254cae01adef7d83d787368806a837c
691d8cb0f4df41bc46ac00b6936949804e428fb7
refs/heads/master
2021-01-12T09:55:09.534469
2017-03-10T22:39:41
2017-03-10T22:39:41
76,298,477
2
3
null
2017-03-11T11:53:47
2016-12-12T21:48:56
C++
UTF-8
C++
false
false
12,311
ino
/********************************************NOTE******************************************************************** * Statt Pin 13 habe ich pin A2 zur Tonausgabe verwendet. ********************************************************************************************************************/ /****************************************************************************************************************//** * \file displayTest_Aufgabe1.8 * \brief Uebung 1, Aufgabe 8 * \author Alexander Nahrwold * \date 2.11.2016 /****************************************************************************************************************/ /* * Plan: * - 1 second interrupt for traffic light * - ADC done interrupt * - main loop will * -- count seconds and switch lights on/off * -- check ADC done flage periodically and store value (not necessarily required) * -- after both checks are done display will be printed with local, updated values * * Source: * - ADC Interrupt: http://www.glennsweeney.com/tutorials/interrupt-driven-analog-conversion-with-an-atmega328p * - Arduino timed interrupts: http://playground.arduino.cc/Code/Timer1 * - Timed Interrupts: http://www.instructables.com/id/Arduino-Timer-Interrupts/step2/Structuring-Timer-Interrupts/ /****************************************************************************************************************/ // Include Files #include <LiquidCrystal.h> //!< include LCD functions: #include "pitches.h" //!< for /****************************************************************************************************************/ // Global Variables int RS_pin = 3; //!< LCD RS pin connects to pin3 int E_pin = 4; //!< LCD E pin connects to pin4 int DB4_pin = 6; //!< LCD DB4 pin connects to pin6 int DB5_pin = 7; //!< LCD DB5 pin connects to pin7 int DB6_pin = 8; //!< LCD DB6 pin connects to pin8 int DB7_pin = 9; //!< LCD DB7 pin connects to pin9 LiquidCrystal lcd( RS_pin, E_pin, DB4_pin, DB5_pin, DB6_pin, DB7_pin); //!< define the LCD screen int analogValue = -1; //!< global variable, stores the result from analog pin int g_ledPin1 = 10; //!< red int g_ledPin2 = 11; //!< yellow int g_ledPin3 = 12; //!< green int g_speakerPin = 13; //!< pin associated with the speaker int toggle1 = 0; //!< interrupt toggler int g_traffic_light_counter = 0; //!< counter for ISR to control traffic light /****************************************************************************************************************/ // function declaration void SwitchTrafficLight( int light_color ); int ButtonCheck( int adc_count, char* button_clicked_buffer, int buffer_size ); void SetupTimer1( void ); /****************************************************************************************************************/ // constants #define RED_LIGHT 0 #define YELLOW_LIGHT 1 #define GREEN_LIGHT 2 #define RED_LIGHT_TIME 0 //!< start time red light #define YELLOW_LIGHT_1_TIME 5 //!< start time yellow light #define GREEN_LIGHT_TIME 8 //!< start time green light #define YELLOW_LIGHT_2_TIME 9 //!< start time yello light #define MAX_TIME 9 //!< overflow time #define RED_FREQUENCY 100 //!< frequency for speaker in Hz #define GREEN_FREQUENCY 400 //!< frequency for speaker in Hz #define ONE_SECOND 1000 #define THREE_SECONDS 3*ONE_SECOND #define FIVE_SECONDS 5*ONE_SECOND // references ADC counts for button clicks #define BUTTON_1 1 //!< ADC count button 1/S1 click #define BUTTON_2 242 //!< ADC count button 2/S2 click #define BUTTON_3 473 //!< ADC count button 3/S3 click #define BUTTON_4 679 //!< ADC count button 4/S4 click #define BUTTON_5 831 //!< ADC count button 5/S5 click #define NO_BUTTONS 1023 //!< ADC count no buttons clicked #define BTN_ADC_TOLERANCE 50 //!< tolerance for ADC counts for button click #define FAILURE -1 #define SUCCESS 0 #define DISPLAY_LINE_1 0 //!< display line 1 #define DISPLAY_LINE_2 1 //!< display line 2 #define DISPLAY_LINE_3 2 //!< display line 3 #define DISPLAY_LINE_4 3 //!< display line 4 #define DISPLAY_BEGIN 0 //!< display begin #define DISPLAY_END 19 //!< display end /****************************************************************************************************************//* * \brief setup function /****************************************************************************************************************/ void setup() { // LCD has 4 lines with 20 chars lcd.begin(20, 4); lcd.print("system ready"); // set ledPin as output pinMode( g_ledPin1, OUTPUT ); pinMode( g_ledPin2, OUTPUT ); pinMode( g_ledPin3, OUTPUT ); //pinMode( g_speakerPin, OUTPUT ); SwitchTrafficLight( RED_LIGHT ); tone( A2, RED_FREQUENCY ); g_traffic_light_counter = 0; SetupTimer1( ); // TIMER_EXAMPLE - setup timer here } // Interrupts /****************************************************************************************************************//** * \brief interupt service routine for timer 1 - TIMER_EXAMPLE * attach timer 1 comparision to interrupt vector table * -> THIS WILL BE EXECUTED everytime timer1 interrupt is triggered * \source http://www.instructables.com/id/Arduino-Timer-Interrupts/step2/Structuring-Timer-Interrupts/ /****************************************************************************************************************/ ISR( TIMER1_COMPA_vect ) { g_traffic_light_counter++; if( g_traffic_light_counter > MAX_TIME ) { g_traffic_light_counter = 0; } } /****************************************************************************************************************//* * \brief main loop /****************************************************************************************************************/ void loop() { delay( 100 ); static char button_print[ 100 ] = "No Button"; static char light_print[ 100 ] = "red"; static int current_light = -1; //!< identifies the current light // implement your code here: lcd.clear( ); // DISPLAY LINE 1 /////////////////////////////////////////////////////// // read and print analog button value lcd.print( "Analog 0: " ); analogValue = analogRead( A0 ); lcd.print( analogValue ); // DISPLAY LINE 2 /////////////////////////////////////////////////////// // determine which button is clicked int clicked_button = ButtonCheck( analogValue, button_print, sizeof( button_print ) ); // when button 1 is pressed, leave RED_LIGHT phase // REMEMBER: IF BUTTONS ARE NOT CONNECTED, IT WILL LOOK LIKE BUTTON 1 // IS ACTIVE if( clicked_button == BUTTON_1 && current_light == RED_LIGHT) { g_traffic_light_counter = YELLOW_LIGHT_1_TIME; } // print results lcd.setCursor( DISPLAY_BEGIN, DISPLAY_LINE_2 ); lcd.print( button_print ); // DISPLAY LINE 3 /////////////////////////////////////////////////////// switch( g_traffic_light_counter ) // TIMER_EXAMPLE { case RED_LIGHT_TIME: current_light = RED_LIGHT; SwitchTrafficLight( current_light ); strcpy( light_print, "red"); tone( A2, RED_FREQUENCY ); break; case YELLOW_LIGHT_1_TIME: noTone( A2 ); current_light = YELLOW_LIGHT; SwitchTrafficLight( current_light ); strcpy( light_print, "yellow"); break; case GREEN_LIGHT_TIME: current_light = GREEN_LIGHT; SwitchTrafficLight( current_light ); strcpy( light_print, "green"); tone( A2, GREEN_FREQUENCY); break; case YELLOW_LIGHT_2_TIME: noTone( A2 ); current_light = YELLOW_LIGHT; SwitchTrafficLight( current_light ); strcpy( light_print, "yellow"); break; default: break; } lcd.setCursor( DISPLAY_BEGIN, DISPLAY_LINE_3 ); lcd.print( light_print ); // wait for 100 ms (reduces display flickering) delay( 100 ); } /****************************************************************************************************************//** * \brief switches traffic light * \param light_color color of light you want to switch /****************************************************************************************************************/ void SwitchTrafficLight( int light_color ) { switch( light_color ) { case RED_LIGHT: digitalWrite(g_ledPin1, HIGH); digitalWrite(g_ledPin2, LOW); digitalWrite(g_ledPin3, LOW); break; case YELLOW_LIGHT: digitalWrite(g_ledPin1, LOW); digitalWrite(g_ledPin2, HIGH); digitalWrite(g_ledPin3, LOW); break; case GREEN_LIGHT: digitalWrite(g_ledPin1, LOW); digitalWrite(g_ledPin2, LOW); digitalWrite(g_ledPin3, HIGH); break; default: break; } } /****************************************************************************************************************//* * \brief checks which button is clicked on S-Trike experimentation board * \param adc_count ADC value returned by analog read function * \param button_clicked output: char array with string description of button * \return return the reference value for button click /****************************************************************************************************************/ int ButtonCheck( int adc_count, char* button_clicked_buffer, int buffer_size ) { int return_value = FAILURE; #define MIN_STRING_SIZE 100 strncpy( button_clicked_buffer, "Not Set.", buffer_size ); if( buffer_size >= MIN_STRING_SIZE ) { if( adc_count >= 0 ) { /* * assume adc_count=250 * adc_count_plus = 300 * adc_count_mius = 200 * BUTTON_2=242 */ int adc_count_plus = adc_count + BTN_ADC_TOLERANCE; int adc_count_minus = adc_count - BTN_ADC_TOLERANCE; if( adc_count_plus > BUTTON_1 && adc_count_minus < BUTTON_1) { strncpy( button_clicked_buffer, "Button: 1", buffer_size ); return_value = BUTTON_1; } else if( adc_count_plus > BUTTON_2 && adc_count_minus < BUTTON_2) { strncpy( button_clicked_buffer, "Button: 2", buffer_size ); return_value = BUTTON_2; } else if( adc_count_plus > BUTTON_3 && adc_count_minus < BUTTON_3) { strncpy( button_clicked_buffer, "Button: 3", buffer_size ); return_value = BUTTON_3; } else if( adc_count_plus > BUTTON_4 && adc_count_minus < BUTTON_4) { strncpy( button_clicked_buffer, "Button: 4", buffer_size ); return_value = BUTTON_4; } else if( adc_count_plus > BUTTON_5 && adc_count_minus < BUTTON_5) { strncpy( button_clicked_buffer, "Button: 5", buffer_size); return_value = BUTTON_5; } else { strncpy( button_clicked_buffer, "No Button.", buffer_size ); return_value = NO_BUTTONS; } } } return( return_value ); } /****************************************************************************************************************//** * \brief setup timer 1 for Compare Match (CTC) with 1 sec resolution - TIMER_EXAMPLE * \details modified from \source to accomodate 256 prescaler and 8MHz clk * \source http://www.instructables.com/id/Arduino-Timer-Interrupts/step2/Structuring-Timer-Interrupts/ /****************************************************************************************************************/ void SetupTimer1( void ) { cli(); // stop interrupts // set timer1 interrupt at 1Hz TCCR1A = 0; // set entire TCCR1A register to 0 TCCR1B = 0; // same for TCCR1B TCNT1 = 0; // initialize counter value to 0 // set compare match register for 1hz increments OCR1A = 31249; // = (8*10^6) / (1*256) - 1 (must be <65536) // turn on CTC mode TCCR1B |= (1 << WGM12); // Set CS10 and CS12 bits for 256 prescaler TCCR1B |= (1 << CS12); // enable timer compare interrupt TIMSK1 |= (1 << OCIE1A); sei(); // allow interrupts }
[ "alexnahr@gmail.com" ]
alexnahr@gmail.com
18d354cb289310595a7e9c9071b21d9cf6b82f2e
cd64cca3d9e72e4ef0273e32b0f2d852ddabdadf
/ElementAppearingMoreThan25PercentInSortedArray/ElementAppearingMoreThan25PercentInSortedArray/main.cpp
84e0426b89d0663fc3df23996c1bb53a365d99ed
[]
no_license
stereotype13/LeetCodePractice
48f4471a5e0b4d890ac31760f399f91173e197d8
1151084f16485c1ac0d5fadd6b533c0fb350a50b
refs/heads/master
2020-11-25T03:34:57.825558
2020-03-09T21:33:02
2020-03-09T21:33:02
228,477,225
0
0
null
null
null
null
UTF-8
C++
false
false
1,202
cpp
/* Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time. Return that integer. Example 1: Input: arr = [1,2,2,6,6,6,6,7,10] Output: 6 Constraints: 1 <= arr.length <= 10^4 0 <= arr[i] <= 10^5 */ #include <iostream> #include <vector> #include <unordered_map> #include <algorithm> using namespace std; class Solution { public: int findSpecialInteger(vector<int>& arr) { unordered_map<int, int> frequencies; for (const auto& i : arr) frequencies[i]++; auto& p = *max_element(frequencies.begin(), frequencies.end(), [](const auto& p1, const auto& p2) { return p1.second < p2.second; }); return p.first; } }; class Solution2 { public: int findSpecialInteger(vector<int>& arr) { if (arr.size() == 1) return arr[0]; int count = 1; for (int i = 1; i < (int)arr.size(); ++i) { if (arr[i] == arr[i - 1]) { ++count; if (count / 4.0 > 0.25) return arr[i]; continue; } count = 1; } return -1; } }; int main() { Solution2 solution; vector<int> input1{ 1,2,2,6,6,6,6,7,10 }; cout << solution.findSpecialInteger(input1) << endl; cin.get(); return 0; }
[ "rhodel3@gatech.edu" ]
rhodel3@gatech.edu
5c01091bfc37af24ad98fcbc16ce8c24cb6e895c
a5051d65ab1eeec604fcb565742eb8837077439d
/off/把数组排成最小的数.cpp
2b9dc9ac5197eeb715d298aed94aab17497675c0
[]
no_license
Aspiration1314/Off
81b3d02fa37bfb28321604f4f22a412816a42884
39705aed537e95520e7c2b59e4d6e3dd54d8e010
refs/heads/master
2020-04-30T02:26:00.849937
2019-03-19T16:56:59
2019-03-19T16:56:59
176,559,243
0
0
null
null
null
null
GB18030
C++
false
false
727
cpp
/*思路:通过字符串解决大数问题,然后通过自定义的字符串比较规则,对字符串排序*/ class Solution { public: string PrintMinNumber(vector<int> numbers) { if (numbers.size()<1) return string(); string result; vector<string> numberString; for (int i = 0; i<numbers.size(); i++) { stringstream ss; ss << numbers[i]; string s = ss.str(); numberString.push_back(s); } sort(numberString.begin(), numberString.end(), Compare); for (int i = 0; i<numberString.size(); i++) result.append(numberString[i]); return result; } static bool Compare(const string &str1, const string &str2) { string s1 = str1 + str2; string s2 = str2 + str1; return s1<s2; } };
[ "1114544658@qq.com" ]
1114544658@qq.com
d50d2f7b3779570cb4bff481bf6ed0a83808f780
47c3da6a94aa6039bd9cccf30a5424843c955eb0
/Ones.cpp
360c492111a010fee678979531fd904f1dc85da4
[]
no_license
colinmrees/PE129
6eccf42b4de5657d9d39bb62c3094c9264249932
e4e10c18f936c2ae1b018f1ab46b7c51268774e7
refs/heads/master
2021-05-05T03:11:18.111547
2018-02-01T07:29:12
2018-02-01T07:29:12
119,791,134
0
0
null
null
null
null
UTF-8
C++
false
false
4,848
cpp
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; #define lint __uint128_t int intlog2 ( lint val) { if (val == 0) return 0; if (val == 1) return 0; int ret = 0; while (val > 1) { val >>= 1; ret++; } return ret; } lint intpow2 ( int val ){ lint ret = 1; while( val-- ) ret*=2; return ret; } /**** *Calulates a vector of all possible whole divisors of the totient using the array of all primes, p. */ void allFactors ( lint t, int* p, vector<lint>& trials ){ vector<lint> each; vector<lint>::iterator it; lint eachProduct; double maxfactor = sqrt((double)t); for (int i = 0; p[i]<= maxfactor; ++i ){ //iterate over all primes eachProduct = 1; while ( t%p[i] == 0 ){ t=t/p[i]; eachProduct *= p[i]; vector<lint> temp; temp.resize(trials.size()); transform(trials.begin(),trials.end(),temp.begin(),bind1st(multiplies<lint>(),eachProduct)); int size1 = each.size(); each.insert(each.end(), temp.begin(), temp.end()); if( size1 ) inplace_merge(each.begin(), each.begin()+size1, each.end()); } int size2 = trials.size(); trials.insert(trials.end(), each.begin(), each.end()); inplace_merge(trials.begin(), trials.begin()+size2, trials.end()); each.clear(); } if( t != 1 ){ vector<lint> temp; temp.resize(trials.size()); transform(trials.begin(),trials.end(),temp.begin(),bind1st(multiplies<lint>(),t)); int size2 = trials.size(); trials.insert(trials.end(), temp.begin(), temp.end()); inplace_merge(trials.begin(), trials.begin()+size2, trials.end()); } } /**** * Uses the Euler Product Formula to calculate the totient function of n, using the array of all primes, P. */ lint ePF( lint n, int* p){ lint totient = n; double maxfactor = sqrt((double)n); //cout << "Debug: " << maxfactor << endl; for (int i = 0; p[i]<= maxfactor; ++i ){ //iterate over all primes //cout << "Debug: " << i << " " << p[i] << endl; if ( n%p[i] == 0 ){ totient = totient/p[i]*(p[i]-1); } while ( n%p[i] == 0 ){ n=n/p[i]; } } if( n != 1 ){ totient = totient/n*(n-1); } return totient; } /**** * Uses the sieve of Eratosthenes algorithm to calculate all primes less than m */ void primes(int m, int* p, bool* sieve ){ for( int i = 2; i < m; ++i ) sieve[i-2]=1; int x=0; for( int i = 2; i < m; ++i ){ if (sieve[i-2]){ p[x]=i; x++; for( lint j = (lint)i*i; j < m; j=j+i ) sieve[j-2] = 0; } } //cout << x << endl; //used to determine value of x } /**** * Calculates the smallest integer comprised of repeating 1s, R(k), which is a multiple of input n */ int main( int argc, char** argv ){ //Calculate Primes int m = int(sqrt(9e13)); //looking for all primes less than m int num = 632759; //1.3*m/(log(m)-1); //number of primes less than m. int *p = new int[num]; bool *sieve = new bool[m-2]; primes(m, p, sieve); delete sieve; //Input and iterate over all records char in[40]; lint input; cin >> in; int records = atoi(in); int total = 0; for (int r = 0; r < records; ++r){ cin >> in; input = atol(in); //n if ( input < 1 || input %5 == 0 || input % 2 == 0) { //Catch invalid inputs cout << 0 << endl; } else { //Calculate the totient of n*9 and create a vector containing all whole divisors of the totient vector<lint> trials; trials.push_back(1); lint totient = ePF(input*9, p); allFactors ( totient, p, trials ); lint k = 0; // R(k)%n //Pre-calculate the values needed to calculate R(k) in modulo n int numPre = 80; //number of powers of 2 to pre-calculate in modulo lint mul[numPre]; lint add[numPre]; mul[0] = 10; add[0] = 1; for( int i = 1; i < numPre; ++i){ mul[i] = (mul[i-1]*mul[i-1])%input; add[i] = (add[i-1]*mul[i-1]+add[i-1])%input; } //iterate over all divisors of the tortient, and for each calculate R(k)%n from the previous and check if it is 0 lint tinput = 0; lint last = 0; lint compare; for ( vector<lint>::iterator it = trials.begin()+1; it != trials.end(); ++it){ //iterate over all trials if( input == 1 ){ cout << 1 << endl; break; } tinput = *it-last; last = *it; lint copInput = tinput; for( int i = 0; copInput > 0; ++i ){ //increase R(k) in increments of 10^2^i if( copInput % 2 ){ k=(k*mul[i]+add[i])%input; } copInput /= 2; if (i >= numPre ){ cerr << "Error: Increase NumPre" << endl; break; } } if( k == 0 ){ cout << (long)*it << endl; //if the solution is found, output the value of the successful trial break; } } } } delete p; }
[ "cmrees@gmail.com" ]
cmrees@gmail.com
23ae1f3f7df14117187ddb2546c3a6fbe4ce3c23
3329ff94ba44f5a575b5398985a33aa948b5f944
/0.00705/uniform/lagrangian/sprayCloud/sprayCloudOutputProperties
516a5217550fbdbe61cee3dccd105f34ada42faf
[]
no_license
zlsherl/SKPS_simple
38cfac333dd65ed752e34c9f00b555d4255d2efc
0de13926915af0c7eaf1904fe57a8149a7741ba1
refs/heads/main
2023-05-26T20:03:42.391527
2021-06-12T10:24:09
2021-06-12T10:24:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,509
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2012 | | \\ / A nd | Website: www.openfoam.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "0.00705/uniform/lagrangian/sprayCloud"; object sprayCloudOutputProperties; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // injectionModel { model1 { volumeTotal 0.00874187; massInjected 5.99558e-06; nInjections 28110; parcelsAddedTotal 11078; timeStep0 0.00705; } } patchInteractionModel { escapedParcels 0; escapedMass 0; standardWallInteraction { nEscape 3 ( 1 ( 0 ) 1 ( 0 ) 1 ( 0 ) ); massEscape 3 ( 1 ( 0 ) 1 ( 0 ) 1 ( 0 ) ); nStick 3 ( 1 ( 0 ) 1 ( 0 ) 1 ( 0 ) ); massStick 3 ( 1 ( 0 ) 1 ( 0 ) 1 ( 0 ) ); } } phaseChangeModel { mass 5.99558e-06; } // ************************************************************************* //
[ "krystek.pietrzak@gmail.com" ]
krystek.pietrzak@gmail.com
7d36990c18124d01302e0327c973e846a40bff0f
792fbf91f3da85c65db3b99a3f881e0686a19a7e
/IMApp/IMApp/TestApi.cpp
6dc08cae3c0667dec2aae5738c271dce019aa8c7
[]
no_license
wannianhong/txWindowsIMDemo
17e652c5384e70a69f2ced747495ee946ce4416c
e9d70d1194ffe0ca747a729d3585d8b3108db24f
refs/heads/master
2020-11-29T06:02:42.080324
2019-12-25T04:35:20
2019-12-25T04:35:20
230,039,382
0
0
null
null
null
null
UTF-8
C++
false
false
26,646
cpp
#include "TestApi.h" #include "json.h" #include "IMWnd.h" #include <time.h> //批量发送 void Test_TIMMsgBatchSend() { //构造消息文本元素 Json::Value json_value_elem; json_value_elem[kTIMElemType] = TIMElemType::kTIMElem_Text; json_value_elem[kTIMTextElemContent] = "this is batch send msgs"; //构造消息 Json::Value json_value_msg; json_value_msg[kTIMMsgSender] = CIMWnd::GetInst().login_id; json_value_msg[kTIMMsgClientTime] = time(NULL); json_value_msg[kTIMMsgServerTime] = time(NULL); json_value_msg[kTIMMsgElemArray].append(json_value_elem); // 构造批量发送ID数组列表 Json::Value json_value_ids(Json::arrayValue); json_value_ids.append("user2"); json_value_ids.append("user3"); // 构造批量发送接口参数 Json::Value json_value_batchsend; json_value_batchsend[kTIMMsgBatchSendParamIdentifierArray] = json_value_ids; json_value_batchsend[kTIMMsgBatchSendParamMsg] = json_value_msg; int ret = TIMMsgBatchSend(json_value_batchsend.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_param, const void* user_data) { if (code != ERR_SUCC) { // 批量发送成功 CIMWnd::GetInst().Logf("TESTAPI", kTIMLog_Error, "TIMMsgBatchSend cb code:%u desc:%s", code, desc); return; } Json::Value json_result; Json::Reader reader; if (!reader.parse(json_param, json_result)) { CIMWnd::GetInst().Logf("TESTAPI", kTIMLog_Error, "TIMMsgBatchSend result parse Failure!%s",reader.getFormattedErrorMessages().c_str()); return; } for (Json::ArrayIndex i = 0; i < json_result.size(); i++) { Json::Value& res = json_result[i]; std::string id = res[kTIMMsgBatchSendResultIdentifier].asString(); int sub_code = res[kTIMMsgBatchSendResultCode].asInt(); std::string sub_desc = res[kTIMMsgBatchSendResultDesc].asString(); if (code != ERR_SUCC) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMMsgBatchSend to id:%s Failure! code:%u desc:%s", id.c_str(), sub_code, sub_desc.c_str()); } else { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "TIMMsgBatchSend to id:%s Success!", id.c_str()); } } }, nullptr); if (TIM_SUCC != ret) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMMsgBatchSend Failure!ret %d", ret); } } void Test_MsgFind() { Json::Value json_msg_locator; // 一条消息对应一个消息定位符(精准定位) json_msg_locator[kTIMMsgLocatorIsRevoked] = false; //消息是否被撤回 json_msg_locator[kTIMMsgLocatorTime] = 123; //填入消息的时间 json_msg_locator[kTIMMsgLocatorSeq] = 1; json_msg_locator[kTIMMsgLocatorIsSelf] = false; json_msg_locator[kTIMMsgLocatorRand] = 12345678; Json::Value json_msg_locators; json_msg_locators.append(json_msg_locator); TIMMsgFindByMsgLocatorList("user2", kTIMConv_C2C, json_msg_locators.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_param, const void* user_data) { if (code != ERR_SUCC) { CIMWnd::GetInst().Logf("TESTAPI", kTIMLog_Error, "TIMMsgBatchSend cb code:%u desc:%s", code, desc); return; } }, nullptr); } void Test_MsgImport() { Json::Value json_value_elem; //构造消息文本元素 json_value_elem[kTIMElemType] = TIMElemType::kTIMElem_Text; json_value_elem[kTIMTextElemContent] = "this is import msg"; Json::Value json_value_msg; //构造消息 json_value_msg[kTIMMsgSender] = CIMWnd::GetInst().login_id; json_value_msg[kTIMMsgClientTime] = time(NULL); json_value_msg[kTIMMsgServerTime] = time(NULL); json_value_msg[kTIMMsgElemArray].append(json_value_elem); Json::Value json_value_msgs; //消息数组 json_value_msgs.append(json_value_msg); TIMMsgImportMsgList("user3", kTIMConv_C2C, json_value_msgs.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_param, const void* user_data) { if (code != ERR_SUCC) { CIMWnd::GetInst().Logf("TESTAPI", kTIMLog_Error, "TIMMsgBatchSend cb code:%u desc:%s", code, desc); return; } }, nullptr); } void Test_MsgDelete() { Json::Value json_value_msg(Json::objectValue); Json::Value json_value_msgdelete; json_value_msgdelete[kTIMMsgDeleteParamIsRamble] = false; json_value_msgdelete[kTIMMsgDeleteParamMsg] = json_value_msg; TIMMsgDelete("user2", kTIMConv_C2C, json_value_msgdelete.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_param, const void* user_data) { if (code != ERR_SUCC) { CIMWnd::GetInst().Logf("TESTAPI", kTIMLog_Error, "TIMMsgBatchSend cb code:%u desc:%s", code, desc); return; } }, nullptr); } void Test_SetGroupInfo() { //*修改群组名称和群通知 Json::Value json_value_setgroupinfo; json_value_setgroupinfo[kTIMGroupModifyInfoParamGroupId] = "first group id"; json_value_setgroupinfo[kTIMGroupModifyInfoParamModifyFlag] = kTIMGroupModifyInfoFlag_Name | kTIMGroupModifyInfoFlag_Notification; json_value_setgroupinfo[kTIMGroupModifyInfoParamGroupName] = "first group name to other name"; json_value_setgroupinfo[kTIMGroupModifyInfoParamNotification] = "first group notification"; //*/ /* 修改群主 Json::Value json_value_setgroupinfo; json_value_setgroupinfo[kTIMGroupModifyInfoParamGroupId] = "first group id"; json_value_setgroupinfo[kTIMGroupModifyInfoParamModifyFlag] = kTIMGroupModifyInfoFlag_Owner; json_value_setgroupinfo[kTIMGroupModifyInfoParamOwner] = "user2"; //*/ int ret = TIMGroupModifyGroupInfo(json_value_setgroupinfo.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_param, const void* user_data) { if (code != ERR_SUCC) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMGroupModifyGroupInfo cb code:%u desc:%s", code, desc); return; } }, nullptr); if (TIM_SUCC != ret) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMGroupSetGroupInfo Failure!ret %d", ret); } } void Test_SetGroupMemberInfo() { // 设置 成员为管理员 Json::Value json_value_setgroupmeminfo; json_value_setgroupmeminfo[kTIMGroupModifyMemberInfoParamGroupId] = "third group id"; json_value_setgroupmeminfo[kTIMGroupModifyMemberInfoParamIdentifier] = "user2"; json_value_setgroupmeminfo[kTIMGroupModifyMemberInfoParamModifyFlag] = kTIMGroupMemberModifyFlag_MemberRole | kTIMGroupMemberModifyFlag_NameCard; json_value_setgroupmeminfo[kTIMGroupModifyMemberInfoParamMemberRole] = kTIMMemberRole_Admin; json_value_setgroupmeminfo[kTIMGroupModifyMemberInfoParamNameCard] = "change name card"; int ret = TIMGroupModifyMemberInfo(json_value_setgroupmeminfo.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_param, const void* user_data) { if (code != ERR_SUCC) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMGroupSetMemberInfo cb code:%u desc:%s", code, desc); return; } }, nullptr); if (TIM_SUCC != ret) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMGroupSetMemberInfo Failure!ret %d", ret); } } // 获取未决信息 并处理 void Test_GroupGetPendencyList() { Json::Value get_pendency_option; get_pendency_option[kTIMGroupPendencyOptionStartTime] = 0; get_pendency_option[kTIMGroupPendencyOptionMaxLimited] = 0; int ret = TIMGroupGetPendencyList(get_pendency_option.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_param, const void* user_data) { if (code != ERR_SUCC) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMGroupGetPendencyList cb code:%u desc:%s", code, desc); return; } Json::Value group_pendency_result; Json::Reader reader; if (!reader.parse(json_param, group_pendency_result)) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMGroupGetPendencyList Json Parse Failure!%s", reader.getFormattedErrorMessages().c_str()); return; } Json::Value& group_pendency_array = group_pendency_result[kTIMGroupPendencyResultPendencyArray]; for (Json::ArrayIndex i = 0; i < group_pendency_array.size(); i++) { /* 上报未决消息已读 uint64_t timestamp = group_pendency_array[i][kTIMGroupPendencyAddTime].asUInt64(); int ret = TIMGroupReportPendencyReaded(timestamp, [](int32_t code, const char* desc, const char* json_param, const void* user_data) { if (code != ERR_SUCC) { // CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMGroupHandlePendency cb code:%u desc:%s", code, desc); return; } }, nullptr); if (TIM_SUCC != ret) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMGroupHandlePendency Failure!ret %d", ret); } //*/ //* 处理 每一个pendency 为accept Json::Value pendency; //构造 GroupPendency Json::Value handle_pendency; handle_pendency[kTIMGroupHandlePendencyParamIsAccept] = true; handle_pendency[kTIMGroupHandlePendencyParamHandleMsg] = "I accept this pendency"; handle_pendency[kTIMGroupHandlePendencyParamPendency] = pendency; int ret = TIMGroupHandlePendency(handle_pendency.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_param, const void* user_data) { if (code != ERR_SUCC) { // CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMGroupHandlePendency cb code:%u desc:%s", code, desc); return; } }, nullptr); if (TIM_SUCC != ret) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMGroupHandlePendency Failure!ret %d", ret); } //*/ } // HandlePendency }, nullptr); if (TIM_SUCC != ret) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Error, "TIMGroupGetPendencyList Failure!ret %d", ret); } } void Test_GetMsgList() { Json::Value json_elem(Json::objectValue); json_elem[kTIMElemType] = 0; json_elem[kTIMTextElemContent] = "2"; Json::Value json_elem_array(Json::arrayValue); json_elem_array.append(json_elem); Json::Value json_msg(Json::objectValue); json_msg[kTIMMsgClientTime] = 1652039330; json_msg[kTIMMsgConvId] = "user2"; json_msg[kTIMMsgConvType] = 1; json_msg[kTIMMsgElemArray] = json_elem_array; json_msg[kTIMMsgIsFormSelf] = true; json_msg[kTIMMsgIsRead] = true; json_msg[kTIMMsgRand] = 3984852732LL; json_msg[kTIMMsgSender] = "user1"; json_msg[kTIMMsgSeq] = 1; json_msg[kTIMMsgServerTime] = 1652039330; json_msg[kTIMMsgStatus] = 2; Json::Value json_msgget_param; json_msgget_param[kTIMMsgGetMsgListParamLastMsg] = json_msg; json_msgget_param[kTIMMsgGetMsgListParamIsRamble] = false; json_msgget_param[kTIMMsgGetMsgListParamIsForward] = false; json_msgget_param[kTIMMsgGetMsgListParamCount] = 100; std::string json = json_msgget_param.toStyledString(); int ret = TIMMsgGetMsgList("user2", kTIMConv_C2C, json.c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "TIMMsgGetMsgList cb code:%u desc:%s", code, desc); }, nullptr); } //****************** 好友关系链接口使用**********************/ void TestFriendshipGetProfileList() { Json::Value json_get_profile_list_param; json_get_profile_list_param[kTIMFriendShipGetProfileListParamForceUpdate] = false; json_get_profile_list_param[kTIMFriendShipGetProfileListParamIdentifierArray].append("user1"); json_get_profile_list_param[kTIMFriendShipGetProfileListParamIdentifierArray].append("user2"); json_get_profile_list_param[kTIMFriendShipGetProfileListParamIdentifierArray].append("user4"); TIMProfileGetUserProfileList(json_get_profile_list_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "GetProfileList cb code:%u desc:%s", code, desc); CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params); }, nullptr); } void TestFriendshipModifySelfProfile() { Json::Value modify_item; modify_item[kTIMUserProfileItemNickName] = "change my nick name"; // 修改昵称 modify_item[kTIMUserProfileItemGender] = kTIMGenderType_Female; // 修改性别 modify_item[kTIMUserProfileItemAddPermission] = kTIMProfileAddPermission_NeedConfirm; // 修改添加好友权限 Json::Value json_user_profile_item_custom; json_user_profile_item_custom[kTIMUserProfileCustemStringInfoKey] = "Str"; json_user_profile_item_custom[kTIMUserProfileCustemStringInfoValue] = "my define data"; modify_item[kTIMUserProfileItemCustomStringArray].append(json_user_profile_item_custom); int ret = TIMProfileModifySelfUserProfile(modify_item.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "GetProfileList cb code:%u desc:%s", code, desc); CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params); }, nullptr); } void TestFriendshipGetFriendProfileList() { int ret = TIMFriendshipGetFriendProfileList([](int32_t code, const char* desc, const char* json_params, const void* user_data) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "GetProfileList cb code:%u desc:%s", code, desc); CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params); }, nullptr); } void TestFriendshipAddFriend() { Json::Value json_add_friend_param; json_add_friend_param[kTIMFriendshipAddFriendParamIdentifier] = "user4"; json_add_friend_param[kTIMFriendshipAddFriendParamFriendType] = FriendTypeBoth; json_add_friend_param[kTIMFriendshipAddFriendParamAddSource] = "Windows"; json_add_friend_param[kTIMFriendshipAddFriendParamAddWording] = "I am Iron Man"; int ret = TIMFriendshipAddFriend(json_add_friend_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, " cb code:%u desc:%s", code, desc); CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params); }, nullptr); } void TestTIMFriendshipDeleteFriend() { Json::Value json_delete_friend_param; json_delete_friend_param[kTIMFriendshipDeleteFriendParamIdentifierArray].append("user4"); json_delete_friend_param[kTIMFriendshipDeleteFriendParamFriendType] = FriendTypeBoth; int ret = TIMFriendshipDeleteFriend(json_delete_friend_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc); CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params); }, nullptr); } void TestTIMFriendshipGetPendencyList() { Json::Value json_get_pendency_list_param; json_get_pendency_list_param[kTIMFriendshipGetPendencyListParamType] = FriendPendencyTypeBoth; json_get_pendency_list_param[kTIMFriendshipGetPendencyListParamStartSeq] = 0; int ret = TIMFriendshipGetPendencyList(json_get_pendency_list_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc); CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params); }, nullptr); } void TestTIMFriendshipReportPendencyReaded() { uint64_t time_stamp = 1563026447; int ret = TIMFriendshipReportPendencyReaded(time_stamp, [](int32_t code, const char* desc, const char* json_params, const void* user_data) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc); CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params); }, nullptr); } void TestTIMFriendshipDeletePendency() { Json::Value json_delete_pendency_param; json_delete_pendency_param[kTIMFriendshipDeletePendencyParamType] = FriendPendencyTypeSendOut; json_delete_pendency_param[kTIMFriendshipDeletePendencyParamIdentifierArray].append("user4"); int ret = TIMFriendshipDeletePendency(json_delete_pendency_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc); CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params); }, nullptr); } void TestTIMFriendshipHandleFriendAddRequest() { Json::Value json_handle_friend_add_param; json_handle_friend_add_param[kTIMFriendResponeIdentifier] = "user1"; json_handle_friend_add_param[kTIMFriendResponeAction] = ResponseActionAgreeAndAdd; json_handle_friend_add_param[kTIMFriendResponeRemark] = "I am Captain China"; json_handle_friend_add_param[kTIMFriendResponeGroupName] = "schoolmate"; int ret = TIMFriendshipHandleFriendAddRequest(json_handle_friend_add_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc); CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params); }, nullptr); } void TestTIMFriendshipModifyFriendProfile() { Json::Value json_modify_friend_profile_item; json_modify_friend_profile_item[kTIMFriendProfileItemRemark] = "xxxx yyyy"; // 修改备注 json_modify_friend_profile_item[kTIMFriendProfileItemGroupNameArray].append("group1"); // 修改好友所在分组 json_modify_friend_profile_item[kTIMFriendProfileItemGroupNameArray].append("group2"); Json::Value json_modify_friend_profilie_custom; json_modify_friend_profilie_custom[kTIMFriendProfileCustemStringInfoKey] = "Str"; json_modify_friend_profilie_custom[kTIMFriendProfileCustemStringInfoValue] = "this is changed value"; json_modify_friend_profile_item[kTIMFriendProfileItemCustomStringArray].append(json_modify_friend_profilie_custom); Json::Value json_modify_friend_info_param; json_modify_friend_info_param[kTIMFriendshipModifyFriendProfileParamIdentifier] = "user4"; json_modify_friend_info_param[kTIMFriendshipModifyFriendProfileParamItem] = json_modify_friend_profile_item; int ret = TIMFriendshipModifyFriendProfile(json_modify_friend_info_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc); CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params); }, nullptr); } void TestTIMFriendshipCheckFriendType() { Json::Value json_check_friend_list_param; json_check_friend_list_param[kTIMFriendshipCheckFriendTypeParamCheckType] = FriendTypeBoth; json_check_friend_list_param[kTIMFriendshipCheckFriendTypeParamIdentifierArray].append("user4"); int ret = TIMFriendshipCheckFriendType(json_check_friend_list_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc); CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params); }, nullptr); } void TestTIMFriendshipCreateFriendGroup() { Json::Value json_create_friend_group_param; json_create_friend_group_param[kTIMFriendshipCreateFriendGroupParamNameArray].append("Group123"); json_create_friend_group_param[kTIMFriendshipCreateFriendGroupParamNameArray].append("Group321"); json_create_friend_group_param[kTIMFriendshipCreateFriendGroupParamIdentifierArray].append("user4"); json_create_friend_group_param[kTIMFriendshipCreateFriendGroupParamIdentifierArray].append("user10"); int ret = TIMFriendshipCreateFriendGroup(json_create_friend_group_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc); CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params); }, nullptr); } void TestTIMFriendshipGetFriendGroupList() { Json::Value json_get_friend_group_list_param; json_get_friend_group_list_param.append("Group123"); //json_get_friend_group_list_param.append("Group1"); //json_get_friend_group_list_param.append("Group2"); int ret = TIMFriendshipGetFriendGroupList(json_get_friend_group_list_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc); CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params); }, nullptr); } void TestTIMFriendshipModifyFriendGroup() { Json::Value json_modify_friend_group_param; json_modify_friend_group_param[kTIMFriendshipModifyFriendGroupParamName] = "Group123"; json_modify_friend_group_param[kTIMFriendshipModifyFriendGroupParamNewName] = "GroupNewName"; json_modify_friend_group_param[kTIMFriendshipModifyFriendGroupParamDeleteIdentifierArray].append("user4"); json_modify_friend_group_param[kTIMFriendshipModifyFriendGroupParamAddIdentifierArray].append("user9"); json_modify_friend_group_param[kTIMFriendshipModifyFriendGroupParamAddIdentifierArray].append("user5"); int ret = TIMFriendshipModifyFriendGroup(json_modify_friend_group_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc); CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params); }, nullptr); } void TestTIMFriendshipDeleteFriendGroup() { Json::Value json_delete_friend_group_param; json_delete_friend_group_param.append("GroupNewName"); int ret = TIMFriendshipDeleteFriendGroup(json_delete_friend_group_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc); CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params); }, nullptr); } void TestTIMFriendshipAddToBlackList() { Json::Value json_add_to_blacklist_param; json_add_to_blacklist_param.append("user5"); json_add_to_blacklist_param.append("user10"); int ret = TIMFriendshipAddToBlackList(json_add_to_blacklist_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc); CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params); }, nullptr); } void TestTIMFriendshipGetBlackList() { int ret = TIMFriendshipGetBlackList([](int32_t code, const char* desc, const char* json_params, const void* user_data) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc); CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params); }, nullptr); } void TestTIMFriendshipDeleteFromBlackList() { Json::Value json_delete_from_blacklist_param; json_delete_from_blacklist_param.append("user5"); json_delete_from_blacklist_param.append("user10"); int ret = TIMFriendshipDeleteFromBlackList(json_delete_from_blacklist_param.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_params, const void* user_data) { CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "cb code:%u desc:%s", code, desc); CIMWnd::GetInst().Logf("TestApi", kTIMLog_Info, "json_params:%s", json_params); }, nullptr); } // 此函数用于测试各个API功能 void TestApi() { const void* user_data = nullptr; Json::Value modify_item; //TestFriendshipGetProfileList(); //TestFriendshipModifySelfProfile(); //TestTIMFriendshipDeleteFriend(); //TestFriendshipAddFriend(); //TestFriendshipGetFriendProfileList(); TestTIMFriendshipModifyFriendProfile(); //TestTIMFriendshipGetPendencyList(); //TestTIMFriendshipReportPendencyReaded(); //TestTIMFriendshipDeletePendency(); //TestTIMFriendshipHandleFriendAddRequest(); //TestTIMFriendshipCheckFriendType(); //TestTIMFriendshipCreateFriendGroup(); //TestTIMFriendshipGetFriendGroupList(); //TestTIMFriendshipModifyFriendGroup(); //TestTIMFriendshipDeleteFriendGroup(); //TestTIMFriendshipAddToBlackList(); //TestTIMFriendshipGetBlackList(); //TestTIMFriendshipDeleteFromBlackList(); //TIMSetRecvNewMsgCallback(RecvNewMsgCallback, user_data); //Test_MsgImport(); //Json::Value identifiers(Json::arrayValue); //... // Json::Value customs(Json::arrayValue); //... // Json::Value option; //option[kTIMGroupMemberGetInfoOptionInfoFlag] = kTIMGroupMemberInfoFlag_None; //option[kTIMGroupMemberGetInfoOptionRoleFlag] = kTIMGroupMemberRoleFlag_All; //option[kTIMGroupMemberGetInfoOptionCustomArray] = customs; //Json::Value getmeminfo_opt; //getmeminfo_opt[kTIMGroupGetMemberInfoListParamGroupId] = groupid; //getmeminfo_opt[kTIMGroupGetMemberInfoListParamIdentifierArray] = identifiers; //getmeminfo_opt[kTIMGroupGetMemberInfoListParamOption] = option; //getmeminfo_opt[kTIMGroupGetMemberInfoListParamNextSeq] = 0; //int ret = TIMGroupGetMemberInfoList(getmeminfo_opt.toStyledString().c_str(), [](int32_t code, const char* desc, const char* json_param, const void* user_data) { //}, this); //Test_GetMsgList(); }
[ "97548471@qq.com" ]
97548471@qq.com
bec4ebc306a2a449dbf9af54f70f26cce26cffa4
6a67533bd1661402512a94dba97a0d5392464770
/src/resolver/resolver-bu.cc
9deef00d14d90d434de4528533f71884ba9637a5
[ "BSD-3-Clause" ]
permissive
cforall/resolv-proto
2d6ac3abeee68887398647232a9eec8b843978a6
4eb7c0b9f4e75b940205e808e14fa57f13541246
refs/heads/master
2021-06-22T12:28:04.413238
2021-01-05T03:23:06
2021-01-05T03:23:06
173,825,134
2
0
null
null
null
null
UTF-8
C++
false
false
13,750
cc
// Copyright (c) 2015 University of Waterloo // // The contents of this file are covered under the licence agreement in // the file "LICENCE" distributed with this repository. #include <algorithm> #include <string> #include <utility> #include <vector> #include "resolver.h" #if defined RP_DIR_BU #include "arg_pack.h" #endif #include "cost.h" #include "env.h" #include "env_substitutor.h" #include "expand_conversions.h" #include "func_table.h" #include "interpretation.h" #include "resolve_assertions.h" #include "unify.h" #include "ast/expr.h" #include "ast/forall.h" #include "ast/forall_substitutor.h" #include "ast/mutator.h" #include "ast/typed_expr_visitor.h" #include "ast/typed_expr_mutator.h" #include "data/cast.h" #include "data/collections.h" #include "data/debug.h" #include "data/list.h" #include "data/mem.h" #include "data/option.h" #include "lists/eager_merge.h" //using Funcs = decltype( std::declval<FuncTable>().findAll( std::declval<std::string>() ) ); using Funcs = std::vector<FuncTable::inner_iterator>; /// Return an interpretation for all zero-arg functions in funcs InterpretationList matchFuncs( Resolver& resolver, const Funcs& funcs, const Env& outEnv, ResolverMode resolve_mode ) { InterpretationList results; // attempt to match functions to arguments for ( const auto& it : funcs ) { const auto& index = it->second; // find functions with no parameters auto with0Params = index.find( 0 ); if ( with0Params == index.end() ) continue; for ( const Decl* decl : with0Params() ) { const FuncDecl* func = as_checked<FuncDecl>(decl); // VarDecl indexed with -1 params // skip functions returning no values, unless at top level if ( ! resolve_mode.allow_void && func->returns()->size() == 0 ) continue; Env env = outEnv; const TypedExpr* call = new CallExpr{ func, resolver.id_src }; // check type assertions if necessary if ( RP_ASSN_CHECK( ! resolveAssertions( resolver, call, env ) ) ) continue; // no interpretation with zero arg cost results.push_back( new Interpretation{ call, move(env), func->poly_cost() } ); } } return results; } /// Return an interpretation for all single-argument interpretations in funcs InterpretationList matchFuncs( Resolver& resolver, const Funcs& funcs, InterpretationList&& args, const Env& outEnv, ResolverMode resolve_mode ) { InterpretationList results; for ( const Interpretation* arg : args ) { DBG( " arg: " << *arg ); // attempt to match functions to arguments for ( const auto& it : funcs ) { const auto& index = it->second; // find functions with the correct number of parameters auto n = arg->type()->size(); auto withNParams = index.find( n ); if ( withNParams == index.end() ) continue; for ( const Decl* decl : withNParams() ) { // VarDecl indexed with -1 params const FuncDecl* func = as_checked<FuncDecl>(decl); // skip functions returning no values, unless at top level if ( ! resolve_mode.allow_void && func->returns()->size() == 0 ) continue; // Environment for call bindings Cost cost = func->poly_cost() + arg->cost; // cost for this call Env env = arg->env ? arg->env : outEnv; unique_ptr<Forall> forall = Forall::from( func->forall(), resolver.id_src ); List<Type> params = forall ? ForallSubstitutor{ forall.get() }( func->params() ) : func->params(); // skip functions that don't match the parameter types if ( n == 1 ) { // concrete type arg if ( ! unify( params[0], arg->type(), cost, env ) ) continue; } else { // tuple type arg const List<Type>& argTypes = as<TupleType>( arg->type() )->types(); for ( unsigned i = 0; i < n; ++i ) { if ( ! unify( params[i], argTypes[i], cost, env ) ) goto nextFunc; } } { // extra scope so no goto errors for the labelled break simulation const TypedExpr* call = new CallExpr{ func, List<TypedExpr>{ arg->expr }, move(forall) }; // check type assertions if necessary if ( RP_ASSN_CHECK( ! resolveAssertions( resolver, call, env ) ) ) continue; // create new interpretation for resolved call results.push_back( new Interpretation{ call, env, cost, copy(arg->cost) } ); } nextFunc:; } } } return results; } //#define RP_DIR_BU #if defined RP_DIR_BU /// Unifies prefix of argument type with parameter type (required to be size 1) bool unifyFirst( const Type* paramType, const Type* argType, Cost& cost, Env& env ) { auto aid = typeof(argType); if ( aid == typeof<VoidType>() ) { return false; // paramType size == 1 } else if ( aid == typeof<TupleType>() ) { return unify(paramType, as<TupleType>(argType)->types()[0], cost, env ); } else { return unify(paramType, argType, cost, env); } } using ComboList = std::vector<InterpretationList>; InterpretationList matchFuncs( Resolver& resolver, const Funcs& funcs, ComboList&& args, const Env& outEnv, ResolverMode resolve_mode ) { InterpretationList results{}; for ( const auto& it : funcs ) { for ( const Decl* decl : it->second ) { const FuncDecl* func = as_safe<FuncDecl>(decl); if ( ! func ) continue; // skip VarDecl // skip void-returning functions unless at top level if ( ! resolve_mode.allow_void && func->returns()->size() == 0 ) continue; // skip functions without enough parameters if ( func->params().size() < args.size() ) continue; // generate forall and parameter types for forall unique_ptr<Forall> rForall = Forall::from( func->forall(), resolver.id_src ); const Type* rType; List<Type> rParams; if ( rForall ) { ForallSubstitutor m{ rForall.get() }; rType = m( func->returns() ); rParams = m( func->params() ); } else { rType = func->returns(); rParams = func->params(); } Cost rCost = func->poly_cost(); // iteratively build matches, one parameter at a time std::vector<ArgPack> combos{ ArgPack{ outEnv } }; std::vector<ArgPack> nextCombos{}; for ( const Type* param : rParams ) { assume(param->size() == 1, "parameter list should be flattened"); // find interpretations with matching type for ( ArgPack& combo : combos ) { // test matches for leftover combo args if ( combo.on_last > 0 ) { const TupleType* cType = as_checked<TupleType>(combo.crnt->type()); unsigned cInd = cType->size() - combo.on_last; const Type* crntType = cType->types()[ cInd ]; Cost cCost = combo.cost; Env cEnv = combo.env; if ( unify( param, crntType, cCost, cEnv ) ) { // build new combo which consumes more arguments nextCombos.emplace_back( combo, move(cCost), cEnv, combo.on_last-1 ); } // replace combo with truncated expression combo.truncate(); } // skip combos with no arguments left if ( combo.next == args.size() ) continue; // build new combos from matching interpretations for ( const Interpretation* i : args[combo.next] ) { Cost iCost = combo.cost + i->cost; Env iEnv = combo.env; // fail if cannot merge interpretation into combo if ( i->env && ! iEnv.merge( i->env ) ) continue; // fail if interpretation type does not match parameter if ( ! unifyFirst( param, i->type(), iCost, iEnv ) ) continue; // Build new ArgPack for this interpretation, noting leftovers nextCombos.emplace_back( combo, i, move(iCost), iEnv, i->type()->size()-1 ); } } // reset for next parameter combos.swap( nextCombos ); nextCombos.clear(); // exit early if no combinations if ( combos.empty() ) break; } // Validate matching combos, add to final result list for ( ArgPack& combo : combos ) { // skip combos with leftover arguments if ( combo.next != args.size() ) continue; // truncate any incomplete compbos combo.truncate(); // make interpretation for this combo const TypedExpr* call = new CallExpr{ func, move(combo.args), copy(rForall), rType }; Env cEnv = combo.env; // check type assertions if necessary if ( RP_ASSN_CHECK( ! resolveAssertions( resolver, call, cEnv ) ) ) continue; results.push_back( new Interpretation{ call, move(cEnv), rCost + combo.cost, move(combo.argCost) } ); } } } return results; } #elif defined RP_DIR_CO /// Create a list of argument expressions from a list of interpretations List<TypedExpr> argsFrom( const InterpretationList& is ) { List<TypedExpr> args; for ( const Interpretation* i : is ) { args.push_back( i->expr ); } return args; } /// List of argument combinations using ComboList = std::vector< std::pair<Cost, InterpretationList> >; /// Return an interpretation for all matches between functions in funcs and /// argument packs in combos InterpretationList matchFuncs( Resolver& resolver, const Funcs& funcs, ComboList&& combos, const Env& outEnv, ResolverMode resolve_mode ) { InterpretationList results; for ( const auto& combo : combos ) { DBG( " combo: " << print_all_deref( combo.second ) ); // attempt to match functions to arguments for ( const auto& it : funcs ) { const auto& index = it->second; // find function with appropriate number of parameters auto n = 0; for ( const Interpretation* arg : combo.second ) { n += arg->type()->size(); } auto withNParams = index.find( n ); if ( withNParams == index.end() ) continue; for ( const Decl* decl : withNParams() ) { // VarDecl indexed with -1 params const FuncDecl* func = as_checked<FuncDecl>(decl); // skip functions returning no values unless at top level if ( ! resolve_mode.allow_void && func->returns()->size() == 0 ) continue; // Environment for call bindings Cost cost = func->poly_cost() + combo.first; Env env = outEnv; unique_ptr<Forall> forall = Forall::from( func->forall(), resolver.id_src ); List<Type> params = forall ? ForallSubstitutor{ forall.get() }( func->params() ) : func->params(); // skip functions that don't match the parameter types if ( ! unifyList( params, combo.second, cost, env ) ) continue; const TypedExpr* call = new CallExpr{ func, argsFrom( combo.second ), move(forall) }; // check type assertions if at top level if ( RP_ASSN_CHECK( ! resolveAssertions( resolver, call, env ) ) ) continue; // create new interpretation for resolved call results.push_back( new Interpretation{ call, env, move(cost), move(combo.first) } ); } } } return results; } #endif /// Combination validator that fails on ambiguous interpretations in combinations struct interpretation_unambiguous { bool operator() ( const std::vector< InterpretationList >& queues, const std::vector< unsigned >& inds ) { for( unsigned i = 0; i < queues.size(); ++i ) { if ( queues[ i ][ inds[i] ]->is_ambiguous() ) return false; } return true; } }; InterpretationList Resolver::resolve( const Expr* expr, const Env& env, ResolverMode resolve_mode ) { InterpretationList results; auto eid = typeof(expr); if ( eid == typeof<ValExpr>() ) { // do nothing for expressions which are already typed results.push_back( new Interpretation{ as<ValExpr>(expr), copy(env) } ); } else if ( eid == typeof<NameExpr>() ) { const NameExpr* nameExpr = as<NameExpr>( expr ); // find all candidates with this name Funcs withName = funcs.findAll( nameExpr->name() ); for ( const auto& it : withName ) { for ( const Decl* decl : it->second ) { results.push_back( new Interpretation{ new VarExpr{ decl }, copy(env), Cost::zero() } ); } } } else if ( eid == typeof<FuncExpr>() ) { const FuncExpr* funcExpr = as<FuncExpr>( expr ); // find candidates with this function name, skipping if none Funcs withName = funcs.findAll( funcExpr->name() ); // get interpretations for subexpressions (if any) switch( funcExpr->args().size() ) { case 0: { results = matchFuncs( *this, withName, env, resolve_mode ); } break; case 1: { results = matchFuncs( *this, withName, resolve( funcExpr->args().front(), env ), env, resolve_mode ); } break; default: { std::vector<InterpretationList> sub_results; sub_results.reserve( funcExpr->args().size() ); for ( auto& sub : funcExpr->args() ) { // break early if no subexpression results InterpretationList sresults = resolve( sub, env ); if ( sresults.empty() ) return results; sub_results.push_back( move(sresults) ); } #if defined RP_DIR_BU results = matchFuncs( *this, withName, move(sub_results), env, resolve_mode ); #elif defined RP_DIR_CO interpretation_unambiguous valid; auto merged = unsorted_eager_merge< const Interpretation*, Cost, interpretation_cost>( sub_results, valid ); results = matchFuncs( *this, withName, move(merged), env, resolve_mode ); #endif } break; } } else unreachable("Unsupported expression type"); if ( resolve_mode.expand_conversions ) { expandConversions( results, conversions ); } return results; } InterpretationList Resolver::resolveWithType( const Expr* expr, const Type* targetType, const Env& env ) { #if defined RP_ASN_IMM auto resolve_mode = ResolverMode{}.without_conversions().with_void_as( targetType ).without_assertions(); #else auto resolve_mode = ResolverMode{}.without_conversions().with_void_as( targetType ); #endif return convertTo( targetType, resolve( expr, env, resolve_mode ), conversions ); }
[ "a3moss@uwaterloo.ca" ]
a3moss@uwaterloo.ca
c3c1229f72a9077abb3e285c4d049b3a2260ee98
0ee479c186a0b7b025d8847cb67235bd1b980ec9
/Pi_semaforo_rtos/Pi_semaforo_rtos.ino
afaaba1aaf5b94dfb2a62887cbea82fbe6407bf1
[]
no_license
gervasiogesse/Projeto-Integrador
2c1a09d2079feca353b9f52901ea4ab7a1abbe8e
186b6f4c98817e5511022e43f3e7d4de297d7c09
refs/heads/master
2020-09-14T06:38:29.520197
2019-12-18T01:39:03
2019-12-18T01:39:03
223,052,499
0
0
null
null
null
null
UTF-8
C++
false
false
7,140
ino
/* * Autores: Gervasio Gesse Junior * Iris menezes Barbosa * Titulo: Projeto Integrador 6 bimestre Univesp Polo Jandira * Data: 23 de Novembro de 2019 * Resumo: Semáforo com intervalo de tempo variável com * sinalização sonora para ficlitar a travessia deficientes * visuais e pessoas com mobilidade reduzida. */ #include <Arduino_FreeRTOS.h> #include <semphr.h> #include "string.h" #include <SoftwareSerial.h> //Define a saida para os leds const int vermelho = 4; const int amarelo = 5; const int verde = 6; const int p_vermelho = 7; const int p_verde = 8; const int botao = 2; const int buzzer = 3; //Define os pinos para a serial SoftwareSerial mySerial(10, 11); // RX, TX // Define a estrutura do semaforo SemaphoreHandle_t xSerialSemaphore; // Define buffer char bufferPC[64] = {'\0'}; char bufferBT[64] = {'\0'}; // Define o tempo em segundos para os estados do semaforo int t_vermelho = 10, t_amarelo = 10, t_verde = 10; // Define as tasks void TaskBlink( void *pvParameters ); void TaskSemaforoPrincipal( void *pvParameters ); void TaskComSerial( void *pvParameters ); void TaskBluetoothSerial( void *pvParameters ); void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); mySerial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native USB, on LEONARDO, MICRO, YUN, and other 32u4 based boards. } if ( xSerialSemaphore == NULL ) // Verifica se o semaforo existe e se não existir cria { xSerialSemaphore = xSemaphoreCreateMutex(); // Cria um semaforo mutex if ( ( xSerialSemaphore ) != NULL ) xSemaphoreGive( ( xSerialSemaphore ) ); // Libera o semaforo } if ( xSerialSemaphore != NULL ) { //Cria as tasks de comunicacao xTaskCreate(TaskComSerial, "ComSerial", 128, NULL, 2, NULL ); xTaskCreate(TaskBluetoothSerial, "BluetoothSerial", 128, NULL, 2, NULL ); } else { Serial.println("**** Erro ao criar semaforo!"); } // Now set up two tasks to run independently. xTaskCreate( TaskBlink , (const portCHAR *)"Blink" // A name just for humans , 128 // This stack size can be checked & adjusted by reading the Stack Highwater , NULL , 2 // Priority, with 3 (configMAX_PRIORITIES - 1) being the highest, and 0 being the lowest. , NULL ); xTaskCreate( TaskSemaforoPrincipal , (const portCHAR *) "SemaforoPrincipal" , 128 // Stack size , NULL , 2 // Priority , NULL ); } void loop() { //Em branco. Tudo é feito pelas tasks do SO } /*--------------------------------------------------*/ /*---------------------- Tasks ---------------------*/ /*--------------------------------------------------*/ void TaskBlink(void *pvParameters) // Task blink para teste. { (void) pvParameters; // inicializa digital LED_BUILTIN interno no pino 13 como output. pinMode(LED_BUILTIN, OUTPUT); pinMode(botao, INPUT_PULLUP); for (;;) // A Task shall never return or exit. { if(digitalRead(botao) == 0){ t_vermelho = 40; digitalWrite(LED_BUILTIN, HIGH); } else{ digitalWrite(LED_BUILTIN, HIGH); // liga o led interno vTaskDelay( 200 / portTICK_PERIOD_MS ); // aguarda um segundo digitalWrite(LED_BUILTIN, LOW); // desliga o led interno vTaskDelay( 1800 / portTICK_PERIOD_MS ); // aguarda um segundo } } } void TaskComSerial(void *pvParameters) { (void) pvParameters; char caractere; int i=0; for (;;) { //Trocar portMAX_DELAY por ( TickType_t ) 5 para ticks e deposi desistir if ( xSemaphoreTake( xSerialSemaphore, ( TickType_t ) 5 ) == pdTRUE ) { // Enquanto receber algo pela serial while(Serial.available() > 0) { // Lê byte da serial PC caractere = Serial.read(); // Serial.print("Recebi: "); // Serial.println(caractere); // Concatena valores bufferPC[i] = caractere; i++; bufferPC[i]= '\0'; // Aguarda buffer serial ler próximo caractere vTaskDelay(1); } i=0; if(bufferBT[0] != '\0'){ Serial.println(bufferBT); if(strncmp(bufferBT, "+DISC:SUCCESS", 13) == 0){ Serial.println("DesConectado"); } if(strncmp(bufferBT, "OK", 2) == 0){ Serial.println("Conectado"); t_vermelho = 40; } } bufferBT[0] = '\0'; xSemaphoreGive( xSerialSemaphore ); } vTaskDelay(pdMS_TO_TICKS(1000)); } } void TaskBluetoothSerial(void *pvParameters) { (void) pvParameters; char caractere; int i=0; for (;;) { //Trocar portMAX_DELAY por ( TickType_t ) 5 para ticks e deposi desistir if ( xSemaphoreTake( xSerialSemaphore, ( TickType_t ) 5 ) == pdTRUE ) { // Enquanto receber algo pela serial while(mySerial.available() > 0) { // Lê byte da serial caractere = mySerial.read(); Serial.print("Recebi BT: "); Serial.println(caractere); // Concatena valores bufferBT[i] = caractere; i++; bufferBT[i]= '\0'; // Aguarda buffer serial ler próximo caractere vTaskDelay(1); } i=0; if(bufferPC[0] != '\0'){ mySerial.println(bufferPC); Serial.println(bufferPC); } bufferPC[0] = '\0'; xSemaphoreGive( xSerialSemaphore ); } vTaskDelay(pdMS_TO_TICKS(1000)); } } void TaskSemaforoPrincipal(void *pvParameters) // Task blink para teste. { (void) pvParameters; // inicializa os pinos do leds que representam os estados. pinMode(verde, OUTPUT); pinMode(amarelo, OUTPUT); pinMode(vermelho, OUTPUT); pinMode(p_vermelho, OUTPUT); pinMode(p_verde, OUTPUT); pinMode(buzzer, OUTPUT); int qtd=0; for (;;) // A Task shall never return or exit. { digitalWrite(vermelho, LOW); digitalWrite(verde, HIGH); // liga o led verde para carro digitalWrite(p_vermelho, HIGH); //liga o led vermelho para pedestres digitalWrite(p_verde, LOW); vTaskDelay( t_verde * 1000 / portTICK_PERIOD_MS ); // Tempo do estado aberto carro digitalWrite(verde, LOW); digitalWrite(amarelo, HIGH); vTaskDelay( t_amarelo * 1000 / portTICK_PERIOD_MS ); // Tempo do estado amarelo carro digitalWrite(amarelo, LOW); digitalWrite(p_vermelho, LOW); digitalWrite(vermelho, HIGH); digitalWrite(p_verde, HIGH); qtd = (t_vermelho - 5)/2; while(qtd > 0){ digitalWrite(buzzer, HIGH); vTaskDelay( 1 * 500 / portTICK_PERIOD_MS ); digitalWrite(buzzer, LOW); vTaskDelay( 2 * 1500 / portTICK_PERIOD_MS ); qtd = qtd - 1; } digitalWrite(p_verde, LOW); for(int i=0; i < 5; i++){ digitalWrite(buzzer, HIGH); digitalWrite(p_vermelho, HIGH); vTaskDelay( 1 * 1000 / portTICK_PERIOD_MS ); digitalWrite(buzzer, LOW); digitalWrite(p_vermelho, LOW); vTaskDelay( 1 * 1000 / portTICK_PERIOD_MS ); } // vTaskDelay( t_vermelho * 1000 / portTICK_PERIOD_MS ); // Tempo do estado vermelho carro // Desliga flag t_vermelho = 10; } }
[ "gervasio.81@gmail.com" ]
gervasio.81@gmail.com
e3f483a5ce60eee11b217794213e1088096612a5
30dd9ff200f97b525b069577471d23387b23970b
/src/sensing/driver/velodyne/velodyne_laserscan/include/velodyne_laserscan/VelodyneLaserScan.h
32280b2b1dc1b1da790257676d0a1267877a587e
[ "BSD-3-Clause" ]
permissive
ColleyLi/AutowareArchitectureProposal
cd544ef913e3c49852d385883c3e3ee5b518b1b8
80ac2a8823d342e5a1e34703dbde27e8e9b5cd98
refs/heads/master
2022-04-18T01:41:53.649137
2020-04-21T12:18:58
2020-04-21T12:18:58
257,659,506
2
0
Apache-2.0
2020-04-21T17:03:50
2020-04-21T17:03:49
null
UTF-8
C++
false
false
2,573
h
// Copyright (C) 2018, 2019 Kevin Hallenbeck, Joshua Whitley // All rights reserved. // // Software License Agreement (BSD License 2.0) // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of {copyright_holder} nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifndef VELODYNELASERSCAN_H #define VELODYNELASERSCAN_H #include <ros/ros.h> #include <sensor_msgs/LaserScan.h> #include <sensor_msgs/PointCloud2.h> #include <boost/thread/lock_guard.hpp> #include <boost/thread/mutex.hpp> #include <dynamic_reconfigure/server.h> #include <velodyne_laserscan/VelodyneLaserScanConfig.h> namespace velodyne_laserscan { class VelodyneLaserScan { public: VelodyneLaserScan(ros::NodeHandle & nh, ros::NodeHandle & nh_priv); private: boost::mutex connect_mutex_; void connectCb(); void recvCallback(const sensor_msgs::PointCloud2ConstPtr & msg); ros::NodeHandle nh_; ros::Subscriber sub_; ros::Publisher pub_; VelodyneLaserScanConfig cfg_; dynamic_reconfigure::Server<VelodyneLaserScanConfig> srv_; void reconfig(VelodyneLaserScanConfig & config, uint32_t level); unsigned int ring_count_; }; } // namespace velodyne_laserscan #endif // VELODYNELASERSCAN_H
[ "yukky.saito@gmail.com" ]
yukky.saito@gmail.com
81b0dae78ca5454b0c051ff1c2b295c40d047885
b22f93e45064cf15aa25000af2990f112af48421
/src/qt/test/uritests.cpp
2b8b8046b025f5b78b7b93ad9e47c180655b2777
[ "MIT" ]
permissive
regtable/netcoin-2
5e9056fd3fc27654e6632df1cdf5f7343e1db8b9
026f272d174e53df9276ad7029945969edbd6afe
refs/heads/master
2020-03-08T01:06:52.075379
2017-12-29T10:03:13
2017-12-29T10:03:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,842
cpp
#include "uritests.h" #include "../guiutil.h" #include "../walletmodel.h" #include <QUrl> void URITests::uriTests() { SendCoinsRecipient rv; QUrl uri; uri.setUrl(QString("netcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?req-dontexist=")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("netcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?dontexist=")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 0); uri.setUrl(QString("netcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?label=Wikipedia Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString("Wikipedia Example Address")); QVERIFY(rv.amount == 0); uri.setUrl(QString("netcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=0.001")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 100000); uri.setUrl(QString("netcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1.001")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 100100000); uri.setUrl(QString("netcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=100&label=Wikipedia Example")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.amount == 10000000000LL); QVERIFY(rv.label == QString("Wikipedia Example")); uri.setUrl(QString("netcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?message=Wikipedia Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString()); QVERIFY(GUIUtil::parseBitcoinURI("netcoin://LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?message=Wikipedia Example Address", &rv)); QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9")); QVERIFY(rv.label == QString()); // We currently don't implement the message parameter (ok, yea, we break spec...) uri.setUrl(QString("netcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?req-message=Wikipedia Example Address")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("netcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1,000&label=Wikipedia Example")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("netcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1,000.0&label=Wikipedia Example")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); }
[ "kosextertioner@yahoo.com" ]
kosextertioner@yahoo.com
c197ac5b165f9b326c97c46212509d191f83b1aa
a164f47a067c044161360e7f3d29e6ce42a5c557
/inc/MusicLoader.hpp
38870cfad46489a24dd107ababf57a639b49d6fc
[ "Apache-2.0" ]
permissive
Xwilarg/RhythmParadise
d437c33e1417d12b616e163516a375e37b466ae0
a29558a47127e1ad29b3fc2d7fff0df6f844fbb4
refs/heads/master
2020-09-12T15:02:39.827345
2019-12-01T00:55:30
2019-12-01T00:55:30
222,460,585
0
0
null
null
null
null
UTF-8
C++
false
false
907
hpp
#pragma once #ifdef _WIN32 #pragma comment(lib, "irrKlang.lib") #endif # include <irrKlang.h> # include <string> namespace rhythm { class MusicLoader final { public: MusicLoader() = delete; ~MusicLoader() noexcept; static bool LoadMusic(const std::string& path) noexcept; static void PlayMusic() noexcept; static void StopMusic() noexcept; static void SetMusicVolume(float value) noexcept; // value is the position of the music between 0 and 1 static void SetMusicPosition(float value) noexcept; // return a value between 0 and 1 static float GetMusicPosition() noexcept; // return the number of ms elapsed static int GetMusicPositionIsMs() noexcept; private: static irrklang::ISoundEngine* _engine; static irrklang::ISound* _music; static std::string _path; }; }
[ "xwilarg@yahoo.fr" ]
xwilarg@yahoo.fr
cac5e4e7183bc95963e3b43c3e6dbdb21dd19aa8
8ac157eda8e6fe4dab420e47da32300e63c62489
/Toph/Jenia's Homework.cpp
d177875acb3c029ef7051cb93ecd60621d2290ad
[]
no_license
mdskrumi/Online-Judge-Problem-Solutions
f11cc0e577437012c7da7f2ab376fa01638f95f5
453e5d5c2464a63bd919fe95bb16f4cc4a1c2513
refs/heads/master
2020-09-28T05:29:00.453502
2020-08-13T16:00:12
2020-08-13T16:00:12
226,700,158
5
0
null
null
null
null
UTF-8
C++
false
false
1,878
cpp
#include<bits/stdc++.h> #include<ctype.h> #include<string.h> #include<stdio.h> #define TAKING freopen("input.txt" , "r" , stdin); #define MAKING freopen("output.txt","w" , stdout); #define ll long long #define sf scanf #define pf printf #define pb push_back #define mp make_pair #define nl "\n" #define BOLT ios_base::sync_with_stdio(0) #define all(x) x.begin(), x.end() #define rall(x) x.rbegin(), x.rend() #define fi first #define se second #define sz(v) (int)(v).size() #define REMOVE_ALL(str , c) str.erase(remove(str.begin(), str.end(), c), str.end()) #define PIE acos(-1) using namespace std; inline int ini(){int n;cin >> n;return n;} inline ll inl(){ll n;cin >> n;return n;} inline double ind(){double n;cin >> n;return n;} inline string ins(){string n;cin >> n;return n;} inline string insl(){string n;getline(cin,n);return n;} inline int string_to_int(string s){int n;stringstream ss;ss << s;ss >> n;return n;} // Same for double and long long inline string int_to_string(int n){string s;stringstream ss;ss << n;ss >> s;return s;} // Same for double and long long inline long long string_to_Long_Long(string s){ll res = 0;for(int i = 0 ; i < s.size() ; i++){res = res*10 + (s[i]-'0');}return res;} typedef vector <int> vi; typedef pair <int,long long> pii; int main(){ BOLT; int t = ini(); while(t--){ cout << setprecision(16) << fixed ; double a = ind(); cout << a - (sqrt(a)/2)*(sqrt(a)/2)*PIE << " " << 2*PIE*(sqrt(a)/2) << nl; } return 0; }
[ "mdskrumi@gmail.com" ]
mdskrumi@gmail.com
894e4508ed06492948dfefee20540c3cc4ec40e3
1afdb4bce52b84572782b9a33a52bbd4000d784e
/learn/STL/iterator_bidirectional.cpp
53be426731d7c7f2ea93c74b36a779a5ce53039e
[]
no_license
manishsurolia/C-Plus-Plus
4eaeffaa9d020efdef5fe1c423a2a482ba1a9699
7991d9a0d911b376fc984cd60d96c9b869301d1d
refs/heads/main
2023-04-14T19:36:31.259053
2021-05-06T13:06:55
2021-05-06T13:06:55
363,832,487
0
0
null
null
null
null
UTF-8
C++
false
false
952
cpp
/* * The second kind of iterator is bidirectional. * * We can increment it, decrement it, but we can't add a value to the iterator. * * itr++ // allowed * itr-- //allowed * * itr = itr + 5; // Not allowed. * itr = itr - 5; // Not allowed. * if (itr1 < itr2) // Not allowed. * * Below are the containers, which provide bi-directional container. * List, set/multiset, map/multimap. * * Linked list, we know that the nodes of a list is scattered in memory. So, we * can;t do above operations. * set/multiset, map/multimap, are created with the use of binary tree. * so again, above mentioned operations are not allowed on iterators. */ #include <iostream> #include <set> int main(int argc, char **argv) { std :: set <int> myset = {10, 30, 20, 40}; for (std::set <int> :: iterator itr = myset.begin(); itr != myset.end(); itr++) { std::cout <<*itr << " "; } std::cout<<std::endl; return 0; }
[ "manishsurolia@gmail.com" ]
manishsurolia@gmail.com
5c809e4f70337c289cd127fcc38f16ff89e22cde
2005da53aca39bddd2514ba0d75a8b5e65415391
/Effects/13_pacman.h
9902f933ded1c2befbd5c6df914036fd4af0e7e6
[]
no_license
Dovgalyuk/LedTable_emulator
9612b7595dd636ddf0627e19177b6a30ba97045e
261ac1b4c22ab9f4b70d428329c6a3b8988b6ac8
refs/heads/master
2020-12-02T03:27:44.264454
2019-12-30T13:08:46
2019-12-30T13:08:46
230,872,319
0
0
null
2019-12-30T07:48:07
2019-12-30T07:48:07
null
UTF-8
C++
false
false
3,260
h
#pragma once #include "Effects/effect.h" #define PACMAN_W 10 #define PACMAN_H 10 static const uint32_t pacman1[PACMAN_W*PACMAN_H] PROGMEM = { 0x000000, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0x000000, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0x000000, 0xffff00, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0xffff00, 0xffff00, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0x000000, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0x000000, 0x000000, }; static const uint32_t pacman2[PACMAN_W*PACMAN_H] PROGMEM = { 0x000000, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0x000000, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0x000000, 0xffff00, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0xffff00, 0xffff00, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0x000000, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0x000000, 0x000000, 0x000000, 0xffff00, 0xffff00, 0xffff00, 0xffff00, 0x000000, 0x000000, 0x000000, }; class Pacman : public Effect { public: Pacman() {} void on_init() { phase = 0; } void on_update() { fader(255); CRGB c(255, 255, 255); for (int i = PACMAN_W - phase ; i < WIDTH ; i += 4) { setPixColor(i, PACMAN_H / 2 - 1, c); setPixColor(i + 1, PACMAN_H / 2 - 1, c); setPixColor(i, PACMAN_H / 2, c); setPixColor(i + 1, PACMAN_H / 2, c); } drawSprite(0, 0, PACMAN_W, PACMAN_H, phase / 2 ? pacman1 : pacman2); phase = (phase + 1) % 4; } private: static void drawSprite(int x, int y, int w, int h, const uint32_t *spr) { for (int i = 0 ; i < w ; ++i) { for (int j = 0 ; j < h ; ++j) { int v = pgm_read_dword(spr + i + j * w); if (v) setPixColor(x + i, y + j, CRGB(v)); } } } private: int phase; };
[ "pavel.dovgaluk@gmail.com" ]
pavel.dovgaluk@gmail.com