hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
f87a7cc0e3b31dc80900071d5c83dddc50a2cc3b
419
cpp
C++
src/style/Function.cpp
logaritmdev/dezel-core-ui
e243ba99b790ca300be2ef3152da1596e4e34164
[ "MIT" ]
null
null
null
src/style/Function.cpp
logaritmdev/dezel-core-ui
e243ba99b790ca300be2ef3152da1596e4e34164
[ "MIT" ]
null
null
null
src/style/Function.cpp
logaritmdev/dezel-core-ui
e243ba99b790ca300be2ef3152da1596e4e34164
[ "MIT" ]
1
2020-02-13T01:55:34.000Z
2020-02-13T01:55:34.000Z
#include "Function.h" #include "InvalidInvocationException.h" #include <string> namespace Dezel { namespace Style { using std::to_string; Function::Function(string name, Callback callback) : name(name), callback(callback) { } //------------------------------------------------------------------------------ // MARK: Public API //------------------------------------------------------------------------------ } }
19.045455
83
0.446301
logaritmdev
f87e89d1064fba1d2721358c40ba63553b595437
2,229
cpp
C++
src/core/logic.cpp
JackWolfard/cash
a646c0b94d075fa424a93904b7499a0dee90ac89
[ "BSD-3-Clause" ]
14
2018-08-08T19:02:21.000Z
2022-01-07T14:42:43.000Z
src/core/logic.cpp
JackWolfard/cash
a646c0b94d075fa424a93904b7499a0dee90ac89
[ "BSD-3-Clause" ]
null
null
null
src/core/logic.cpp
JackWolfard/cash
a646c0b94d075fa424a93904b7499a0dee90ac89
[ "BSD-3-Clause" ]
3
2020-04-20T20:58:34.000Z
2021-11-23T14:50:14.000Z
#include "logic.h" #include "proxyimpl.h" #include "context.h" using namespace ch::internal; logic_buffer::logic_buffer(uint32_t size, const std::string& name, const source_location& sloc) : lnode(ctx_curr()->create_node<proxyimpl>(size, name, sloc)) {} logic_buffer::logic_buffer(uint32_t size, const logic_buffer& src, uint32_t src_offset, const std::string& name, const source_location& sloc) : lnode(ctx_curr()->create_node<refimpl>( src.impl(), src_offset, size, ((!src.name().empty() && !name.empty()) ? (src.name() + '.' + name) : ""), sloc)) {} const logic_buffer& logic_buffer::source() const { assert(impl_); return reinterpret_cast<const logic_buffer&>(impl_->src(0)); } void logic_buffer::write(uint32_t dst_offset, const lnode& src, uint32_t src_offset, uint32_t length) { assert(impl_); this->ensure_proxy(); reinterpret_cast<proxyimpl*>(impl_)->write(dst_offset, src.impl(), src_offset, length, impl_->sloc()); } lnodeimpl* logic_buffer::clone(const std::string& name, const source_location& sloc) const { assert(impl_); this->ensure_proxy(); auto node = reinterpret_cast<proxyimpl*>(impl_)->source(0, impl_->size(), name, sloc); if (node != impl_->src(0).impl()) return node; return ctx_curr()->create_node<proxyimpl>(node, name, sloc); } lnodeimpl* logic_buffer::sliceref(size_t size, size_t start, const std::string& name, const source_location& sloc) const { const_cast<logic_buffer*>(this)->ensure_proxy(); return ctx_curr()->create_node<refimpl>(impl_, start, size, name, sloc); } void logic_buffer::ensure_proxy() const { auto impl = impl_; if (type_proxy == impl->type()) return; auto proxy = ctx_curr()->create_node<proxyimpl>(impl->size(), "", impl->sloc()); impl->replace_uses(proxy); proxy->write(0, impl, 0, impl->size(), impl->sloc()); }
33.268657
104
0.577389
JackWolfard
f87e8b380cf1a015a1f191be94654d611ac51251
38,559
cpp
C++
planning/scenario_planning/lane_driving/motion_planning/obstacle_avoidance_planner/src/node.cpp
kmiya/AutowareArchitectureProposal.iv
386b52c9cc90f4535ad833014f2f9500f0e64ccf
[ "Apache-2.0" ]
null
null
null
planning/scenario_planning/lane_driving/motion_planning/obstacle_avoidance_planner/src/node.cpp
kmiya/AutowareArchitectureProposal.iv
386b52c9cc90f4535ad833014f2f9500f0e64ccf
[ "Apache-2.0" ]
null
null
null
planning/scenario_planning/lane_driving/motion_planning/obstacle_avoidance_planner/src/node.cpp
kmiya/AutowareArchitectureProposal.iv
386b52c9cc90f4535ad833014f2f9500f0e64ccf
[ "Apache-2.0" ]
1
2021-07-20T09:38:30.000Z
2021-07-20T09:38:30.000Z
// Copyright 2020 Tier IV, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "obstacle_avoidance_planner/node.hpp" #include <algorithm> #include <chrono> #include <limits> #include <memory> #include <string> #include <vector> #include "autoware_perception_msgs/msg/dynamic_object.hpp" #include "autoware_perception_msgs/msg/dynamic_object_array.hpp" #include "autoware_planning_msgs/msg/path.hpp" #include "autoware_planning_msgs/msg/trajectory.hpp" #include "boost/optional.hpp" #include "geometry_msgs/msg/transform_stamped.hpp" #include "geometry_msgs/msg/twist_stamped.hpp" #include "obstacle_avoidance_planner/debug.hpp" #include "obstacle_avoidance_planner/eb_path_optimizer.hpp" #include "obstacle_avoidance_planner/mpt_optimizer.hpp" #include "obstacle_avoidance_planner/process_cv.hpp" #include "obstacle_avoidance_planner/util.hpp" #include "opencv2/core.hpp" #include "rclcpp/rclcpp.hpp" #include "rclcpp/time.hpp" #include "std_msgs/msg/bool.hpp" #include "tf2/utils.h" #include "tf2_ros/transform_listener.h" #include "vehicle_info_util/vehicle_info.hpp" #include "visualization_msgs/msg/marker_array.hpp" ObstacleAvoidancePlanner::ObstacleAvoidancePlanner() : Node("obstacle_avoidance_planner"), min_num_points_for_getting_yaw_(2) { rclcpp::Clock::SharedPtr clock = std::make_shared<rclcpp::Clock>(RCL_ROS_TIME); tf_buffer_ptr_ = std::make_unique<tf2_ros::Buffer>(clock); tf_listener_ptr_ = std::make_unique<tf2_ros::TransformListener>(*tf_buffer_ptr_); rclcpp::QoS durable_qos{1}; durable_qos.transient_local(); trajectory_pub_ = create_publisher<autoware_planning_msgs::msg::Trajectory>("~/output/path", 1); avoiding_traj_pub_ = create_publisher<autoware_planning_msgs::msg::Trajectory>( "/planning/scenario_planning/lane_driving/obstacle_avoidance_candidate_trajectory", durable_qos); debug_smoothed_points_pub_ = create_publisher<autoware_planning_msgs::msg::Trajectory>( "~/debug/smoothed_points", durable_qos); is_avoidance_possible_pub_ = create_publisher<autoware_planning_msgs::msg::IsAvoidancePossible>( "/planning/scenario_planning/lane_driving/obstacle_avoidance_ready", durable_qos); debug_markers_pub_ = create_publisher<visualization_msgs::msg::MarkerArray>("~/debug/marker", durable_qos); debug_clearance_map_pub_ = create_publisher<nav_msgs::msg::OccupancyGrid>("~/debug/clearance_map", durable_qos); debug_object_clearance_map_pub_ = create_publisher<nav_msgs::msg::OccupancyGrid>("~/debug/object_clearance_map", durable_qos); debug_area_with_objects_pub_ = create_publisher<nav_msgs::msg::OccupancyGrid>("~/debug/area_with_objects", durable_qos); path_sub_ = create_subscription<autoware_planning_msgs::msg::Path>( "~/input/path", rclcpp::QoS{1}, std::bind(&ObstacleAvoidancePlanner::pathCallback, this, std::placeholders::_1)); twist_sub_ = create_subscription<geometry_msgs::msg::TwistStamped>( "/localization/twist", rclcpp::QoS{1}, std::bind(&ObstacleAvoidancePlanner::twistCallback, this, std::placeholders::_1)); objects_sub_ = create_subscription<autoware_perception_msgs::msg::DynamicObjectArray>( "~/input/objects", rclcpp::QoS{10}, std::bind(&ObstacleAvoidancePlanner::objectsCallback, this, std::placeholders::_1)); is_avoidance_sub_ = create_subscription<autoware_planning_msgs::msg::EnableAvoidance>( "/planning/scenario_planning/lane_driving/obstacle_avoidance_approval", rclcpp::QoS{10}, std::bind(&ObstacleAvoidancePlanner::enableAvoidanceCallback, this, std::placeholders::_1)); is_publishing_area_with_objects_ = declare_parameter("is_publishing_area_with_objects", false); is_publishing_clearance_map_ = declare_parameter("is_publishing_clearance_map", false); is_showing_debug_info_ = declare_parameter("is_showing_debug_info", true); is_using_vehicle_config_ = declare_parameter("is_using_vehicle_config", false); is_stopping_if_outside_drivable_area_ = declare_parameter("is_stopping_if_outside_drivable_area", true); enable_avoidance_ = declare_parameter("enable_avoidance", true); qp_param_ = std::make_unique<QPParam>(); traj_param_ = std::make_unique<TrajectoryParam>(); constrain_param_ = std::make_unique<ConstrainParam>(); vehicle_param_ = std::make_unique<VehicleParam>(); mpt_param_ = std::make_unique<MPTParam>(); qp_param_->max_iteration = declare_parameter("qp_max_iteration", 10000); qp_param_->eps_abs = declare_parameter("qp_eps_abs", 1.0e-8); qp_param_->eps_rel = declare_parameter("qp_eps_rel", 1.0e-11); qp_param_->eps_abs_for_extending = declare_parameter("qp_eps_abs_for_extending", 1.0e-6); qp_param_->eps_rel_for_extending = declare_parameter("qp_eps_rel_for_extending", 1.0e-8); qp_param_->eps_abs_for_visualizing = declare_parameter("qp_eps_abs_for_visualizing", 1.0e-6); qp_param_->eps_rel_for_visualizing = declare_parameter("qp_eps_rel_for_visualizing", 1.0e-8); traj_param_->num_sampling_points = declare_parameter("num_sampling_points", 100); traj_param_->num_joint_buffer_points = declare_parameter("num_joint_buffer_points", 2); traj_param_->num_joint_buffer_points_for_extending = declare_parameter("num_joint_buffer_points_for_extending", 4); traj_param_->num_offset_for_begin_idx = declare_parameter("num_offset_for_begin_idx", 2); traj_param_->num_fix_points_for_extending = declare_parameter("num_fix_points_for_extending", 2); traj_param_->forward_fixing_mpt_distance = declare_parameter("forward_fixing_mpt_distance", 10); traj_param_->delta_arc_length_for_optimization = declare_parameter("delta_arc_length_for_optimization", 1.0); traj_param_->delta_arc_length_for_mpt_points = declare_parameter("delta_arc_length_for_mpt_points", 1.0); traj_param_->delta_arc_length_for_trajectory = declare_parameter("delta_arc_length_for_trajectory", 0.1); traj_param_->delta_dist_threshold_for_closest_point = declare_parameter("delta_dist_threshold_for_closest_point", 3.0); traj_param_->delta_yaw_threshold_for_closest_point = declare_parameter("delta_yaw_threshold_for_closest_point", 1.0); traj_param_->delta_yaw_threshold_for_straight = declare_parameter("delta_yaw_threshold_for_straight", 0.02); traj_param_->trajectory_length = declare_parameter("trajectory_length", 200); traj_param_->forward_fixing_distance = declare_parameter("forward_fixing_distance", 10.0); traj_param_->backward_fixing_distance = declare_parameter("backward_fixing_distance", 5.0); traj_param_->max_avoiding_ego_velocity_ms = declare_parameter("max_avoiding_ego_velocity_ms", 6.0); traj_param_->max_avoiding_objects_velocity_ms = declare_parameter("max_avoiding_objects_velocity_ms", 0.1); traj_param_->center_line_width = declare_parameter("center_line_width", 1.7); traj_param_->acceleration_for_non_deceleration_range = declare_parameter("acceleration_for_non_deceleration_range", 1.0); traj_param_->max_dist_for_extending_end_point = declare_parameter("max_dist_for_extending_end_point", 5.0); traj_param_->is_avoiding_unknown = declare_parameter("avoiding_object_type.unknown", true); traj_param_->is_avoiding_car = declare_parameter("avoiding_object_type.car", true); traj_param_->is_avoiding_truck = declare_parameter("avoiding_object_type.truck", true); traj_param_->is_avoiding_bus = declare_parameter("avoiding_object_type.bus", true); traj_param_->is_avoiding_bicycle = declare_parameter("avoiding_object_type.bicycle", true); traj_param_->is_avoiding_motorbike = declare_parameter("avoiding_object_type.motorbike", true); traj_param_->is_avoiding_pedestrian = declare_parameter("avoiding_object_type.pedestrian", true); traj_param_->is_avoiding_animal = declare_parameter("avoiding_object_type.animal", true); constrain_param_->is_getting_constraints_close2path_points = declare_parameter("is_getting_constraints_close2path_points", false); constrain_param_->clearance_for_straight_line = declare_parameter("clearance_for_straight_line", 0.05); constrain_param_->clearance_for_joint = declare_parameter("clearance_for_joint", 0.1); constrain_param_->range_for_extend_joint = declare_parameter("range_for_extend_joint", 1.6); constrain_param_->clearance_for_only_smoothing = declare_parameter("clearance_for_only_smoothing", 0.1); constrain_param_->clearance_from_object_for_straight = declare_parameter("clearance_from_object_for_straight", 10.0); constrain_param_->clearance_from_road = declare_parameter("clearance_from_road", 0.1); constrain_param_->clearance_from_object = declare_parameter("clearance_from_object", 0.6); constrain_param_->extra_desired_clearance_from_road = declare_parameter("extra_desired_clearance_from_road", 0.2); constrain_param_->min_object_clearance_for_joint = declare_parameter("min_object_clearance_for_joint", 3.2); constrain_param_->max_x_constrain_search_range = declare_parameter("max_x_constrain_search_range", 0.4); constrain_param_->coef_x_constrain_search_resolution = declare_parameter("coef_x_constrain_search_resolution", 1.0); constrain_param_->coef_y_constrain_search_resolution = declare_parameter("coef_y_constrain_search_resolution", 0.5); constrain_param_->keep_space_shape_x = declare_parameter("keep_space_shape_x", 3.0); constrain_param_->keep_space_shape_y = declare_parameter("keep_space_shape_y", 2.0); constrain_param_->max_lon_space_for_driveable_constraint = declare_parameter("max_lon_space_for_driveable_constraint", 0.5); constrain_param_->clearance_for_fixing = 0.0; min_delta_dist_for_replan_ = declare_parameter("min_delta_dist_for_replan", 5.0); min_delta_time_sec_for_replan_ = declare_parameter("min_delta_time_sec_for_replan", 1.0); distance_for_path_shape_change_detection_ = declare_parameter("distance_for_path_shape_change_detection", 2.0); // vehicle param vehicle_info_util::VehicleInfo vehicle_info = vehicle_info_util::VehicleInfo::create(*this); vehicle_param_->width = vehicle_info.vehicle_width_m_; vehicle_param_->length = vehicle_info.vehicle_length_m_; vehicle_param_->wheelbase = vehicle_info.wheel_base_m_; vehicle_param_->rear_overhang = vehicle_info.rear_overhang_m_; vehicle_param_->front_overhang = vehicle_info.front_overhang_m_; if (is_using_vehicle_config_) { double vehicle_width = vehicle_info.vehicle_width_m_; traj_param_->center_line_width = vehicle_width; constrain_param_->keep_space_shape_y = vehicle_width; } constrain_param_->min_object_clearance_for_deceleration = constrain_param_->clearance_from_object + constrain_param_->keep_space_shape_y * 0.5; double max_steer_deg = 0; max_steer_deg = declare_parameter("max_steer_deg", 30.0); vehicle_param_->max_steer_rad = max_steer_deg * M_PI / 180.0; vehicle_param_->steer_tau = declare_parameter("steer_tau", 0.1); // mpt param mpt_param_->is_hard_fixing_terminal_point = declare_parameter("is_hard_fixing_terminal_point", true); mpt_param_->num_curvature_sampling_points = declare_parameter("num_curvature_sampling_points", 5); mpt_param_->base_point_weight = declare_parameter("base_point_weight", 2000.0); mpt_param_->top_point_weight = declare_parameter("top_point_weight", 1000.0); mpt_param_->mid_point_weight = declare_parameter("mid_point_weight", 1000.0); mpt_param_->lat_error_weight = declare_parameter("lat_error_weight", 10.0); mpt_param_->yaw_error_weight = declare_parameter("yaw_error_weight", 0.0); mpt_param_->steer_input_weight = declare_parameter("steer_input_weight", 0.1); mpt_param_->steer_rate_weight = declare_parameter("steer_rate_weight", 100.0); mpt_param_->steer_acc_weight = declare_parameter("steer_acc_weight", 0.000001); mpt_param_->terminal_lat_error_weight = declare_parameter("terminal_lat_error_weight", 0.0); mpt_param_->terminal_yaw_error_weight = declare_parameter("terminal_yaw_error_weight", 100.0); mpt_param_->terminal_path_lat_error_weight = declare_parameter("terminal_path_lat_error_weight", 1000.0); mpt_param_->terminal_path_yaw_error_weight = declare_parameter("terminal_path_yaw_error_weight", 1000.0); mpt_param_->zero_ff_steer_angle = declare_parameter("zero_ff_steer_angle", 0.5); mpt_param_->clearance_from_road = vehicle_param_->width * 0.5 + constrain_param_->clearance_from_road + constrain_param_->extra_desired_clearance_from_road; mpt_param_->clearance_from_object = vehicle_param_->width * 0.5 + constrain_param_->clearance_from_object; mpt_param_->base_point_dist_from_base_link = 0; mpt_param_->top_point_dist_from_base_link = (vehicle_param_->length - vehicle_param_->rear_overhang); mpt_param_->mid_point_dist_from_base_link = (mpt_param_->base_point_dist_from_base_link + mpt_param_->top_point_dist_from_base_link) * 0.5; in_objects_ptr_ = std::make_unique<autoware_perception_msgs::msg::DynamicObjectArray>(); // set parameter callback set_param_res_ = this->add_on_set_parameters_callback( std::bind(&ObstacleAvoidancePlanner::paramCallback, this, std::placeholders::_1)); initialize(); } ObstacleAvoidancePlanner::~ObstacleAvoidancePlanner() {} rcl_interfaces::msg::SetParametersResult ObstacleAvoidancePlanner::paramCallback( const std::vector<rclcpp::Parameter> & parameters) { auto update_param = [&](const std::string & name, double & v) { auto it = std::find_if( parameters.cbegin(), parameters.cend(), [&name](const rclcpp::Parameter & parameter) {return parameter.get_name() == name;}); if (it != parameters.cend()) { v = it->as_double(); return true; } return false; }; // trajectory total/fixing length update_param("trajectory_length", traj_param_->trajectory_length); update_param("forward_fixing_distance", traj_param_->forward_fixing_distance); update_param("backward_fixing_distance", traj_param_->backward_fixing_distance); // clearance for unique points update_param("clearance_for_straight_line", constrain_param_->clearance_for_straight_line); update_param("clearance_for_joint", constrain_param_->clearance_for_joint); update_param("clearance_for_only_smoothing", constrain_param_->clearance_for_only_smoothing); update_param( "clearance_from_object_for_straight", constrain_param_->clearance_from_object_for_straight); // clearance(distance) when generating trajectory update_param("clearance_from_road", constrain_param_->clearance_from_road); update_param("clearance_from_object", constrain_param_->clearance_from_object); update_param("min_object_clearance_for_joint", constrain_param_->min_object_clearance_for_joint); update_param( "extra_desired_clearance_from_road", constrain_param_->extra_desired_clearance_from_road); // avoiding param update_param("max_avoiding_objects_velocity_ms", traj_param_->max_avoiding_objects_velocity_ms); update_param("max_avoiding_ego_velocity_ms", traj_param_->max_avoiding_ego_velocity_ms); update_param("center_line_width", traj_param_->center_line_width); update_param( "acceleration_for_non_deceleration_range", traj_param_->acceleration_for_non_deceleration_range); // mpt param update_param("base_point_weight", mpt_param_->base_point_weight); update_param("top_point_weight", mpt_param_->top_point_weight); update_param("mid_point_weight", mpt_param_->mid_point_weight); update_param("lat_error_weight", mpt_param_->lat_error_weight); update_param("yaw_error_weight", mpt_param_->yaw_error_weight); update_param("steer_input_weight", mpt_param_->steer_input_weight); update_param("steer_rate_weight", mpt_param_->steer_rate_weight); update_param("steer_acc_weight", mpt_param_->steer_acc_weight); rcl_interfaces::msg::SetParametersResult result; result.successful = true; result.reason = "success"; return result; } // ROS callback functions void ObstacleAvoidancePlanner::pathCallback(const autoware_planning_msgs::msg::Path::SharedPtr msg) { std::lock_guard<std::mutex> lock(mutex_); current_ego_pose_ptr_ = getCurrentEgoPose(); if ( msg->points.empty() || msg->drivable_area.data.empty() || !current_ego_pose_ptr_ || !current_twist_ptr_) { return; } autoware_planning_msgs::msg::Trajectory output_trajectory_msg = generateTrajectory(*msg); trajectory_pub_->publish(output_trajectory_msg); } void ObstacleAvoidancePlanner::twistCallback(const geometry_msgs::msg::TwistStamped::SharedPtr msg) { current_twist_ptr_ = std::make_unique<geometry_msgs::msg::TwistStamped>(*msg); } void ObstacleAvoidancePlanner::objectsCallback( const autoware_perception_msgs::msg::DynamicObjectArray::SharedPtr msg) { in_objects_ptr_ = std::make_unique<autoware_perception_msgs::msg::DynamicObjectArray>(*msg); } void ObstacleAvoidancePlanner::enableAvoidanceCallback( const autoware_planning_msgs::msg::EnableAvoidance::SharedPtr msg) { enable_avoidance_ = msg->enable_avoidance; } // End ROS callback functions autoware_planning_msgs::msg::Trajectory ObstacleAvoidancePlanner::generateTrajectory( const autoware_planning_msgs::msg::Path & path) { auto t_start = std::chrono::high_resolution_clock::now(); const auto traj_points = generateOptimizedTrajectory(*current_ego_pose_ptr_, path); const auto post_processed_traj = generatePostProcessedTrajectory(*current_ego_pose_ptr_, path.points, traj_points); autoware_planning_msgs::msg::Trajectory output; output.header = path.header; output.points = post_processed_traj; prev_path_points_ptr_ = std::make_unique<std::vector<autoware_planning_msgs::msg::PathPoint>>(path.points); auto t_end = std::chrono::high_resolution_clock::now(); float elapsed_ms = std::chrono::duration<float, std::milli>(t_end - t_start).count(); RCLCPP_INFO_EXPRESSION( get_logger(), is_showing_debug_info_, "Total time: = %f [ms]\n==========================", elapsed_ms); return output; } std::vector<autoware_planning_msgs::msg::TrajectoryPoint> ObstacleAvoidancePlanner::generateOptimizedTrajectory( const geometry_msgs::msg::Pose & ego_pose, const autoware_planning_msgs::msg::Path & path) { if (!needReplan( ego_pose, prev_ego_pose_ptr_, path.points, prev_replanned_time_ptr_, prev_path_points_ptr_, prev_trajectories_ptr_)) { return getPrevTrajectory(path.points); } prev_ego_pose_ptr_ = std::make_unique<geometry_msgs::msg::Pose>(ego_pose); prev_replanned_time_ptr_ = std::make_unique<rclcpp::Time>(this->now()); DebugData debug_data; const auto optional_trajs = eb_path_optimizer_ptr_->generateOptimizedTrajectory( enable_avoidance_, ego_pose, path, prev_trajectories_ptr_, in_objects_ptr_->objects, &debug_data); if (!optional_trajs) { RCLCPP_WARN_THROTTLE( get_logger(), *get_clock(), std::chrono::milliseconds(1000).count(), "[Avoidance] Optimization failed, passing previous trajectory"); const bool is_prev_traj = true; const auto prev_trajs_inside_area = calcTrajectoryInsideArea( getPrevTrajs(path.points), path.points, debug_data.clearance_map, path.drivable_area.info, &debug_data, is_prev_traj); prev_trajectories_ptr_ = std::make_unique<Trajectories>( makePrevTrajectories(*current_ego_pose_ptr_, path.points, prev_trajs_inside_area.get())); const auto prev_traj = util::concatTraj(prev_trajs_inside_area.get()); publishingDebugData(debug_data, path, prev_traj, *vehicle_param_); return prev_traj; } const auto trajs_inside_area = getTrajectoryInsideArea( optional_trajs.get(), path.points, debug_data.clearance_map, path.drivable_area.info, &debug_data); prev_trajectories_ptr_ = std::make_unique<Trajectories>( makePrevTrajectories(*current_ego_pose_ptr_, path.points, trajs_inside_area)); const auto optimized_trajectory = util::concatTraj(trajs_inside_area); publishingDebugData(debug_data, path, optimized_trajectory, *vehicle_param_); return optimized_trajectory; } void ObstacleAvoidancePlanner::initialize() { RCLCPP_WARN(get_logger(), "[ObstacleAvoidancePlanner] Resetting"); eb_path_optimizer_ptr_ = std::make_unique<EBPathOptimizer>( is_showing_debug_info_, *qp_param_, *traj_param_, *constrain_param_, *vehicle_param_, *mpt_param_); prev_path_points_ptr_ = nullptr; prev_trajectories_ptr_ = nullptr; } std::unique_ptr<geometry_msgs::msg::Pose> ObstacleAvoidancePlanner::getCurrentEgoPose() { geometry_msgs::msg::TransformStamped tf_current_pose; try { tf_current_pose = tf_buffer_ptr_->lookupTransform( "map", "base_link", rclcpp::Time(0), rclcpp::Duration::from_seconds(1.0)); } catch (tf2::TransformException ex) { RCLCPP_ERROR(get_logger(), "[ObstacleAvoidancePlanner] %s", ex.what()); return nullptr; } geometry_msgs::msg::Pose p; p.orientation = tf_current_pose.transform.rotation; p.position.x = tf_current_pose.transform.translation.x; p.position.y = tf_current_pose.transform.translation.y; p.position.z = tf_current_pose.transform.translation.z; std::unique_ptr<geometry_msgs::msg::Pose> p_ptr = std::make_unique<geometry_msgs::msg::Pose>(p); return p_ptr; } std::vector<autoware_planning_msgs::msg::TrajectoryPoint> ObstacleAvoidancePlanner::generatePostProcessedTrajectory( const geometry_msgs::msg::Pose & ego_pose, const std::vector<autoware_planning_msgs::msg::PathPoint> & path_points, const std::vector<autoware_planning_msgs::msg::TrajectoryPoint> & optimized_points) const { auto t_start = std::chrono::high_resolution_clock::now(); std::vector<autoware_planning_msgs::msg::TrajectoryPoint> trajectory_points; if (path_points.empty()) { autoware_planning_msgs::msg::TrajectoryPoint tmp_point; tmp_point.pose = ego_pose; tmp_point.twist.linear.x = 0; trajectory_points.push_back(tmp_point); return trajectory_points; } if (optimized_points.empty()) { trajectory_points = util::convertPathToTrajectory(path_points); return trajectory_points; } trajectory_points = convertPointsToTrajectory(path_points, optimized_points); auto t_end = std::chrono::high_resolution_clock::now(); float elapsed_ms = std::chrono::duration<float, std::milli>(t_end - t_start).count(); RCLCPP_INFO_EXPRESSION( get_logger(), is_showing_debug_info_, "Post processing time: = %f [ms]", elapsed_ms); return trajectory_points; } bool ObstacleAvoidancePlanner::needReplan( const geometry_msgs::msg::Pose & ego_pose, const std::unique_ptr<geometry_msgs::msg::Pose> & prev_ego_pose, const std::vector<autoware_planning_msgs::msg::PathPoint> & path_points, const std::unique_ptr<rclcpp::Time> & prev_replanned_time, const std::unique_ptr<std::vector<autoware_planning_msgs::msg::PathPoint>> & prev_path_points, std::unique_ptr<Trajectories> & prev_trajs) { if (!prev_ego_pose || !prev_replanned_time || !prev_path_points || !prev_trajs) { return true; } if (isPathShapeChanged(ego_pose, path_points, prev_path_points)) { RCLCPP_INFO(get_logger(), "[Avoidance] Path shape is changed, reset prev trajs"); prev_trajs = nullptr; return true; } if (!util::hasValidNearestPointFromEgo( *current_ego_pose_ptr_, *prev_trajectories_ptr_, *traj_param_)) { RCLCPP_INFO( get_logger(), "[Avoidance] Could not find valid nearest point from ego, reset prev trajs"); prev_trajs = nullptr; return true; } const double delta_dist = util::calculate2DDistance(ego_pose.position, prev_ego_pose->position); if (delta_dist > min_delta_dist_for_replan_) { return true; } rclcpp::Duration delta_time = this->now() - *prev_replanned_time; const double delta_time_sec = delta_time.seconds(); if (delta_time_sec > min_delta_time_sec_for_replan_) { return true; } return false; } bool ObstacleAvoidancePlanner::isPathShapeChanged( const geometry_msgs::msg::Pose & ego_pose, const std::vector<autoware_planning_msgs::msg::PathPoint> & path_points, const std::unique_ptr<std::vector<autoware_planning_msgs::msg::PathPoint>> & prev_path_points) { if (!prev_path_points) { return true; } const int default_nearest_prev_path_idx = 0; const int nearest_prev_path_idx = util::getNearestIdx( *prev_path_points, ego_pose, default_nearest_prev_path_idx, traj_param_->delta_yaw_threshold_for_closest_point); const int default_nearest_path_idx = 0; const int nearest_path_idx = util::getNearestIdx( path_points, ego_pose, default_nearest_path_idx, traj_param_->delta_yaw_threshold_for_closest_point); const auto prev_first = prev_path_points->begin() + nearest_prev_path_idx; const auto prev_last = prev_path_points->end(); std::vector<autoware_planning_msgs::msg::PathPoint> truncated_prev_points(prev_first, prev_last); const auto first = path_points.begin() + nearest_path_idx; const auto last = path_points.end(); std::vector<autoware_planning_msgs::msg::PathPoint> truncated_points(first, last); for (const auto & prev_point : truncated_prev_points) { double min_dist = std::numeric_limits<double>::max(); for (const auto & point : truncated_points) { const double dist = util::calculate2DDistance(point.pose.position, prev_point.pose.position); if (dist < min_dist) { min_dist = dist; } } if (min_dist > distance_for_path_shape_change_detection_) { return true; } } return false; } std::vector<autoware_planning_msgs::msg::TrajectoryPoint> ObstacleAvoidancePlanner::convertPointsToTrajectory( const std::vector<autoware_planning_msgs::msg::PathPoint> & path_points, const std::vector<autoware_planning_msgs::msg::TrajectoryPoint> & trajectory_points) const { std::vector<geometry_msgs::msg::Point> interpolated_points = util::getInterpolatedPoints(trajectory_points, traj_param_->delta_arc_length_for_trajectory); // add discarded point in the process of interpolation interpolated_points.push_back(trajectory_points.back().pose.position); if (interpolated_points.size() < min_num_points_for_getting_yaw_) { return util::convertPathToTrajectory(path_points); } std::vector<geometry_msgs::msg::Point> candidate_points = interpolated_points; geometry_msgs::msg::Pose last_pose; last_pose.position = candidate_points.back(); last_pose.orientation = util::getQuaternionFromPoints( candidate_points.back(), candidate_points[candidate_points.size() - 2]); const auto extended_point_opt = util::getLastExtendedPoint( path_points.back(), last_pose, traj_param_->delta_yaw_threshold_for_closest_point, traj_param_->max_dist_for_extending_end_point); if (extended_point_opt) { candidate_points.push_back(extended_point_opt.get()); } const int zero_velocity_idx = util::getZeroVelocityIdx( is_showing_debug_info_, candidate_points, path_points, prev_trajectories_ptr_, *traj_param_); auto traj_points = util::convertPointsToTrajectoryPointsWithYaw(candidate_points); traj_points = util::fillTrajectoryWithVelocity(traj_points, 1e4); if (prev_trajectories_ptr_) { const int max_skip_comparison_velocity_idx_for_optimized_points = calculateNonDecelerationRange(traj_points, *current_ego_pose_ptr_, current_twist_ptr_->twist); const auto optimized_trajectory = util::concatTraj(*prev_trajectories_ptr_); traj_points = util::alignVelocityWithPoints( traj_points, optimized_trajectory, zero_velocity_idx, max_skip_comparison_velocity_idx_for_optimized_points); } const int max_skip_comparison_idx_for_path_points = -1; traj_points = util::alignVelocityWithPoints( traj_points, path_points, zero_velocity_idx, max_skip_comparison_idx_for_path_points); return traj_points; } void ObstacleAvoidancePlanner::publishingDebugData( const DebugData & debug_data, const autoware_planning_msgs::msg::Path & path, const std::vector<autoware_planning_msgs::msg::TrajectoryPoint> & traj_points, const VehicleParam & vehicle_param) { autoware_planning_msgs::msg::Trajectory traj; traj.header = path.header; traj.points = debug_data.foa_data.avoiding_traj_points; avoiding_traj_pub_->publish(traj); autoware_planning_msgs::msg::Trajectory debug_smoothed_points; debug_smoothed_points.header = path.header; debug_smoothed_points.points = debug_data.smoothed_points; debug_smoothed_points_pub_->publish(debug_smoothed_points); autoware_planning_msgs::msg::IsAvoidancePossible is_avoidance_possible; is_avoidance_possible.is_avoidance_possible = debug_data.foa_data.is_avoidance_possible; is_avoidance_possible_pub_->publish(is_avoidance_possible); std::vector<autoware_planning_msgs::msg::TrajectoryPoint> traj_points_debug = traj_points; // Add z information for virtual wall if (!traj_points_debug.empty()) { const int idx = util::getNearestIdx( path.points, traj_points.back().pose, 0, traj_param_->delta_yaw_threshold_for_closest_point); traj_points_debug.back().pose.position.z = path.points.at(idx).pose.position.z + 1.0; } debug_markers_pub_->publish( getDebugVisualizationMarker(debug_data, traj_points_debug, vehicle_param)); if (is_publishing_area_with_objects_) { debug_area_with_objects_pub_->publish( getDebugCostmap(debug_data.area_with_objects_map, path.drivable_area)); } if (is_publishing_clearance_map_) { debug_clearance_map_pub_->publish( getDebugCostmap(debug_data.clearance_map, path.drivable_area)); debug_object_clearance_map_pub_->publish( getDebugCostmap(debug_data.only_object_clearance_map, path.drivable_area)); } } int ObstacleAvoidancePlanner::calculateNonDecelerationRange( const std::vector<autoware_planning_msgs::msg::TrajectoryPoint> & traj_points, const geometry_msgs::msg::Pose & ego_pose, const geometry_msgs::msg::Twist & ego_twist) const { const int default_idx = 0; const int nearest_idx = util::getNearestIdx( traj_points, ego_pose, default_idx, traj_param_->delta_yaw_threshold_for_closest_point); const double non_decelerating_arc_length = (ego_twist.linear.x - traj_param_->max_avoiding_ego_velocity_ms) / traj_param_->acceleration_for_non_deceleration_range; if (non_decelerating_arc_length < 0 || traj_points.size() < 2) { return 0; } double accum_arc_length = 0; for (int i = nearest_idx + 1; i < traj_points.size(); i++) { accum_arc_length += util::calculate2DDistance(traj_points[i].pose.position, traj_points[i - 1].pose.position); if (accum_arc_length > non_decelerating_arc_length) { return i; } } return 0; } Trajectories ObstacleAvoidancePlanner::getTrajectoryInsideArea( const Trajectories & trajs, const std::vector<autoware_planning_msgs::msg::PathPoint> & path_points, const cv::Mat & road_clearance_map, const nav_msgs::msg::MapMetaData & map_info, DebugData * debug_data) const { debug_data->current_vehicle_footprints = util::getVehicleFootprints(trajs.model_predictive_trajectory, *vehicle_param_); const auto current_trajs_inside_area = calcTrajectoryInsideArea(trajs, path_points, road_clearance_map, map_info, debug_data); if (!current_trajs_inside_area) { RCLCPP_WARN( get_logger(), "[Avoidance] Current trajectory is not inside drivable area, passing previous one. " "Might stop at the end of drivable trajectory."); auto prev_trajs = getPrevTrajs(path_points); const bool is_prev_traj = true; const auto prev_trajs_inside_area = calcTrajectoryInsideArea( prev_trajs, path_points, road_clearance_map, map_info, debug_data, is_prev_traj); return prev_trajs_inside_area.get(); } return current_trajs_inside_area.get(); } boost::optional<Trajectories> ObstacleAvoidancePlanner::calcTrajectoryInsideArea( const Trajectories & trajs, const std::vector<autoware_planning_msgs::msg::PathPoint> & path_points, const cv::Mat & road_clearance_map, const nav_msgs::msg::MapMetaData & map_info, DebugData * debug_data, const bool is_prev_traj) const { if (!is_stopping_if_outside_drivable_area_) { const auto stop_idx = getStopIdx(path_points, trajs, map_info, road_clearance_map, debug_data); if (stop_idx) { auto clock = rclcpp::Clock(RCL_ROS_TIME); RCLCPP_WARN_THROTTLE( get_logger(), clock, std::chrono::milliseconds(1000).count(), "[Avoidance] Expecting over drivable area"); } return getBaseTrajectory(path_points, trajs); } const auto optional_stop_idx = getStopIdx(path_points, trajs, map_info, road_clearance_map, debug_data); if (!is_prev_traj && optional_stop_idx) { return boost::none; } auto tmp_trajs = getBaseTrajectory(path_points, trajs); if (is_prev_traj) { tmp_trajs.extended_trajectory = std::vector<autoware_planning_msgs::msg::TrajectoryPoint>{}; debug_data->is_expected_to_over_drivable_area = true; } if (optional_stop_idx && !prev_trajectories_ptr_) { if (optional_stop_idx.get() < trajs.model_predictive_trajectory.size()) { tmp_trajs.model_predictive_trajectory = std::vector<autoware_planning_msgs::msg::TrajectoryPoint>{ trajs.model_predictive_trajectory.begin(), trajs.model_predictive_trajectory.begin() + optional_stop_idx.get()}; tmp_trajs.extended_trajectory = std::vector<autoware_planning_msgs::msg::TrajectoryPoint>{}; debug_data->is_expected_to_over_drivable_area = true; } } return tmp_trajs; } Trajectories ObstacleAvoidancePlanner::getPrevTrajs( const std::vector<autoware_planning_msgs::msg::PathPoint> & path_points) const { if (!prev_trajectories_ptr_) { const auto traj = util::convertPathToTrajectory(path_points); Trajectories trajs; trajs.smoothed_trajectory = traj; trajs.model_predictive_trajectory = traj; return trajs; } else { return *prev_trajectories_ptr_; } } std::vector<autoware_planning_msgs::msg::TrajectoryPoint> ObstacleAvoidancePlanner::getPrevTrajectory( const std::vector<autoware_planning_msgs::msg::PathPoint> & path_points) const { std::vector<autoware_planning_msgs::msg::TrajectoryPoint> traj; const auto & trajs = getPrevTrajs(path_points); traj.insert( traj.end(), trajs.model_predictive_trajectory.begin(), trajs.model_predictive_trajectory.end()); traj.insert(traj.end(), trajs.extended_trajectory.begin(), trajs.extended_trajectory.end()); return traj; } Trajectories ObstacleAvoidancePlanner::makePrevTrajectories( const geometry_msgs::msg::Pose & ego_pose, const std::vector<autoware_planning_msgs::msg::PathPoint> & path_points, const Trajectories & trajs) const { const auto post_processed_smoothed_traj = generatePostProcessedTrajectory(ego_pose, path_points, trajs.smoothed_trajectory); Trajectories trajectories; trajectories.smoothed_trajectory = post_processed_smoothed_traj; trajectories.mpt_ref_points = trajs.mpt_ref_points; trajectories.model_predictive_trajectory = trajs.model_predictive_trajectory; trajectories.extended_trajectory = trajs.extended_trajectory; return trajectories; } Trajectories ObstacleAvoidancePlanner::getBaseTrajectory( const std::vector<autoware_planning_msgs::msg::PathPoint> & path_points, const Trajectories & trajs) const { auto basee_trajs = trajs; if (!trajs.extended_trajectory.empty()) { const auto extended_point_opt = util::getLastExtendedTrajPoint( path_points.back(), trajs.extended_trajectory.back().pose, traj_param_->delta_yaw_threshold_for_closest_point, traj_param_->max_dist_for_extending_end_point); if (extended_point_opt) { basee_trajs.extended_trajectory.push_back(extended_point_opt.get()); } } else if (!trajs.model_predictive_trajectory.empty()) { const auto extended_point_opt = util::getLastExtendedTrajPoint( path_points.back(), trajs.model_predictive_trajectory.back().pose, traj_param_->delta_yaw_threshold_for_closest_point, traj_param_->max_dist_for_extending_end_point); if (extended_point_opt) { basee_trajs.extended_trajectory.push_back(extended_point_opt.get()); } } double prev_velocity = 1e4; for (auto & p : basee_trajs.model_predictive_trajectory) { if (p.twist.linear.x < 1e-6) { p.twist.linear.x = prev_velocity; } else { prev_velocity = p.twist.linear.x; } } for (auto & p : basee_trajs.extended_trajectory) { if (p.twist.linear.x < 1e-6) { p.twist.linear.x = prev_velocity; } else { prev_velocity = p.twist.linear.x; } } return basee_trajs; } boost::optional<int> ObstacleAvoidancePlanner::getStopIdx( const std::vector<autoware_planning_msgs::msg::PathPoint> & path_points, const Trajectories & trajs, const nav_msgs::msg::MapMetaData & map_info, const cv::Mat & road_clearance_map, DebugData * debug_data) const { const int nearest_idx = util::getNearestIdx( path_points, *current_ego_pose_ptr_, 0, traj_param_->delta_yaw_threshold_for_closest_point); const double accum_ds = util::getArcLength(path_points, nearest_idx); auto target_points = trajs.model_predictive_trajectory; if (accum_ds < traj_param_->num_sampling_points * traj_param_->delta_arc_length_for_mpt_points) { target_points.insert( target_points.end(), trajs.extended_trajectory.begin(), trajs.extended_trajectory.end()); const auto extended_mpt_point_opt = util::getLastExtendedTrajPoint( path_points.back(), trajs.model_predictive_trajectory.back().pose, traj_param_->delta_yaw_threshold_for_closest_point, traj_param_->max_dist_for_extending_end_point); if (extended_mpt_point_opt) { target_points.push_back(extended_mpt_point_opt.get()); } } const auto footprints = util::getVehicleFootprints(target_points, *vehicle_param_); const int debug_nearest_footprint_idx = util::getNearestIdx(target_points, current_ego_pose_ptr_->position); std::vector<util::Footprint> debug_truncated_footprints( footprints.begin() + debug_nearest_footprint_idx, footprints.end()); debug_data->vehicle_footprints = debug_truncated_footprints; const auto optional_idx = process_cv::getStopIdx(footprints, *current_ego_pose_ptr_, road_clearance_map, map_info); return optional_idx; }
46.400722
100
0.784331
kmiya
f880d67f623805842572bafe87231793003b5c06
3,447
hh
C++
elements/aqm/pi2.hh
nokia/ClickNF
2cae2976e0be99144520ba44ddf9622d482ba1c5
[ "MIT" ]
32
2017-11-02T12:33:21.000Z
2022-02-07T22:25:58.000Z
elements/aqm/pi2.hh
frankfanslc/ClickNF
996b2f6e16b23b38a55e1fbcc23046ef240b022c
[ "MIT" ]
2
2019-02-18T08:47:16.000Z
2019-05-24T14:41:23.000Z
elements/aqm/pi2.hh
frankfanslc/ClickNF
996b2f6e16b23b38a55e1fbcc23046ef240b022c
[ "MIT" ]
10
2018-06-13T11:54:53.000Z
2020-09-08T06:52:43.000Z
/* * pi2.{cc,hh} -- element implements pi square aqm dequeueing mechanism * Myriana Rifai * * Copyright (c) 2019 Nokia Bell Labs * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * */ #ifndef CLICK_PI2_HH #define CLICK_PI2_HH #include <click/element.hh> #include <click/ewma.hh> #include <click/timer.hh> CLICK_DECLS class Storage; class PI2 : public Element { public: // Queue sizes are shifted by this much. enum { QUEUE_SCALE = 10 }; typedef DirectEWMAX<StabilityEWMAXParameters<QUEUE_SCALE, uint64_t, int64_t> > ewma_type; PI2() CLICK_COLD; ~PI2() CLICK_COLD; const char *class_name() const { return "PI2"; } const char *port_count() const { return "2/1"; } const char *processing() const { return PULL; } int queue_size() const; const ewma_type &average_queue_size() const { return _size; } int drops() const { return _drops; } int configure(Vector<String> &, ErrorHandler *) CLICK_COLD; int check_params(unsigned, unsigned, ErrorHandler *) const ; int initialize(ErrorHandler *) CLICK_COLD; void cleanup(CleanupStage) CLICK_COLD; void take_state(Element *, ErrorHandler *); bool can_live_reconfigure() const { return true; } int live_reconfigure(Vector<String> &, ErrorHandler *); void add_handlers() CLICK_COLD; Packet *mark(Packet *); bool ecn(Packet *); void handle_drop(Packet *); Packet *pull(int); void run_timer(Timer *); protected: Timer _timer; Storage *_queue_l4s; Storage *_queue_classic; Vector<Storage *> _queues; ewma_type _size; int _random_value; int _last_jiffies; int _drops; double _p; // _a = 20, _b = 200 in Hz unsigned int _k, _w, _a, _b, _target_q, _old_q, _prev_q, _cur_q, _t_shift; // _k = 2, _w = 32, _target_q = 20 , _t_shift = 40 in ms Timestamp _T; Vector<Element *> _queue_elements; static String read_parameter(Element *, void *); static const int MAX_RAND=2147483647; }; CLICK_ENDDECLS #endif
36.670213
148
0.724978
nokia
f8822550f5901f53f9eb9876a9280c9d7212e951
1,046
hpp
C++
src/cpp/ee/ads/NullBannerAd.hpp
enrevol/ee-x
60a66ad3dc6e14802a7c5d8d585a8499be13f5b8
[ "MIT" ]
null
null
null
src/cpp/ee/ads/NullBannerAd.hpp
enrevol/ee-x
60a66ad3dc6e14802a7c5d8d585a8499be13f5b8
[ "MIT" ]
null
null
null
src/cpp/ee/ads/NullBannerAd.hpp
enrevol/ee-x
60a66ad3dc6e14802a7c5d8d585a8499be13f5b8
[ "MIT" ]
null
null
null
// // NullAdView.hpp // ee_x // // Created by Zinge on 10/27/17. // // #ifndef EE_X_NULL_BANNER_AD_HPP #define EE_X_NULL_BANNER_AD_HPP #ifdef __cplusplus #include "ee/ads/NullAd.hpp" #include "ee/ads/IBannerAd.hpp" namespace ee { namespace ads { class NullBannerAd : public IBannerAd, public NullAd { public: NullBannerAd(); virtual bool isVisible() const override; virtual void setVisible(bool visible) override; virtual std::pair<float, float> getAnchor() const override; virtual void setAnchor(float x, float y) override; virtual std::pair<float, float> getPosition() const override; virtual void setPosition(float x, float y) override; virtual std::pair<float, float> getSize() const override; virtual void setSize(float width, float height) override; private: bool visible_; int positionX_; int positionY_; float anchorX_; float anchorY_; int width_; int height_; }; } // namespace ads } // namespace ee #endif // __cplusplus #endif /* EE_X_NULL_BANNER_AD_HPP */
20.92
65
0.707457
enrevol
f884d749e21228f6525c5b7453a9cb3e4eedd7df
16,862
cpp
C++
src/xci/graphics/Primitives.cpp
rbrich/xcik
4eab7d1dfc8b0bc269137e28af076be943c15041
[ "Apache-2.0" ]
11
2019-08-21T12:48:45.000Z
2022-01-21T01:49:01.000Z
src/xci/graphics/Primitives.cpp
rbrich/xcik
4eab7d1dfc8b0bc269137e28af076be943c15041
[ "Apache-2.0" ]
3
2019-10-20T19:10:41.000Z
2021-02-11T10:32:40.000Z
src/xci/graphics/Primitives.cpp
rbrich/xcik
4eab7d1dfc8b0bc269137e28af076be943c15041
[ "Apache-2.0" ]
1
2020-10-09T20:08:17.000Z
2020-10-09T20:08:17.000Z
// Primitives.cpp created on 2018-08-03 as part of xcikit project // https://github.com/rbrich/xcikit // // Copyright 2018–2021 Radek Brich // Licensed under the Apache License, Version 2.0 (see LICENSE file) #include "Primitives.h" #include "Renderer.h" #include "Window.h" #include "View.h" #include "Texture.h" #include "Shader.h" #include "vulkan/VulkanError.h" #include <xci/compat/macros.h> #include <cassert> #include <cstring> namespace xci::graphics { PrimitivesBuffers::~PrimitivesBuffers() { m_device_memory.free(); for (auto buffer : m_uniform_buffers) vkDestroyBuffer(device(), buffer, nullptr); vkDestroyBuffer(device(), m_index_buffer, nullptr); vkDestroyBuffer(device(), m_vertex_buffer, nullptr); } void PrimitivesBuffers::create( const std::vector<float>& vertex_data, const std::vector<uint16_t>& index_data, VkDeviceSize uniform_base, const std::vector<std::byte>& uniform_data) { // vertex buffer VkBufferCreateInfo vertex_buffer_ci = { .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size = sizeof(vertex_data[0]) * vertex_data.size(), .usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, .sharingMode = VK_SHARING_MODE_EXCLUSIVE, }; VK_TRY("vkCreateBuffer(vertex)", vkCreateBuffer(device(), &vertex_buffer_ci, nullptr, &m_vertex_buffer)); VkMemoryRequirements vertex_mem_req; vkGetBufferMemoryRequirements(device(), m_vertex_buffer, &vertex_mem_req); auto vertex_offset = m_device_memory.reserve(vertex_mem_req); // index buffer VkBufferCreateInfo index_buffer_ci = { .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size = sizeof(index_data[0]) * index_data.size(), .usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT, .sharingMode = VK_SHARING_MODE_EXCLUSIVE, }; VK_TRY("vkCreateBuffer(index)", vkCreateBuffer(device(), &index_buffer_ci, nullptr, &m_index_buffer)); VkMemoryRequirements index_mem_req; vkGetBufferMemoryRequirements(device(), m_index_buffer, &index_mem_req); auto index_offset = m_device_memory.reserve(index_mem_req); // uniform buffers for (size_t i = 0; i < Window::cmd_buf_count; i++) { VkBufferCreateInfo uniform_buffer_ci = { .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size = uniform_base + uniform_data.size(), .usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, .sharingMode = VK_SHARING_MODE_EXCLUSIVE, }; VK_TRY("vkCreateBuffer(uniform)", vkCreateBuffer(device(), &uniform_buffer_ci, nullptr, &m_uniform_buffers[i])); VkMemoryRequirements mem_req; vkGetBufferMemoryRequirements(device(), m_uniform_buffers[i], &mem_req); m_uniform_offsets[i] = m_device_memory.reserve(mem_req); } // allocate memory and copy data m_device_memory.allocate(); m_device_memory.bind_buffer(m_vertex_buffer, vertex_offset); m_device_memory.copy_data(vertex_offset, vertex_buffer_ci.size, vertex_data.data()); m_device_memory.bind_buffer(m_index_buffer, index_offset); m_device_memory.copy_data(index_offset, index_buffer_ci.size, index_data.data()); for (size_t i = 0; i < Window::cmd_buf_count; i++) { m_device_memory.bind_buffer(m_uniform_buffers[i], m_uniform_offsets[i]); if (!uniform_data.empty()) { m_device_memory.copy_data( m_uniform_offsets[i] + uniform_base, uniform_data.size(), uniform_data.data()); } } } void PrimitivesBuffers::bind(VkCommandBuffer cmd_buf) { VkDeviceSize offset = 0; vkCmdBindVertexBuffers(cmd_buf, 0, 1, &m_vertex_buffer, &offset); vkCmdBindIndexBuffer(cmd_buf, m_index_buffer, 0, VK_INDEX_TYPE_UINT16); } void PrimitivesBuffers::copy_mvp(size_t cmd_buf_idx, const std::array<float, 16>& mvp) { m_device_memory.copy_data(m_uniform_offsets[cmd_buf_idx], c_mvp_size, mvp.data()); } VkDevice PrimitivesBuffers::device() const { return m_renderer.vk_device(); } // ----------------------------------------------------------------------------- PrimitivesDescriptorSets::~PrimitivesDescriptorSets() { if (m_descriptor_sets[0] != VK_NULL_HANDLE) m_descriptor_pool.free(Window::cmd_buf_count, m_descriptor_sets); } void PrimitivesDescriptorSets::create(const VkDescriptorSetLayout layout) { // create descriptor sets std::array<VkDescriptorSetLayout, Window::cmd_buf_count> layouts; // NOLINT for (auto& item : layouts) item = layout; m_descriptor_pool.allocate(Window::cmd_buf_count, layouts.data(), m_descriptor_sets); } void PrimitivesDescriptorSets::update( const PrimitivesBuffers& buffers, VkDeviceSize uniform_base, const std::vector<UniformBinding>& uniform_bindings, const TextureBinding& texture_binding) { for (size_t i = 0; i < Window::cmd_buf_count; i++) { std::vector<VkDescriptorBufferInfo> buffer_info; std::vector<VkWriteDescriptorSet> write_descriptor_set; buffer_info.reserve(uniform_bindings.size() + 1); write_descriptor_set.reserve(uniform_bindings.size() + 1); // mvp buffer_info.push_back({ .buffer = buffers.vk_uniform_buffer(i), .offset = 0, .range = c_mvp_size, }); write_descriptor_set.push_back(VkWriteDescriptorSet{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = m_descriptor_sets[i], .dstBinding = 0, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, .pBufferInfo = &buffer_info.back(), }); // uniforms for (const auto& uni : uniform_bindings) { buffer_info.push_back({ .buffer = buffers.vk_uniform_buffer(i), .offset = uniform_base + uni.offset, .range = uni.range, }); write_descriptor_set.push_back(VkWriteDescriptorSet{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = m_descriptor_sets[i], .dstBinding = uni.binding, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, .pBufferInfo = &buffer_info.back(), }); } // texture VkDescriptorImageInfo image_info; // keep alive for vkUpdateDescriptorSets() if (texture_binding.ptr) { auto* texture = texture_binding.ptr; image_info = { .sampler = texture->vk_sampler(), .imageView = texture->vk_image_view(), .imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, }; write_descriptor_set.push_back(VkWriteDescriptorSet{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = m_descriptor_sets[i], .dstBinding = texture_binding.binding, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &image_info, }); } vkUpdateDescriptorSets(m_renderer.vk_device(), (uint32_t) write_descriptor_set.size(), write_descriptor_set.data(), 0, nullptr); } } void PrimitivesDescriptorSets::bind( VkCommandBuffer cmd_buf, size_t cmd_buf_idx, const VkPipelineLayout pipeline_layout) { vkCmdBindDescriptorSets(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &m_descriptor_sets[cmd_buf_idx], 0, nullptr); } // ----------------------------------------------------------------------------- Primitives::Primitives(Renderer& renderer, VertexFormat format, PrimitiveType type) : m_format(format), m_renderer(renderer) { assert(type == PrimitiveType::TriFans); } Primitives::~Primitives() { destroy_pipeline(); } static uint32_t get_vertex_float_count(VertexFormat format) { switch (format) { case VertexFormat::V2t2: return 4; case VertexFormat::V2t22: return 6; case VertexFormat::V2c4t2: return 8; case VertexFormat::V2c4t22: return 10; } UNREACHABLE; } void Primitives::reserve(size_t vertices) { m_vertex_data.reserve(vertices * get_vertex_float_count(m_format)); // heuristic for quads (won't match for other primitives) // each 4 vertices (a quad) require 6 indices (two triangles) m_index_data.reserve(vertices / 4 * 6); } void Primitives::begin_primitive() { assert(m_open_vertices == -1); m_open_vertices = 0; destroy_pipeline(); } void Primitives::end_primitive() { assert(m_open_vertices >= 3); // fan triangles: 0 1 2, 0 2 3, 0 3 4, ... const auto base = m_closed_vertices; auto offset = 1; while (offset + 1 < m_open_vertices) { m_index_data.push_back(base); m_index_data.push_back(base + offset); m_index_data.push_back(base + ++offset); } m_closed_vertices += m_open_vertices; m_open_vertices = -1; } void Primitives::add_vertex(ViewportCoords xy, float u, float v) { assert(m_format == VertexFormat::V2t2); assert(m_open_vertices != -1); m_open_vertices++; m_vertex_data.push_back(xy.x.value); m_vertex_data.push_back(xy.y.value); m_vertex_data.push_back(u); m_vertex_data.push_back(v); } void Primitives::add_vertex(ViewportCoords xy, float u1, float v1, float u2, float v2) { assert(m_format == VertexFormat::V2t22); assert(m_open_vertices != -1); m_open_vertices++; m_vertex_data.push_back(xy.x.value); m_vertex_data.push_back(xy.y.value); m_vertex_data.push_back(u1); m_vertex_data.push_back(v1); m_vertex_data.push_back(u2); m_vertex_data.push_back(v2); } void Primitives::add_vertex(ViewportCoords xy, Color color, float u, float v) { assert(m_format == VertexFormat::V2c4t2); assert(m_open_vertices != -1); m_open_vertices++; m_vertex_data.push_back(xy.x.value); m_vertex_data.push_back(xy.y.value); m_vertex_data.push_back(color.red_f()); m_vertex_data.push_back(color.green_f()); m_vertex_data.push_back(color.blue_f()); m_vertex_data.push_back(color.alpha_f()); m_vertex_data.push_back(u); m_vertex_data.push_back(v); } void Primitives::add_vertex(ViewportCoords xy, Color color, float u1, float v1, float u2, float v2) { assert(m_format == VertexFormat::V2c4t22); assert(m_open_vertices != -1); m_open_vertices++; m_vertex_data.push_back(xy.x.value); m_vertex_data.push_back(xy.y.value); m_vertex_data.push_back(color.red_f()); m_vertex_data.push_back(color.green_f()); m_vertex_data.push_back(color.blue_f()); m_vertex_data.push_back(color.alpha_f()); m_vertex_data.push_back(u1); m_vertex_data.push_back(v1); m_vertex_data.push_back(u2); m_vertex_data.push_back(v2); } void Primitives::clear() { destroy_pipeline(); m_vertex_data.clear(); m_index_data.clear(); clear_uniforms(); m_closed_vertices = 0; m_open_vertices = -1; m_texture.ptr = nullptr; m_blend = BlendFunc::Off; } void Primitives::set_shader(Shader& shader) { m_shader = &shader; destroy_pipeline(); } void Primitives::set_texture(uint32_t binding, Texture& texture) { m_texture.binding = binding; m_texture.ptr = &texture; destroy_pipeline(); } void Primitives::clear_uniforms() { m_uniform_data.clear(); m_uniforms.clear(); destroy_pipeline(); } void Primitives::add_uniform_data(uint32_t binding, const void* data, size_t size) { assert(binding > 0); // zero is reserved for MVP matrix assert(std::find_if(m_uniforms.cbegin(), m_uniforms.cend(), [binding](const UniformBinding& u) { return u.binding == binding; }) == m_uniforms.cend()); // the binding was already added auto offset = align_uniform(m_uniform_data.size()); m_uniform_data.resize(offset + size); std::memcpy(&m_uniform_data[offset], data, size); m_uniforms.push_back({binding, offset, size}); destroy_pipeline(); } void Primitives::add_uniform(uint32_t binding, float f1, float f2) { struct { float f1, f2; } buf { f1, f2 }; add_uniform_data(binding, &buf, sizeof(buf)); } void Primitives::add_uniform(uint32_t binding, Color color) { FloatColor buf {color}; add_uniform_data(binding, &buf, sizeof(buf)); } void Primitives::add_uniform(uint32_t binding, Color color1, Color color2) { struct { FloatColor c1, c2; } buf { color1, color2 }; add_uniform_data(binding, &buf, sizeof(buf)); } void Primitives::set_blend(BlendFunc func) { m_blend = func; destroy_pipeline(); } void Primitives::update() { if (empty()) return; if (!m_pipeline) { update_pipeline(); } if (m_texture.ptr) m_texture.ptr->update(); } void Primitives::draw(View& view) { if (empty()) return; if (!m_pipeline) { assert(!"Primitives: call update before draw!"); return; } auto* window = dynamic_cast<Window*>(view.window()); auto cmd_buf = window->vk_command_buffer(); vkCmdBindPipeline(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipeline->vk()); // set viewport VkViewport viewport = { .x = 0.0f, .y = 0.0f, .width = (float) m_renderer.vk_image_extent().width, .height = (float) m_renderer.vk_image_extent().height, .minDepth = 0.0f, .maxDepth = 1.0f, }; vkCmdSetViewport(cmd_buf, 0, 1, &viewport); // set scissor region VkRect2D scissor = { .offset = {0, 0}, .extent = { INT32_MAX, INT32_MAX }, }; if (view.has_crop()) { auto cr = view.rect_to_framebuffer(view.get_crop()); scissor.offset.x = cr.x.as<int32_t>(); scissor.offset.y = cr.y.as<int32_t>(); scissor.extent.width = cr.w.as<int32_t>(); scissor.extent.height = cr.h.as<int32_t>(); } vkCmdSetScissor(cmd_buf, 0, 1, &scissor); m_buffers->bind(cmd_buf); window->add_command_buffer_resource(m_buffers); // projection matrix auto mvp = view.projection_matrix(); assert(mvp.size() * sizeof(mvp[0]) == c_mvp_size); auto i = window->command_buffer_index(); m_buffers->copy_mvp(i, mvp); // descriptor sets m_descriptor_sets->bind(cmd_buf, i, m_pipeline_layout->vk()); window->add_command_buffer_resource(m_descriptor_sets); vkCmdDrawIndexed(cmd_buf, static_cast<uint32_t>(m_index_data.size()), 1, 0, 0, 0); } void Primitives::draw(View& view, const ViewportCoords& pos) { view.push_offset(pos); draw(view); view.pop_offset(); } VkDevice Primitives::device() const { return m_renderer.vk_device(); } void Primitives::update_pipeline() { assert(m_shader != nullptr); PipelineLayoutCreateInfo pipeline_layout_ci; for (const auto& uniform : m_uniforms) pipeline_layout_ci.add_uniform_binding(uniform.binding); if (m_texture.ptr != nullptr) pipeline_layout_ci.add_texture_binding(m_texture.binding); m_pipeline_layout = &m_renderer.get_pipeline_layout(pipeline_layout_ci); PipelineCreateInfo pipeline_ci(*m_shader, m_pipeline_layout->vk(), m_renderer.vk_render_pass()); pipeline_ci.set_vertex_format(m_format); pipeline_ci.set_color_blend(m_blend); m_pipeline = &m_renderer.get_pipeline(pipeline_ci); auto uniform_base = align_uniform(c_mvp_size); m_buffers = std::make_shared<PrimitivesBuffers>(m_renderer); m_buffers->create(m_vertex_data, m_index_data, uniform_base, m_uniform_data); m_descriptor_pool = m_renderer.get_descriptor_pool(Window::cmd_buf_count, pipeline_layout_ci.descriptor_pool_sizes()); m_descriptor_sets = std::make_shared<PrimitivesDescriptorSets>(m_renderer, m_descriptor_pool.get()); m_descriptor_sets->create(m_pipeline_layout->vk_descriptor_set_layout()); m_descriptor_sets->update(*m_buffers, uniform_base, m_uniforms, m_texture); } void Primitives::destroy_pipeline() { if (m_pipeline == nullptr) return; m_buffers.reset(); m_descriptor_sets.reset(); m_pipeline = nullptr; } VkDeviceSize Primitives::align_uniform(VkDeviceSize offset) { const auto min_alignment = m_renderer.min_uniform_offset_alignment(); auto unaligned = offset % min_alignment; if (unaligned > 0) offset += min_alignment - unaligned; return offset; } } // namespace xci::graphics
30.327338
122
0.659115
rbrich
f888b9b913bea0295d270b2f4bb06291fd8d0310
252
cpp
C++
src/fatal.cpp
franko/elementary-plotlib
d11b56a13893781d84a8e93183f01b13140dd4e3
[ "MIT" ]
14
2020-04-03T02:14:08.000Z
2021-07-16T21:05:56.000Z
src/fatal.cpp
franko/elementary-plotlib
d11b56a13893781d84a8e93183f01b13140dd4e3
[ "MIT" ]
2
2020-04-22T15:40:42.000Z
2020-04-28T21:17:23.000Z
src/fatal.cpp
franko/libcanvas
d11b56a13893781d84a8e93183f01b13140dd4e3
[ "MIT" ]
1
2020-04-30T07:49:02.000Z
2020-04-30T07:49:02.000Z
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include "fatal.h" void fatal_exception(const char* msg, ...) { va_list ap; va_start(ap, msg); vfprintf(stderr, msg, ap); fputs("\n", stderr); va_end(ap); abort(); }
14
37
0.599206
franko
f88a00d3eec19507b915f09fa3f1c1554e0e594c
636
cpp
C++
source/ImageSymLoader.cpp
xzrunner/s2loader
6317bbec560db93f866bda78373ef58aed504ca3
[ "MIT" ]
null
null
null
source/ImageSymLoader.cpp
xzrunner/s2loader
6317bbec560db93f866bda78373ef58aed504ca3
[ "MIT" ]
null
null
null
source/ImageSymLoader.cpp
xzrunner/s2loader
6317bbec560db93f866bda78373ef58aed504ca3
[ "MIT" ]
null
null
null
#include "s2loader/ImageSymLoader.h" #include <gum/Image.h> #include <gum/ImageSymbol.h> #include <gum/ImagePool.h> #include <simp/NodeID.h> namespace s2loader { ImageSymLoader::ImageSymLoader(gum::ImageSymbol& sym) : m_sym(sym) { } void ImageSymLoader::Load(const bimp::FilePath& res_path, float scale, bool async) { int pkg_id = simp::NodeID::GetPkgID(m_sym.GetID()); auto img = gum::ImagePool::Instance()->Create(pkg_id, res_path, async); if (!img) { return; } m_sym.SetImage(img); auto w = img->GetWidth(); auto h = img->GetHeight(); m_sym.SetRegion(sm::ivec2(0, 0), sm::ivec2(w, h), sm::vec2(0, 0), 0, scale); } }
20.516129
82
0.687107
xzrunner
f88b48791b1989df091bd1f5243a99ff90fcd269
14,690
cpp
C++
test/unit/module/bessel/cyl_bessel_in.cpp
the-moisrex/eve
80b52663eefee11460abb0aedf4158a5067cf7dc
[ "MIT" ]
340
2020-09-16T21:12:48.000Z
2022-03-28T15:40:33.000Z
test/unit/module/bessel/cyl_bessel_in.cpp
the-moisrex/eve
80b52663eefee11460abb0aedf4158a5067cf7dc
[ "MIT" ]
383
2020-09-17T06:56:35.000Z
2022-03-13T15:58:53.000Z
test/unit/module/bessel/cyl_bessel_in.cpp
the-moisrex/eve
80b52663eefee11460abb0aedf4158a5067cf7dc
[ "MIT" ]
28
2021-02-27T23:11:23.000Z
2022-03-25T12:31:29.000Z
//================================================================================================== /** EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #include "test.hpp" #include <eve/function/cyl_bessel_in.hpp> #include <eve/function/diff/cyl_bessel_in.hpp> #include <eve/constant/inf.hpp> #include <eve/constant/minf.hpp> #include <eve/constant/nan.hpp> #include <eve/platform.hpp> #include <cmath> #include <boost/math/special_functions/bessel.hpp> #include <boost/math/special_functions/bessel_prime.hpp> //================================================================================================== //== Types tests //================================================================================================== EVE_TEST_TYPES( "Check return types of cyl_bessel_in" , eve::test::simd::ieee_reals ) <typename T>(eve::as<T>) { using v_t = eve::element_type_t<T>; using i_t = eve::as_integer_t<v_t>; using I_t = eve::wide<i_t, eve::cardinal_t<T>>; TTS_EXPR_IS( eve::cyl_bessel_in(T(), T()) , T); TTS_EXPR_IS( eve::cyl_bessel_in(v_t(),v_t()), v_t); TTS_EXPR_IS( eve::cyl_bessel_in(i_t(),T()), T); TTS_EXPR_IS( eve::cyl_bessel_in(I_t(),T()), T); TTS_EXPR_IS( eve::cyl_bessel_in(i_t(),v_t()), v_t); TTS_EXPR_IS( eve::cyl_bessel_in(I_t(),v_t()), T); }; //================================================================================================== //== integral orders //================================================================================================== EVE_TEST( "Check behavior of cyl_bessel_in on wide with integral order" , eve::test::simd::ieee_reals , eve::test::generate(eve::test::ramp(0), eve::test::randoms(0.0, 10.0)) ) <typename T>(T n , T a0) { using v_t = eve::element_type_t<T>; auto eve__cyl_bessel_in = [](auto n, auto x) { return eve::cyl_bessel_in(n, x); }; auto std__cyl_bessel_in = [](auto n, auto x)->v_t { return boost::math::cyl_bessel_i(n, x); }; if constexpr( eve::platform::supports_invalids ) { TTS_ULP_EQUAL(eve__cyl_bessel_in(0, eve::minf(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(2, eve::inf(eve::as<v_t>())), eve::inf(eve::as<v_t>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(3, eve::nan(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0); } //scalar large x TTS_ULP_EQUAL(eve__cyl_bessel_in(3, v_t(1500)), eve::inf(eve::as<v_t>()), 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(2, v_t(50)), std__cyl_bessel_in(2, v_t(50)), 5.0); //scalar forward TTS_ULP_EQUAL(eve__cyl_bessel_in(0, v_t(10)), std__cyl_bessel_in(0, v_t(10)) , 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(1, v_t(5)), std__cyl_bessel_in(1, v_t(5)) , 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(2, v_t(10)), std__cyl_bessel_in(2, v_t(10)) , 35.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(3, v_t(5)), std__cyl_bessel_in(3, v_t(5)) , 35.0); //scalar small TTS_ULP_EQUAL(eve__cyl_bessel_in(0, v_t(0.1)), std__cyl_bessel_in(0, v_t(0.1)) , 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(1, v_t(0.2)), std__cyl_bessel_in(1, v_t(0.2)) , 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(2, v_t(0.1)), std__cyl_bessel_in(2, v_t(0.1)) , 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(3, v_t(0.2)), std__cyl_bessel_in(3, v_t(0.2)) , 5.0); //scalar medium TTS_ULP_EQUAL(eve__cyl_bessel_in(10, v_t(8)), std__cyl_bessel_in(10, v_t(8)) , 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(20, v_t(8)), std__cyl_bessel_in(20, v_t(8)) , 5.0); if constexpr( eve::platform::supports_invalids ) { TTS_ULP_EQUAL(eve__cyl_bessel_in(0, eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(2, eve::inf(eve::as<T>())), eve::inf(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(3, eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0); } //simd large x TTS_ULP_EQUAL(eve__cyl_bessel_in(3, T(1500)), eve::inf(eve::as<T>()), 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(2, T(50)), T(std__cyl_bessel_in(2, v_t(50))), 5.0); //simd forward TTS_ULP_EQUAL(eve__cyl_bessel_in(2, T(10)), T(std__cyl_bessel_in(2, v_t(10))) , 35.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(3, T(5)), T(std__cyl_bessel_in(3, v_t(5))) , 35.0); //simd small TTS_ULP_EQUAL(eve__cyl_bessel_in(0, T(0.1)), T(std__cyl_bessel_in(0, v_t(0.1))) , 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(1, T(0.2)), T(std__cyl_bessel_in(1, v_t(0.2))) , 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(2, T(0.1)), T(std__cyl_bessel_in(2, v_t(0.1))) , 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(3, T(0.2)), T(std__cyl_bessel_in(3, v_t(0.2))) , 5.0); //simd medium TTS_ULP_EQUAL(eve__cyl_bessel_in(10, T(8)), T(std__cyl_bessel_in(10, v_t(8))) , 7.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(20, T(8)), T(std__cyl_bessel_in(20, v_t(8))) , 5.0); if constexpr( eve::platform::supports_invalids ) { TTS_ULP_EQUAL(eve__cyl_bessel_in(T(0), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(2), eve::inf(eve::as<T>())), eve::inf(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(3), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0); } // large x TTS_ULP_EQUAL(eve__cyl_bessel_in(T(3), T(1500)), eve::inf(eve::as<T>()), 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(2), T(50)), T(std__cyl_bessel_in(2, v_t(50))), 5.0); // forward TTS_ULP_EQUAL(eve__cyl_bessel_in(T(2), T(10)), T(std__cyl_bessel_in(2, v_t(10))) , 35.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(3), T(5)), T(std__cyl_bessel_in(3, v_t(5))) , 35.0); // serie TTS_ULP_EQUAL(eve__cyl_bessel_in(T(2), T(0.1)), T(std__cyl_bessel_in(2, v_t(0.1))) , 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(3), T(0.2)), T(std__cyl_bessel_in(3, v_t(0.2))) , 5.0); // besseljy TTS_ULP_EQUAL(eve__cyl_bessel_in(T(10), T(8)), T(std__cyl_bessel_in(10, v_t(8))) , 7.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(20), T(8)), T(std__cyl_bessel_in(20, v_t(8))) , 5.0); using i_t = eve::as_integer_t<v_t>; using I_t = eve::wide<i_t, eve::cardinal_t<T>>; if constexpr( eve::platform::supports_invalids ) { TTS_ULP_EQUAL(eve__cyl_bessel_in(I_t(0), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(I_t(2), eve::inf(eve::as<T>())), eve::inf(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(I_t(3), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0); } // large x TTS_ULP_EQUAL(eve__cyl_bessel_in(I_t(3), T(1500)), eve::inf(eve::as<T>()), 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(I_t(2), T(50)), T(std__cyl_bessel_in(2, v_t(50))), 5.0); // forward TTS_ULP_EQUAL(eve__cyl_bessel_in(I_t(2), T(10)), T(std__cyl_bessel_in(2, v_t(10))) , 35.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(I_t(3), T(5)), T(std__cyl_bessel_in(3, v_t(5))) , 35.0); // serie TTS_ULP_EQUAL(eve__cyl_bessel_in(I_t(2), T(0.1)), T(std__cyl_bessel_in(2, v_t(0.1))) , 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(I_t(3), T(0.2)), T(std__cyl_bessel_in(3, v_t(0.2))) , 5.0); // besseljy TTS_ULP_EQUAL(eve__cyl_bessel_in(I_t(10), T(8)), T(std__cyl_bessel_in(10, v_t(8))) , 7.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(I_t(20), T(8)), T(std__cyl_bessel_in(20, v_t(8))) , 5.0); TTS_ULP_EQUAL(map(eve__cyl_bessel_in, n, a0), map(std__cyl_bessel_in, n, a0) , 500.0); TTS_ULP_EQUAL(map(eve__cyl_bessel_in, -n, a0), map(std__cyl_bessel_in, -n, a0) , 500.0); }; //================================================================================================== //== non integral orders //================================================================================================== EVE_TEST( "Check behavior of cyl_bessel_in on wide with non integral order" , eve::test::simd::ieee_reals , eve::test::generate(eve::test::randoms(0.0, 10.0) , eve::test::randoms(0.0, 10.0)) ) <typename T>(T n, T a0 ) { using v_t = eve::element_type_t<T>; auto eve__cyl_bessel_in = [](auto n, auto x) { return eve::cyl_bessel_in(n, x); }; auto std__cyl_bessel_in = [](auto n, auto x)->v_t { return boost::math::cyl_bessel_i(double(n), double(x)); }; if constexpr( eve::platform::supports_invalids ) { TTS_ULP_EQUAL(eve__cyl_bessel_in(T(0.5), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(2.5), eve::inf(eve::as<T>())), eve::inf(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(3.5), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0); } // large x TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(3.5), v_t(1500)), eve::inf(eve::as<v_t>()), 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(2.5), v_t(50)), std__cyl_bessel_in(v_t(2.5), v_t(50)), 10.0); // forward TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(2.5), v_t(10)), std__cyl_bessel_in(v_t(2.5), v_t(10)) , 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(3.5), v_t(5)), std__cyl_bessel_in(v_t(3.5), v_t(5)) , 10.0); // serie TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(2.5), v_t(0.1)), std__cyl_bessel_in(v_t(2.5), v_t(0.1)) , 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(3.5), v_t(0.2)), std__cyl_bessel_in(v_t(3.5), v_t(0.2)) , 10.0); // besseljy TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(10.5), v_t(8)), std__cyl_bessel_in(v_t(10.5), v_t(8)) , 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(10.5), v_t(8)), std__cyl_bessel_in(v_t(10.5), v_t(8)) , 10.0); if constexpr( eve::platform::supports_invalids ) { TTS_ULP_EQUAL(eve__cyl_bessel_in(T(0.5), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(2.5), eve::inf(eve::as<T>())), eve::inf(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(3.5), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0); } // large x TTS_ULP_EQUAL(eve__cyl_bessel_in(T(3.5), T(700)), T(std__cyl_bessel_in(v_t(3.5), v_t(700))), 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(2.5), T(50)), T(std__cyl_bessel_in(v_t(2.5), v_t(50))), 10.0); // forward TTS_ULP_EQUAL(eve__cyl_bessel_in(T(2.5), T(10)), T(std__cyl_bessel_in(v_t(2.5), v_t(10))) , 310.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(3.5), T(5)), T(std__cyl_bessel_in(v_t(3.5), v_t(5))) , 310.0); // serie TTS_ULP_EQUAL(eve__cyl_bessel_in(T(2.5), T(0.1)), T(std__cyl_bessel_in(v_t(2.5), v_t(0.1))) , 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(3.5), T(0.2)), T(std__cyl_bessel_in(v_t(3.5), v_t(0.2))) , 10.0); // besseljy TTS_ULP_EQUAL(eve__cyl_bessel_in(T(10.5), T(8)), T(std__cyl_bessel_in(v_t(10.5), v_t(8))) , 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(10.5), T(8)), T(std__cyl_bessel_in(v_t(10.5), v_t(8))) , 10.0); TTS_RELATIVE_EQUAL(eve__cyl_bessel_in(n, a0), map(std__cyl_bessel_in, n, a0) , 1.0e-3); }; EVE_TEST( "Check behavior of cyl_bessel_in on wide with negative non integral order" , eve::test::simd::ieee_reals , eve::test::generate(eve::test::randoms(0.0, 10.0) , eve::test::randoms(0.0, 10.0)) ) <typename T>(T n, T a0 ) { using v_t = eve::element_type_t<T>; auto eve__cyl_bessel_in = [](auto n, auto x) { return eve::cyl_bessel_in(n, x); }; auto std__cyl_bessel_in = [](auto n, auto x)->v_t { return boost::math::cyl_bessel_i(double(n), double(x)); }; if constexpr( eve::platform::supports_invalids ) { TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-0.5), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-2.5), eve::inf(eve::as<T>())), eve::inf(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-3.5), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0); } // large x TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(-3.5), v_t(1500)), eve::inf(eve::as<v_t>()), 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(-2.5), v_t(60)), std__cyl_bessel_in(v_t(-2.5), v_t(60)), 10.0); // forward TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(-2.5), v_t(10)), std__cyl_bessel_in(v_t(-2.5), v_t(10)) , 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(-3.5), v_t(5)), std__cyl_bessel_in(v_t(-3.5), v_t(5)) , 10.0); // serie TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(-2.5), v_t(0.1)), std__cyl_bessel_in(v_t(-2.5), v_t(0.1)) , 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(-3.5), v_t(0.2)), std__cyl_bessel_in(v_t(-3.5), v_t(0.2)) , 10.0); // besseljy TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(-10.5), v_t(8)), std__cyl_bessel_in(v_t(-10.5), v_t(8)) , 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(-10.5), v_t(8)), std__cyl_bessel_in(v_t(-10.5), v_t(8)) , 10.0); if constexpr( eve::platform::supports_invalids ) { TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-0.5), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-2.5), eve::inf(eve::as<T>())), eve::inf(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-3.5), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0); } // large x TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-3.5), T(1500)), eve::inf(eve::as<T>()), 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-2.5), T(50)), T(std__cyl_bessel_in(v_t(-2.5), v_t(50))), 10.0); // forward TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-2.5), T(10)), T(std__cyl_bessel_in(v_t(-2.5), v_t(10))) , 310.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-3.5), T(5)), T(std__cyl_bessel_in(v_t(-3.5), v_t(5))) , 310.0); // serie TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-2.5), T(0.1)), T(std__cyl_bessel_in(v_t(-2.5), v_t(0.1))) , 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-3.5), T(0.2)), T(std__cyl_bessel_in(v_t(-3.5), v_t(0.2))) , 10.0); // besseljy TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-10.5), T(8)), T(std__cyl_bessel_in(v_t(-10.5), v_t(8))) , 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-10.5), T(8)), T(std__cyl_bessel_in(v_t(-10.5), v_t(8))) , 10.0); TTS_RELATIVE_EQUAL(eve__cyl_bessel_in(-n, a0), map(std__cyl_bessel_in, -n, a0) , 1.0e-3); }; EVE_TEST( "Check behavior of diff of cyl_bessel_in on wide" , eve::test::simd::ieee_reals , eve::test::generate(eve::test::randoms(0.0, 10.0) , eve::test::randoms(0.0, 10.0)) ) <typename T>(T n, T a0 ) { using v_t = eve::element_type_t<T>; auto eve__diff_bessel_in = [](auto n, auto x) { return eve::diff(eve::cyl_bessel_in)(n, x); }; auto std__diff_bessel_in = [](auto n, auto x)->v_t { return boost::math::cyl_bessel_i_prime(double(n), double(x)); }; TTS_RELATIVE_EQUAL(eve__diff_bessel_in(n, a0), map(std__diff_bessel_in, n, a0) , 1.0e-3); };
55.855513
120
0.608169
the-moisrex
f88c0c8d4ea436210f169a7c6b725e1c5e84713a
5,251
cc
C++
open_spiel/examples/fsicfr_liars_dice.cc
ajain-23/open_spiel
a6a0f0129571bb6f0e6832e870e299663fb7cdd5
[ "Apache-2.0" ]
3,167
2019-08-27T06:50:30.000Z
2022-03-31T22:33:48.000Z
open_spiel/examples/fsicfr_liars_dice.cc
AliBeikmohammadi/open_spiel
38941dee3beb52ffdb134b66f420a758634d9a20
[ "Apache-2.0" ]
650
2019-08-27T16:24:09.000Z
2022-03-30T19:41:09.000Z
open_spiel/examples/fsicfr_liars_dice.cc
AliBeikmohammadi/open_spiel
38941dee3beb52ffdb134b66f420a758634d9a20
[ "Apache-2.0" ]
774
2019-08-27T10:36:04.000Z
2022-03-29T15:44:42.000Z
// Copyright 2019 DeepMind Technologies Ltd. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <memory> #include "open_spiel/abseil-cpp/absl/strings/str_cat.h" #include "open_spiel/algorithms/fsicfr.h" #include "open_spiel/algorithms/tabular_best_response_mdp.h" #include "open_spiel/games/liars_dice.h" #include "open_spiel/spiel.h" #include "open_spiel/spiel_globals.h" #include "open_spiel/spiel_utils.h" namespace open_spiel { namespace algorithms { namespace { constexpr const int kSeed = 1873561; using liars_dice::LiarsDiceState; void BuildGraph(FSICFRGraph* graph, const State& state, Action chance_id_0, Action chance_id_1, int max_predecessors, int parent_node_id, Action parent_action, int parent_other_player_chance_id) { if (state.IsTerminal()) { const auto& ld_state = static_cast<const LiarsDiceState&>(state); std::string terminal_key = absl::StrCat("terminal ", ld_state.dice_outcome(0, 0), " ", ld_state.dice_outcome(1, 0), " ", ld_state.calling_player(), " ", ld_state.last_bid()); FSICFRNode* node = graph->GetOrCreateTerminalNode( terminal_key, state.PlayerReturn(0), max_predecessors); FSICFRNode* parent_node = graph->GetNode(parent_node_id); SPIEL_CHECK_TRUE(parent_node != nullptr); // Connect to the parent. parent_node->AddChild(parent_action, parent_other_player_chance_id, node); } else if (state.IsChanceNode()) { std::vector<Action> legal_actions = state.LegalActions(); for (Action outcome : legal_actions) { Action next_chance_id_0 = chance_id_0; Action next_chance_id_1 = chance_id_1; if (chance_id_0 == kInvalidAction) { next_chance_id_0 = outcome; } else { next_chance_id_1 = outcome; } std::unique_ptr<State> next_state = state.Child(outcome); BuildGraph(graph, *next_state, next_chance_id_0, next_chance_id_1, max_predecessors, parent_node_id, parent_action, parent_other_player_chance_id); } } else { std::string info_state_string = state.InformationStateString(); Player player = state.CurrentPlayer(); int my_chance_id = player == 0 ? chance_id_0 : chance_id_1; int other_chance_id = player == 0 ? chance_id_1 : chance_id_0; std::vector<Action> legal_actions = state.LegalActions(); FSICFRNode* node = graph->GetOrCreateDecisionNode(legal_actions, info_state_string, player, max_predecessors, my_chance_id); int next_max_predecessors = node->max_predecessors + 1; int node_id = node->id; node->max_predecessors = std::max(max_predecessors, node->max_predecessors); FSICFRNode* parent_node = graph->GetNode(parent_node_id); // Connect it to the parent. if (parent_node != nullptr) { parent_node->AddChild(parent_action, parent_other_player_chance_id, node); } // Recrusively build the graph from the children. for (Action action : legal_actions) { std::unique_ptr<State> next_state = state.Child(action); BuildGraph(graph, *next_state, chance_id_0, chance_id_1, next_max_predecessors, node_id, action, other_chance_id); } } } void RunFSICFR() { std::unique_ptr<FSICFRGraph> graph = std::make_unique<FSICFRGraph>(); std::shared_ptr<const Game> game = LoadGame("liars_dice_ir"); std::unique_ptr<State> initial_state = game->NewInitialState(); std::cout << "Building the graph." << std::endl; BuildGraph(graph.get(), *initial_state, kInvalidAction, kInvalidAction, 0, -1, kInvalidAction, -1); std::cout << "Graph has " << graph->size() << " nodes." << std::endl; std::cout << "Topologically sorting the nodes." << std::endl; graph->TopSort(); FSICFRSolver solver(*game, kSeed, {6, 6}, graph.get()); std::cout << "Running iterations" << std::endl; int max_iterations = 1000000; int total_iterations = 0; int num_iterations = 0; // solver.RunIteration(); // std::exit(-1); while (total_iterations < max_iterations) { solver.RunIterations(num_iterations); // Must use the best response MDP since it supports imperfect recall. TabularPolicy average_policy = solver.GetAveragePolicy(); TabularBestResponseMDP tbr(*game, average_policy); TabularBestResponseMDPInfo br_info = tbr.NashConv(); total_iterations += num_iterations; std::cout << total_iterations << " " << br_info.nash_conv << std::endl; num_iterations = (num_iterations == 0 ? 10 : total_iterations); } } } // namespace } // namespace algorithms } // namespace open_spiel int main(int argc, char** argv) { open_spiel::algorithms::RunFSICFR(); }
40.083969
80
0.697772
ajain-23
f88c2a22990818344fa1d81a415acb3b7c0a2ad5
7,184
cxx
C++
RhoNNO/TRadon.cxx
marcelkunze/rhonno
b9a06557c5e059ab25ad9077a13dbaeb449ed85e
[ "MIT" ]
2
2019-07-12T12:16:22.000Z
2020-09-19T14:51:47.000Z
RhoNNO/TRadon.cxx
marcelkunze/rhonno
b9a06557c5e059ab25ad9077a13dbaeb449ed85e
[ "MIT" ]
null
null
null
RhoNNO/TRadon.cxx
marcelkunze/rhonno
b9a06557c5e059ab25ad9077a13dbaeb449ed85e
[ "MIT" ]
2
2017-09-27T13:12:39.000Z
2019-07-12T12:14:43.000Z
// radon_function // various functions for performing the fuzzy Radon transform // M.Kunze, Heidelberg University, 2018 #include <stdlib.h> #include <math.h> #include "TNtuple.h" #include "TVector3.h" #include "TH2D.h" #include "TPolyMarker3D.h" #include "TPolyLine3D.h" #include "TRadon.h" #include <string> #include <iostream> #include <random> using namespace std; ClassImp(TRadon) #define DGAMMA 0.1 #define NGAMMA 40 #define DKAPPA 0.125 #define NKAPPA 25 #define DPHI M_PI/30. #define NPHI 30 #define TAUMAX 0.5*M_PI #define DRAWTRACK false #define signum(x) (x > 0) ? 1 : ((x < 0) ? -1 : 0) TRadon::TRadon(double sig, double thr) : sigma(sig), threshold(thr), Hlist(0) { nt1 = new TNtuple("RadonTransform","Radon Transform","kappa:phi:gamma:sigma:density:x:y:z"); nt2 = new TNtuple("RadonTrackParameters","Radon Track Parameters","kappa:phi:gamma:sigma:density:x:y:z"); float gamma = -2.0; for (int i=0;i<NGAMMA;i++,gamma+=DGAMMA) { string name = "Gamma=" + to_string(gamma); string title = "Radon density in r/Phi " + name; Hlist.Add(new TH2D(name.data(),title.data(),40,0.0,4.,30,0.0,3.0)); } } TRadon::~TRadon() { Hlist.Write(); nt1->Write(); delete nt1; nt2->Write(); delete nt2; } /* * Do a RADON transform of coordinates (all lengths in meter) * (1 GeV/c == 2.22m Radius at B=1.5T) */ std::vector<RADON>& TRadon::Transform(std::vector<TVector3> &points) { hits = points; double kappa,gamma,phi; long k=0,g=0,p=0; gamma = -2.0; for (g=0;g<NGAMMA;g++,gamma += DGAMMA) { kappa = -1.125; for (k=0;k<NKAPPA;k++) { kappa = kappa + DKAPPA; phi = 0.; for (p=0;p<NPHI;p++) { phi = phi + DPHI; RADON t; t.kappa = kappa; t.phi = phi; t.gamma = gamma; t.sigma = sigma; long nhits = Density(t,hits); if (t.density > threshold && nhits > 3) { printf("\nDensity: %f",t.density); TH2D *h = (TH2D *) Hlist[(int) g]; h->Fill(1./kappa,phi,t.density); rt.push_back(t); // Note the candidate track parameters } } } } return rt; } long TRadon::Density(RADON &t, std::vector<TVector3> &points) { long nhits = 0, index = 0; double density = 0.0; vector<TVector3>::iterator it; for(it = points.begin(); it != points.end(); it++, index++) { TVector3 point=*it; t.x = point.x(); t.y = point.y(); t.z = point.z(); double d = radon_hit_density(&t); density += d; t.density = density; if (d > 1.0) { t.index.push_back(index); nhits++; } } return nhits; } double TRadon::getEta_g(RADON *t) { double sp,cp,x2,y2; sp = sin(t->phi); cp = cos(t->phi); x2 = (t->kappa * t->x + sp) * (t->kappa * t->x + sp); y2 = (t->kappa * t->y - cp) * (t->kappa * t->y - cp); return sqrt(x2+y2); } double TRadon::getTau_i(RADON *t) { double sp,cp, nom, denom; sp = sin(t->phi); cp = cos(t->phi); nom = t->y * sp + t->x * cp; denom = (1.0 / t->kappa) + t->x * sp - t->y * cp; return (signum(t->kappa)) * atan(nom/denom); } double TRadon::getZ_g(RADON *t) { return ((t->gamma * getTau_i(t)) - t->z); } double TRadon::radon_hit_density(RADON *t) { double eta_g,gamma,kappa,error,z_g,k2,s2,g2,factor, kappafunction,efunction,radon; eta_g = getEta_g(t); gamma = t->gamma; kappa = t->kappa; error = t->sigma; z_g = getZ_g(t) ; k2 = kappa * kappa; s2 = error * error; g2 = gamma * gamma; factor = 1. / (2 * M_PI * s2 * TAUMAX); kappafunction = abs(kappa) / sqrt(eta_g + k2 * g2); efunction = -1.0 / (2 * s2) * (((eta_g - 1.0) * (eta_g - 1.0) / k2) + (eta_g * z_g * z_g / (eta_g + k2 * g2))); radon = factor * kappafunction * exp(efunction); return radon; } /* * Create a tuple with Track coordinates */ void TRadon::GenerateTrack(std::vector<TVector3> &points, int np, double delta, double radius, double phi, double gamma, double error) { default_random_engine generator; double tau = 0.025; for (int i=0; i<np; i++,tau+=delta) { float X,Y,Z; X = radius * ( sin(phi + (signum(radius)) * tau) - sin(phi)); Y = radius * (-cos(phi + (signum(radius)) * tau) + cos(phi)); Z = gamma * tau; if (error > 0.0) { normal_distribution<float> distribution0(X,error); X = distribution0(generator); normal_distribution<float> distribution1(Y,error); Y = distribution1(generator); normal_distribution<float> distribution2(Z,error); Z = distribution2(generator); } points.push_back(TVector3(X,Y,Z)); } } void TRadon::Draw(Option_t *option) { int n = 1; vector<RADON>::iterator radon; for(radon = rt.begin(); radon != rt.end(); radon++) { RADON t=*radon;; double radius = 1./t.kappa; printf("\nTrack candidate #%d r:%f k:%f p:%f g:%f : %f ",n++,radius,t.kappa,t.phi,t.gamma,t.density); printf("\nAssociated hits: "); for (unsigned long j = 0; j < t.index.size(); j++) { cout << t.index[j] << " "; } nt2->Fill(t.kappa,t.phi,t.gamma,t.sigma,t.density,t.x,t.y,t.z); // Store results as ROOT ntuple if (t.density > threshold) { printf("Density > %f", threshold); std::vector<TVector3> nt3; if (DRAWTRACK) GenerateTrack(nt3,25,0.025,radius,t.phi,t.gamma); else for (unsigned long i=0;i<t.index.size();i++) { long index = t.index[i]; float x = hits[index].x(); float y = hits[index].y(); float z = hits[index].z(); TVector3 p(x,y,z); nt3.push_back(p); } // Draw the track candidates TPolyMarker3D *hitmarker = new TPolyMarker3D(nt3.size()); TPolyLine3D *connector = new TPolyLine3D(nt3.size()); int j = 0; vector<TVector3>::iterator it; for(it = nt3.begin(); it != nt3.end(); it++, j++) { TVector3 point=*it; hitmarker->SetPoint(j,point.x(),point.y(),point.z()); hitmarker->SetMarkerSize(0.1); hitmarker->SetMarkerColor(kYellow); hitmarker->SetMarkerStyle(kFullDotLarge); hitmarker->Draw(option); connector->SetPoint(j, point.x(),point.y(),point.z()); connector->SetLineWidth(1); connector->SetLineColor(kYellow); connector->Draw(option); printf("\n%d: x:%f y:%f z:%f d:%f ",j,point.x(),point.y(),point.z(),point.Mag()); } } } }
30.184874
136
0.518235
marcelkunze
f88c8d94c3c043e07996124658bbc58ffe03bdc5
10,013
cpp
C++
waifu2x-converter-gls/src/convertRoutine.cpp
ymdymd/glsCV
fa89193d653767f11e01ec1bd13e2f3461a5b1b3
[ "BSD-3-Clause" ]
null
null
null
waifu2x-converter-gls/src/convertRoutine.cpp
ymdymd/glsCV
fa89193d653767f11e01ec1bd13e2f3461a5b1b3
[ "BSD-3-Clause" ]
31
2016-05-09T01:31:21.000Z
2016-08-11T11:34:39.000Z
waifu2x-converter-gls/src/convertRoutine.cpp
oasi-adamay/glsCV
fa89193d653767f11e01ec1bd13e2f3461a5b1b3
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2016, oasi-adamay All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of glsCV nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * convertRoutine.cpp * (ここにファイルの簡易説明を記入) * * Created on: 2015/05/31 * Author: wlamigo * changed : oasi-adamay * (ここにファイルの説明を記入) */ #include "convertRoutine.hpp" #include "glsCV.h" //#ifdef _DEBUG //#define _ENABLE_TMR_ #if defined(_ENABLE_TMR_) #include "Timer.h" #define _TMR_(...) Timer tmr(__VA_ARGS__) #else #define _TMR_(...) #endif namespace w2xc { // converting process inside program static bool convertWithModelsBasic(cv::Mat &inputPlane, cv::Mat &outputPlane, std::vector<std::unique_ptr<Model> > &models); static bool convertWithModelsBlockSplit(cv::Mat &inputPlane, cv::Mat &outputPlane, std::vector<std::unique_ptr<Model> > &models); bool convertWithModels(cv::Mat &inputPlane, cv::Mat &outputPlane, std::vector<std::unique_ptr<Model> > &models, bool blockSplitting) { cv::Size blockSize = modelUtility::getInstance().getBlockSize(); bool requireSplitting = (inputPlane.size().width * inputPlane.size().height) > blockSize.width * blockSize.height * 3 / 2; // requireSplitting = true; if (blockSplitting && requireSplitting) { return convertWithModelsBlockSplit(inputPlane, outputPlane, models); } else { //insert padding to inputPlane cv::Mat tempMat; int nModel = (int)models.size(); cv::Size outputSize = inputPlane.size(); cv::copyMakeBorder(inputPlane, tempMat, nModel, nModel, nModel, nModel, cv::BORDER_REPLICATE); bool ret = convertWithModelsBasic(tempMat, outputPlane, models); tempMat = outputPlane(cv::Range(nModel, outputSize.height + nModel), cv::Range(nModel, outputSize.width + nModel)); assert( tempMat.size().width == outputSize.width && tempMat.size().height == outputSize.height); tempMat.copyTo(outputPlane); return ret; } } #ifdef USE_GLS static bool convertWithModelsBasic(cv::Mat &inputPlane, cv::Mat &outputPlane, std::vector<std::unique_ptr<Model> > &models) { // padding is require before calling this function //std::unique_ptr<std::vector<cv::Mat> > inputPlanes = std::unique_ptr< // std::vector<cv::Mat> >(new std::vector<cv::Mat>()); //std::unique_ptr<std::vector<cv::Mat> > outputPlanes = std::unique_ptr< // std::vector<cv::Mat> >(new std::vector<cv::Mat>()); std::vector<gls::GlsMat> inputPlanes; std::vector<gls::GlsMat> outputPlanes; inputPlanes.clear(); inputPlanes.push_back((GlsMat)inputPlane); for (int index = 0; index < models.size(); index++) { std::cout << "Layer#" << (index) << " : " << models[index]->getNInputPlanes() << " > " << models[index]->getNOutputPlanes() << std::endl; if (!models[index]->filter(inputPlanes, outputPlanes)) { std::exit(-1); } if (index != models.size() - 1) { inputPlanes = outputPlanes; } } outputPlane = (Mat)outputPlanes[0]; return true; } #elif defined(USE_GLS_NEW) static bool convertWithModelsBasic(cv::Mat &inputPlane, cv::Mat &outputPlane, std::vector<std::unique_ptr<Model> > &models) { _TMR_("convertWithModelsBasic\t:"); // padding is require before calling this function CV_Assert(inputPlane.type() == CV_32FC1); CV_Assert(inputPlane.dims == 2); if (!inputPlane.isContinuous()){ inputPlane = inputPlane.clone(); // to be continuous } int _size[3] = { 1, inputPlane.size[0], inputPlane.size[1] }; // gls::GlsMat inputPlanes(cv::Mat(3, _size, CV_32FC1, inputPlane.data)); //upload gls::GlsMat inputPlanes; { _TMR_("upload \t\t:"); cv::Mat _inputPlanes = cv::Mat(3, _size, CV_32FC1, inputPlane.data); inputPlanes = (gls::GlsMat)_inputPlanes; } gls::GlsMat outputPlanes; for (int index = 0; index <= models.size(); index++) { #if !defined(_ENABLE_TMR_) { std::cout << "\r["; int progress = 0; for (; progress < index; progress++) std::cout << "="; for (; progress < (int)models.size(); progress++) std::cout << " "; std::cout << "]"; std::cout.flush(); } #endif if (index >= (int)models.size()) { break; } { // core processing std::string str = "Layer#" + to_string(index) + " ( " + to_string(models[index]->getNInputPlanes()) + " > " + to_string(models[index]->getNOutputPlanes()) + " )\t:"; _TMR_(str); if (!models[index]->filter(inputPlanes, outputPlanes)) { std::exit(-1); } } if (index != models.size() - 1) { inputPlanes = outputPlanes; } } { _TMR_("download\t\t:"); outputPlane = cv::Mat(inputPlane.size(), inputPlane.type()); cv::Mat _outputPlanes(3, _size, CV_32FC1, outputPlane.data); outputPlanes.download(_outputPlanes); } std::cout << " complete." << std::endl; return true; } #else static bool convertWithModelsBasic(cv::Mat &inputPlane, cv::Mat &outputPlane, std::vector<std::unique_ptr<Model> > &models) { // padding is require before calling this function CV_Assert(inputPlane.type() == CV_32FC1); int _size[3] = { 1, inputPlane.size[0], inputPlane.size[1] }; cv::Mat inputPlanes = cv::Mat(3, _size, CV_32FC1); cv::Mat outputPlanes; { cv::Mat roi(inputPlane.size(), CV_32FC1, inputPlanes.ptr<float>(0)); inputPlane.copyTo(roi); } for (int index = 0; index < models.size(); index++) { std::cout << "Layer#" << (index) << " : " << models[index]->getNInputPlanes() << " > " << models[index]->getNOutputPlanes() << std::endl; if (!models[index]->filter(inputPlanes, outputPlanes)) { std::exit(-1); } if (index != models.size() - 1) { inputPlanes = outputPlanes; } } { outputPlane = cv::Mat(inputPlane.size(), inputPlane.type()); cv::Mat roi(inputPlane.size(), CV_32FC1, outputPlanes.ptr<float>(0)); roi.copyTo(outputPlane); } return true; } #endif static bool convertWithModelsBlockSplit(cv::Mat &inputPlane, cv::Mat &outputPlane, std::vector<std::unique_ptr<Model> > &models) { _TMR_("convertWithModelsBlockSplit\t:"); // padding is not required before calling this function // initialize local variables cv::Size blockSize = modelUtility::getInstance().getBlockSize(); unsigned int nModel = (int)models.size(); //insert padding to inputPlane cv::Mat tempMat; cv::Size outputSize = inputPlane.size(); cv::copyMakeBorder(inputPlane, tempMat, nModel, nModel, nModel, nModel, cv::BORDER_REPLICATE); // calcurate split rows/cols unsigned int splitColumns = static_cast<unsigned int>(std::ceil( static_cast<float>(outputSize.width) / static_cast<float>(blockSize.width - 2 * nModel))); unsigned int splitRows = static_cast<unsigned int>(std::ceil( static_cast<float>(outputSize.height) / static_cast<float>(blockSize.height - 2 * nModel))); // start to convert cv::Mat processRow; cv::Mat processBlock; cv::Mat processBlockOutput; cv::Mat writeMatTo; cv::Mat writeMatFrom; outputPlane = cv::Mat::zeros(outputSize, CV_32FC1); for (unsigned int r = 0; r < splitRows; r++) { if (r == splitRows - 1) { processRow = tempMat.rowRange(r * (blockSize.height - 2 * nModel), tempMat.size().height); } else { processRow = tempMat.rowRange(r * (blockSize.height - 2 * nModel), r * (blockSize.height - 2 * nModel) + blockSize.height); } for (unsigned int c = 0; c < splitColumns; c++) { if (c == splitColumns - 1) { processBlock = processRow.colRange( c * (blockSize.width - 2 * nModel), tempMat.size().width); } else { processBlock = processRow.colRange( c * (blockSize.width - 2 * nModel), c * (blockSize.width - 2 * nModel) + blockSize.width); } std::cout << "start process block (" << c << "," << r << ") ..." << std::endl; if (!convertWithModelsBasic(processBlock, processBlockOutput, models)) { std::cerr << "w2xc::convertWithModelsBasic()\n" "in w2xc::convertWithModelsBlockSplit() : \n" "something error has occured. stop." << std::endl; return false; } writeMatFrom = processBlockOutput( cv::Range(nModel, processBlockOutput.size().height - nModel), cv::Range(nModel, processBlockOutput.size().width - nModel)); writeMatTo = outputPlane( cv::Range(r * (blockSize.height - 2 * nModel), r * (blockSize.height - 2 * nModel) + processBlockOutput.size().height - 2 * nModel), cv::Range(c * (blockSize.height - 2 * nModel), c * (blockSize.height - 2 * nModel) + processBlockOutput.size().width - 2 * nModel)); assert( writeMatTo.size().height == writeMatFrom.size().height && writeMatTo.size().width == writeMatFrom.size().width); writeMatFrom.copyTo(writeMatTo); } // end process 1 column } // end process all blocks return true; } }
30.159639
83
0.679317
ymdymd
f88d763dfa7f260361ec544c0ddc67dd1f8933f9
1,382
cc
C++
plugins/coreaudio/CoreAudioRenderer.cc
jjzhang166/mous
54a219712970bd6fabbac85102e1615babb69c41
[ "BSD-2-Clause" ]
1
2018-04-04T05:48:37.000Z
2018-04-04T05:48:37.000Z
plugins/coreaudio/CoreAudioRenderer.cc
aliakbarRashidi/mous
54a219712970bd6fabbac85102e1615babb69c41
[ "BSD-2-Clause" ]
null
null
null
plugins/coreaudio/CoreAudioRenderer.cc
aliakbarRashidi/mous
54a219712970bd6fabbac85102e1615babb69c41
[ "BSD-2-Clause" ]
null
null
null
#include "CoreAudioRenderer.h" #include <iostream> using namespace std; #include <unistd.h> extern "C" { #include "cmus/op.h" #include "cmus/mixer.h" } const char* program_name = "CoreAudioRenderer"; CoreAudioRenderer::CoreAudioRenderer() { op_pcm_ops.init(); op_mixer_ops.init(); } CoreAudioRenderer::~CoreAudioRenderer() { Close(); op_pcm_ops.exit(); op_mixer_ops.exit(); } ErrorCode CoreAudioRenderer::Open() { int maxVol = 0; op_mixer_ops.open(&maxVol); return ErrorCode::Ok; } void CoreAudioRenderer::Close() { op_mixer_ops.close(); } ErrorCode CoreAudioRenderer::Setup(int32_t& channels, int32_t& sampleRate, int32_t& bitsPerSample) { op_pcm_ops.drop(); op_pcm_ops.close(); const sample_format_t sf = sf_bits(bitsPerSample) | sf_rate(sampleRate) | sf_channels(channels) | sf_signed(1); op_pcm_ops.open(sf, nullptr); return ErrorCode::Ok; } ErrorCode CoreAudioRenderer::Write(const char* buf, uint32_t len) { op_pcm_ops.write(buf, static_cast<int>(len)); op_pcm_wait(len); return ErrorCode::Ok; } int CoreAudioRenderer::VolumeLevel() const { int l, r; op_mixer_ops.get_volume(&l, &r); return (l + r) / 2; } void CoreAudioRenderer::SetVolumeLevel(int avg) { op_mixer_ops.set_volume(avg, avg); } std::vector<const BaseOption*> CoreAudioRenderer::Options() const { return {}; }
19.194444
115
0.69754
jjzhang166
f89358a42dc7aa82998f13cf7e020491653d8e00
1,637
cc
C++
src/block_diagonal_check.cc
jwlawson/ptope
2c664ac4fb7b036a298e7c6a1b2cf58d803f227a
[ "Apache-2.0" ]
1
2019-02-22T03:03:13.000Z
2019-02-22T03:03:13.000Z
src/block_diagonal_check.cc
jwlawson/ptope
2c664ac4fb7b036a298e7c6a1b2cf58d803f227a
[ "Apache-2.0" ]
9
2016-08-31T16:34:59.000Z
2016-09-12T16:29:55.000Z
src/block_diagonal_check.cc
jwlawson/ptope
2c664ac4fb7b036a298e7c6a1b2cf58d803f227a
[ "Apache-2.0" ]
null
null
null
/* * block_diagonal_check.h * Copyright 2015 John Lawson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "block_diagonal_check.h" namespace ptope { bool BlockDiagonalCheck::operator()(const arma::mat m) { _unvisited.clear(); _components.clear(); while(!_queue.empty()) { _queue.pop(); } for(arma::uword i = 0; i < m.n_cols; ++i) { _unvisited.push_back(i); } arma::uword current_component = 0; while(!_unvisited.empty()) { _components.push_back(std::vector<arma::uword>()); _queue.push(_unvisited.back()); _unvisited.pop_back(); while(!_queue.empty()) { arma::uword col = _queue.front(); _queue.pop(); for(auto unv_it = _unvisited.end(); unv_it > _unvisited.begin();) { /* Here we need a reverse iterator, wbut one which can be used to erase * elements. Hence this slightly hacky version. */ --unv_it; arma::uword row = *unv_it; if(m(row,col) != 0) { /* Vertex row is connected to vertex col */ _unvisited.erase(unv_it); _components[current_component].push_back(row); _queue.push(row); } } } } return _components.size() == 1; } }
29.763636
75
0.682957
jwlawson
f89af632110139cc11d949f4276ca6bd7ee4e284
808
cpp
C++
BashuOJ-Code/2906.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
BashuOJ-Code/2906.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
BashuOJ-Code/2906.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<iomanip> #include<algorithm> #include<queue> #include<stack> #include<vector> #define ri register int using namespace std; int n,cnt,a0,a1,b0,b1,base,x; inline int getint() { int num=0,bj=1; char c=getchar(); while(c<'0'||c>'9')bj=(c=='-'||bj==-1)?-1:1,c=getchar(); while(c>='0'&&c<='9')num=num*10+c-'0',c=getchar(); return num*bj; } inline int gcd(int t1,int t2){return !t2?t1:gcd(t2,t1%t2);} int main() { n=getint(); for(ri i=1;i<=n;i++) { a0=getint(),a1=getint(),b0=getint(),b1=getint(),cnt=0; for(ri j=1;j*j<=b1;j++) { if(b1%j==0) { int k=b1/j; if(gcd(j,a0)==a1&&(j/gcd(j,b0)*b0)==b1)cnt++; if(j*j!=b1&&gcd(k,a0)==a1&&(k/gcd(k,b0)*b0)==b1)cnt++; } } printf("%d\n",cnt); } return 0; }
19.707317
59
0.585396
magicgh
f89e012b47b9ec1b002c3a547a9015bbd31b2700
6,517
cpp
C++
SPHINXsys/src/shared/particle_dynamics/base_particle_dynamics.cpp
SoftwareImpacts/SIMPAC-2020-34
eb2d69e61548eaa11b5a9c20e312d135c5d857f5
[ "Apache-2.0" ]
2
2020-09-24T07:39:22.000Z
2021-04-24T22:12:49.000Z
SPHINXsys/src/shared/particle_dynamics/base_particle_dynamics.cpp
SoftwareImpacts/SIMPAC-2020-34
eb2d69e61548eaa11b5a9c20e312d135c5d857f5
[ "Apache-2.0" ]
null
null
null
SPHINXsys/src/shared/particle_dynamics/base_particle_dynamics.cpp
SoftwareImpacts/SIMPAC-2020-34
eb2d69e61548eaa11b5a9c20e312d135c5d857f5
[ "Apache-2.0" ]
null
null
null
/** * @file base_particle_dynamics.cpp * @author Luhui Han, Chi ZHang and Xiangyu Hu * @version 0.1 */ #include "base_particle_dynamics.h" #include "base_particle_dynamics.hpp" //=============================================================================================// namespace SPH { Real GlobalStaticVariables::physical_time_ = 0.0; //=============================================================================================// void InnerIterator(size_t number_of_particles, InnerFunctor &inner_functor, Real dt) { for (size_t i = 0; i < number_of_particles; ++i) inner_functor(i, dt); } //=============================================================================================// void InnerIterator_parallel(size_t number_of_particles, InnerFunctor &inner_functor, Real dt) { parallel_for(blocked_range<size_t>(0, number_of_particles), [&](const blocked_range<size_t>& r) { for (size_t i = r.begin(); i < r.end(); ++i) { inner_functor(i, dt); } }, ap); } //=================================================================================================// void CellListIteratorSplitting(SplitCellLists& split_cell_lists, CellListFunctor& cell_list_functor, Real dt) { //forward sweeping for (size_t k = 0; k != split_cell_lists.size(); ++k) { ConcurrentCellLists& cell_lists = split_cell_lists[k]; for (size_t l = 0; l != cell_lists.size(); ++l) cell_list_functor(cell_lists[l], dt); } //backward sweeping for (size_t k = split_cell_lists.size(); k != 0; --k) { ConcurrentCellLists& cell_lists = split_cell_lists[k - 1]; for (size_t l = cell_lists.size(); l != 0; --l) cell_list_functor(cell_lists[l - 1], dt); } } //=================================================================================================// void CellListIteratorSplitting_parallel(SplitCellLists& split_cell_lists, CellListFunctor& cell_list_functor, Real dt) { //forward sweeping for (size_t k = 0; k != split_cell_lists.size(); ++k) { ConcurrentCellLists& cell_lists = split_cell_lists[k]; parallel_for(blocked_range<size_t>(0, cell_lists.size()), [&](const blocked_range<size_t>& r) { for (size_t l = r.begin(); l < r.end(); ++l) cell_list_functor(cell_lists[l], dt); }, ap); } //backward sweeping for (size_t k = split_cell_lists.size(); k >= 1; --k) { ConcurrentCellLists& cell_lists = split_cell_lists[k - 1]; parallel_for(blocked_range<size_t>(0, cell_lists.size()), [&](const blocked_range<size_t>& r) { for (size_t l = r.end(); l >= r.begin() + 1; --l) { cell_list_functor(cell_lists[l -1], dt); } }, ap); } } //=================================================================================================// void InnerIteratorSplitting(SplitCellLists& split_cell_lists, InnerFunctor &inner_functor, Real dt) { for (size_t k = 0; k != split_cell_lists.size(); ++k) { ConcurrentCellLists& cell_lists = split_cell_lists[k]; for (size_t l = 0; l != cell_lists.size(); ++l) { IndexVector& particle_indexes = cell_lists[l]->real_particle_indexes_; for (size_t i = 0; i != particle_indexes.size(); ++i) { inner_functor(particle_indexes[i], dt); } } } } //=================================================================================================// void InnerIteratorSplitting_parallel(SplitCellLists& split_cell_lists, InnerFunctor& inner_functor, Real dt) { for (size_t k = 0; k != split_cell_lists.size(); ++k) { ConcurrentCellLists& cell_lists = split_cell_lists[k]; parallel_for(blocked_range<size_t>(0, cell_lists.size()), [&](const blocked_range<size_t>& r) { for (size_t l = r.begin(); l < r.end(); ++l) { IndexVector& particle_indexes = cell_lists[l]->real_particle_indexes_; for (size_t i = 0; i < particle_indexes.size(); ++i) { inner_functor(particle_indexes[i], dt); } } }, ap); } } //=================================================================================================// void InnerIteratorSplittingSweeping(SplitCellLists& split_cell_lists, InnerFunctor& inner_functor, Real dt) { Real dt2 = dt * 0.5; //forward sweeping for (size_t k = 0; k != split_cell_lists.size(); ++k) { ConcurrentCellLists& cell_lists = split_cell_lists[k]; for (size_t l = 0; l != cell_lists.size(); ++l) { IndexVector& particle_indexes = cell_lists[l]->real_particle_indexes_; for (size_t i = 0; i != particle_indexes.size(); ++i) { inner_functor(particle_indexes[i], dt2); } } } //backward sweeping for (size_t k = split_cell_lists.size(); k != 0; --k) { ConcurrentCellLists& cell_lists = split_cell_lists[k - 1]; for (size_t l = 0; l != cell_lists.size(); ++l) { IndexVector& particle_indexes = cell_lists[l]->real_particle_indexes_; for (size_t i = particle_indexes.size(); i != 0; --i) { inner_functor(particle_indexes[i - 1], dt2); } } } } //=================================================================================================// void InnerIteratorSplittingSweeping_parallel(SplitCellLists& split_cell_lists, InnerFunctor &inner_functor, Real dt) { Real dt2 = dt * 0.5; //forward sweeping for (size_t k = 0; k != split_cell_lists.size(); ++k) { ConcurrentCellLists& cell_lists = split_cell_lists[k]; parallel_for(blocked_range<size_t>(0, cell_lists.size()), [&](const blocked_range<size_t>& r) { for (size_t l = r.begin(); l < r.end(); ++l) { IndexVector& particle_indexes = cell_lists[l]->real_particle_indexes_; for (size_t i = 0; i < particle_indexes.size(); ++i) { inner_functor(particle_indexes[i], dt2); } } }, ap); } //backward sweeping for (size_t k = split_cell_lists.size(); k != 0; --k) { ConcurrentCellLists& cell_lists = split_cell_lists[k - 1]; parallel_for(blocked_range<size_t>(0, cell_lists.size()), [&](const blocked_range<size_t>& r) { for (size_t l = r.begin(); l < r.end(); ++l) { IndexVector& particle_indexes = cell_lists[l]->real_particle_indexes_; for (size_t i = particle_indexes.size(); i != 0; --i) { inner_functor(particle_indexes[i - 1], dt2); } } }, ap); } } //=============================================================================================// } //=============================================================================================//
36.407821
102
0.540126
SoftwareImpacts
f89f10e98f3397294caa6ae1ab1a6e559ac1ed94
1,184
cpp
C++
c++/reverse_string_ii.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
c++/reverse_string_ii.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
c++/reverse_string_ii.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
/* Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original. Example: Input: s = "abcdefg", k = 2 Output: "bacdfeg" Restrictions: The string consists of lower English letters only. Length of the given string and k will in the range [1, 10000] */ /* * */ #include "helper.h" class Solution { public: string reverseStr(string s, int k) { for (int i = 0; i < s.length(); i += 2 * k) { if (i + k >= s.length()) { reverse(s.begin() + i, s.end()); } else { reverse(s.begin() + i, s.begin() + i + k); } } return s; } }; int main() { Solution s; cout << s.reverseStr("abcdefg", 2) << endl; cout << s.reverseStr("abcdefg", 12) << endl; cout << s.reverseStr("hyzqyljrnigxvdtneasepfahmtyhlohwxmkqcdfehybknvdmfrfvtbsovjbdhevlfxpdaovjgunjqlimjkfnqcqnajmebeddqsgl", 39) << endl; return 0; }
31.157895
338
0.628378
SongZhao
f8a4350b740a31d57bb5677d091a93b605ce57be
1,334
cpp
C++
Source Code V2/TssInSphere/ApplyCurls.cpp
DavidGeUSA/TSS
e364e324948c68efc6362a0db3aa51696227fa60
[ "MIT" ]
11
2020-09-27T07:35:22.000Z
2022-03-09T11:01:31.000Z
Source Code V2/TssInSphere/ApplyCurls.cpp
DavidGeUSA/TSS
e364e324948c68efc6362a0db3aa51696227fa60
[ "MIT" ]
1
2020-10-28T13:14:58.000Z
2020-10-28T21:04:44.000Z
Source Code V2/TssInSphere/ApplyCurls.cpp
DavidGeUSA/TSS
e364e324948c68efc6362a0db3aa51696227fa60
[ "MIT" ]
7
2020-09-27T07:35:24.000Z
2022-01-02T13:53:21.000Z
/******************************************************************* Author: David Ge (dge893@gmail.com, aka Wei Ge) Last modified: 03/31/2018 Allrights reserved by David Ge ********************************************************************/ #include "ApplyCurls.h" ApplyCurls::ApplyCurls() { } void ApplyCurls::SetFields(FieldPoint3D *fields, FieldPoint3D *curls, double *factorE, double *factorH) { _fields = fields; _curls = curls; _factorE = factorE; _factorH = factorH; index = 0; } void ApplyCurlsEven::handleData(int m, int n, int p) { _fields[index].E.x += *_factorE * _curls[index].E.x; _fields[index].E.y += *_factorE * _curls[index].E.y; _fields[index].E.z += *_factorE * _curls[index].E.z; _fields[index].H.x += *_factorH * _curls[index].H.x; _fields[index].H.y += *_factorH * _curls[index].H.y; _fields[index].H.z += *_factorH * _curls[index].H.z; // index++; } void ApplyCurlsOdd::handleData(int m, int n, int p) { _fields[index].E.x += *_factorH * _curls[index].H.x; _fields[index].E.y += *_factorH * _curls[index].H.y; _fields[index].E.z += *_factorH * _curls[index].H.z; _fields[index].H.x += *_factorE * _curls[index].E.x; _fields[index].H.y += *_factorE * _curls[index].E.y; _fields[index].H.z += *_factorE * _curls[index].E.z; // index++; }
30.318182
104
0.578711
DavidGeUSA
f8a48e3639f865d2ed01568a400eda4871c15f9e
1,157
cpp
C++
Solutions/FLOW015.cpp
nikramakrishnan/codechef-solutions
f7ab2199660275e972a387541ecfc24fd358e03e
[ "MIT" ]
1
2022-03-26T09:38:02.000Z
2022-03-26T09:38:02.000Z
Solutions/FLOW015.cpp
nikramakrishnan/codechef-solutions
f7ab2199660275e972a387541ecfc24fd358e03e
[ "MIT" ]
null
null
null
Solutions/FLOW015.cpp
nikramakrishnan/codechef-solutions
f7ab2199660275e972a387541ecfc24fd358e03e
[ "MIT" ]
null
null
null
/*Important notes. Read this before you read/copy my code. HINT: To determine whether a year is a leap year, follow these steps: 1.If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5. 2.If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4. 3.If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5. 4.The year is a leap year (it has 366 days). 5.The year is not a leap year (it has 365 days). Now go try writing the program again. */ #include<iostream> using namespace std; int main(){ int t,y,day; cin>>t; while(t--){ cin>>y; day=0; for(int i=1900;i<=y;i++){ if((i%400)==1) day+=2; else if((i%100)==1) day++; else if((i%4)==1) day+=2; else day++; day=(day)%7; } switch(day){ case 0: cout<<"sunday"<<endl;break; case 1: cout<<"monday"<<endl;break; case 2: cout<<"tuesday"<<endl;break; case 3: cout<<"wednesday"<<endl;break; case 4: cout<<"thursday"<<endl;break; case 5: cout<<"friday"<<endl;break; case 6: cout<<"saturday"<<endl;break; } } }
28.219512
84
0.592048
nikramakrishnan
f8a53d0a87cd66006e38d180d29989125d21774c
1,313
cpp
C++
examples/login.cpp
Sherlock92/greentop
aa278d08babe02326b3ab85a6eafb858d780dec5
[ "MIT" ]
5
2019-06-30T06:29:46.000Z
2021-12-17T12:41:23.000Z
examples/login.cpp
Sherlock92/greentop
aa278d08babe02326b3ab85a6eafb858d780dec5
[ "MIT" ]
2
2018-01-09T17:14:45.000Z
2020-03-23T00:16:50.000Z
examples/login.cpp
Sherlock92/greentop
aa278d08babe02326b3ab85a6eafb858d780dec5
[ "MIT" ]
7
2015-09-13T18:40:58.000Z
2020-01-24T10:57:56.000Z
#include <iostream> #include "greentop/ExchangeApi.h" using namespace greentop; int main(int argc, char* argv[]) { if (argc != 3 && argc != 4 && argc != 5) { std::cerr << "Usage: " << std::endl << argv[0] << " <application key> <username> <password>" << std::endl << " OR" << std::endl << argv[0] << " <username> <password> <certificate filename> <key filename>" << std::endl << " OR" << std::endl << argv[0] << " <application key> <SSO token>" << std::endl; return 1; } bool result = false; if (argc == 3) { // login has been performed by some other means eg using the "interactive login" described in the documentation. ExchangeApi exchangeApi(argv[1]); exchangeApi.setSsoid(argv[2]); // we don't know whether or not the token is valid, assume it is. result = true; } else if (argc == 4) { ExchangeApi exchangeApi(argv[1]); result = exchangeApi.login(argv[2], argv[3]); } else if (argc == 5) { ExchangeApi exchangeApi; result = exchangeApi.login(argv[1], argv[2], argv[3], argv[4]); } if (result) { std::cerr << "SUCCESS" << std::endl; } else { std::cerr << "FAILED" << std::endl; } return 0; }
32.02439
120
0.5377
Sherlock92
f8a57148fd7b220ab8f4df85c3196b2b642a64cf
212
hpp
C++
firmware/robot2015/src-ctrl/modules/task-signals.hpp
JNeiger/robocup-firmware
c1bfd4ba24070eaa4e012fdc88aa468aafcc2e4e
[ "Apache-2.0" ]
1
2018-09-25T20:28:58.000Z
2018-09-25T20:28:58.000Z
firmware/robot2015/src-ctrl/modules/task-signals.hpp
JNeiger/robocup-firmware
c1bfd4ba24070eaa4e012fdc88aa468aafcc2e4e
[ "Apache-2.0" ]
null
null
null
firmware/robot2015/src-ctrl/modules/task-signals.hpp
JNeiger/robocup-firmware
c1bfd4ba24070eaa4e012fdc88aa468aafcc2e4e
[ "Apache-2.0" ]
null
null
null
#pragma once // This is where the signals for different threads are defined for use across // mutliple files static const uint32_t MAIN_TASK_CONTINUE = 1 << 0; static const uint32_t SUB_TASK_CONTINUE = 1 << 1;
26.5
77
0.764151
JNeiger
f8a9cc3c7346fb0ae73958b08b220a47aa3a6f56
14,522
cpp
C++
ccxx/cxefile.cpp
oudream/ccxx
7746ef93b48bf44157048a43c4878152fe6a4d2b
[ "MIT" ]
39
2015-12-09T09:28:46.000Z
2021-11-16T12:57:25.000Z
ccxx/cxefile.cpp
oudream/ccxx
7746ef93b48bf44157048a43c4878152fe6a4d2b
[ "MIT" ]
1
2020-10-17T02:23:42.000Z
2020-10-17T02:23:42.000Z
ccxx/cxefile.cpp
oudream/ccxx
7746ef93b48bf44157048a43c4878152fe6a4d2b
[ "MIT" ]
8
2018-05-29T12:48:13.000Z
2022-02-27T01:45:57.000Z
#include "cxefile.h" using namespace std; const char cc_flag_line = '\n'; const char cc_flag_tab = '\t'; const char cc_flag_space = ' '; static map<string, string> f_eFileDeclare; static vector<EFileElement> f_eFileEle; static string f_eFC; static map<string,vector<string> > f_mapTableToFiledName; EFileElement::EFileElement() { clear(); } EFileElement::~EFileElement() { clear(); } EFileElement &EFileElement::operator=(const EFileElement &o) { _className = o._className; _InstanceName = o._InstanceName; _field = o._field; _rec = o._rec; _unit = o._unit; _type = o._type; return *this; } void EFileElement::clear() { _className.clear(); _InstanceName.clear(); _field.clear(); _rec.clear(); _unit.clear(); _type = ee_type_none; } vector<string> EFileElement::toEfileBuffer() { vector<string> sLines; sLines.clear(); switch(_type) { case ee_type_row: // Only Horizontal Table { string sLine; // sLine = "<" + _className + "::" + _InstanceName + ">"; sLines.push_back(sLine); // field sLine = "@"; if(_field.size()>0) { sLine.push_back(cc_flag_tab); sLine += CxString::join(_field,cc_flag_tab); } sLines.push_back(sLine); // record for (size_t i = 0; i < _rec.size(); ++i) { vector<string> rec = _rec.at(i); sLine = "#"; sLine.push_back(cc_flag_tab); sLine += CxString::join(rec,cc_flag_tab); sLines.push_back(sLine); } // end sLine = "</" + _className + "::" + _InstanceName + ">"; sLines.push_back(sLine); } break; default: break; } return sLines; } int EFileElement::fromEfileBuffer(const char *pData, int iLength) { return 0; } vector<map<string, string> > EFileElement::getRec() { vector<map<string, string> > vRecs; vRecs.clear(); // cxPrompt()<<"field size" << _field.size(); // cxPrompt()<<"_rec size" << _rec.size(); if(_field.size()==0 || _rec.size()==0 ) return vRecs; for(size_t i=0;i<_rec.size();++i) { map<string, string> map1; vector<string> rec = _rec.at(i); // cxPrompt()<<"rec size" << rec.size(); if(rec.size()!=_field.size())continue; for(size_t j=0;j<rec.size();++j) { map1[_field.at(j)] = rec.at(j); } vRecs.push_back(map1); } return vRecs; } void EFileElement::setRec(vector<map<string, string> > &vRec) { if(_field.size()==0 )return; _rec.clear(); for(size_t i=0;i<vRec.size();++i) { map<string, string> map1 = vRec.at(i); if(_field.size()!= map1.size())continue; vector<string> rec; for(size_t j=0;j<_field.size();++j) { rec.push_back(CxContainer::value(map1,_field.at(j))); } _rec.push_back(rec); } } void EFileElement::setRec2(vector<map<string, string> > &vRec) { if(vRec.size()<1) return; _field.clear(); map<string,string> map1 = vRec.at(0); for(map<string,string>::const_iterator it = map1.begin(); it != map1.end(); ++it) { // update local value _field.push_back(it->first); } if(_field.size()<1) return; _rec.clear(); for(size_t i=0;i<vRec.size();++i) { map1 = vRec.at(i); if(_field.size()!= map1.size())continue; vector<string> rec; for(size_t j=0;j<_field.size();++j) { rec.push_back(CxContainer::value(map1,_field.at(j))); } _rec.push_back(rec); } } int EFileElement::saveTable(vector<int> &columnTypes) { if(_InstanceName.length()>0 && _field.size()>0 && _rec.size()>0) { // string sTn = "t1"; // std::vector<std::string> columnNames; // columnNames.push_back("f1"); // columnNames.push_back("f2"); // std::vector<std::vector<std::string> > rows; // std::vector<std::string> row; // row.push_back("1"); // row.push_back("2"); // rows.push_back(row); // return CxDatabase::defaultDb()->saveTable(sTn, columnNames, rows); CxDatabase * oDb = CxDatabase::getDefaultDb(); return oDb ? oDb->saveTable(_InstanceName, _field, _rec) : -1; // return CxDatabase::defaultDb()->saveTable(_InstanceName, _field, _rec, columnTypes, true); } return -1; } int EFileElement::loadTable(const string &sql) { vector<map<string, string> > vRecs; CxDatabase * oDb = CxDatabase::getDefaultDb(); if (oDb) { vRecs = oDb->queryToMapVector(sql); } if(vRecs.size()>0) { setRec(vRecs); } return TRUE; } int EFileElement::loadTable2(const string &sql) { CxDatabase * oDb = CxDatabase::getDefaultDb(); vector<map<string, string> > vRecs; if (oDb) { vRecs = oDb->queryToMapVector(sql); } if(vRecs.size()>0) { setRec2(vRecs); } return TRUE; } ////////////////////////////////////////////////////////////////////////////////////////// ExplainEfile::ExplainEfile() { } bool ExplainEfile::check(const string &sFile, const string &sErr) { //need to do return false; } int ExplainEfile::explain(const char *pData, int iLength, map<string, string> &heads, map<string, string> &majors, vector<map<string, string> > &details) { return 0; } int ExplainEfile::explain(const char *pData, int iLength, map<string, string> &declare, vector<EFileElement> &vObj) { vector<string> sLines = CxString::split(string(pData, iLength), cc_flag_line); return explain(sLines,declare,vObj); } int ExplainEfile::explain(string &data, map<string, string> &declare, vector<EFileElement> &vObj) { vector<string> sLines = CxString::split(data, cc_flag_line); return explain(sLines,declare,vObj); } int ExplainEfile::explain(const vector<string> &data, map<string, string> &declare, vector<EFileElement> &vObj) { string sLine; EFileElement ee; int err = FALSE; for (size_t i = 0; i < data.size(); ++i) { sLine = CxString::trim(data.at(i)); if (sLine.empty()) continue; switch (sLine.data()[0]) { case '<':// head { if(sLine.size()<2)break; if((sLine.data()[1])=='!') // declare { string s = CxString::unquote(sLine, '!', '!'); s = CxString::trim(s); declare = CxString::splitToMap(s,'=',' '); } else if((sLine.data()[1])!='/') // class instance { string s = CxString::unquote(sLine, '<', '>'); s = CxString::trim(s); string v = CxString::token(s, "::"); ee.clear(); ee.setName(v,s); } else { vObj.push_back(ee); //end table err = TRUE; } } break; case '@':// declare { if(sLine.size()<2)break; if((sLine.data()[1])=='@')// list { } else if ((sLine.data()[1])=='#')// { } else // horizontal table { string s = sLine.substr(1, sLine.size()-1); ee.seField(CxString::split(s, cc_flag_tab)); ee.setType(EFileElement::ee_type_row); } } break; case '#': // record { if (sLine.size() > 1) { string s = sLine.substr(1, sLine.size()-1); ee.addRec(CxString::split(s, cc_flag_tab)); // ee.addRec(CxString::split(s, cc_flag_tab, true)); } } break; case '/': // { if (sLine.size() > 2) { string sComment = sLine.substr(2, sLine.size()-2); } } break; case '%':// comments { if (sLine.size() > 2) { string s = sLine.substr(2, sLine.size()-2); ee.setUnit(CxString::split(s, cc_flag_tab)); } } break; default: break; } } return err; } vector<char> ExplainEfile::toEfileBuffer(map<string, string> &heads, map<string, string> &majors, vector<map<string, string> > &details) { return vector<char>(); } vector<string> ExplainEfile::toEfileBuffer(map<string, string> &declare, vector<EFileElement> &vObj) { vector<string> sLines; string sLine; sLine = "<! "; sLine += CxString::join(declare, "=", " "); sLine += " !>"; sLines.push_back(sLine); for (size_t i = 0; i < vObj.size(); ++i) { EFileElement ee = vObj.at(i); vector<string> es = ee.toEfileBuffer(); if(es.size()>0)CxContainer::append(sLines,es); } return sLines; } int ExplainEfile::loadFromFile(const string & sFile, map<string, string> &declare, vector<EFileElement> &vObj) { int err = FALSE; vector<string> vBuff; vBuff.clear(); if(CxFile::load(sFile,vBuff,cc_flag_line)>0) { return explain(vBuff,declare,vObj); } return FALSE; } int ExplainEfile::loadFromString(const string &sBuffer, map<string, string> &declare, vector<EFileElement> &vObj) { int err = FALSE; vector<string> vBuff = CxString::split(sBuffer,"\r\n"); if(vBuff.size()>0) { err = explain(vBuff,declare,vObj); } return err; } int ExplainEfile::saveToFile(const string & sFile, map<string, string> &declare, vector<EFileElement> &vObj) { vector<string> sLines = toEfileBuffer(declare,vObj); int err = FALSE; if(sLines.size()>0) { if(CxFile::save(sFile,sLines)) { err = TRUE; } } return err; } void ExplainEfile::clear() { f_eFileDeclare.clear(); f_eFileEle.clear(); } void ExplainEfile::setFieldTemplate(map<string, vector<string> > &map1) { f_mapTableToFiledName = map1; } bool ExplainEfile::createDeclare(map<string, string> &declare) { f_eFileDeclare = declare; return true; } bool ExplainEfile::createElement_sql(const string &sClassName, const string &sInstanceName, const string &sql,const string &sFieldList) { if(sFieldList.size()<1) return false; EFileElement obj; obj.setName(sClassName,sInstanceName); obj.setType(EFileElement::ee_type_row); vector<string> vField = CxString::split(sFieldList,','); obj.seField(vField); obj.loadTable(sql); f_eFileEle.push_back(obj); return true; } bool ExplainEfile::createElement_sql(const string &sClassName, const string &sInstanceName,const string &sql) { string sKey = sClassName; if(!CxContainer::contain(f_mapTableToFiledName,sKey)) return false; EFileElement obj; obj.setName(sClassName,sInstanceName); obj.setType(EFileElement::ee_type_row); obj.seField(CxContainer::value(f_mapTableToFiledName,sKey)); obj.loadTable(sql); f_eFileEle.push_back(obj); return true; } bool ExplainEfile::createElement_row(const string &sClassName, const string &sInstanceName, const string &row) { EFileElement obj; obj.setName(sClassName,sInstanceName); obj.setType(EFileElement::ee_type_row); vector<vector<string> > v = CxString::splitToLines(row,CxGlobal::middleChar,CxGlobal::splitChar); vector<string> vField,vVale; for(int i=0;i<v.size();++i) { vector<string> vv = v.at(i); if(vv.size()!=2) continue; vField.push_back(vv.at(0)); vVale.push_back(vv.at(1)); } obj.seField(vField); obj.addRec(vVale); f_eFileEle.push_back(obj); return true; } bool ExplainEfile::createElement_rows(const string &sClassName, const string &sInstanceName, vector<string> &rows) { if(rows.size()<1) return false; EFileElement obj; obj.setName(sClassName,sInstanceName); obj.setType(EFileElement::ee_type_row); string row = rows.at(0); vector<vector<string> > v = CxString::splitToLines(row,'=',';'); vector<string> v0,v1; for(int i=0;v.size();++i) { vector<string> vv = v.at(i); if(vv.size()!=2) continue; v0.push_back(vv.at(0)); v1.push_back(vv.at(1)); } obj.seField(v0); obj.addRec(v1); for(int j=0;j<rows.size();++j) { v = CxString::splitToLines(rows.at(j),'=',';'); v1.clear(); for(int i=0;v.size();++i) { vector<string> vv = v.at(i); if(vv.size()!=2) continue; v1.push_back(vv.at(1)); } obj.addRec(v1); } f_eFileEle.push_back(obj); return true; } int ExplainEfile::toFile(const string &sFile) { vector<string> sLines = toEfileBuffer(f_eFileDeclare,f_eFileEle); int err = FALSE; if(sLines.size()>0) { if(CxFile::save(sFile,sLines,"\r\n",true)) { err = TRUE; } } return err; } string ExplainEfile::toString() { string sBuf=""; vector<string> sLines = toEfileBuffer(f_eFileDeclare,f_eFileEle); if(sLines.size()>0) { sBuf = CxString::join(sLines,"\r\n"); } return sBuf; } std::vector<string> CxEfile::toEfileBuffer(const string &sClassName, const string &sInstanceName, const std::vector<string> &sFields, const std::vector<std::vector<string> > &sRows) { vector<string> sLines; string sLine = "<! Version=1.0 System=ccxx.efile Code=utf-8 Data=1.0 !>"; sLines.push_back(sLine+"\n"); // class::instance.name sLine = "<" + sClassName + "::" + sInstanceName + ">"; sLines.push_back(sLine+"\n"); // field sLine = "@"; if(sFields.size()>0) { sLine.push_back(cc_flag_tab); sLine += CxString::join(sFields,cc_flag_tab); } sLines.push_back(sLine+"\n"); // record for (size_t i = 0; i < sRows.size(); ++i) { vector<string> sRow = sRows.at(i); sLine = "#"; sLine.push_back(cc_flag_tab); for (size_t j = 0; j < sRow.size(); ++j) { string & sValue = sRow.at(j); if (sValue.empty()) sValue.push_back('-'); } sLine += CxString::join(sRow,cc_flag_tab); sLines.push_back(sLine+"\n"); } // end sLine = "</" + sClassName + "::" + sInstanceName + ">"; sLines.push_back(sLine+"\n"); return sLines; }
24.530405
181
0.560322
oudream
f8aa775ec18740017816675bff738f4218557e71
27,050
cc
C++
src/cpp/learn/utils_test.cc
SanggunLee/edgetpu
d3cf166783265f475c1ddba5883e150ee84f7bfe
[ "Apache-2.0" ]
320
2019-09-19T07:10:48.000Z
2022-03-12T01:48:56.000Z
src/cpp/learn/utils_test.cc
Machine-Learning-Practice/edgetpu
6d699665efdc5d84944b5233223c55fe5d3bd1a6
[ "Apache-2.0" ]
563
2019-09-27T06:40:40.000Z
2022-03-31T23:12:15.000Z
src/cpp/learn/utils_test.cc
Machine-Learning-Practice/edgetpu
6d699665efdc5d84944b5233223c55fe5d3bd1a6
[ "Apache-2.0" ]
119
2019-09-25T02:51:10.000Z
2022-03-03T08:11:12.000Z
#include "src/cpp/learn/utils.h" #include <cmath> #include "absl/flags/parse.h" #include "absl/memory/memory.h" #include "absl/strings/substitute.h" #include "flatbuffers/flexbuffers.h" #include "glog/logging.h" #include "gtest/gtest.h" #include "src/cpp/basic/basic_engine.h" #include "src/cpp/error_reporter.h" #include "src/cpp/test_utils.h" #include "tensorflow/lite/schema/schema_generated.h" namespace coral { namespace learn { namespace { tflite::QuantizationParametersT* GetKernelQuant(const tflite::ModelT* model_t, int op_index) { CHECK(model_t); CHECK_EQ(model_t->subgraphs.size(), 1); auto& subgraph = model_t->subgraphs[0]; CHECK_GT(subgraph->operators.size(), op_index); auto& conv2d_op = subgraph->operators[op_index]; auto& kernel_tensor = subgraph->tensors[conv2d_op->inputs[1]]; return kernel_tensor->quantization.get(); } // Generates dummy quantization parameters for conv2d operator. // It assumes input tensor of conv2d operator has value within range [-1.0, 1.0] std::vector<std::unique_ptr<tflite::QuantizationParametersT>> GenerateQuantParamsForConv2d() { // quant_params[0] is for kernel tensor. // quant_params[1] is for bias tensor. // quant_params[2] is for output tensor. std::vector<std::unique_ptr<tflite::QuantizationParametersT>> quant_params(3); quant_params[0] = CreateQuantParam(/*min=*/{-1.0f}, /*max=*/{1.0f}, /*scale=*/{1.0f / 128}, /*zero_point=*/{128}); quant_params[1] = CreateQuantParam(/*min=*/{}, /*max=*/{}, /*scale=*/{1.0f / (128 * 128)}, /*zero_point=*/{0}); quant_params[2] = CreateQuantParam(/*min=*/{-1.0f}, /*max=*/{1.0f}, /*scale=*/{1.0f / 128}, /*zero_point=*/{128}); return quant_params; } // Builds a test graph that consists of // input_tensor // | // v // Conv2d/FC // | // v // output_tensor std::unique_ptr<tflite::ModelT> BuildTestGraph( const std::vector<int>& input_shape, const std::vector<int>& kernel_shape, const std::vector<float>& kernel) { EdgeTpuErrorReporter reporter; auto model_t = absl::make_unique<tflite::ModelT>(); model_t->description = "Hand-crafted tflite graph for testing"; // Must specify, current version is 3. model_t->version = 3; // Create sentinel buffer. internal::AppendBuffer(/*buffer_size_bytes=*/0, model_t.get()); // Create a subgraph with only input tensor. auto subgraph = absl::make_unique<tflite::SubGraphT>(); const int input_buffer_index = internal::AppendBuffer(/*buffer_size_bytes=*/0, model_t.get()); auto input_tensor_quant = CreateQuantParam(/*min=*/{-128.0f}, /*max=*/{128.0f}, /*scale=*/{1.0f}, /*zero_point=*/{128}); const int input_tensor_index = internal::AppendTensor( input_shape, /*name=*/"TestGraph/input", input_buffer_index, tflite::TensorType_UINT8, std::move(input_tensor_quant), subgraph.get()); subgraph->inputs.push_back(input_tensor_index); // Current graph output is input tensor itself. subgraph->outputs.push_back(input_tensor_index); model_t->subgraphs.push_back(std::move(subgraph)); // Add Conv2d Operator. auto conv2d_kernel_quant = CreateQuantParam(/*min=*/{-128.0f}, /*max=*/{128.0f}, /*scale=*/{1.0f}, /*zero_point=*/{128}); auto conv2d_bias_quant = CreateQuantParam(/*min=*/{}, /*max=*/{}, /*scale=*/{1.0f}, /*zero_point=*/{0}); auto conv2d_output_quant = CreateQuantParam(/*min=*/{-128.0f}, /*max=*/{128.0f}, /*scale=*/{1.0f}, /*zero_point=*/{128}); std::vector<internal::TensorConfig> tensor_configs; std::vector<int> bias_shape = {kernel_shape[0]}; const std::vector<tflite::TensorT*> output_tensors = GetGraphOutputTensors(model_t.get()); CHECK_EQ(output_tensors.size(), 1); const tflite::TensorT* current_output_tensor = output_tensors[0]; std::vector<int> output_shape = internal::CalculateLinearLayerOutputShape( current_output_tensor->shape, kernel_shape); tensor_configs.push_back({"TestGraph/Conv2d/Kernel", tflite::TensorType_UINT8, internal::TensorLocation::kParameter, kernel_shape, conv2d_kernel_quant.release()}); tensor_configs.push_back({"TestGraph/Conv2d/Bias", tflite::TensorType_INT32, internal::TensorLocation::kParameter, bias_shape, conv2d_bias_quant.release()}); tensor_configs.push_back({"TestGraph/Conv2d/Output", tflite::TensorType_UINT8, internal::TensorLocation::kOutput, output_shape, conv2d_output_quant.release()}); int conv2d_op_index; if (kernel_shape.size() == 2) { CHECK_EQ( AppendOperator(tensor_configs, tflite::BuiltinOperator_FULLY_CONNECTED, model_t.get(), &conv2d_op_index, &reporter), kEdgeTpuApiOk); } else { CHECK_EQ(AppendOperator(tensor_configs, tflite::BuiltinOperator_CONV_2D, model_t.get(), &conv2d_op_index, &reporter), kEdgeTpuApiOk); } // Set kernel value. auto* kernel_quant = GetKernelQuant(model_t.get(), conv2d_op_index); const auto quant_kernel = Quantize<uint8_t>(kernel, kernel_quant->scale[0], kernel_quant->zero_point[0]); internal::SetLinearParams(quant_kernel, /*bias=*/{}, conv2d_op_index, model_t.get()); return model_t; } // Returns pointer to graph input tensor. It assumes that there is only one // input to the graph. tflite::TensorT* GetGraphInputTensor(const tflite::ModelT* model_t) { CHECK(model_t); CHECK_EQ(model_t->subgraphs.size(), 1); const auto& subgraph = model_t->subgraphs[0]; // Get current graph input. const auto& graph_inputs = subgraph->inputs; CHECK_EQ(graph_inputs.size(), 1); const int graph_input_tensor_index = graph_inputs[0]; VLOG(1) << "Graph input tensor index: " << graph_input_tensor_index; const auto& graph_input_tensor = subgraph->tensors[graph_input_tensor_index]; return graph_input_tensor.get(); } // Runs inference with ModelT as input type. std::vector<float> RunInference(const tflite::ModelT* model_t, const std::vector<float>& input_tensor) { // Finish building flat buffer. auto fbb = GetFlatBufferBuilder(model_t); auto flat_buffer_model = tflite::FlatBufferModel::BuildFromBuffer( reinterpret_cast<const char*>(fbb->GetBufferPointer()), fbb->GetSize()); BasicEngine basic_engine(std::move(flat_buffer_model)); const tflite::TensorT* graph_input_tensor = GetGraphInputTensor(model_t); const auto& q_param = graph_input_tensor->quantization; const auto q_input_tensor = Quantize<uint8_t>(input_tensor, q_param->scale[0], q_param->zero_point[0]); std::vector<std::vector<float>> results = basic_engine.RunInference(q_input_tensor); CHECK_EQ(results.size(), 1); std::vector<float> result = results[0]; int result_size = result.size(); VLOG(1) << "result_size: " << result_size; for (int i = 0; i < result_size; ++i) { VLOG(1) << "index: " << i << " value: " << result[i]; } return result; } std::unique_ptr<tflite::ModelT> LoadModel(const std::string& model_path) { std::string input_model_content; EdgeTpuErrorReporter error_reporter; CHECK_EQ(ReadFile(model_path, &input_model_content, &error_reporter), kEdgeTpuApiOk) << error_reporter.message(); const tflite::Model* model = tflite::GetModel(input_model_content.data()); CHECK(model); return absl::WrapUnique<tflite::ModelT>(model->UnPack()); } TEST(UtilsTest, BuildConvTestGrapAndRunInference) { const std::vector<float> kernel = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // kernel 1 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, // kernel 2 }; auto model_t = BuildTestGraph(/*input_shape=*/{1, 1, 1, 5}, /*kernel_shape=*/{2, 1, 1, 5}, kernel); EXPECT_EQ(model_t->subgraphs.size(), 1); EXPECT_EQ(model_t->subgraphs[0]->operators.size(), 1); const auto result = RunInference( model_t.get(), /*input_tensor=*/{1.0f, 2.0f, 3.0f, 4.0f, 5.0f}); EXPECT_EQ(2, result.size()); EXPECT_NEAR(15.0f, result[0], 0.01); EXPECT_NEAR(55.0f, result[1], 0.01); } TEST(UtilsTest, BuildFCTestGrapAndRunInference) { const std::vector<float> kernel = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // kernel 1 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, // kernel 2 }; auto model_t = BuildTestGraph(/*input_shape=*/{1, 5}, /*kernel_shape=*/{2, 5}, kernel); EXPECT_EQ(model_t->subgraphs.size(), 1); EXPECT_EQ(model_t->subgraphs[0]->operators.size(), 1); const auto result = RunInference( model_t.get(), /*input_tensor=*/{1.0f, 2.0f, 3.0f, 4.0f, 5.0f}); EXPECT_EQ(2, result.size()); EXPECT_NEAR(15.0f, result[0], 0.01); EXPECT_NEAR(55.0f, result[1], 0.01); } TEST(UtilsTest, AppendL2Norm) { const std::vector<float> kernel = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // kernel 1 -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, // kernel 2 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, // kernel 3 }; auto model_t = BuildTestGraph(/*input_shape=*/{1, 1, 1, 5}, /*kernel_shape=*/{3, 1, 1, 5}, kernel); EdgeTpuErrorReporter error_reporter; int op_index; ASSERT_EQ(kEdgeTpuApiOk, internal::AppendL2Norm(model_t.get(), &op_index, &error_reporter)); EXPECT_EQ(1, op_index); EXPECT_EQ(2, model_t->subgraphs[0]->operators.size()); const auto result = RunInference( model_t.get(), /*input_tensor=*/{1.0f, 2.0f, 3.0f, 4.0f, 5.0f}); EXPECT_EQ(3, result.size()); EXPECT_NEAR(1 / std::sqrt(11.0f), result[0], 0.01); EXPECT_NEAR(-1 / std::sqrt(11.0f), result[1], 0.01); EXPECT_NEAR(3 / std::sqrt(11.0f), result[2], 0.01); } TEST(UtilsTest, AppendConv2dLayer) { const std::vector<float> kernel = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // kernel 1 -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, // kernel 2 }; auto model_t = BuildTestGraph(/*input_shape=*/{1, 1, 1, 5}, /*kernel_shape=*/{2, 1, 1, 5}, kernel); EdgeTpuErrorReporter error_reporter; int op_index; ASSERT_EQ(kEdgeTpuApiOk, internal::AppendL2Norm(model_t.get(), &op_index, &error_reporter)); ASSERT_EQ(kEdgeTpuApiOk, internal::AppendLinearLayer( /*kernel_shape=*/{4, 1, 1, 2}, GenerateQuantParamsForConv2d(), model_t.get(), &op_index, &error_reporter)); ASSERT_EQ(2, op_index); // Set weights for fully-connected layer. const std::vector<float>& fc_weights = { std::sqrt(2.0f) / 2, -std::sqrt(2.0f) / 2, // kernel 1 std::sqrt(2.0f) / 2, std::sqrt(2.0f) / 2, // kernel 2 std::sqrt(7.0f) / 4, 3.0f / 4, // kernel 3 std::sqrt(5.0f) / 3, 2.0f / 3, // kernel 4 }; auto* conv_weights_quant = GetKernelQuant(model_t.get(), op_index); const auto quant_conv_weights = Quantize<uint8_t>(fc_weights, conv_weights_quant->scale[0], conv_weights_quant->zero_point[0]); internal::SetLinearParams(quant_conv_weights, /*bias=*/{}, op_index, model_t.get()); EXPECT_EQ(model_t->subgraphs[0]->operators.size(), 3); const auto result = RunInference( model_t.get(), /*input_tensor=*/{1.0f, 2.0f, 3.0f, 4.0f, 5.0f}); // output tensor of L2Norm layer is [sqrt(2)/2, -sqrt(2)/2], with above // `fc_weights`, result is expected to be: // [1, 0, (sqrt(14)-sqrt(18))/8, (sqrt(10)-sqrt(8))/6] EXPECT_EQ(4, result.size()); EXPECT_NEAR(1.0f, result[0], 0.01); EXPECT_NEAR(0.0f, result[1], 0.01); EXPECT_NEAR((std::sqrt(14.0f) - std::sqrt(18.0f)) / 8, result[2], 0.01); EXPECT_NEAR((std::sqrt(10.0f) - std::sqrt(8.0f)) / 6, result[3], 0.01); } TEST(UtilsTest, AppendFullyConnectedLayer) { const std::vector<float> kernel = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // kernel 1 -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, // kernel 2 }; auto model_t = BuildTestGraph(/*input_shape=*/{1, 5}, /*kernel_shape=*/{2, 5}, kernel); EdgeTpuErrorReporter error_reporter; int op_index; ASSERT_EQ(kEdgeTpuApiOk, internal::AppendL2Norm(model_t.get(), &op_index, &error_reporter)); ASSERT_EQ(kEdgeTpuApiOk, internal::AppendLinearLayer( /*kernel_shape=*/{4, 2}, GenerateQuantParamsForConv2d(), model_t.get(), &op_index, &error_reporter)); ASSERT_EQ(2, op_index); // Set weights for fully-connected layer. const std::vector<float>& fc_weights = { std::sqrt(2.0f) / 2, -std::sqrt(2.0f) / 2, // kernel 1 std::sqrt(2.0f) / 2, std::sqrt(2.0f) / 2, // kernel 2 std::sqrt(7.0f) / 4, 3.0f / 4, // kernel 3 std::sqrt(5.0f) / 3, 2.0f / 3, // kernel 4 }; auto* fc_weights_quant = GetKernelQuant(model_t.get(), op_index); const auto quant_fc_weights = Quantize<uint8_t>( fc_weights, fc_weights_quant->scale[0], fc_weights_quant->zero_point[0]); internal::SetLinearParams(quant_fc_weights, /*bias=*/{}, op_index, model_t.get()); EXPECT_EQ(model_t->subgraphs[0]->operators.size(), 3); const auto result = RunInference( model_t.get(), /*input_tensor=*/{1.0f, 2.0f, 3.0f, 4.0f, 5.0f}); // output tensor of L2Norm layer is [sqrt(2)/2, -sqrt(2)/2], with above // `fc_weights`, result is expected to be: // [1, 0, (sqrt(14)-sqrt(18))/8, (sqrt(10)-sqrt(8))/6] EXPECT_EQ(4, result.size()); EXPECT_NEAR(1.0f, result[0], 0.01); EXPECT_NEAR(0.0f, result[1], 0.01); EXPECT_NEAR((std::sqrt(14.0f) - std::sqrt(18.0f)) / 8, result[2], 0.01); EXPECT_NEAR((std::sqrt(10.0f) - std::sqrt(8.0f)) / 6, result[3], 0.01); } TEST(UtilsTest, AppendReshape) { const std::vector<float> kernel = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // kernel 1 -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, // kernel 2 }; auto model_t = BuildTestGraph(/*input_shape=*/{1, 1, 1, 5}, /*kernel_shape=*/{2, 1, 1, 5}, kernel); EdgeTpuErrorReporter error_reporter; int op_index; ASSERT_EQ(kEdgeTpuApiOk, internal::AppendL2Norm(model_t.get(), &op_index, &error_reporter)); ASSERT_EQ(kEdgeTpuApiOk, internal::AppendLinearLayer( /*kernel_shape=*/{4, 1, 1, 2}, GenerateQuantParamsForConv2d(), model_t.get(), &op_index, &error_reporter)); const auto conv_op_index = op_index; ASSERT_EQ(kEdgeTpuApiOk, internal::AppendReshape(model_t.get(), &op_index, &error_reporter)); ASSERT_EQ(3, op_index); // Set weights for fully-connected layer. const std::vector<float>& conv_weights = { std::sqrt(2.0f) / 2, -std::sqrt(2.0f) / 2, // kernel 1 std::sqrt(2.0f) / 2, std::sqrt(2.0f) / 2, // kernel 2 std::sqrt(7.0f) / 4, 3.0f / 4, // kernel 3 std::sqrt(5.0f) / 3, 2.0f / 3, // kernel 4 }; auto* conv_weights_quant = GetKernelQuant(model_t.get(), conv_op_index); const auto quant_conv_weights = Quantize<uint8_t>(conv_weights, conv_weights_quant->scale[0], conv_weights_quant->zero_point[0]); internal::SetLinearParams(quant_conv_weights, /*bias=*/{}, conv_op_index, model_t.get()); ASSERT_EQ(model_t->subgraphs[0]->operators.size(), 4); // Check graph's output tensor's shape. const std::vector<tflite::TensorT*> output_tensors = GetGraphOutputTensors(model_t.get()); ASSERT_EQ(output_tensors.size(), 1); const tflite::TensorT* current_output_tensor = output_tensors[0]; ASSERT_EQ(current_output_tensor->shape.size(), 2); EXPECT_EQ(current_output_tensor->shape[0], 1); EXPECT_EQ(current_output_tensor->shape[1], 4); const auto result = RunInference( model_t.get(), /*input_tensor=*/{1.0f, 2.0f, 3.0f, 4.0f, 5.0f}); // output tensor of L2Norm layer is [sqrt(2)/2, -sqrt(2)/2], with above // `fc_weights`, result is expected to be: // [1, 0, (sqrt(14)-sqrt(18))/8, (sqrt(10)-sqrt(8))/6] ASSERT_EQ(4, result.size()); EXPECT_NEAR(1.0f, result[0], 0.01); EXPECT_NEAR(0.0f, result[1], 0.01); EXPECT_NEAR((std::sqrt(14.0f) - std::sqrt(18.0f)) / 8, result[2], 0.01); EXPECT_NEAR((std::sqrt(10.0f) - std::sqrt(8.0f)) / 6, result[3], 0.01); } TEST(UtilsTest, AppendSoftmax) { const std::vector<float> kernel = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // kernel 1 -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, // kernel 2 }; auto model_t = BuildTestGraph(/*input_shape=*/{1, 1, 1, 5}, /*kernel_shape=*/{2, 1, 1, 5}, kernel); EdgeTpuErrorReporter error_reporter; int op_index; ASSERT_EQ(kEdgeTpuApiOk, internal::AppendL2Norm(model_t.get(), &op_index, &error_reporter)); ASSERT_EQ(kEdgeTpuApiOk, internal::AppendLinearLayer( /*kernel_shape=*/{4, 1, 1, 2}, GenerateQuantParamsForConv2d(), model_t.get(), &op_index, &error_reporter)); const auto fc_op_index = op_index; ASSERT_EQ(kEdgeTpuApiOk, internal::AppendReshape(model_t.get(), &op_index, &error_reporter)); ASSERT_EQ(kEdgeTpuApiOk, internal::AppendSoftmax(model_t.get(), &op_index, &error_reporter)); ASSERT_EQ(4, op_index); // Set weights for fully-connected layer. const std::vector<float>& fc_weights = { std::sqrt(2.0f) / 2, -std::sqrt(2.0f) / 2, // kernel 1 std::sqrt(2.0f) / 2, std::sqrt(2.0f) / 2, // kernel 2 std::sqrt(7.0f) / 4, 3.0f / 4, // kernel 3 std::sqrt(5.0f) / 3, 2.0f / 3, // kernel 4 }; auto* fc_weights_quant = GetKernelQuant(model_t.get(), fc_op_index); const auto quant_fc_weights = Quantize<uint8_t>( fc_weights, fc_weights_quant->scale[0], fc_weights_quant->zero_point[0]); internal::SetLinearParams(quant_fc_weights, /*bias=*/{}, fc_op_index, model_t.get()); EXPECT_EQ(model_t->subgraphs[0]->operators.size(), 5); const auto result = RunInference( model_t.get(), /*input_tensor=*/{1.0f, 2.0f, 3.0f, 4.0f, 5.0f}); ASSERT_EQ(4, result.size()); // Result after Fully-connect layer is: // [1, 0, (sqrt(14)-sqrt(18))/8, (sqrt(10)-sqrt(8))/6] std::vector<float> unnormalized_results = { std::exp(1.0f), std::exp(0.0f), std::exp((std::sqrt(14.0f) - std::sqrt(18.0f)) / 8), std::exp((std::sqrt(10.0f) - std::sqrt(8.0f)) / 6)}; float sum = 0; for (const auto& r : unnormalized_results) { sum += r; } EXPECT_NEAR(unnormalized_results[0] / sum, result[0], 0.01); EXPECT_NEAR(unnormalized_results[1] / sum, result[1], 0.01); EXPECT_NEAR(unnormalized_results[2] / sum, result[2], 0.01); EXPECT_NEAR(unnormalized_results[3] / sum, result[3], 0.01); } // Test finding operators with a real model. TEST(UtilsTest, FindOperators) { const std::string& model_path = TestDataPath("mobilenet_v1_1.0_224_quant.tflite"); const auto model_t = LoadModel(model_path); const tflite::BuiltinOperator target_op = tflite::BuiltinOperator_CONV_2D; const auto& conv_op_indices = FindOperators(target_op, model_t.get()); EXPECT_EQ( std::vector<int>({0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28}), conv_op_indices); } // Test finding a single operator with a real model. TEST(UtilsTest, FindSingleOperator) { const std::string& model_path = TestDataPath("mobilenet_v1_1.0_224_quant.tflite"); const auto model_t = LoadModel(model_path); EXPECT_EQ(30, FindSingleOperator(tflite::BuiltinOperator_SOFTMAX, model_t.get())); EXPECT_EQ(-1, FindSingleOperator(tflite::BuiltinOperator_LSTM, model_t.get())); EXPECT_EQ(-1, FindSingleOperator(tflite::BuiltinOperator_DEPTHWISE_CONV_2D, model_t.get())); } // Test finding operators given input tensor with a real model. TEST(UtilsTest, FindOperatorsWithInput) { const std::string& model_path = TestDataPath("mobilenet_v1_1.0_224_quant.tflite"); const auto model_t = LoadModel(model_path); const tflite::BuiltinOperator target_op = tflite::BuiltinOperator_CONV_2D; // Use MobilenetV1/MobilenetV1/Conv2d_8_depthwise/Relu6 as input tensor. const int input_tensor_index = 75; const int base_op_index = 0; const std::vector<int> conv_op_indices = FindOperatorsWithInput( target_op, input_tensor_index, model_t.get(), base_op_index); EXPECT_EQ(std::vector<int>({16}), conv_op_indices); } // Test finding a single operator given input tensor with a real model. TEST(UtilsTest, FindSingleOperatorWithInput) { const std::string& model_path = TestDataPath("mobilenet_v1_1.0_224_quant.tflite"); const auto model_t = LoadModel(model_path); // Use MobilenetV1/Logits/SpatialSqueeze as input tensor. const int input_tensor_index = 4; const int base_op_index = 0; const int softmax_op_index = FindSingleOperatorWithInput( tflite::BuiltinOperator_SOFTMAX, input_tensor_index, model_t.get(), base_op_index); EXPECT_EQ(30, softmax_op_index); const int nonexist_op_index = FindSingleOperatorWithInput( tflite::BuiltinOperator_LSTM, input_tensor_index, model_t.get(), base_op_index); EXPECT_EQ(-1, nonexist_op_index); } TEST(UtilsTest, AppendFullyConnectedAndSoftmaxLayerToModelInvalidInputFilePath) { const std::string& in_model_path = TestDataPath("invalid_path.tflite"); const std::string out_model_path = coral::GetTempPrefix() + "/retrained_model_edgetpu.tflite"; const int embedding_vector_dim = 1024; std::vector<float> weights(embedding_vector_dim * 3, 0.0f); std::vector<float> biases(3, 0.0f); const float out_tensor_min = -1.0f; const float out_tensor_max = 1.0f; EdgeTpuErrorReporter reporter; ASSERT_EQ(AppendFullyConnectedAndSoftmaxLayerToModel( in_model_path, out_model_path, weights.data(), weights.size(), biases.data(), biases.size(), out_tensor_min, out_tensor_max, &reporter), kEdgeTpuApiError); const std::string& expected_message = absl::Substitute("Failed to open file: $0", in_model_path); EXPECT_EQ(reporter.message(), expected_message); } class UtilsRealModelTest : public ::testing::TestWithParam<bool> { protected: void SetUp() override { tpu_tflite_ = GetParam(); } std::string GenerateModelPath(const std::string& file_name) { return tpu_tflite_ ? file_name + "_edgetpu.tflite" : file_name + ".tflite"; } bool tpu_tflite_ = false; std::string input_model_name_; void TestAppendFullyConnectedAndSoftmaxLayerToModel( const std::string& in_model_path, const std::string& out_model_path) { BasicEngine in_model_engine(in_model_path); const auto& input_tensor_shape = in_model_engine.get_input_tensor_shape(); std::vector<uint8_t> random_input = GetRandomInput( input_tensor_shape[1] * input_tensor_shape[2] * input_tensor_shape[3]); const auto& in_model_results = in_model_engine.RunInference(random_input); ASSERT_EQ(1, in_model_results.size()); const auto& in_model_result = in_model_results[0]; const int embedding_vector_dim = in_model_engine.get_all_output_tensors_sizes()[0]; float embedding_vector_sum = 0.0f; for (int i = 0; i < embedding_vector_dim; ++i) { embedding_vector_sum += in_model_result[i]; } // Generates dummy weights, of dimension embedding_vector_dim x 3. Each // kernel has the following pattern (times a scalar to make max logits score // = 1) : Kernel 1: 1, 1, 1, ... Kernel 2: 2, 2, 2, ... kernel 3: 3, 3, 3, // ... std::vector<float> weights(embedding_vector_dim * 3); const float scalar = 1 / (embedding_vector_sum * 3); std::fill(weights.begin(), weights.begin() + embedding_vector_dim, scalar); std::fill(weights.begin() + embedding_vector_dim, weights.begin() + embedding_vector_dim * 2, scalar * 2); std::fill(weights.begin() + embedding_vector_dim * 2, weights.begin() + embedding_vector_dim * 3, scalar * 3); std::vector<float> biases(3, 0.0f); std::vector<float> expected_fc_output = {embedding_vector_sum * scalar, embedding_vector_sum * scalar * 2, embedding_vector_sum * scalar * 3}; const float out_tensor_min = *std::min_element(expected_fc_output.begin(), expected_fc_output.end()); const float out_tensor_max = *std::max_element(expected_fc_output.begin(), expected_fc_output.end()); EdgeTpuErrorReporter reporter; ASSERT_EQ(AppendFullyConnectedAndSoftmaxLayerToModel( in_model_path, out_model_path, weights.data(), weights.size(), biases.data(), biases.size(), out_tensor_min, out_tensor_max, &reporter), kEdgeTpuApiOk); BasicEngine out_model_engine(out_model_path); const auto& out_model_results = out_model_engine.RunInference(random_input); ASSERT_EQ(1, out_model_results.size()); const auto& out_model_result = out_model_results[0]; // Calculate expected value. std::vector<float> expected = expected_fc_output; float max_score = *std::max_element(expected.begin(), expected.end()); // Subtract max_score to avoid overflow. for (auto& e : expected) { e -= max_score; } float exp_sum = 0.0; for (auto& e : expected) { e = std::exp(e); exp_sum += e; } for (auto& e : expected) { e /= exp_sum; } ASSERT_EQ(3, out_model_result.size()); const float tol = 5e-3; for (int i = 0; i < expected.size(); ++i) { EXPECT_NEAR(expected[i], out_model_result[i], tol); } } }; TEST_P(UtilsRealModelTest, AppendConv2dAndSoftmaxLayerToModel) { const std::string& in_model_path = TestDataPath( GenerateModelPath("mobilenet_v1_1.0_224_quant_embedding_extractor")); const std::string out_model_path = coral::GetTempPrefix() + "/" + GenerateModelPath("retrained_conv_model"); TestAppendFullyConnectedAndSoftmaxLayerToModel(in_model_path, out_model_path); } TEST_P(UtilsRealModelTest, AppendFullyConnectedAndSoftmaxLayerToModel) { const std::string& in_model_path = TestDataPath( GenerateModelPath("efficientnet-edgetpu-S_quant_embedding_extractor")); const std::string out_model_path = coral::GetTempPrefix() + "/" + GenerateModelPath("retrained_fc_model"); TestAppendFullyConnectedAndSoftmaxLayerToModel(in_model_path, out_model_path); } INSTANTIATE_TEST_CASE_P(UtilsRealModelTest, UtilsRealModelTest, ::testing::Values(false, true)); } // namespace } // namespace learn } // namespace coral int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); absl::ParseCommandLine(argc, argv); return RUN_ALL_TESTS(); }
42.265625
80
0.647763
SanggunLee
f8ab1ef69e0673149c22f655a1e406346603a62a
1,936
ipp
C++
include/dracosha/validator/detail/member_helper.ipp
evgeniums/cpp-validator
e4feccdce19c249369ddb631571b60613926febd
[ "BSL-1.0" ]
27
2020-09-18T13:45:33.000Z
2022-03-16T21:14:37.000Z
include/dracosha/validator/detail/member_helper.ipp
evgeniums/cpp-validator
e4feccdce19c249369ddb631571b60613926febd
[ "BSL-1.0" ]
7
2020-08-07T21:48:14.000Z
2021-01-14T12:25:37.000Z
include/dracosha/validator/detail/member_helper.ipp
evgeniums/cpp-validator
e4feccdce19c249369ddb631571b60613926febd
[ "BSL-1.0" ]
1
2021-03-30T09:17:58.000Z
2021-03-30T09:17:58.000Z
/** @copyright Evgeny Sidorov 2020 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ /****************************************************************************/ /** @file validator/detail/member_helper.ipp * * Defines helpers to invoke member methods. * */ /****************************************************************************/ #ifndef DRACOSHA_VALIDATOR_MEMBER_HELPER_IPP #define DRACOSHA_VALIDATOR_MEMBER_HELPER_IPP #include <dracosha/validator/config.hpp> #include <dracosha/validator/member.hpp> #include <dracosha/validator/member_with_name.hpp> DRACOSHA_VALIDATOR_NAMESPACE_BEGIN namespace detail { template <typename T1> template <typename MemberT> auto member_helper_1arg_t<T1,hana::when< ( std::is_constructible<concrete_phrase,T1>::value && !hana::is_a<operator_tag,T1> ) >>::operator () ( MemberT&& member, T1&& name ) const { return make_member_with_name(std::forward<MemberT>(member),std::forward<T1>(name)); } template <typename T1, typename T2> template <typename MemberT> auto member_helper_2args_t<T1,T2,hana::when<std::is_enum<std::decay_t<T2>>::value>>::operator () ( MemberT&& member, T1&& name, T2&& grammar_category ) const { return make_member_with_name(std::forward<MemberT>(member),concrete_phrase(std::forward<T1>(name),std::forward<T2>(grammar_category))); } template <typename ... Args> template <typename MemberT> auto member_helper_t<Args...>::operator () ( MemberT&& member, Args&&... args ) const { return make_member_with_name(std::forward<MemberT>(member),concrete_phrase(std::forward<Args>(args)...)); } } DRACOSHA_VALIDATOR_NAMESPACE_END #endif // DRACOSHA_VALIDATOR_MEMBER_HELPER_IPP
25.473684
139
0.627066
evgeniums
f8abf6fa7f6156c5588988b2f3e8d6d0c56b2cfa
259
hpp
C++
Classes/Fish.hpp
1994/AvoidTuitle
6d9a37e2bf799efb299ae415afd2b22f6f9280be
[ "MIT" ]
null
null
null
Classes/Fish.hpp
1994/AvoidTuitle
6d9a37e2bf799efb299ae415afd2b22f6f9280be
[ "MIT" ]
null
null
null
Classes/Fish.hpp
1994/AvoidTuitle
6d9a37e2bf799efb299ae415afd2b22f6f9280be
[ "MIT" ]
null
null
null
// // Fish.hpp // seven // // Created by rimi on 15/6/12. // // #ifndef Fish_cpp #define Fish_cpp #include <stdio.h> #include "cocos2d.h" USING_NS_CC; class Fish:public Sprite { public: static Sprite * createFish(int type); }; #endif /* Fish_cpp */
12.333333
41
0.648649
1994
f8ac710dbc05ff317d36287456057ad5add0a544
448
cpp
C++
codeforces/edu94/str_sim.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
codeforces/edu94/str_sim.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
codeforces/edu94/str_sim.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
//#define _GLIBCXX_DEBUG #include <iostream> #include <cassert> #include <cstring> #include <vector> #include <algorithm> #include <string> using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while(t--){ int n; cin >> n; string s; cin >> s; for(int i=0 ; i<n ; i++) cout << s[n-1]; cout << "\n"; } return 0; }
16
37
0.513393
udayan14
f8acf57b80159041d0f4a9587836e99a603f06a5
4,567
cpp
C++
Client/AudioInterface.cpp
DylanWalseth/RTSLab8
d08049ef3bc876dfc16774f6f5d0e840e075be81
[ "MIT" ]
null
null
null
Client/AudioInterface.cpp
DylanWalseth/RTSLab8
d08049ef3bc876dfc16774f6f5d0e840e075be81
[ "MIT" ]
null
null
null
Client/AudioInterface.cpp
DylanWalseth/RTSLab8
d08049ef3bc876dfc16774f6f5d0e840e075be81
[ "MIT" ]
null
null
null
/* * AudioInterface.cpp * * Created on: Apr 18, 2015 * Author: Walter Schilling * This is the implementation of the audio Interface. It will manage the system. */ #include "AudioInterface.h" /** * This is the constructor for the class. It will instantiate a new instance of the class. * @param deviceName This is the name of the device. A typical name might be "plughw:1" * @param samplingRate This is the sampling rate for the audio sampls. Typical rates are 11000, 22050, and 44100. * @param channels This is the number of channels. Typically this is 1 or 2. * @param direction This is the direction. It is either SND_PCM_STREAM_CAPTURE or SND_PCM_STREAM_PLAYBACK */ AudioInterface::AudioInterface(char* deviceName, unsigned int samplingRate, int channels, snd_pcm_stream_t direction) { // Determine the length of the device name and allocate memory for it. int deviceLength = strlen(deviceName); this->deviceName = (char*) malloc(deviceLength + 1); // Initialize the buffer with the device name. strcpy(this->deviceName, deviceName); this->samplingRate = samplingRate; this->channels = channels; this->direction = direction; this->handle = NULL; this->params = NULL; frames = DEFAULT_FRAME_SIZE; } /** * This is the destructor. It will clear all allocated space. */ AudioInterface::~AudioInterface() { free(this->deviceName); } /** * This method will close the given device so it is no longer accessible. */ void AudioInterface::close() { // close the hardware we are connected to. snd_pcm_drain(handle); snd_pcm_close(handle); } /** * This method will open the given device so that it can be accessed. */ void AudioInterface::open() { int rc; // This variable is to be used to store the return code from various calls. int dir; /* Open PCM device. */ snd_pcm_open(&handle, this->deviceName, this->direction, 0); /* Allocate a hardware parameters object. */ snd_pcm_hw_params_alloca(&params); /* Fill it in with default values. */ snd_pcm_hw_params_any(handle, params); /* Set the desired hardware parameters. */ /* Interleaved mode */ snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED); /* Signed 16-bit little-endian format */ snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_S16_LE); /* Two channels (stereo) */ snd_pcm_hw_params_set_channels(handle, params, this->channels); // Set the sampling rate appropriately. snd_pcm_hw_params_set_rate_near(handle, params, &(this->samplingRate), &dir); /* Set period size to the given number of frames. */ snd_pcm_hw_params_set_period_size_near(handle, params, &frames, &dir); /* Write the parameters to the driver */ rc = snd_pcm_hw_params(handle, params); if (rc < 0) { fprintf(stderr, "unable to set hw parameters: %s\n", snd_strerror(rc)); exit(1); } } /** * This method will determine, based upon the size of each frame and the number of frames between interrupts the required size of the buffer that is to store the data. * @return */ int AudioInterface::getRequiredBufferSize() { int dir; int size; snd_pcm_hw_params_get_period_size(params, &frames, &dir); size = frames * this->channels * 2; /* 2 bytes/sample */ return size; } /** * This method will read data from the given sound device into the buffer. * @param buffer This is a pointer to a buffer that is to be written into. The calee is responsible for providing this buffer. The buffer must be the isze calculated by the getRequiredBufferisze() method. * @return The return will be the number of bytes written into the buffer. */ int AudioInterface::read(char* buffer) { return snd_pcm_readi(handle, buffer, frames); } /** * This method will write data to the soundcard for playback. * @param buffer This is the buffer that is to be written. It must be of size getRequiredBufferisze(). * @param bufferLength This is the number of valid entries in the buffer. */ void AudioInterface::write(char* buffer, int bufferLength) { int rc; // This variable is to be used to store the return code from various calls. int frames = bufferLength / (2 * this->channels); if (bufferLength > 0) { // Write the data to the soundcard. rc = snd_pcm_writei(this->handle, buffer, frames); if (rc == -EPIPE) { /* EPIPE means underrun */ fprintf(stderr, "underrun occurred\n"); snd_pcm_prepare(this->handle); } else if (rc < 0) { fprintf(stderr, "error from writei: %s\n", snd_strerror(rc)); } else if (rc != (int) frames) { fprintf(stderr, "short write, write %d frames\n", rc); } } }
33.580882
206
0.722794
DylanWalseth
f8af877885d6c04d94b7f300a55536bbf663bb09
1,446
cpp
C++
HAPI_Start/TileMap.cpp
DamienHenderson/GEC-Engine
8d1e89c3dc35adaf65e84de2594c715c600e4681
[ "MIT" ]
null
null
null
HAPI_Start/TileMap.cpp
DamienHenderson/GEC-Engine
8d1e89c3dc35adaf65e84de2594c715c600e4681
[ "MIT" ]
null
null
null
HAPI_Start/TileMap.cpp
DamienHenderson/GEC-Engine
8d1e89c3dc35adaf65e84de2594c715c600e4681
[ "MIT" ]
null
null
null
#include "TileMap.hpp" TileMap::TileMap(const HAPISPACE::CHapiXMLNode& node) { } TileMap::~TileMap() { } void TileMap::Load(const HAPISPACE::CHapiXMLNode & node, Visualisation& vis) { int x_chunks{ 0 }, y_chunks{ 0 }; for (auto& attrib : node.GetAttributes()) { if (attrib.GetName() == "x_chunks") { x_chunks = attrib.AsInt(); } else if (attrib.GetName() == "y_chunks") { y_chunks = attrib.AsInt(); } } chunks_.resize(y_chunks); for (auto& row : chunks_) { row.resize(x_chunks); } for (auto& iter : node.GetChildren()) { if (iter->GetName() == "TileDefs") { // g_tile_defs.LoadDefinitions(*iter); } if (iter->GetName() == "Chunk") { s32 x{ 0 }, y{ 0 }; for (auto& attrib : iter->GetAttributes()) { if (attrib.GetName() == "x") { x = attrib.AsInt(); } if (attrib.GetName() == "y") { y = attrib.AsInt(); } } chunks_[y][x].Load(*iter); std::stringstream ss; ss << "Chunk_" << x << "_" << y; chunks_[y][x].GenerateChunkSprite(vis, ss.str()); } } } void TileMap::Render(Visualisation & vis) { for (auto& row : chunks_) { for (auto& column : row) { column.Render(vis); } } } TileDefinition TileMap::GetTileDefinition(const vec2<f32>& pos) const { for (auto& row : chunks_) { for (auto& column : row) { if (column.Contains(pos)) { return column.GetTileDefinition(pos); } } } return TileDefinition(); }
16.247191
76
0.582296
DamienHenderson
f8b65a0dbc3a2a7deb80efd896e132f219e3831a
1,809
cpp
C++
gfg-DSA/linear-recurrence.cpp
shashankkmciv18/dsa
6feba269292d95d36e84f1adb910fe2ed5467f71
[ "MIT" ]
54
2020-07-31T14:50:23.000Z
2022-03-14T11:03:02.000Z
gfg-DSA/linear-recurrence.cpp
SahilMund/dsa
a94151b953b399ea56ff50cf30dfe96100e8b9a7
[ "MIT" ]
null
null
null
gfg-DSA/linear-recurrence.cpp
SahilMund/dsa
a94151b953b399ea56ff50cf30dfe96100e8b9a7
[ "MIT" ]
30
2020-08-15T17:39:02.000Z
2022-03-10T06:50:18.000Z
// Linear Recurrence Method for calculating high order numbers like // F(100) in fibonacci series. // Steps to Proceed : // Step 1: Determine K, the number of terms F(i) depends. // Ex- K=2 for fibonacci series i.e F(i) = F(i-1) +F(i-2) // Step: 2 Determine initial values i.e F(1) and F(2) // Ex- In fibonacci series, F(1) = 1, F(2) = 1 // Define a column vector Fi as a K X 1 Matrix // Step: 3 Determine Transformation Matrix // Where T is a K x K matrix whose last row is a vector [Ck , Ck-1 .... c1] === F(1) , F(2) ... // Note: the ith row is a zero vector except that its (i+1)th element is 1! // Step: 4 Determine Fn i.e F2=F1*T ==> Fn = T^n-1 * F1 // Computing T^n-1 efficiently can be done in O(lgn) and Multyplying takes O(K^3) ==> O(K^3lgn) // #include <iostream> #include <vector> #define REP(i,n) for (int i = 0; i < n; i++) using namespace std; typedef long long ll; typedef vector < vector <int> > matrix; // Initializing 2D Array const ll MOD = 1000000007; const int K=2; // Computes A * B matrix mul(matrix A, matrix B) { matrix C(K+1, vector <ll> (K+1)); REP(i,K) REP(j,K) REP(k,K) C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % MOD; return C; } // Computes A^p matrix pow(matrix A, int p) { if( p==1) return A; if( p%2 ) { return mul(A, pow(A,p-1)); } matix X = pow(A, p/2); return mul(X,X); } int fib(n) { // Create Vector F1 vector <ll> F1(K+1); // Initialize F1 and F2 , if given F[1] = 1; F[2] = 1; // Create Matrix T matrix T(K+1, vector <ll> (K+1)); T[1][1] = 0, T[1][2] = 1; T[2][1] = 1, T[2][2] = 1; // Raise T to the power n-1 if( N == 1 ) { return 1; } T = pow(T,N-1); // result will the first row of T*F1 ll result = 0; REP(i,k) result = (result + T[1][i] * F1[i]) % MOD return result; }
24.780822
96
0.577114
shashankkmciv18
f8b7dd7896750564660235249a5471034fb074f5
811
hpp
C++
include/RED4ext/Types/generated/mesh/MeshImportedSnapPoint.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
1
2021-02-01T23:07:50.000Z
2021-02-01T23:07:50.000Z
include/RED4ext/Types/generated/mesh/MeshImportedSnapPoint.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
include/RED4ext/Types/generated/mesh/MeshImportedSnapPoint.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/REDhash.hpp> #include <RED4ext/ISerializable.hpp> #include <RED4ext/Types/generated/Matrix.hpp> #include <RED4ext/Types/generated/mesh/ImportedSnapTags.hpp> namespace RED4ext { namespace mesh { struct MeshImportedSnapPoint : ISerializable { static constexpr const char* NAME = "meshMeshImportedSnapPoint"; static constexpr const char* ALIAS = NAME; Matrix localToCloud; // 30 float range; // 70 uint8_t rotationAlignmentSteps; // 74 uint8_t unk75[0x78 - 0x75]; // 75 mesh::ImportedSnapTags snapTags; // 78 uint8_t unk98[0xA0 - 0x98]; // 98 }; RED4EXT_ASSERT_SIZE(MeshImportedSnapPoint, 0xA0); } // namespace mesh } // namespace RED4ext
27.033333
68
0.738594
Cyberpunk-Extended-Development-Team
f8b83a348229825a74972f8adf91c24a60e3b00c
9,914
cpp
C++
artifact/storm/src/storm/storage/memorystructure/MemoryStructure.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm/storage/memorystructure/MemoryStructure.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm/storage/memorystructure/MemoryStructure.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
1
2022-02-05T12:39:53.000Z
2022-02-05T12:39:53.000Z
#include "storm/storage/memorystructure/MemoryStructure.h" #include <iostream> #include "storm/logic/Formulas.h" #include "storm/utility/macros.h" #include "storm/storage/memorystructure/SparseModelMemoryProduct.h" #include "storm/exceptions/InvalidOperationException.h" namespace storm { namespace storage { MemoryStructure::MemoryStructure(TransitionMatrix const& transitionMatrix, storm::models::sparse::StateLabeling const& memoryStateLabeling, std::vector<uint_fast64_t> const& initialMemoryStates) : transitions(transitionMatrix), stateLabeling(memoryStateLabeling), initialMemoryStates(initialMemoryStates) { // intentionally left empty } MemoryStructure::MemoryStructure(TransitionMatrix&& transitionMatrix, storm::models::sparse::StateLabeling&& memoryStateLabeling, std::vector<uint_fast64_t>&& initialMemoryStates) : transitions(std::move(transitionMatrix)), stateLabeling(std::move(memoryStateLabeling)), initialMemoryStates(std::move(initialMemoryStates)) { // intentionally left empty } MemoryStructure::TransitionMatrix const& MemoryStructure::getTransitionMatrix() const { return transitions; } storm::models::sparse::StateLabeling const& MemoryStructure::getStateLabeling() const { return stateLabeling; } std::vector<uint_fast64_t> const& MemoryStructure::getInitialMemoryStates() const { return initialMemoryStates; } uint_fast64_t MemoryStructure::getNumberOfStates() const { return transitions.size(); } uint_fast64_t MemoryStructure::getSuccessorMemoryState(uint_fast64_t const& currentMemoryState, uint_fast64_t const& modelTransitionIndex) const { for (uint_fast64_t successorMemState = 0; successorMemState < getNumberOfStates(); ++successorMemState) { boost::optional<storm::storage::BitVector> const& matrixEntry = transitions[currentMemoryState][successorMemState]; if ((matrixEntry) && matrixEntry.get().get(modelTransitionIndex)) { return successorMemState; } } STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "The successor memorystate for the given transition could not be found."); return getNumberOfStates(); } MemoryStructure MemoryStructure::product(MemoryStructure const& rhs) const { uint_fast64_t lhsNumStates = this->getTransitionMatrix().size(); uint_fast64_t rhsNumStates = rhs.getTransitionMatrix().size(); uint_fast64_t resNumStates = lhsNumStates * rhsNumStates; // Transition matrix TransitionMatrix resultTransitions(resNumStates, std::vector<boost::optional<storm::storage::BitVector>>(resNumStates)); uint_fast64_t resState = 0; for (uint_fast64_t lhsState = 0; lhsState < lhsNumStates; ++lhsState) { for (uint_fast64_t rhsState = 0; rhsState < rhsNumStates; ++rhsState) { assert (resState == (lhsState * rhsNumStates) + rhsState); auto& resStateTransitions = resultTransitions[resState]; for (uint_fast64_t lhsTransitionTarget = 0; lhsTransitionTarget < lhsNumStates; ++lhsTransitionTarget) { auto& lhsTransition = this->getTransitionMatrix()[lhsState][lhsTransitionTarget]; if (lhsTransition) { for (uint_fast64_t rhsTransitionTarget = 0; rhsTransitionTarget < rhsNumStates; ++rhsTransitionTarget) { auto& rhsTransition = rhs.getTransitionMatrix()[rhsState][rhsTransitionTarget]; if (rhsTransition) { uint_fast64_t resTransitionTarget = (lhsTransitionTarget * rhsNumStates) + rhsTransitionTarget; resStateTransitions[resTransitionTarget] = rhsTransition.get() & lhsTransition.get(); // If it is not possible to take the considered transition w.r.t. the considered model, we can delete it. if (resStateTransitions[resTransitionTarget]->empty()) { resStateTransitions[resTransitionTarget] = boost::none; } } } } } ++resState; } } // State Labels storm::models::sparse::StateLabeling resultLabeling(resNumStates); for (std::string lhsLabel : this->getStateLabeling().getLabels()) { storm::storage::BitVector const& lhsLabeledStates = this->getStateLabeling().getStates(lhsLabel); storm::storage::BitVector resLabeledStates(resNumStates, false); for (auto const& lhsState : lhsLabeledStates) { for (uint_fast64_t rhsState = 0; rhsState < rhsNumStates; ++rhsState) { resState = (lhsState * rhsNumStates) + rhsState; resLabeledStates.set(resState, true); } } resultLabeling.addLabel(lhsLabel, std::move(resLabeledStates)); } for (std::string rhsLabel : rhs.getStateLabeling().getLabels()) { STORM_LOG_THROW(!resultLabeling.containsLabel(rhsLabel), storm::exceptions::InvalidOperationException, "Failed to build the product of two memory structures: State labelings are not disjoint as both structures contain the label " << rhsLabel << "."); storm::storage::BitVector const& rhsLabeledStates = rhs.getStateLabeling().getStates(rhsLabel); storm::storage::BitVector resLabeledStates(resNumStates, false); for (auto const& rhsState : rhsLabeledStates) { for (uint_fast64_t lhsState = 0; lhsState < lhsNumStates; ++lhsState) { resState = (lhsState * rhsNumStates) + rhsState; resLabeledStates.set(resState, true); } } resultLabeling.addLabel(rhsLabel, std::move(resLabeledStates)); } // Initial States std::vector<uint_fast64_t> resultInitialMemoryStates; STORM_LOG_THROW(this->getInitialMemoryStates().size() == rhs.getInitialMemoryStates().size(), storm::exceptions::InvalidOperationException, "Tried to build the product of two memory structures that consider a different number of initial model states."); resultInitialMemoryStates.reserve(this->getInitialMemoryStates().size()); auto lhsStateIt = this->getInitialMemoryStates().begin(); auto rhsStateIt = rhs.getInitialMemoryStates().begin(); for (; lhsStateIt != this->getInitialMemoryStates().end(); ++lhsStateIt, ++rhsStateIt) { resultInitialMemoryStates.push_back(*lhsStateIt * rhsNumStates + *rhsStateIt); } return MemoryStructure(std::move(resultTransitions), std::move(resultLabeling), std::move(resultInitialMemoryStates)); } template <typename ValueType, typename RewardModelType> SparseModelMemoryProduct<ValueType, RewardModelType> MemoryStructure::product(storm::models::sparse::Model<ValueType, RewardModelType> const& sparseModel) const { return SparseModelMemoryProduct<ValueType, RewardModelType>(sparseModel, *this); } std::string MemoryStructure::toString() const { std::stringstream stream; stream << "Memory Structure with " << getNumberOfStates() << " states: " << std::endl; for (uint_fast64_t state = 0; state < getNumberOfStates(); ++state) { stream << "State " << state << ": Labels = {"; bool firstLabel = true; for (auto const& label : getStateLabeling().getLabelsOfState(state)) { if (!firstLabel) { stream << ", "; } firstLabel = false; stream << label; } stream << "}, Transitions: " << std::endl; for (uint_fast64_t transitionTarget = 0; transitionTarget < getNumberOfStates(); ++transitionTarget) { stream << "\t From " << state << " to " << transitionTarget << ": \t"; auto const& transition = getTransitionMatrix()[state][transitionTarget]; if (transition) { stream << *transition; } else { stream << "false"; } stream << std::endl; } } return stream.str(); } template SparseModelMemoryProduct<double> MemoryStructure::product(storm::models::sparse::Model<double> const& sparseModel) const; template SparseModelMemoryProduct<double, storm::models::sparse::StandardRewardModel<storm::Interval>> MemoryStructure::product(storm::models::sparse::Model<double, storm::models::sparse::StandardRewardModel<storm::Interval>> const& sparseModel) const; template SparseModelMemoryProduct<storm::RationalNumber> MemoryStructure::product(storm::models::sparse::Model<storm::RationalNumber> const& sparseModel) const; template SparseModelMemoryProduct<storm::RationalFunction> MemoryStructure::product(storm::models::sparse::Model<storm::RationalFunction> const& sparseModel) const; } }
60.084848
332
0.608029
glatteis
f8b86f2c91c7f4bc5730030b44b8d4a30dc1daa6
10,121
cpp
C++
src/Kocmoc.cpp
SimonWallner/kocmoc-demo
a4f769b5ed7592ce50a18ab93c603d4371fbd291
[ "MIT", "Unlicense" ]
12
2015-01-21T07:02:23.000Z
2021-11-15T19:47:53.000Z
src/Kocmoc.cpp
SimonWallner/kocmoc-demo
a4f769b5ed7592ce50a18ab93c603d4371fbd291
[ "MIT", "Unlicense" ]
null
null
null
src/Kocmoc.cpp
SimonWallner/kocmoc-demo
a4f769b5ed7592ce50a18ab93c603d4371fbd291
[ "MIT", "Unlicense" ]
3
2017-03-04T08:50:46.000Z
2020-10-23T14:27:04.000Z
#include "Kocmoc.hpp" #include "Context.hpp" #include "Property.hpp" #include "Exception.hpp" #include "ImageLoader.hpp" #include "KocmocLoader.hpp" #include "utility.hpp" #include "ShaderManager.hpp" #include "AudioPlayer.hpp" #include "AnimationSystem.hpp" #include <gtx/spline.hpp> using namespace kocmoc; Kocmoc* Kocmoc::instance = NULL; Kocmoc& Kocmoc::getInstance(void) { if(!instance) instance = new Kocmoc(); return *instance; } void Kocmoc::Destroy() { // static delete instance; instance = NULL; } Kocmoc::Kocmoc() : useUserCamera(false) { glfwGetMousePos(&mouseOldX, &mouseOldY); showGizmos = util::Property("debugShowGizmo"); } Kocmoc::~Kocmoc() { delete scene; delete gamepad; } bool Kocmoc::isRunning(){ return running; } void Kocmoc::stop(){ running = false; } void Kocmoc::init() { // user camera camera = new FilmCamera(vec3(0.0f, 0.0f, 15.0f), //eye vec3(0, 0, 0), // target vec3(0, 1, 0)); // up float aspectRatio = (float)util::Property("aspectRatio") / ((float)Context::getInstance().width / (float)Context::getInstance().height); if (aspectRatio > 1) // horizontal letter box camera->setGateInPixel(Context::getInstance().width, (float)Context::getInstance().height / aspectRatio); else camera->setGateInPixel((float)Context::getInstance().width * aspectRatio, Context::getInstance().height); camera->setFocalLength(util::Property("cameraFocalLength35")); camera->setFilterMarginInPixel(util::Property("horizontalMargin"), util::Property("verticalMargin")); camera->setupGizmo(); camera->updateMatrixes(); // animation cameras --- cam 1 -------------------------------------------- cam1 = new FilmCamera(vec3(0.0f, 0.0f, 15.0f), //eye vec3(0, 0, 0), // target vec3(0, 1, 0)); // up if (aspectRatio > 1) // horizontal letter box cam1->setGateInPixel(Context::getInstance().width, (float)Context::getInstance().height / aspectRatio); else cam1->setGateInPixel((float)Context::getInstance().width * aspectRatio, Context::getInstance().height); cam1->setFocalLength(util::Property("cameraFocalLength35")); cam1->setFilterMarginInPixel(util::Property("horizontalMargin"), util::Property("verticalMargin")); cam1->updateMatrixes(); // animation cameras --- cam 2 -------------------------------------------- cam2 = new FilmCamera(vec3(0.0f, 0.0f, 15.0f), //eye vec3(0, 0, 0), // target vec3(0, 1, 0)); // up if (aspectRatio > 1) // horizontal letter box cam2->setGateInPixel(Context::getInstance().width, (float)Context::getInstance().height / aspectRatio); else cam2->setGateInPixel((float)Context::getInstance().width * aspectRatio, Context::getInstance().height); cam2->setFocalLength(util::Property("cameraFocalLength35")); cam2->setFilterMarginInPixel(util::Property("horizontalMargin"), util::Property("verticalMargin")); cam2->updateMatrixes(); // ortho cam orthoCam = new OrthoCam(vec3(0, 0, 0), vec3(-1, -1, -1), vec3(0, 1, 0)); orthoCam->updateMatrixes(); scene = new KocmocScene(); ship = KocmocLoader::getInstance().load(util::Property("modelName")); scene->add(ship); scene->add(util::generator::generateStars()); shadowShader = ShaderManager::getInstance().load("shadow.vert", "shadow.frag"); if (showGizmos) scene->add(util::generator::generateGizmo()); { /* inputs */ gamepad = new input::Gamepad(camera); useGamepad = gamepad->init(); useMouse = util::Property("enableMouse"); if (useMouse && util::Property("captureMouse")) glfwDisable(GLFW_MOUSE_CURSOR); } fbo = new FrameBuffer(camera->getFrameWidth(), camera->getFrameHeight(), camera->getGateWidth(), camera->getGateHeight()); fbo->setupShader(); shadowMap = new ShadowMap(util::Property("shadowMapWidth"), util::Property("shadowMapHeight")); AudioPlayer::getInstance().play("kocmoc.ogg"); clock = new Clock(); if (util::Property("useFixedFrameRate")) clock->start(1.0/(float)util::Property("fixedFrameRate")); else clock->start(); animationClock = new AnimationClock(clock); AnimationSystem::getInstance().parseAnimationFile(); overlayCam = new OverlayCam(Context::getInstance().width, Context::getInstance().height); overlayCam->updateMatrixes(); black = new ImageOverlay("black.png", Context::getInstance().width, Context::getInstance().height); title = new ImageOverlay("title.png", 800, 400); credits = new ImageOverlay("credits.png", 800, 400); credits2 = new ImageOverlay("credits2.png", 800, 400); credits3 = new ImageOverlay("credits3.png", 800, 400); running = true; animationClock->play(); } void Kocmoc::start() { while (running) { clock->awaitSchedule(); clock->tick(); timer.tic(); // Check if the window has been closed running = running && glfwGetWindowParam( GLFW_OPENED ); pollKeyboard(); if (useGamepad) gamepad->poll(); if (useMouse) pollMouse(); // update stuff ------------------ AnimationSystem &asi = AnimationSystem::getInstance(); mat4 transform = glm::gtx::transform::rotate(2.0f * asi.getScalar(animationClock->getTime(), "time"), 1.0f, 0.0f, 0.0f); transform = glm::gtx::transform::rotate(15.0f * asi.getScalar(animationClock->getTime(), "time"), 1.0f, 0.3f, 0.2f) * transform; transform = glm::gtx::transform::translate(vec3(1, 0, 0) * 3.0f * asi.getScalar(animationClock->getTime(), "time")) * transform; ship->setTransformation(transform); orthoCam->setFocus(vec3(1, 0, 0) * 3.0f * asi.getScalar(animationClock->getTime(), "time")); orthoCam->updateMatrixes(); black->setOpacity(asi.getScalar(animationClock->getTime(), "black_opacity")); title->setOpacity(asi.getScalar(animationClock->getTime(), "title_opacity")); credits->setOpacity(asi.getScalar(animationClock->getTime(), "credits_opacity")); credits2->setOpacity(asi.getScalar(animationClock->getTime(), "credits2_opacity")); credits3->setOpacity(asi.getScalar(animationClock->getTime(), "credits3_opacity")); cam1->setPosition(asi.getVec3(animationClock->getTime(), "cam1_position")); cam1->setTargetPosition(asi.getVec3(animationClock->getTime(), "cam1_target")); cam1->setUpVector(asi.getVec3(animationClock->getTime(), "cam1_up")); cam1->setFocalLength(asi.getScalar(animationClock->getTime(), "cam1_focalLength")); cam2->setPosition(asi.getVec3(animationClock->getTime(), "cam2_position")); cam2->setTargetPosition(asi.getVec3(animationClock->getTime(), "cam2_target")); cam2->setUpVector(asi.getVec3(animationClock->getTime(), "cam2_up")); cam2->setFocalLength(asi.getScalar(animationClock->getTime(), "cam2_focalLength")); camera->updateMatrixes(); cam1->updateMatrixes(); cam2->updateMatrixes(); // drawing stuff --------------- // shadow map glDisable(GL_FRAMEBUFFER_SRGB); glBindFramebuffer(GL_FRAMEBUFFER, shadowMap->getFBOHandle()); glViewport(0, 0, shadowMap->width, shadowMap->height); glClear(GL_DEPTH_BUFFER_BIT); ship->draw(orthoCam, shadowShader); glEnable(GL_FRAMEBUFFER_SRGB); glBindFramebuffer(GL_FRAMEBUFFER, fbo->getFBOHandle()); glViewport(0, 0, fbo->frameWidth, fbo->frameHeight); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, shadowMap->getTextureHandle()); draw(); glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, Context::getInstance().width, Context::getInstance().height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (Context::getInstance().getWireframe()) { Context::getInstance().setWireframe(false); fbo->drawFBO(); Context::getInstance().setWireframe(true); } else fbo->drawFBO(); drawOverlays(); Context::getInstance().swapBuffers(); if (util::Property("recordSequence")) ImageLoader::getInstance().screenShot(true); } } void Kocmoc::draw() { if (useUserCamera) scene->draw(camera); else { if (AnimationSystem::getInstance().getScalar(animationClock->getTime(), "cam1_selector") > 0.0f) scene->draw(cam1); else scene->draw(cam2); } } void Kocmoc::drawOverlays() { //if (showGizmos) // camera->drawGizmo(); glDisable(GL_DEPTH_TEST); black->draw(); title->draw(); credits->draw(); credits2->draw(); credits3->draw(); glEnable(GL_DEPTH_TEST); } void Kocmoc::pollKeyboard(void) { running = running && !glfwGetKey( GLFW_KEY_ESC ); if (glfwGetKey(GLFW_KEY_F1)) std::cout << "---------------------------------------------------------" << std::endl << "\t F1: this help dialog" <<std::endl << "\t F3: toggle wireframe" << std::endl << "\t F4: print frametime/fps" << std::endl << "\t F5: toggle non-planar projection post" << std::endl << "\t F6: toggle vignetting post" << std::endl << "\t F7: toggle color correction post" << std::endl << "\t '.': take screenshot" << std::endl << "\t R: reload shaders/textures/etc..." << std::endl; if (glfwGetKey(GLFW_KEY_F3)) Context::getInstance().setWireframe(!Context::getInstance().getWireframe()); if (glfwGetKey(GLFW_KEY_F4)) timer.print(); if (glfwGetKey(GLFW_KEY_F5)) { fbo->toggleProjection(); reload(); } if (glfwGetKey(GLFW_KEY_F6)) { fbo->toggleVignetting(); reload(); } if (glfwGetKey(GLFW_KEY_F7)) { fbo->toggleColorCorrection(); reload(); } if (glfwGetKey('.')) ImageLoader::getInstance().screenShot(); if (glfwGetKey('R')) animationClock->setTime(0.0); if (glfwGetKey('W')) camera->dolly(vec3(0, 0, 4.0f) * (float)clock->lastFrameDuration()); if (glfwGetKey('S')) camera->dolly(vec3(0, 0, -4.0f) * (float)clock->lastFrameDuration()); if (glfwGetKey('A')) camera->dolly(vec3(-4.0f, 0, 0.0f) * (float)clock->lastFrameDuration()); if (glfwGetKey('D')) camera->dolly(vec3(4.0f, 0, 0.0f) * (float)clock->lastFrameDuration()); if (glfwGetKey(GLFW_KEY_SPACE)) useUserCamera = !useUserCamera; } void Kocmoc::pollMouse() { int newX, newY; glfwGetMousePos(&newX, &newY); camera->tumble((newX - mouseOldX) * (float)clock->lastFrameDuration() * 0.1f , (newY - mouseOldY) * -(float)clock->lastFrameDuration() * 0.1f); mouseOldX = newX; mouseOldY = newY; } void Kocmoc::reload() { fbo->setupShader(); title->setupShader(); black->setupShader(); }
28.27095
137
0.686691
SimonWallner
f8b8b475c29be7330f546a5b38ab661e443ef5a5
765
cc
C++
2004-class/day2/object-ret.cc
tibbetts/inside-c
a72f6d44f15343e81b35da8edadd0e9c63315d40
[ "MIT" ]
18
2015-01-19T04:18:49.000Z
2022-03-04T06:22:44.000Z
2004-class/day2/object-ret.cc
tibbetts/inside-c
a72f6d44f15343e81b35da8edadd0e9c63315d40
[ "MIT" ]
null
null
null
2004-class/day2/object-ret.cc
tibbetts/inside-c
a72f6d44f15343e81b35da8edadd0e9c63315d40
[ "MIT" ]
4
2020-02-19T22:29:23.000Z
2021-09-22T16:45:52.000Z
#include "stdio.h" class twofield { private: int field1, field2; public: explicit twofield(int f); // Copy constructor. twofield(const twofield &of); ~twofield(); void setField(int f); int getField() const; }; twofield fromint(int j) { twofield of(j); return of; } int main(int argc, char **argv) { int i = fromint(13).getField(); return i; } void twofield::setField(int f) { this->field1 = f; } int twofield::getField() const { return this->field1; } twofield::twofield(int f) { field1 = f; printf("initial value of field was %d.\n", field1); } twofield::twofield(const twofield &of) { field1 = of.field1; } twofield::~twofield() { printf("Last value of field was %d.\n", field1); }
16.630435
55
0.616993
tibbetts
f8ba5ffab3c931453c8ef1b5d80a661073b8aa75
367
cpp
C++
Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Styling/definitions.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Styling/definitions.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Styling/definitions.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzCore/Serialization/SerializeContext.h> #include <GraphCanvas/Styling/definitions.h> int LinkerWarningWorkaround() { return 0; }
22.9375
100
0.746594
cypherdotXd
f8bb1144ae4497943224251410733206e4be5bd4
2,233
cpp
C++
input/input_state.cpp
Ced2911/native
41fd5dcc905592a78017ffbb40eac39b1fdf994a
[ "MIT" ]
2
2016-01-22T20:58:08.000Z
2018-05-02T19:01:30.000Z
input/input_state.cpp
Ced2911/native
41fd5dcc905592a78017ffbb40eac39b1fdf994a
[ "MIT" ]
null
null
null
input/input_state.cpp
Ced2911/native
41fd5dcc905592a78017ffbb40eac39b1fdf994a
[ "MIT" ]
null
null
null
#include "input/input_state.h" #include "input/keycodes.h" const char *GetDeviceName(int deviceId) { switch (deviceId) { case DEVICE_ID_DEFAULT: return "built-in"; case DEVICE_ID_KEYBOARD: return "kbd"; case DEVICE_ID_PAD_0: return "pad"; case DEVICE_ID_X360_0: return "x360"; case DEVICE_ID_ACCELEROMETER: return "accelerometer"; default: return "unknown"; } } // Default pad mapping to button bits. Used for UI and stuff that doesn't use PPSSPP's key mapping system. int MapPadButtonFixed(int keycode) { switch (keycode) { case KEYCODE_BACK: return PAD_BUTTON_BACK; // Back case KEYCODE_MENU: return PAD_BUTTON_MENU; // Menu case KEYCODE_Z: case KEYCODE_SPACE: case KEYCODE_BUTTON_1: case KEYCODE_BUTTON_A: // same as KEYCODE_OUYA_BUTTON_O and KEYCODE_BUTTON_CROSS_PS3 return PAD_BUTTON_A; case KEYCODE_ESCAPE: case KEYCODE_BUTTON_2: case KEYCODE_BUTTON_B: // same as KEYCODE_OUYA_BUTTON_A and KEYCODE_BUTTON_CIRCLE_PS3: return PAD_BUTTON_B; case KEYCODE_DPAD_LEFT: return PAD_BUTTON_LEFT; case KEYCODE_DPAD_RIGHT: return PAD_BUTTON_RIGHT; case KEYCODE_DPAD_UP: return PAD_BUTTON_UP; case KEYCODE_DPAD_DOWN: return PAD_BUTTON_DOWN; default: return 0; } } uint32_t ButtonTracker::Update() { pad_buttons_ |= pad_buttons_async_set; pad_buttons_ &= ~pad_buttons_async_clear; return pad_buttons_; } void ButtonTracker::Process(const KeyInput &input) { int btn = MapPadButtonFixed(input.keyCode); if (btn == 0) return; // For now, use a fixed mapping. Good enough for the basics on most platforms. if (input.flags & KEY_DOWN) { pad_buttons_async_set |= btn; pad_buttons_async_clear &= ~btn; } if (input.flags & KEY_UP) { pad_buttons_async_set &= ~btn; pad_buttons_async_clear |= btn; } } ButtonTracker g_buttonTracker; void UpdateInputState(InputState *input, bool merge) { uint32_t btns = g_buttonTracker.Update(); input->pad_buttons = merge ? (input->pad_buttons | btns) : btns; input->pad_buttons_down = (input->pad_last_buttons ^ input->pad_buttons) & input->pad_buttons; input->pad_buttons_up = (input->pad_last_buttons ^ input->pad_buttons) & input->pad_last_buttons; } void EndInputState(InputState *input) { input->pad_last_buttons = input->pad_buttons; }
29.381579
106
0.765786
Ced2911
f8bc29486b5f537d77561fae8c45488df7e9dbbc
595
cpp
C++
ds18b20_ui.cpp
wintersteiger/wlmcd
7bdc184b875a0be652a0dd346fd9a598c14181d8
[ "MIT" ]
4
2021-01-11T13:50:25.000Z
2021-01-24T19:34:47.000Z
ds18b20_ui.cpp
wintersteiger/wlmcd
7bdc184b875a0be652a0dd346fd9a598c14181d8
[ "MIT" ]
1
2021-02-12T15:49:18.000Z
2021-02-12T16:50:55.000Z
ds18b20_ui.cpp
wintersteiger/wlmcd
7bdc184b875a0be652a0dd346fd9a598c14181d8
[ "MIT" ]
2
2021-01-11T13:53:18.000Z
2021-03-01T10:22:46.000Z
// Copyright (c) Christoph M. Wintersteiger // Licensed under the MIT License. #include "ds18b20_ui.h" DOUBLE_FIELD(UI::statusp, Temperature, "Temperature", DS18B20, "C", device.Temperature()); #define EMPTY() fields.push_back(new Empty(row++, col)); DS18B20UI::DS18B20UI(DS18B20 &ds18b20) { devices.insert(&ds18b20); size_t row = 1, col = 1; Add(new TimeField(statusp, row, col)); Add(new Label(UI::statusp, row++, col + 18, Name())); EMPTY(); fields.push_back(new Temperature(row, col, ds18b20)); } DS18B20UI::~DS18B20UI() { } void DS18B20UI::Layout() { UI::Layout(); }
19.193548
90
0.677311
wintersteiger
f8bc4272e1917689b3202f865aaeb8b083ae4cca
26,239
cpp
C++
emulator/src/mame/drivers/sapi1.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
1
2022-01-15T21:38:38.000Z
2022-01-15T21:38:38.000Z
emulator/src/mame/drivers/sapi1.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
emulator/src/mame/drivers/sapi1.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
// license:BSD-3-Clause // copyright-holders:Miodrag Milanovic, Robbbert /*************************************************************************** SAPI-1 driver by Miodrag Milanovic 2008-09-09 Preliminary driver. 2010-12-07 Added some code to allow sapizps3 to read its rom. With no available docs, the i/o ports are a guess. The ram allocation is based on the actions of the various bios roms. Port 25 is used as a jump vector. in a,(25); ld l,a; jp(hl). 2012-04-19 Connected sapizps3 to a terminal. It is trying to load a 128-byte boot sector from a floppy disk. Modernised driver. Connected sapizps2 to ascii keyboard. System is now usable. According to wikipedia, sapi1 & 2 have cassette facility, while sapi3 uses 8 inch floppy disk. ToDo: - Add cassette to sapi1 and 2 -- UART on port 12, save and load bytes -- port 11 bit 7 for load, chr available -- port 11 bit 6 for save, tx buffer empty - sapi3 is trying to read a disk, so there is no response after showing the logo Unable to proceed due to no info available (& in English). ****************************************************************************/ #include "emu.h" #include "cpu/i8085/i8085.h" //#include "cpu/z80/z80.h" #include "bus/rs232/rs232.h" #include "machine/ay31015.h" #include "machine/keyboard.h" #include "machine/ram.h" #include "video/mc6845.h" #include "screen.h" class sapi1_state : public driver_device { public: sapi1_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag), m_p_videoram(*this, "videoram"), m_bank1(*this, "bank1"), m_line0(*this, "LINE0"), m_line1(*this, "LINE1"), m_line2(*this, "LINE2"), m_line3(*this, "LINE3"), m_line4(*this, "LINE4"), m_maincpu(*this, "maincpu"), m_uart(*this, "uart"), m_v24(*this, "v24"), m_palette(*this, "palette") { } optional_shared_ptr<uint8_t> m_p_videoram; DECLARE_READ8_MEMBER(sapi1_keyboard_r); DECLARE_WRITE8_MEMBER(sapi1_keyboard_w); DECLARE_READ8_MEMBER(sapi2_keyboard_status_r); DECLARE_READ8_MEMBER(sapi2_keyboard_data_r); DECLARE_READ8_MEMBER(sapi3_0c_r); DECLARE_WRITE8_MEMBER(sapi3_00_w); DECLARE_READ8_MEMBER(sapi3_25_r); DECLARE_WRITE8_MEMBER(sapi3_25_w); void kbd_put(u8 data); DECLARE_READ8_MEMBER(uart_status_r); DECLARE_WRITE8_MEMBER(modem_control_w); DECLARE_READ8_MEMBER(uart_ready_r); DECLARE_WRITE8_MEMBER(uart_mode_w); DECLARE_WRITE8_MEMBER(uart_reset_w); DECLARE_DRIVER_INIT(sapizps3); DECLARE_DRIVER_INIT(sapizps3a); DECLARE_DRIVER_INIT(sapizps3b); DECLARE_MACHINE_RESET(sapi1); DECLARE_MACHINE_RESET(sapizps3); MC6845_UPDATE_ROW(crtc_update_row); uint32_t screen_update_sapi1(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect); uint32_t screen_update_sapi3(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect); void sapi3(machine_config &config); void sapi1(machine_config &config); void sapi2(machine_config &config); void sapi3a(machine_config &config); void sapi3b(machine_config &config); void sapi1_mem(address_map &map); void sapi2_mem(address_map &map); void sapi3_io(address_map &map); void sapi3_mem(address_map &map); void sapi3a_io(address_map &map); void sapi3a_mem(address_map &map); void sapi3b_io(address_map &map); void sapi3b_mem(address_map &map); private: uint8_t m_term_data; uint8_t m_keyboard_mask; uint8_t m_refresh_counter; uint8_t m_zps3_25; optional_memory_bank m_bank1; // Only for sapi3 required_ioport m_line0; required_ioport m_line1; required_ioport m_line2; required_ioport m_line3; required_ioport m_line4; required_device<cpu_device> m_maincpu; optional_device<ay31015_device> m_uart; optional_device<rs232_port_device> m_v24; public: optional_device<palette_device> m_palette; }; static const uint8_t MHB2501[] = { 0x0c,0x11,0x13,0x15,0x17,0x10,0x0e,0x00, // @ 0x04,0x0a,0x11,0x11,0x1f,0x11,0x11,0x00, // A 0x1e,0x11,0x11,0x1e,0x11,0x11,0x1e,0x00, // B 0x0e,0x11,0x10,0x10,0x10,0x11,0x0e,0x00, // C 0x1e,0x09,0x09,0x09,0x09,0x09,0x1e,0x00, // D 0x1f,0x10,0x10,0x1e,0x10,0x10,0x1f,0x00, // E 0x1f,0x10,0x10,0x1e,0x10,0x10,0x10,0x00, // F 0x0e,0x11,0x10,0x10,0x13,0x11,0x0f,0x00, // G 0x11,0x11,0x11,0x1f,0x11,0x11,0x11,0x00, // H 0x0e,0x04,0x04,0x04,0x04,0x04,0x0e,0x00, // I 0x01,0x01,0x01,0x01,0x11,0x11,0x0e,0x00, // J 0x11,0x12,0x14,0x18,0x14,0x12,0x11,0x00, // K 0x10,0x10,0x10,0x10,0x10,0x10,0x1f,0x00, // L 0x11,0x1b,0x15,0x15,0x11,0x11,0x11,0x00, // M 0x11,0x11,0x19,0x15,0x13,0x11,0x11,0x00, // N 0x0e,0x11,0x11,0x11,0x11,0x11,0x0e,0x00, // O 0x1e,0x11,0x11,0x1e,0x10,0x10,0x10,0x00, // P 0x0e,0x11,0x11,0x11,0x15,0x12,0x0d,0x00, // Q 0x1e,0x11,0x11,0x1e,0x14,0x12,0x11,0x00, // R 0x0e,0x11,0x10,0x0e,0x01,0x11,0x0e,0x00, // S 0x1f,0x04,0x04,0x04,0x04,0x04,0x04,0x00, // T 0x11,0x11,0x11,0x11,0x11,0x11,0x0e,0x00, // U 0x11,0x11,0x11,0x0a,0x0a,0x04,0x04,0x00, // V 0x11,0x11,0x11,0x15,0x15,0x15,0x0a,0x00, // W 0x11,0x11,0x0a,0x04,0x0a,0x11,0x11,0x00, // X 0x11,0x11,0x0a,0x04,0x04,0x04,0x04,0x00, // Y 0x1f,0x01,0x02,0x04,0x08,0x10,0x1f,0x00, // Z 0x1c,0x10,0x10,0x10,0x10,0x10,0x1c,0x00, // [ 0x00,0x10,0x08,0x04,0x02,0x01,0x00,0x00, // backslash 0x07,0x01,0x01,0x01,0x01,0x01,0x07,0x00, // ] 0x0e,0x11,0x00,0x00,0x00,0x00,0x00,0x00, // ^ 0x00,0x00,0x00,0x00,0x00,0x00,0x1f,0x00, // _ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // 0x04,0x04,0x04,0x04,0x04,0x00,0x04,0x00, // ! 0x0a,0x0a,0x0a,0x00,0x00,0x00,0x00,0x00, // " 0x0a,0x0a,0x1f,0x0a,0x1f,0x0a,0x0a,0x00, // # 0x00,0x11,0x0e,0x0a,0x0e,0x11,0x00,0x00, // 0x18,0x19,0x02,0x04,0x08,0x13,0x03,0x00, // % 0x04,0x0a,0x0a,0x0c,0x15,0x12,0x0d,0x00, // & 0x04,0x04,0x08,0x00,0x00,0x00,0x00,0x00, // ' 0x02,0x04,0x08,0x08,0x08,0x04,0x02,0x00, // ( 0x08,0x04,0x02,0x02,0x02,0x04,0x08,0x00, // ) 0x00,0x04,0x15,0x0e,0x15,0x04,0x00,0x00, // * 0x00,0x04,0x04,0x1f,0x04,0x04,0x00,0x00, // + 0x00,0x00,0x00,0x00,0x08,0x08,0x10,0x00, // , 0x00,0x00,0x00,0x1f,0x00,0x00,0x00,0x00, // - 0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00, // . 0x00,0x01,0x02,0x04,0x08,0x10,0x00,0x00, // / 0x0e,0x11,0x13,0x15,0x19,0x11,0x0e,0x00, // 0 0x04,0x0c,0x04,0x04,0x04,0x04,0x0e,0x00, // 1 0x0e,0x11,0x01,0x06,0x08,0x10,0x1f,0x00, // 2 0x1f,0x01,0x02,0x06,0x01,0x11,0x0e,0x00, // 3 0x02,0x06,0x0a,0x12,0x1f,0x02,0x02,0x00, // 4 0x1f,0x10,0x1e,0x01,0x01,0x11,0x0e,0x00, // 5 0x07,0x08,0x10,0x1e,0x11,0x11,0x0e,0x00, // 6 0x1f,0x01,0x02,0x04,0x08,0x08,0x08,0x00, // 7 0x0e,0x11,0x11,0x0e,0x11,0x11,0x0e,0x00, // 8 0x0e,0x11,0x11,0x0f,0x01,0x02,0x1c,0x00, // 9 0x00,0x00,0x00,0x00,0x08,0x00,0x08,0x00, // : 0x00,0x00,0x04,0x00,0x04,0x04,0x08,0x00, // ; 0x02,0x04,0x08,0x10,0x08,0x04,0x02,0x00, // < 0x00,0x00,0x1f,0x00,0x1f,0x00,0x00,0x00, // = 0x08,0x04,0x02,0x01,0x02,0x04,0x08,0x00, // > 0x0e,0x11,0x01,0x02,0x04,0x00,0x04,0x00 // ? }; /* Address maps */ void sapi1_state::sapi1_mem(address_map &map) { map.unmap_value_high(); map(0x0000, 0x0fff).rom(); map(0x1000, 0x1fff).rom(); // Extension ROM map(0x2000, 0x23ff).ram(); map(0x2400, 0x27ff).rw(this, FUNC(sapi1_state::sapi1_keyboard_r), FUNC(sapi1_state::sapi1_keyboard_w)); // PORT 0 - keyboard //AM_RANGE(0x2800, 0x2bff) AM_NOP // PORT 1 //AM_RANGE(0x2c00, 0x2fff) AM_NOP // PORT 2 //AM_RANGE(0x3000, 0x33ff) AM_NOP // 3214 map(0x3800, 0x3fff).ram().share("videoram"); // AND-1 (video RAM) map(0x4000, 0x7fff).ram(); // REM-1 } void sapi1_state::sapi2_mem(address_map &map) { map.unmap_value_high(); map(0x0000, 0x0fff).rom(); map(0x1000, 0x1fff).rom(); // Extension ROM map(0x2000, 0x23ff).ram(); map(0x2400, 0x27ff).r(this, FUNC(sapi1_state::sapi2_keyboard_status_r)); map(0x2800, 0x28ff).r(this, FUNC(sapi1_state::sapi2_keyboard_data_r)); map(0x3800, 0x3fff).ram().share("videoram"); // AND-1 (video RAM) map(0x4000, 0x7fff).ram(); // REM-1 } void sapi1_state::sapi3_mem(address_map &map) { map.unmap_value_high(); map(0x0000, 0x07ff).ram().bankrw("bank1"); map(0x0800, 0xf7ff).ram(); map(0xf800, 0xffff).ram().share("videoram"); } void sapi1_state::sapi3a_mem(address_map &map) { map.unmap_value_high(); map(0x0000, 0x07ff).ram().bankrw("bank1"); map(0x0800, 0xf7ff).ram(); map(0xf800, 0xfdff).rom(); map(0xfe00, 0xffff).ram(); } void sapi1_state::sapi3b_mem(address_map &map) { map.unmap_value_high(); map(0x0000, 0x07ff).ram().bankrw("bank1"); map(0x0800, 0xafff).ram(); map(0xb000, 0xb7ff).ram().share("videoram"); map(0xb800, 0xffff).ram(); } void sapi1_state::sapi3_io(address_map &map) { map.unmap_value_high(); map.global_mask(0xff); map(0x00, 0x00).w(this, FUNC(sapi1_state::sapi3_00_w)); map(0x25, 0x25).rw(this, FUNC(sapi1_state::sapi3_25_r), FUNC(sapi1_state::sapi3_25_w)); } void sapi1_state::sapi3a_io(address_map &map) { map.unmap_value_high(); map.global_mask(0xff); map(0x00, 0x00).w(this, FUNC(sapi1_state::sapi3_00_w)); map(0x10, 0x10).rw(this, FUNC(sapi1_state::uart_status_r), FUNC(sapi1_state::modem_control_w)); map(0x11, 0x11).rw(this, FUNC(sapi1_state::uart_ready_r), FUNC(sapi1_state::uart_mode_w)); map(0x12, 0x12).rw(m_uart, FUNC(ay51013_device::receive), FUNC(ay51013_device::transmit)); map(0x13, 0x13).w(this, FUNC(sapi1_state::uart_reset_w)); map(0x25, 0x25).rw(this, FUNC(sapi1_state::sapi3_25_r), FUNC(sapi1_state::sapi3_25_w)); } void sapi1_state::sapi3b_io(address_map &map) { map.unmap_value_high(); map.global_mask(0xff); map(0x00, 0x00).w(this, FUNC(sapi1_state::sapi3_00_w)); map(0x0c, 0x0c).r(this, FUNC(sapi1_state::sapi3_0c_r)); map(0x25, 0x25).rw(this, FUNC(sapi1_state::sapi3_25_r), FUNC(sapi1_state::sapi3_25_w)); map(0xe0, 0xe0).rw("crtc", FUNC(mc6845_device::status_r), FUNC(mc6845_device::address_w)); map(0xe1, 0xe1).rw("crtc", FUNC(mc6845_device::register_r), FUNC(mc6845_device::register_w)); } /* Input ports */ static INPUT_PORTS_START( sapi1 ) PORT_START("LINE0") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_V) PORT_CHAR('V') PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_G) PORT_CHAR('G') PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_T) PORT_CHAR('T') PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_5) PORT_CHAR('5') PORT_CHAR('~') PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_B) PORT_CHAR('B') PORT_CHAR(';') PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_H) PORT_CHAR('H') PORT_CHAR('+') PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_Y) PORT_CHAR('Y') PORT_CHAR('/') PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_6) PORT_CHAR('6') PORT_CHAR('\'') PORT_START("LINE1") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_C) PORT_CHAR('C') PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_F) PORT_CHAR('F') PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_R) PORT_CHAR('R') PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_4) PORT_CHAR('4') PORT_CHAR(0xA4) PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_N) PORT_CHAR('N') PORT_CHAR(',') PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_J) PORT_CHAR('J') PORT_CHAR('-') PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_U) PORT_CHAR('U') PORT_CHAR(':') PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_7) PORT_CHAR('7') PORT_CHAR('<') PORT_START("LINE2") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_X) PORT_CHAR('X') PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_D) PORT_CHAR('D') PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_E) PORT_CHAR('E') PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_3) PORT_CHAR('3') PORT_CHAR('"') PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_M) PORT_CHAR('M') PORT_CHAR('.') PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_K) PORT_CHAR('K') PORT_CHAR('*') PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_I) PORT_CHAR('I') PORT_CHAR('@') PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_8) PORT_CHAR('8') PORT_CHAR('>') PORT_START("LINE3") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_Z) PORT_CHAR('Z') PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_S) PORT_CHAR('S') PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_W) PORT_CHAR('W') PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_2) PORT_CHAR('2') PORT_CHAR('?') PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_SPACE) PORT_CHAR(' ') PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_L) PORT_CHAR('L') PORT_CHAR('=') PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_O) PORT_CHAR('O') PORT_CHAR('#') PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_9) PORT_CHAR('9') PORT_CHAR('(') PORT_START("LINE4") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Shift") PORT_CODE(KEYCODE_LSHIFT) PORT_CODE(KEYCODE_RSHIFT) PORT_CHAR(UCHAR_SHIFT_1) PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_A) PORT_CHAR('A') PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_Q) PORT_CHAR('Q') PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_1) PORT_CHAR('1') PORT_CHAR('!') PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Del") PORT_CODE(KEYCODE_BACKSPACE) PORT_CHAR(8) PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_ENTER) PORT_CHAR(13) PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_P) PORT_CHAR('P') PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_0) PORT_CHAR('0') PORT_CHAR(')') INPUT_PORTS_END /************************************** Video **************************************/ uint32_t sapi1_state::screen_update_sapi1(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect) { bool val; uint16_t addr,xpos; uint8_t chr,attr,ra,x,y,b; for(y = 0; y < 24; y++ ) { addr = y*64; xpos = 0; for(x = 0; x < 40; x++ ) { chr = m_p_videoram[addr + x]; attr = (chr >> 6) & 3; chr &= 0x3f; for(ra = 0; ra < 9; ra++ ) { for(b = 0; b < 6; b++ ) { val = 0; if (ra==8) { if (attr==2) val = BIT(m_refresh_counter, 5); } else { val = BIT(MHB2501[(chr<<3) | ra], 5-b); if (attr==1) val = BIT(m_refresh_counter, 5) ? val : 0; } if(attr==3) { bitmap.pix16(y*9+ra, xpos+2*b ) = val; bitmap.pix16(y*9+ra, xpos+2*b+1 ) = val; } else { bitmap.pix16(y*9+ra, xpos+b ) = val; } } } xpos+= (attr==3) ? 12 : 6; if (xpos>=6*40) break; } } m_refresh_counter++; return 0; } // The attributes seem to be different on this one, they need to be understood, so disabled for now uint32_t sapi1_state::screen_update_sapi3(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect) { bool val; uint16_t addr,xpos; uint8_t chr,attr,ra,x,y,b; for(y = 0; y < 20; y++ ) { addr = y*64; xpos = 0; for(x = 0; x < 40; x++ ) { chr = m_p_videoram[addr + x]; attr = 0;//(chr >> 6) & 3; if (chr > 0x3f) chr &= 0x1f; for(ra = 0; ra < 9; ra++ ) { for(b = 0; b < 6; b++ ) { val = 0; if (ra==8) { if (attr==2) val = BIT(m_refresh_counter, 5); } else { val = BIT(MHB2501[(chr<<3) | ra], 5-b); if (attr==1) val = BIT(m_refresh_counter, 5) ? val : 0; } if(attr==3) { bitmap.pix16(y*9+ra, xpos+2*b ) = val; bitmap.pix16(y*9+ra, xpos+2*b+1 ) = val; } else { bitmap.pix16(y*9+ra, xpos+b ) = val; } } } xpos+= (attr==3) ? 12 : 6; if (xpos>=6*40) break; } } m_refresh_counter++; return 0; } MC6845_UPDATE_ROW( sapi1_state::crtc_update_row ) { const rgb_t *palette = m_palette->palette()->entry_list_raw(); uint8_t chr,gfx,inv; uint16_t mem,x; uint32_t *p = &bitmap.pix32(y); for (x = 0; x < x_count; x++) { inv = gfx = 0; if (x == cursor_x) inv ^= 0xff; mem = (2*(ma + x)) & 0xfff; chr = m_p_videoram[mem] & 0x3f; if (ra < 8) gfx = MHB2501[(chr<<3) | ra] ^ inv; /* Display a scanline of a character */ *p++ = palette[BIT(gfx, 5)]; *p++ = palette[BIT(gfx, 4)]; *p++ = palette[BIT(gfx, 3)]; *p++ = palette[BIT(gfx, 2)]; *p++ = palette[BIT(gfx, 1)]; *p++ = palette[BIT(gfx, 0)]; } } /************************************** Keyboard **************************************/ READ8_MEMBER( sapi1_state::sapi1_keyboard_r ) { uint8_t key = 0xff; if (BIT(m_keyboard_mask, 0)) { key &= m_line0->read(); } if (BIT(m_keyboard_mask, 1)) { key &= m_line1->read(); } if (BIT(m_keyboard_mask, 2)) { key &= m_line2->read(); } if (BIT(m_keyboard_mask, 3)) { key &= m_line3->read(); } if (BIT(m_keyboard_mask, 4)) { key &= m_line4->read(); } return key; } WRITE8_MEMBER( sapi1_state::sapi1_keyboard_w ) { m_keyboard_mask = (data ^ 0xff ) & 0x1f; } READ8_MEMBER( sapi1_state::sapi2_keyboard_status_r) { return (m_term_data) ? 0 : 1; } READ8_MEMBER( sapi1_state::sapi2_keyboard_data_r) { uint8_t ret = ~m_term_data; m_term_data = 0; return ret; } void sapi1_state::kbd_put(u8 data) { m_term_data = data; } READ8_MEMBER(sapi1_state::uart_status_r) { uint8_t result = 0; result |= m_uart->tbmt_r() || m_uart->dav_r(); result |= m_uart->or_r() << 1; result |= m_uart->fe_r() << 2; result |= m_uart->pe_r() << 3; // RD4 = RI (= SI) result |= m_v24->dcd_r() << 5; result |= m_v24->dsr_r() << 6; result |= m_v24->cts_r() << 7; return result; } WRITE8_MEMBER(sapi1_state::modem_control_w) { m_v24->write_rts(BIT(data, 0)); m_v24->write_dtr(BIT(data, 1)); // WD2 = BRK // WD3 = S1 // WD4 = KAZ // WD5 = START // WD6 = IET // WD7 = IER } READ8_MEMBER(sapi1_state::uart_ready_r) { return (m_uart->dav_r() << 7) | (m_uart->tbmt_r() << 6) | 0x3f; } WRITE8_MEMBER(sapi1_state::uart_mode_w) { m_uart->write_np(BIT(data, 0)); m_uart->write_tsb(BIT(data, 1)); m_uart->write_nb1(BIT(data, 3)); m_uart->write_nb2(BIT(data, 2)); m_uart->write_eps(BIT(data, 4)); m_uart->write_cs(1); m_uart->write_cs(0); } WRITE8_MEMBER(sapi1_state::uart_reset_w) { // really pulsed by K155AG3 (=74123N): R29=22k, C16=220 (output combined with master reset) m_uart->write_xr(0); m_uart->write_xr(1); } /************************************** Machine **************************************/ READ8_MEMBER( sapi1_state::sapi3_0c_r ) { return 0xc0; } /* switch out the rom shadow */ WRITE8_MEMBER( sapi1_state::sapi3_00_w ) { m_bank1->set_entry(0); } /* to stop execution in random ram */ READ8_MEMBER( sapi1_state::sapi3_25_r ) { return m_zps3_25; } WRITE8_MEMBER( sapi1_state::sapi3_25_w ) { m_zps3_25 = data & 0xfc; //?? } MACHINE_RESET_MEMBER( sapi1_state, sapi1 ) { m_keyboard_mask = 0; m_refresh_counter = 0x20; } MACHINE_RESET_MEMBER( sapi1_state, sapizps3 ) { m_keyboard_mask = 0; m_bank1->set_entry(1); } DRIVER_INIT_MEMBER( sapi1_state, sapizps3 ) { uint8_t *RAM = memregion("maincpu")->base(); m_bank1->configure_entries(0, 2, &RAM[0x0000], 0x10000); } DRIVER_INIT_MEMBER( sapi1_state, sapizps3a ) { uint8_t *RAM = memregion("maincpu")->base(); m_bank1->configure_entries(0, 2, &RAM[0x0000], 0xf800); m_uart->write_swe(0); } DRIVER_INIT_MEMBER( sapi1_state, sapizps3b ) { uint8_t *RAM = memregion("maincpu")->base(); m_bank1->configure_entries(0, 2, &RAM[0x0000], 0x10000); } /* Machine driver */ MACHINE_CONFIG_START(sapi1_state::sapi1) /* basic machine hardware */ MCFG_CPU_ADD("maincpu", I8080A, XTAL(18'000'000) / 9) // Tesla MHB8080A + MHB8224 + MHB8228 MCFG_CPU_PROGRAM_MAP(sapi1_mem) MCFG_MACHINE_RESET_OVERRIDE(sapi1_state, sapi1) /* video hardware */ MCFG_SCREEN_ADD("screen", RASTER) MCFG_SCREEN_REFRESH_RATE(50) MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(2500)) /* not accurate */ MCFG_SCREEN_SIZE(40*6, 24*9) MCFG_SCREEN_VISIBLE_AREA(0, 40*6-1, 0, 24*9-1) MCFG_SCREEN_UPDATE_DRIVER(sapi1_state, screen_update_sapi1) MCFG_SCREEN_PALETTE("palette") MCFG_PALETTE_ADD_MONOCHROME("palette") /* internal ram */ MCFG_RAM_ADD(RAM_TAG) MCFG_RAM_DEFAULT_SIZE("64K") MACHINE_CONFIG_END MACHINE_CONFIG_START(sapi1_state::sapi2) sapi1(config); /* basic machine hardware */ MCFG_CPU_MODIFY("maincpu") MCFG_CPU_PROGRAM_MAP(sapi2_mem) MCFG_DEVICE_ADD("keyboard", GENERIC_KEYBOARD, 0) MCFG_GENERIC_KEYBOARD_CB(PUT(sapi1_state, kbd_put)) MACHINE_CONFIG_END MACHINE_CONFIG_START(sapi1_state::sapi3) sapi2(config); /* basic machine hardware */ MCFG_CPU_MODIFY("maincpu") MCFG_CPU_PROGRAM_MAP(sapi3_mem) MCFG_CPU_IO_MAP(sapi3_io) MCFG_MACHINE_RESET_OVERRIDE(sapi1_state, sapizps3 ) MCFG_SCREEN_MODIFY("screen") MCFG_SCREEN_SIZE(40*6, 20*9) MCFG_SCREEN_VISIBLE_AREA(0, 40*6-1, 0, 20*9-1) MCFG_SCREEN_UPDATE_DRIVER(sapi1_state, screen_update_sapi3) MACHINE_CONFIG_END MACHINE_CONFIG_START(sapi1_state::sapi3b) sapi3(config); /* basic machine hardware */ MCFG_CPU_MODIFY("maincpu") MCFG_CPU_PROGRAM_MAP(sapi3b_mem) MCFG_CPU_IO_MAP(sapi3b_io) MCFG_MC6845_ADD("crtc", MC6845, "screen", 1008000) // guess MCFG_MC6845_SHOW_BORDER_AREA(false) MCFG_MC6845_CHAR_WIDTH(6) MCFG_MC6845_UPDATE_ROW_CB(sapi1_state, crtc_update_row) MCFG_SCREEN_MODIFY("screen") MCFG_SCREEN_UPDATE_DEVICE("crtc", mc6845_device, screen_update) MCFG_SCREEN_NO_PALETTE MACHINE_CONFIG_END static DEVICE_INPUT_DEFAULTS_START( terminal ) DEVICE_INPUT_DEFAULTS( "RS232_RXBAUD", 0xff, RS232_BAUD_9600 ) DEVICE_INPUT_DEFAULTS( "RS232_TXBAUD", 0xff, RS232_BAUD_9600 ) DEVICE_INPUT_DEFAULTS( "RS232_STARTBITS", 0xff, RS232_STARTBITS_1 ) DEVICE_INPUT_DEFAULTS( "RS232_DATABITS", 0xff, RS232_DATABITS_8 ) // high bit stripped off in software DEVICE_INPUT_DEFAULTS( "RS232_PARITY", 0xff, RS232_PARITY_NONE ) DEVICE_INPUT_DEFAULTS( "RS232_STOPBITS", 0xff, RS232_STOPBITS_1 ) DEVICE_INPUT_DEFAULTS_END MACHINE_CONFIG_START(sapi1_state::sapi3a) /* basic machine hardware */ MCFG_CPU_ADD("maincpu", I8080A, XTAL(18'000'000) / 9) // Tesla MHB8080A + MHB8224 + MHB8228 MCFG_CPU_PROGRAM_MAP(sapi3a_mem) MCFG_CPU_IO_MAP(sapi3a_io) MCFG_MACHINE_RESET_OVERRIDE(sapi1_state, sapizps3 ) /* video hardware */ MCFG_DEVICE_ADD("uart", AY51013, 0) // Tesla MHB1012 MCFG_AY51013_TX_CLOCK(XTAL(12'288'000) / 80) // not actual rate? MCFG_AY51013_RX_CLOCK(XTAL(12'288'000) / 80) // not actual rate? MCFG_AY51013_READ_SI_CB(DEVREADLINE("v24", rs232_port_device, rxd_r)) MCFG_AY51013_WRITE_SO_CB(DEVWRITELINE("v24", rs232_port_device, write_txd)) MCFG_AY51013_AUTO_RDAV(true) // RDAV not actually tied to RDE, but pulsed by K155AG3 (=74123N): R25=22k, C14=220 MCFG_RS232_PORT_ADD("v24", default_rs232_devices, "terminal") MCFG_DEVICE_CARD_DEVICE_INPUT_DEFAULTS("terminal", terminal) /* internal ram */ MCFG_RAM_ADD(RAM_TAG) MCFG_RAM_DEFAULT_SIZE("64K") MACHINE_CONFIG_END /************************************** Roms **************************************/ ROM_START( sapi1 ) ROM_REGION( 0x10000, "maincpu", 0 ) ROM_SYSTEM_BIOS( 0, "mb1", "MB1" ) ROMX_LOAD( "sapi1.rom", 0x0000, 0x1000, CRC(c6e85b01) SHA1(2a26668249c6161aef7215a1e2b92bfdf6fe3671), ROM_BIOS(1)) ROM_SYSTEM_BIOS( 1, "mb2", "MB2 (ANK-1)" ) ROMX_LOAD( "mb2_4.bin", 0x0000, 0x1000, CRC(a040b3e0) SHA1(586990a07a96323741679a11ff54ad0023da87bc), ROM_BIOS(2)) ROM_REGION( 0x1000, "chargen", 0 ) ROM_LOAD( "sapi1.chr", 0x0000, 0x1000, CRC(9edafa2c) SHA1(a903db0e8923cca91646274d010dc19b6b377e3e) ) ROM_END ROM_START( sapizps2 ) ROM_REGION( 0x10000, "maincpu", 0 ) ROM_SYSTEM_BIOS( 0, "v4", "MIKOS 4" ) ROMX_LOAD( "36.bin", 0x0000, 0x0800, CRC(a27f340a) SHA1(d07d208fcbe428897336c17197d3e8fb52181f38), ROM_BIOS(1)) ROMX_LOAD( "37.bin", 0x0800, 0x0800, CRC(30daa708) SHA1(66e990c40788ee25cf6cabd4842a78daf4fcdddd), ROM_BIOS(1)) ROM_SYSTEM_BIOS( 1, "v5", "MIKOS 5" ) ROMX_LOAD( "mikos5_1.bin", 0x0000, 0x0800, CRC(c2a83ca3) SHA1(a3678253d7690c89945e791ea0f8e15b081c9126), ROM_BIOS(2)) ROMX_LOAD( "mikos5_2.bin", 0x0800, 0x0800, CRC(c4458a04) SHA1(0cc909323f0e6507d95e57ea39e1deb8bd57bf89), ROM_BIOS(2)) ROMX_LOAD( "mikos5_3.bin", 0x1000, 0x0800, CRC(efb499f3) SHA1(78f0ca3ff10d7af4ae94ab820723296beb035f8f), ROM_BIOS(2)) ROMX_LOAD( "mikos5_4.bin", 0x1800, 0x0800, CRC(4d90e9be) SHA1(8ec554198697550a49432e8210d43700ef1d6a32), ROM_BIOS(2)) ROM_SYSTEM_BIOS( 2, "mb3", "MB3 (Consul)" ) ROMX_LOAD( "mb3_1.bin", 0x0000, 0x1000, CRC(be895f88) SHA1(7fc2a92f41d978a9f0ccd0e235ea3c6146adfb6f), ROM_BIOS(3)) ROM_END ROM_START( sapizps3 ) ROM_REGION( 0x10800, "maincpu", 0 ) // These 2 bioses use videoram at F800 ROM_SYSTEM_BIOS( 0, "per", "Perina" ) ROMX_LOAD( "perina_1988.bin",0x10000, 0x0800, CRC(d71e8d3a) SHA1(9b3a26ea7c2f2c8a1fb10b51c1c880acc9fd806d), ROM_BIOS(1)) ROM_SYSTEM_BIOS( 1, "1zmod", "JPR-1Zmod" ) ROMX_LOAD( "jpr1zmod.bin", 0x10000, 0x0800, CRC(69a29b07) SHA1(1cd31032954fcd7d10b1586be62db6f7597eb4f2), ROM_BIOS(2)) ROM_END ROM_START( sapizps3a ) ROM_REGION( 0x10000, "maincpu", 0 ) // This bios uses a terminal ROM_LOAD( "jpr1a.bin", 0xf800, 0x0800, CRC(3ed89786) SHA1(dcc8657b4884bfe58d114c539b733b73d038ee30)) ROM_END ROM_START( sapizps3b ) ROM_REGION( 0x10800, "maincpu", 0 ) // This bios uses a 6845 ROM_LOAD( "pkt1.bin", 0x10000, 0x0800, CRC(ed5a2725) SHA1(3383c15f87f976400b8d0f31829e2a95236c4b6c)) ROM_END /* Driver */ // YEAR NAME PARENT COMPAT MACHINE INPUT CLASS INIT COMPANY FULLNAME FLAGS COMP( 1985, sapi1, 0, 0, sapi1, sapi1, sapi1_state, 0, "Tesla", "SAPI-1 ZPS 1", MACHINE_NO_SOUND_HW ) COMP( 1985, sapizps2, sapi1, 0, sapi2, sapi1, sapi1_state, 0, "Tesla", "SAPI-1 ZPS 2", MACHINE_NO_SOUND_HW ) COMP( 1985, sapizps3, sapi1, 0, sapi3, sapi1, sapi1_state, sapizps3, "Tesla", "SAPI-1 ZPS 3", MACHINE_NOT_WORKING | MACHINE_NO_SOUND_HW ) COMP( 1985, sapizps3a, sapi1, 0, sapi3a, sapi1, sapi1_state, sapizps3a, "Tesla", "SAPI-1 ZPS 3 (terminal)", MACHINE_NOT_WORKING | MACHINE_NO_SOUND_HW ) COMP( 1985, sapizps3b, sapi1, 0, sapi3b, sapi1, sapi1_state, sapizps3b, "Tesla", "SAPI-1 ZPS 3 (6845)", MACHINE_NOT_WORKING | MACHINE_NO_SOUND_HW )
33.813144
162
0.701665
rjw57
f8bfce818aeaf12f4827ac8abab188a46a6f6d8b
7,939
cpp
C++
tesseract_common/test/plugin_loader_unit.cpp
daoran/tesseract
2c593d12a0a470bd2672fdf6ff86843dd69b6e4a
[ "BSD-3-Clause", "BSD-2-Clause", "Apache-2.0" ]
25
2021-11-08T05:41:28.000Z
2022-03-29T12:17:30.000Z
tesseract_common/test/plugin_loader_unit.cpp
daoran/tesseract
2c593d12a0a470bd2672fdf6ff86843dd69b6e4a
[ "BSD-3-Clause", "BSD-2-Clause", "Apache-2.0" ]
79
2021-10-30T19:53:38.000Z
2022-03-31T21:37:43.000Z
tesseract_common/test/plugin_loader_unit.cpp
daoran/tesseract
2c593d12a0a470bd2672fdf6ff86843dd69b6e4a
[ "BSD-3-Clause", "BSD-2-Clause", "Apache-2.0" ]
10
2021-11-09T03:02:08.000Z
2022-03-23T02:24:33.000Z
/** * @file plugin_loader_unit.h * @brief Plugin Loader Unit Tests * * @author Levi Armstrong * @date March 25, 2021 * @version TODO * @bug No known bugs * * @copyright Copyright (c) 2021, Southwest Research Institute * * @par License * Software License Agreement (Apache License) * @par * 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 * @par * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tesseract_common/macros.h> TESSERACT_COMMON_IGNORE_WARNINGS_PUSH #include <gtest/gtest.h> TESSERACT_COMMON_IGNORE_WARNINGS_POP #include <tesseract_common/class_loader.h> #include <tesseract_common/plugin_loader.h> #include "test_plugin_base.h" const std::string tesseract_common::TestPluginBase::SECTION_NAME = "TestBase"; TEST(TesseractClassLoaderUnit, parseEnvironmentVariableListUnit) // NOLINT { std::string env_var = "UNITTESTENV=a:b:c"; putenv(env_var.data()); std::set<std::string> s = tesseract_common::parseEnvironmentVariableList("UNITTESTENV"); std::vector<std::string> v(s.begin(), s.end()); EXPECT_EQ(v[0], "a"); EXPECT_EQ(v[1], "b"); EXPECT_EQ(v[2], "c"); } TEST(TesseractClassLoaderUnit, LoadTestPlugin) // NOLINT { using tesseract_common::ClassLoader; using tesseract_common::TestPluginBase; const std::string lib_name = "tesseract_common_test_plugin_multiply"; const std::string lib_dir = std::string(TEST_PLUGIN_DIR); const std::string symbol_name = "plugin"; { std::vector<std::string> sections = ClassLoader::getAvailableSections(lib_name, lib_dir); EXPECT_EQ(sections.size(), 1); EXPECT_EQ(sections.at(0), "TestBase"); sections = ClassLoader::getAvailableSections(lib_name, lib_dir, true); EXPECT_TRUE(sections.size() > 1); } { std::vector<std::string> symbols = ClassLoader::getAvailableSymbols("TestBase", lib_name, lib_dir); EXPECT_EQ(symbols.size(), 1); EXPECT_EQ(symbols.at(0), symbol_name); } { EXPECT_TRUE(ClassLoader::isClassAvailable(symbol_name, lib_name, lib_dir)); auto plugin = ClassLoader::createSharedInstance<TestPluginBase>(symbol_name, lib_name, lib_dir); EXPECT_TRUE(plugin != nullptr); EXPECT_NEAR(plugin->multiply(5, 5), 25, 1e-8); } // For some reason on Ubuntu 18.04 it does not search the current directory when only the library name is provided #if BOOST_VERSION > 106800 { EXPECT_TRUE(ClassLoader::isClassAvailable(symbol_name, lib_name)); auto plugin = ClassLoader::createSharedInstance<TestPluginBase>(symbol_name, lib_name); EXPECT_TRUE(plugin != nullptr); EXPECT_NEAR(plugin->multiply(5, 5), 25, 1e-8); } #endif { EXPECT_FALSE(ClassLoader::isClassAvailable(symbol_name, lib_name, "does_not_exist")); EXPECT_FALSE(ClassLoader::isClassAvailable(symbol_name, "does_not_exist", lib_dir)); EXPECT_FALSE(ClassLoader::isClassAvailable("does_not_exist", lib_name, lib_dir)); } { EXPECT_FALSE(ClassLoader::isClassAvailable(symbol_name, "does_not_exist")); EXPECT_FALSE(ClassLoader::isClassAvailable("does_not_exist", lib_name)); } { // NOLINTNEXTLINE EXPECT_ANY_THROW(ClassLoader::createSharedInstance<TestPluginBase>(symbol_name, lib_name, "does_not_exist")); // NOLINTNEXTLINE EXPECT_ANY_THROW(ClassLoader::createSharedInstance<TestPluginBase>(symbol_name, "does_not_exist", lib_dir)); // NOLINTNEXTLINE EXPECT_ANY_THROW(ClassLoader::createSharedInstance<TestPluginBase>("does_not_exist", lib_name, lib_dir)); } { EXPECT_ANY_THROW(ClassLoader::createSharedInstance<TestPluginBase>(symbol_name, "does_not_exist")); // NOLINT EXPECT_ANY_THROW(ClassLoader::createSharedInstance<TestPluginBase>("does_not_exist", lib_name)); // NOLINT } } TEST(TesseractPluginLoaderUnit, LoadTestPlugin) // NOLINT { using tesseract_common::PluginLoader; using tesseract_common::TestPluginBase; { PluginLoader plugin_loader; plugin_loader.search_paths.insert(std::string(TEST_PLUGIN_DIR)); plugin_loader.search_libraries.insert("tesseract_common_test_plugin_multiply"); EXPECT_TRUE(plugin_loader.isPluginAvailable("plugin")); auto plugin = plugin_loader.instantiate<TestPluginBase>("plugin"); EXPECT_TRUE(plugin != nullptr); EXPECT_NEAR(plugin->multiply(5, 5), 25, 1e-8); std::vector<std::string> sections = plugin_loader.getAvailableSections(); EXPECT_EQ(sections.size(), 1); EXPECT_EQ(sections.at(0), "TestBase"); sections = plugin_loader.getAvailableSections(true); EXPECT_TRUE(sections.size() > 1); std::vector<std::string> symbols = plugin_loader.getAvailablePlugins<TestPluginBase>(); EXPECT_EQ(symbols.size(), 1); EXPECT_EQ(symbols.at(0), "plugin"); symbols = plugin_loader.getAvailablePlugins("TestBase"); EXPECT_EQ(symbols.size(), 1); EXPECT_EQ(symbols.at(0), "plugin"); } // For some reason on Ubuntu 18.04 it does not search the current directory when only the library name is provided #if BOOST_VERSION > 106800 { PluginLoader plugin_loader; plugin_loader.search_libraries.insert("tesseract_common_test_plugin_multiply"); EXPECT_TRUE(plugin_loader.isPluginAvailable("plugin")); auto plugin = plugin_loader.instantiate<TestPluginBase>("plugin"); EXPECT_TRUE(plugin != nullptr); EXPECT_NEAR(plugin->multiply(5, 5), 25, 1e-8); } #endif { PluginLoader plugin_loader; plugin_loader.search_system_folders = false; plugin_loader.search_paths.insert("does_not_exist"); plugin_loader.search_libraries.insert("tesseract_common_test_plugin_multiply"); { EXPECT_FALSE(plugin_loader.isPluginAvailable("plugin")); auto plugin = plugin_loader.instantiate<TestPluginBase>("plugin"); EXPECT_TRUE(plugin == nullptr); } } { PluginLoader plugin_loader; plugin_loader.search_system_folders = false; plugin_loader.search_libraries.insert("tesseract_common_test_plugin_multiply"); { EXPECT_FALSE(plugin_loader.isPluginAvailable("does_not_exist")); auto plugin = plugin_loader.instantiate<TestPluginBase>("does_not_exist"); EXPECT_TRUE(plugin == nullptr); } plugin_loader.search_system_folders = true; { EXPECT_FALSE(plugin_loader.isPluginAvailable("does_not_exist")); auto plugin = plugin_loader.instantiate<TestPluginBase>("does_not_exist"); EXPECT_TRUE(plugin == nullptr); } } { PluginLoader plugin_loader; plugin_loader.search_system_folders = false; plugin_loader.search_libraries.insert("does_not_exist"); { EXPECT_FALSE(plugin_loader.isPluginAvailable("plugin")); auto plugin = plugin_loader.instantiate<TestPluginBase>("plugin"); EXPECT_TRUE(plugin == nullptr); } plugin_loader.search_system_folders = true; { EXPECT_FALSE(plugin_loader.isPluginAvailable("plugin")); auto plugin = plugin_loader.instantiate<TestPluginBase>("plugin"); EXPECT_TRUE(plugin == nullptr); } } { PluginLoader plugin_loader; EXPECT_FALSE(plugin_loader.isPluginAvailable("plugin")); auto plugin = plugin_loader.instantiate<TestPluginBase>("plugin"); EXPECT_TRUE(plugin == nullptr); } { PluginLoader plugin_loader; plugin_loader.search_system_folders = false; EXPECT_FALSE(plugin_loader.isPluginAvailable("plugin")); auto plugin = plugin_loader.instantiate<TestPluginBase>("plugin"); EXPECT_TRUE(plugin == nullptr); } } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
34.072961
114
0.736239
daoran
f8c1a03594027fe0986ea2d3c3ec87961f7bea81
2,085
cpp
C++
cpp/util/common.cpp
simpleton/profilo
91ef4ba1a8316bad2b3080210316dfef4761e180
[ "Apache-2.0" ]
null
null
null
cpp/util/common.cpp
simpleton/profilo
91ef4ba1a8316bad2b3080210316dfef4761e180
[ "Apache-2.0" ]
null
null
null
cpp/util/common.cpp
simpleton/profilo
91ef4ba1a8316bad2b3080210316dfef4761e180
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2004-present, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.h" #include <chrono> #include <algorithm> #if defined(__linux__) || defined(ANDROID) # include <sys/syscall.h> // __NR_gettid, __NR_clock_gettime #else # include <pthread.h> // pthread_self() #endif namespace facebook { namespace profilo { static const int64_t kSecondNanos = 1000000000; #if defined(__linux__) || defined(ANDROID) int64_t monotonicTime() { timespec ts{}; syscall(__NR_clock_gettime, CLOCK_MONOTONIC, &ts); return static_cast<int64_t>(ts.tv_sec) * kSecondNanos + ts.tv_nsec; } #else int64_t monotonicTime() { auto now = std::chrono::steady_clock::now().time_since_epoch(); return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count(); } #endif #if defined(__linux__) || defined(ANDROID) int32_t threadID() { return static_cast<int32_t>(syscall(__NR_gettid)); } #elif __MACH__ int32_t threadID() { return static_cast<int32_t>(pthread_mach_thread_np(pthread_self())); } #else #error "Do not have a threadID implementation for this platform" #endif #if defined(__linux__) || defined(ANDROID) int32_t systemClockTickIntervalMs() { int clockTick = static_cast<int32_t>(sysconf(_SC_CLK_TCK)); if (clockTick <= 0) { return 0; } return std::max(1000 / clockTick, 1); } #elif __MACH__ int32_t systemClockTickIntervalMs() { return 10; // Plain value to support tests running on OSX. } #else #error "Do not have systemClockTickIntervalMs implementation for this platform" #endif } // profilo } // facebook
27.434211
79
0.738129
simpleton
f8c6f4cd3c1e3104ca66f480bd5a5fc2e1af0046
589
cpp
C++
peg/bluebook/find_the_character.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-07-16T01:46:38.000Z
2020-07-16T01:46:38.000Z
peg/bluebook/find_the_character.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
null
null
null
peg/bluebook/find_the_character.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-05-27T14:30:43.000Z
2020-05-27T14:30:43.000Z
#include <cctype> #include <iostream> #include <string> using namespace std; inline void use_io_optimizations() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } int main() { use_io_optimizations(); char wanted; cin >> wanted; cin.ignore(); string sentence; getline(cin, sentence, '.'); unsigned int occurrences {0}; for (auto symbol : sentence) { if (tolower(symbol) == tolower(wanted)) { ++occurrences; } } cout << sentence << '\n' << occurrences << '\n'; return 0; }
14.725
47
0.561969
Rkhoiwal
f8cb18e9c09a49bd20739273bcc05d9a1006a95e
1,819
cc
C++
ch3/send-more.cc
araya-andres/classic_computer_sci
3cb67563f10be75f586315d156506cf76e18f884
[ "Unlicense" ]
21
2017-10-12T05:03:09.000Z
2022-03-30T00:56:53.000Z
ch3/send-more.cc
araya-andres/classic_computer_sci
3cb67563f10be75f586315d156506cf76e18f884
[ "Unlicense" ]
1
2017-11-14T05:29:12.000Z
2017-11-14T17:28:48.000Z
ch3/send-more.cc
araya-andres/classic_computer_sci
3cb67563f10be75f586315d156506cf76e18f884
[ "Unlicense" ]
10
2018-03-30T14:37:48.000Z
2022-02-21T01:15:52.000Z
#include "common.h" #include "csp.h" #include "prettyprint.hpp" #include <iostream> #include <numeric> #include <string> #include <vector> std::vector<char> flatten(const std::vector<std::string>& v) { std::vector<char> flat; auto it = flat.begin(); for (const auto& s: v) it = flat.insert(it, s.cbegin(), s.cend()); return flat; } inline bool has_duplicate_values(const Assigment<char, int>& a) { return unique(map_values_to_vector(a)).size() < a.size(); } std::pair<int, bool> word_to_value(const std::string& w, const Assigment<char, int>& a) { int n = 0; for (auto ch : w) { auto it = a.find(ch); if (it == a.end()) return {0, false}; n = n * 10 + it->second; } return {n, true}; } struct SendMoreMoneyConstraint { bool contains(char c) const { return c == ch; } bool is_satisfied(const Assigment<char, int>& a) const { if (has_duplicate_values(a)) return false; if (a.size() < n) return true; std::vector<int> values; for (const auto& w: words) { const auto [value, ok] = word_to_value(w, a); if (!ok) return false; values.push_back(value); } auto sum = std::accumulate(values.cbegin(), values.cend() - 1, 0); return sum == values.back(); } char ch; size_t n; std::vector<std::string> words; }; int main() { std::vector<std::string> words{"send", "more", "money"}; Constraints<SendMoreMoneyConstraint> constraints; Domains<char, int> domains; auto variables = unique(flatten(words)); for (auto ch: variables) { constraints.push_back({ch, variables.size(), words}); domains.insert({ch, {0,1,2,3,4,5,6,7,8,9}}); } std::cout << backtracking_search(constraints, domains, variables) << '\n'; }
30.316667
89
0.598681
araya-andres
f8cf564ef2ef49d1b9c3391dff499ef55d9050bd
6,563
cpp
C++
2 course/EVM/lab_17/main.cpp
SgAkErRu/labs
9cf71e131513beb3c54ad3599f2a1e085bff6947
[ "BSD-3-Clause" ]
null
null
null
2 course/EVM/lab_17/main.cpp
SgAkErRu/labs
9cf71e131513beb3c54ad3599f2a1e085bff6947
[ "BSD-3-Clause" ]
null
null
null
2 course/EVM/lab_17/main.cpp
SgAkErRu/labs
9cf71e131513beb3c54ad3599f2a1e085bff6947
[ "BSD-3-Clause" ]
null
null
null
// -- системные либы -- // #include <windows.h> #include <vector> #include <algorithm> #include <random> #include <ctime> // Файлы заголовков C RunTime #include <stdlib.h> #include <malloc.h> #include <memory.h> #include <tchar.h> #include "resource.h" // -- мои классы -- // #include "bitstring.h" #include "five.h" #define MAX_LOADSTRING 100 using namespace std; // Глобальные переменные: static HINSTANCE hInst; // -- текущий экземпляр приложения -- // static Five op1; // наши операнды static Five op2; static time_t seed = time(nullptr); static mt19937 mt(seed); // -- объявления функций, включенных в этот модуль кода -- // BOOL InitInstance(HINSTANCE, int); // -- инициализация главного окна -- // LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // -- обработчик сообщений для главного окна -- // LRESULT CALLBACK About(HWND, UINT, WPARAM, LPARAM); // -- обработчик сообщений для диалогового окна "О программе" -- // void get_rand_op() // Генерируем операнды { uniform_int_distribution<int> dist_for_len(1, 5); uniform_int_distribution<int> dist_for_digit(0, 4); size_t len1 = dist_for_len(mt); size_t len2 = dist_for_len(mt); string op1_str = ""; for (size_t i = 0; i < len1; ++i) { op1_str += to_string(dist_for_digit(mt)); } string op2_str = ""; for (size_t i = 0; i < len2; ++i) { op2_str += to_string(dist_for_digit(mt)); } op1 = {op1_str}; op2 = {op2_str}; if (op1<op2) swap(op1,op2); } // -- главная функция -- // int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance) UNREFERENCED_PARAMETER(lpCmdLine) setlocale( LC_ALL, "rus" ); // Выполнить инициализацию приложения: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_MAIN)); // -- для горячих клавиш -- // MSG msg; // Цикл основного сообщения: while (GetMessage(&msg, nullptr, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return int(msg.wParam); } // -- создаем (инициализируем) главное окно программы -- // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { hInst = hInstance; // -- сохранить дескриптор экземпляра в глобальной переменной -- // HWND hWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MAIN),nullptr,DLGPROC(WndProc)); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } // -- обрабатывает сообщения (сигналы, события) в главном окне -- // // WM_COMMAND - обработка меню приложения -- // // WM_DESTROY - ввести сообщение о выходе и вернуться -- // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId; static LOGFONTW lf; HFONT hFont1; Five res; switch (message) { case WM_INITDIALOG: // -- делаем шрифт побольше -- // lf.lfHeight = 24; lstrcpy(LPTSTR(&lf.lfFaceName), L"Microsoft Sans Serif"); hFont1 = CreateFontIndirect(&lf); // -- устанавливаем шрифт для текста -- // SendMessage(GetDlgItem(hWnd,IDC_OP1_TEXT), WM_SETFONT, WPARAM(hFont1), TRUE ); SendMessage(GetDlgItem(hWnd,IDC_OP2_TEXT), WM_SETFONT, WPARAM(hFont1), TRUE ); SendMessage(GetDlgItem(hWnd,ID_OP1), WM_SETFONT, WPARAM(hFont1), TRUE ); SendMessage(GetDlgItem(hWnd,ID_OP2), WM_SETFONT, WPARAM(hFont1), TRUE ); SendMessage(GetDlgItem(hWnd,IDB_ADD), WM_SETFONT, WPARAM(hFont1), TRUE ); SendMessage(GetDlgItem(hWnd,IDB_SUB), WM_SETFONT, WPARAM(hFont1), TRUE ); SendMessage(GetDlgItem(hWnd,IDB_MUL), WM_SETFONT, WPARAM(hFont1), TRUE ); SendMessage(GetDlgItem(hWnd,IDB_DIV), WM_SETFONT, WPARAM(hFont1), TRUE ); SendMessage(GetDlgItem(hWnd,IDC_RES_TEXT), WM_SETFONT, WPARAM(hFont1), TRUE ); SendMessage(GetDlgItem(hWnd,ID_RES), WM_SETFONT, WPARAM(hFont1), TRUE ); SendMessage(GetDlgItem(hWnd,IDB_FORWARD), WM_SETFONT, WPARAM(hFont1), TRUE ); SendMessage(GetDlgItem(hWnd,IDOK), WM_SETFONT, WPARAM(hFont1), TRUE ); get_rand_op(); SetDlgItemTextA(hWnd,ID_OP1,op1.toString().c_str()); SetDlgItemTextA(hWnd,ID_OP2,op2.toString().c_str()); return TRUE; case WM_COMMAND: wmId = LOWORD(wParam); // Разобрать выбор в меню: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, DLGPROC(About)); break; case IDM_EXIT: case IDCANCEL: case IDOK: DestroyWindow(hWnd); break; case IDB_FORWARD: get_rand_op(); SetDlgItemTextA(hWnd,ID_OP1,op1.toString().c_str()); SetDlgItemTextA(hWnd,ID_OP2,op2.toString().c_str()); SetDlgItemTextA(hWnd,ID_RES,""); break; case IDB_ADD: res = op1+op2; SetDlgItemTextA(hWnd,ID_RES,res.toString().c_str()); break; case IDB_SUB: res = op1-op2; SetDlgItemTextA(hWnd,ID_RES,res.toString().c_str()); break; case IDB_MUL: res = op1*op2; SetDlgItemTextA(hWnd,ID_RES,res.toString().c_str()); break; case IDB_DIV: if (size_t(std::count(op2.begin(),op2.end(),0)) != op2.get_size()) { res = op1/op2; SetDlgItemTextA(hWnd,ID_RES,res.toString().c_str()); } else { SetDlgItemTextA(hWnd,ID_RES,"zero divide"); } break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_DESTROY: PostQuitMessage(0); break; } return FALSE; } // Обработчик сообщений для окна "О программе". LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam) switch (message) { case WM_INITDIALOG: return TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return TRUE; } break; } return FALSE; }
30.668224
120
0.610544
SgAkErRu
f8d28173e818cf3982045871aab8aaadf5d44aa8
2,241
cpp
C++
GEngine/GRendererInfra/GRiRenderer.cpp
hegaoxiang/new---
1c65dce79fa292ff8d2f79fb4cf9d8e207a82be1
[ "Zlib" ]
null
null
null
GEngine/GRendererInfra/GRiRenderer.cpp
hegaoxiang/new---
1c65dce79fa292ff8d2f79fb4cf9d8e207a82be1
[ "Zlib" ]
null
null
null
GEngine/GRendererInfra/GRiRenderer.cpp
hegaoxiang/new---
1c65dce79fa292ff8d2f79fb4cf9d8e207a82be1
[ "Zlib" ]
null
null
null
#include "GRiRenderer.h" float GRiRenderer::AspectRatio() const { return static_cast<float>(mClientWidth) / mClientHeight; } HWND GRiRenderer::MainWnd()const { return mhMainWnd; } void GRiRenderer::SetClientWidth(int width) { mClientWidth = width; } void GRiRenderer::SetClientHeight(int height) { mClientHeight = height; } bool GRiRenderer::IsRunning() const { return mIsRunning; } void GRiRenderer::SetCamera(GRiCamera* cam) { pCamera = cam; } void GRiRenderer::SetScene(GScene* scene) { pScene = scene; } GRiRendererFactory* GRiRenderer::GetFactory() { return mFactory.get(); } void GRiRenderer::SyncTextures(std::unordered_map<std::string, std::unique_ptr<GRiTexture>>& mTextures) { pTextures.clear(); std::unordered_map<std::string, std::unique_ptr<GRiTexture>>::iterator i; for (i = mTextures.begin(); i != mTextures.end(); i++) { pTextures[i->first] = i->second.get(); } } void GRiRenderer::SyncMaterials(std::unordered_map<std::string, std::unique_ptr<GRiMaterial>>& mMaterials) { pMaterials.clear(); std::unordered_map<std::string, std::unique_ptr<GRiMaterial>>::iterator i; for (i = mMaterials.begin(); i != mMaterials.end(); i++) { pMaterials[i->first] = i->second.get(); } } void GRiRenderer::SyncMeshes(std::unordered_map<std::string, std::unique_ptr<GRiMesh>>& mMeshes) { pMeshes.clear(); std::unordered_map<std::string, std::unique_ptr<GRiMesh>>::iterator i; for (i = mMeshes.begin(); i != mMeshes.end(); i++) { pMeshes[i->first] = i->second.get(); } } void GRiRenderer::SyncSceneObjects(std::unordered_map<std::string, std::unique_ptr<GRiSceneObject>>& mSceneObjects, std::vector<GRiSceneObject*>* mSceneObjectLayer) { pSceneObjects.clear(); std::unordered_map<std::string, std::unique_ptr<GRiSceneObject>>::iterator i; for (i = mSceneObjects.begin(); i != mSceneObjects.end(); i++) { pSceneObjects[i->first] = i->second.get(); } for (size_t layer = 0; layer != (size_t)(RenderLayer::Count); layer++) { pSceneObjectLayer[layer].clear(); for (auto pSObj : mSceneObjectLayer[layer]) { pSceneObjectLayer[layer].push_back(pSObj); } } } int GRiRenderer::GetClientWidth()const { return mClientWidth; } int GRiRenderer::GetClientHeight()const { return mClientHeight; }
23.34375
164
0.714859
hegaoxiang
f8d59dc510fbd2e182e6d7397e856d11b14e869f
582
cpp
C++
algorithms/max-min/main.cpp
valentinvstoyanov/dsa-cpp
0d47377eff2df2888e7394b39203220e7aa82441
[ "MIT" ]
null
null
null
algorithms/max-min/main.cpp
valentinvstoyanov/dsa-cpp
0d47377eff2df2888e7394b39203220e7aa82441
[ "MIT" ]
null
null
null
algorithms/max-min/main.cpp
valentinvstoyanov/dsa-cpp
0d47377eff2df2888e7394b39203220e7aa82441
[ "MIT" ]
null
null
null
#include <iostream> #include "max_min.h" int main() { int arr[10] = {-199, 20, -200, 50, 1000, 1000, - 201, 1541, 0, 1}; auto mm = MaxMin(arr, 10); std::cout << "max = " << mm.first << ", min = " << mm.second << std::endl; std::cout << "max = " << Max(arr, 10) << std::endl; std::cout << "max = " << Max(arr, 0) << std::endl; std::cout << "max = " << Max<int>(nullptr, 1) << std::endl; std::cout << "min = " << Min(arr, 10) << std::endl; std::cout << "min = " << Min(arr, 0) << std::endl; std::cout << "min = " << Min<int>(nullptr, 10) << std::endl; return 0; }
38.8
76
0.501718
valentinvstoyanov
f8d87d10e11c2ceea2ea15f7130423e82793e1f0
1,676
cc
C++
test/quic/test_client_work.cc
cbodley/nexus
6e5b19b6c6c74007a0643c55eb0775eb86e38f9b
[ "BSL-1.0" ]
6
2021-10-31T10:33:30.000Z
2022-03-25T20:54:58.000Z
test/quic/test_client_work.cc
cbodley/nexus
6e5b19b6c6c74007a0643c55eb0775eb86e38f9b
[ "BSL-1.0" ]
null
null
null
test/quic/test_client_work.cc
cbodley/nexus
6e5b19b6c6c74007a0643c55eb0775eb86e38f9b
[ "BSL-1.0" ]
null
null
null
#include <nexus/quic/server.hpp> #include <gtest/gtest.h> #include <optional> #include <nexus/quic/client.hpp> #include <nexus/quic/connection.hpp> #include <nexus/global_init.hpp> #include "certificate.hpp" namespace nexus { // constuct a client and server on different io_contexts class Client : public testing::Test { protected: static constexpr const char* alpn = "\04quic"; global::context global = global::init_client_server(); ssl::context ssl = test::init_server_context(alpn); ssl::context sslc = test::init_client_context(alpn); boost::asio::io_context scontext; quic::server server = quic::server{scontext.get_executor()}; boost::asio::ip::address localhost = boost::asio::ip::make_address("127.0.0.1"); quic::acceptor acceptor{server, udp::endpoint{localhost, 0}, ssl}; boost::asio::io_context ccontext; quic::client client{ccontext.get_executor(), udp::endpoint{}, sslc}; }; TEST_F(Client, connection_work) { auto conn = quic::connection{client, acceptor.local_endpoint(), "host"}; ccontext.poll(); ASSERT_FALSE(ccontext.stopped()); // connection maintains work conn.close(); ccontext.poll(); ASSERT_TRUE(ccontext.stopped()); // close stops work } TEST_F(Client, two_connection_work) { auto conn1 = quic::connection{client, acceptor.local_endpoint(), "host"}; ccontext.poll(); ASSERT_FALSE(ccontext.stopped()); auto conn2 = quic::connection{client, acceptor.local_endpoint(), "host"}; ccontext.poll(); ASSERT_FALSE(ccontext.stopped()); conn1.close(); ccontext.poll(); ASSERT_FALSE(ccontext.stopped()); conn2.close(); ccontext.poll(); ASSERT_TRUE(ccontext.stopped()); } } // namespace nexus
26.1875
82
0.718974
cbodley
f8dbb3eb647fa85d9e91dd7d50d4d5184d990d08
5,500
cpp
C++
robolibJNI/lib/SolenoidJNI.cpp
robolib/robolibJNI
a8f74daf29f2ada8defff97b708f682bfd738071
[ "BSD-3-Clause", "MIT" ]
null
null
null
robolibJNI/lib/SolenoidJNI.cpp
robolib/robolibJNI
a8f74daf29f2ada8defff97b708f682bfd738071
[ "BSD-3-Clause", "MIT" ]
null
null
null
robolibJNI/lib/SolenoidJNI.cpp
robolib/robolibJNI
a8f74daf29f2ada8defff97b708f682bfd738071
[ "BSD-3-Clause", "MIT" ]
null
null
null
#include <jni.h> #include "Log.hpp" #include "HAL/HAL.hpp" #include "io_github_robolib_jni_SolenoidJNI.h" TLogLevel solenoidJNILogLevel = logERROR; #define SOLENOIDJNI_LOG(level) \ if (level > solenoidJNILogLevel) ; \ else Log().Get(level) typedef void *VoidPointer; /* * Class: io_github_robolib_jni_SolenoidJNI * Method: initializeSolenoidPort * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/IntBuffer;)V */ JNIEXPORT jobject JNICALL Java_io_github_robolib_jni_SolenoidJNI_initializeSolenoidPort (JNIEnv *env, jclass, jobject port_pointer, jobject status) { SOLENOIDJNI_LOG(logDEBUG) << "Calling SolenoidJNI initializeSolenoidPort"; VoidPointer *port_pointer_pointer = (VoidPointer *)env->GetDirectBufferAddress(port_pointer); SOLENOIDJNI_LOG(logDEBUG) << "Port Ptr = " << *port_pointer_pointer; char *aschars = (char *)(*port_pointer_pointer); SOLENOIDJNI_LOG(logDEBUG) << '\t' << (int)aschars[0] << '\t' << (int)aschars[1] << std::endl; jint *status_pointer = (jint*)env->GetDirectBufferAddress(status); SOLENOIDJNI_LOG(logDEBUG) << "Status Ptr = " << status_pointer; VoidPointer *solenoid_port_pointer = new VoidPointer; *solenoid_port_pointer = initializeSolenoidPort(*port_pointer_pointer, status_pointer); SOLENOIDJNI_LOG(logDEBUG) << "Status = " << *status_pointer; SOLENOIDJNI_LOG(logDEBUG) << "Solenoid Port Pointer = " << *solenoid_port_pointer; int *asints = (int *)(*solenoid_port_pointer); SOLENOIDJNI_LOG(logDEBUG) << '\t' << asints[0] << '\t' << asints[1] << std::endl; return env->NewDirectByteBuffer(solenoid_port_pointer, 4); } /* * Class: io_github_robolib_jni_SolenoidJNI * Method: getPortWithModule * Signature: (BB)Ljava/nio/ByteBuffer; */ JNIEXPORT jobject JNICALL Java_io_github_robolib_jni_SolenoidJNI_getPortWithModule (JNIEnv *env, jclass, jbyte module, jbyte channel) { VoidPointer *port_pointer = new VoidPointer; *port_pointer = getPortWithModule(module, channel); return env->NewDirectByteBuffer(port_pointer, 4); } /* * Class: io_github_robolib_jni_SolenoidJNI * Method: setSolenoid * Signature: (Ljava/nio/ByteBuffer;BLjava/nio/IntBuffer;)V */ JNIEXPORT void JNICALL Java_io_github_robolib_jni_SolenoidJNI_setSolenoid (JNIEnv *env, jclass, jobject solenoid_port, jbyte value, jobject status) { SOLENOIDJNI_LOG(logDEBUG) << "Calling SolenoidJNI SetSolenoid"; VoidPointer *solenoid_port_pointer = (VoidPointer *)env->GetDirectBufferAddress(solenoid_port); SOLENOIDJNI_LOG(logDEBUG) << "Solenoid Port Pointer = " << *solenoid_port_pointer; jint *status_pointer = (jint*)env->GetDirectBufferAddress(status); SOLENOIDJNI_LOG(logDEBUG) << "Status Ptr = " << status_pointer; setSolenoid(*solenoid_port_pointer, value, status_pointer); } /* * Class: io_github_robolib_jni_SolenoidJNI * Method: getSolenoid * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/IntBuffer;)B */ JNIEXPORT jbyte JNICALL Java_io_github_robolib_jni_SolenoidJNI_getSolenoid (JNIEnv *env, jclass, jobject solenoid_port, jobject status) { VoidPointer *solenoid_port_pointer = (VoidPointer *)env->GetDirectBufferAddress(solenoid_port); jint *status_pointer = (jint*)env->GetDirectBufferAddress(status); return getSolenoid(*solenoid_port_pointer, status_pointer); } /* * Class: io_github_robolib_jni_SolenoidJNI * Method: getPCMSolenoidBlackList * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/IntBuffer;)B */ JNIEXPORT jbyte JNICALL Java_io_github_robolib_jni_SolenoidJNI_getPCMSolenoidBlackList (JNIEnv *env, jclass, jobject solenoid_port, jobject status) { VoidPointer *solenoid_port_pointer = (VoidPointer *)env->GetDirectBufferAddress(solenoid_port); jint *status_pointer = (jint*)env->GetDirectBufferAddress(status); return getPCMSolenoidBlackList(*solenoid_port_pointer, status_pointer); } /* * Class: io_github_robolib_jni_SolenoidJNI * Method: getPCMSolenoidVoltageStickyFault * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/IntBuffer;)Z */ JNIEXPORT jboolean JNICALL Java_io_github_robolib_jni_SolenoidJNI_getPCMSolenoidVoltageStickyFault (JNIEnv *env, jclass, jobject solenoid_port, jobject status) { VoidPointer *solenoid_port_pointer = (VoidPointer *)env->GetDirectBufferAddress(solenoid_port); jint *status_pointer = (jint *)env->GetDirectBufferAddress(status); return getPCMSolenoidVoltageStickyFault(*solenoid_port_pointer, status_pointer); } /* * Class: io_github_robolib_jni_SolenoidJNI * Method: getPCMSolenoidVoltageFault * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/IntBuffer;)Z */ JNIEXPORT jboolean JNICALL Java_io_github_robolib_jni_SolenoidJNI_getPCMSolenoidVoltageFault (JNIEnv *env, jclass, jobject solenoid_port, jobject status) { VoidPointer *solenoid_port_pointer = (VoidPointer *)env->GetDirectBufferAddress(solenoid_port); jint *status_pointer = (jint *)env->GetDirectBufferAddress(status); return getPCMSolenoidVoltageFault(*solenoid_port_pointer, status_pointer); } /* * Class: io_github_robolib_jni_SolenoidJNI * Method: clearAllPCMStickyFaults * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/IntBuffer;)V */ JNIEXPORT void JNICALL Java_io_github_robolib_jni_SolenoidJNI_clearAllPCMStickyFaults (JNIEnv *env, jclass, jobject solenoid_port, jobject status) { VoidPointer *solenoid_port_pointer = (VoidPointer *)env->GetDirectBufferAddress(solenoid_port); jint *status_pointer = (jint *)env->GetDirectBufferAddress(status); clearAllPCMStickyFaults_sol(*solenoid_port_pointer, status_pointer); }
37.671233
98
0.781091
robolib
f8dc8baf6f425fde5cd36be06c4236aa54650252
3,070
cpp
C++
mof2oal/src/cimreference.cpp
juergh/dash-sdk
16757836f1f96ee3220992f70bffe92c18e08e76
[ "AMDPLPA" ]
13
2015-08-06T14:55:10.000Z
2021-12-26T04:41:54.000Z
mof2oal/src/cimreference.cpp
juergh/dash-sdk
16757836f1f96ee3220992f70bffe92c18e08e76
[ "AMDPLPA" ]
null
null
null
mof2oal/src/cimreference.cpp
juergh/dash-sdk
16757836f1f96ee3220992f70bffe92c18e08e76
[ "AMDPLPA" ]
1
2017-06-17T14:15:41.000Z
2017-06-17T14:15:41.000Z
/* * <AMD 3BSD notice header> * * Copyright (c) 2006, 2007, 2008 Advanced Micro Devices, Inc. * * All rights reserved. * * This file is subject to the license found in the LICENSE.AMD file which * states the following in part: * * Redistribution and use in any form of this material and any product * thereof including software in source or binary forms, along with any * related documentation, with or without modification ("this material"), * is permitted provided that the following conditions are met: * * * Redistributions of source code of any software must retain the above * copyright notice and all terms of this license as part of the code. * * * Redistributions in binary form of any software must reproduce the * above copyright notice and all terms of this license in any related * documentation and/or other materials. * * * Neither the names nor trademarks of Advanced Micro Devices, Inc. * or any copyright holders or contributors may be used to endorse or * promote products derived from this material without specific prior * written permission. */ #include "cimreference.h" #include "util.h" /* * Constructor */ CCIMReference::CCIMReference (string reference_object, string reference_name) : _reference_object (reference_object), _reference_name (reference_name) { } /* * generateCode */ string CCIMReference::generateCode (void) { string code; if (!g_oalcs && !g_oaldll) { code = "\t/**\r\n\t * "; code += _desc; code += "\r\n\t */\r\n"; /* Write the get function header */ code += "\tCCIMObjectPath get" + _reference_name + "(void)\r\n"; /* Write the get function body. */ code += "\t{\r\n\t\tCOALObject::checkUpdateCache (\"" + _reference_name + "\");\r\n"; code += "\r\n\t\tCCIMValue value = this->_ins.getProperty (\"" + _reference_name + "\").getValue ();\r\n"; code += " \r\n\t\tCCIMObjectPath " + _reference_name + " = to<CCIMObjectPath> (value);\r\n"; code += "\r\t\treturn " + _reference_name + ";\r\n"; code += "\t}\r\n"; } else { code = CSkeleton::instance ()->getContent ("REFERENCE"); code = ::replaceStr (code, "%REFERENCE_OBJ%", _reference_object); code = ::replaceStr (code, "%REFERENCE_DESC%", _desc); code = ::replaceStr (code, "%REFERENCE_NAME%", _reference_name); } return code; #if 0 /* Write the description */ ::writeString (fp, "/*\r\n"); ::writeString (fp, _desc); ::writeString (fp, "*/\r\n"); /* Write the get function header */ ::writeString (fp, "CCIMObjectPath get" + _reference_name + "(void) const\r\n"); /* Write the get function body. */ ::writeString (fp, "{\r\n\tcheckUpdateCache (\"" + _reference_name + "\");\r\n"); ::writeString (fp, "{\r\n\tCCIMObjectPath " + _reference_name + " = toCCIMObjectPath (_ins.getProperty (" + _reference_name + ").getValue ());\r\n"); ::writeString (fp, "return " + _reference_name + "\r\n"); ::writeString (fp, "}\r\n"); #endif return ""; }
32.659574
90
0.642997
juergh
f8dcda3292bd380f70b15c59883be5546b91e374
488
cpp
C++
libraries/graphics/src/graphics/Bloom.cpp
Darlingnotin/Antisocial_VR
f1debafb784ed5a63a40fe9b80790fbaccfedfce
[ "Apache-2.0" ]
272
2021-01-07T03:06:08.000Z
2022-03-25T03:54:07.000Z
libraries/graphics/src/graphics/Bloom.cpp
Darlingnotin/Antisocial_VR
f1debafb784ed5a63a40fe9b80790fbaccfedfce
[ "Apache-2.0" ]
1,021
2020-12-12T02:33:32.000Z
2022-03-31T23:36:37.000Z
libraries/graphics/src/graphics/Bloom.cpp
Darlingnotin/Antisocial_VR
f1debafb784ed5a63a40fe9b80790fbaccfedfce
[ "Apache-2.0" ]
77
2020-12-15T06:59:34.000Z
2022-03-23T22:18:04.000Z
// // Bloom.cpp // libraries/graphics/src/graphics // // Created by Sam Gondelman on 8/7/2018 // Copyright 2018 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "Bloom.h" using namespace graphics; const float Bloom::INITIAL_BLOOM_INTENSITY { 0.25f }; const float Bloom::INITIAL_BLOOM_THRESHOLD { 0.7f }; const float Bloom::INITIAL_BLOOM_SIZE { 0.9f };
27.111111
88
0.729508
Darlingnotin
f8ddbb317b54bb4acee8495c980a53566ebabb55
7,068
cpp
C++
t11_arvore_binaria_busca/TesteNoBinario.cpp
lucasjoao/data_structures
8413a76eb831c57697e823163afc3b8f821c0d8b
[ "Unlicense" ]
null
null
null
t11_arvore_binaria_busca/TesteNoBinario.cpp
lucasjoao/data_structures
8413a76eb831c57697e823163afc3b8f821c0d8b
[ "Unlicense" ]
null
null
null
t11_arvore_binaria_busca/TesteNoBinario.cpp
lucasjoao/data_structures
8413a76eb831c57697e823163afc3b8f821c0d8b
[ "Unlicense" ]
null
null
null
// Copyright #include <gtest/gtest.h> #include <vector> #include <cstdio> #include "NoBinario.hpp" #define TAM1 10 #define TAM2 20 int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } class Objeto {}; class NoBinarioTest : public ::testing::Test { protected: NoBinario<Objeto*>* objeto; NoBinario<int>* inteiro; public: virtual void SetUp() { this->inteiro = new NoBinario<int>(10); this->objeto = new NoBinario<Objeto*>(new Objeto()); } }; TEST_F(NoBinarioTest, getDado) { Objeto* o = new Objeto(); ASSERT_EQ(10, *(inteiro->getDado())); inteiro = new NoBinario<int>(5); ASSERT_EQ(5, *(inteiro->getDado())); inteiro = new NoBinario<int>(15); ASSERT_EQ(15, *(inteiro->getDado())); objeto = new NoBinario<Objeto*>(o); ASSERT_EQ(o, *(objeto->getDado())); } TEST_F(NoBinarioTest, busca) { ASSERT_EQ(10, *(inteiro->busca(10, inteiro))); ASSERT_NO_THROW(inteiro->inserir(5, inteiro)); ASSERT_EQ(5, *(inteiro->busca(5, inteiro))); ASSERT_NO_THROW(inteiro->inserir(20, inteiro)); ASSERT_EQ(20, *(inteiro->busca(20, inteiro))); ASSERT_NO_THROW(inteiro->inserir(3, inteiro)); ASSERT_EQ(3, *(inteiro->busca(3, inteiro))); ASSERT_NO_THROW(inteiro->inserir(16, inteiro)); ASSERT_EQ(16, *(inteiro->busca(16, inteiro))); ASSERT_ANY_THROW(inteiro->busca(14, inteiro)); } TEST_F(NoBinarioTest, inserir) { int i; for (i = 0; i < TAM1; i++) { ASSERT_NO_THROW(inteiro->inserir(i, inteiro)); } for (i = TAM1 + 1; i < TAM2; i++) { ASSERT_NO_THROW(inteiro->inserir(i, inteiro)); } for (i = 0; i < TAM1; i++) { ASSERT_EQ(i, *(inteiro->busca(i, inteiro))); } for (i = TAM1+1; i < TAM2; i++) { ASSERT_EQ(i, *(inteiro->busca(i, inteiro))); } } TEST_F(NoBinarioTest, remover) { int i; for (i = 0; i < TAM1; i++) { ASSERT_NO_THROW(inteiro->inserir(i, inteiro)); } for (i = TAM1+1; i < TAM2; i++) { ASSERT_NO_THROW(inteiro->inserir(i, inteiro)); } for (i = 0; i < TAM1; i++) { ASSERT_EQ(i, *(inteiro->busca(i, inteiro))); } for (i = TAM1+1; i < TAM2; i++) { ASSERT_EQ(i, *(inteiro->busca(i, inteiro))); } for (i = 0; i < TAM1; i++) { ASSERT_NO_THROW(inteiro->remover(inteiro, i)); } for (i = TAM1+1; i < TAM2; i++) { ASSERT_NO_THROW(inteiro->remover(inteiro, i)); } for (i = 0; i < TAM1; i++) { ASSERT_ANY_THROW(inteiro->busca(i, inteiro)); } for (i = TAM1+1; i < TAM2; i++) { ASSERT_ANY_THROW(inteiro->busca(i, inteiro)); } } TEST_F(NoBinarioTest, removerArvEsq) { inteiro->inserir(7, inteiro); inteiro->inserir(5, inteiro); inteiro->inserir(4, inteiro); inteiro->inserir(6, inteiro); inteiro->remover(inteiro, 7); NoBinario<int>* esq = inteiro->getEsquerda(); ASSERT_EQ(*(esq->getDado()), 5); ASSERT_EQ(*(esq->getDireita()->getDado()), 6); ASSERT_EQ(*(esq->getEsquerda()->getDado()), 4); } TEST_F(NoBinarioTest, removerArvDir) { inteiro->inserir(2, inteiro); inteiro->inserir(5, inteiro); inteiro->inserir(4, inteiro); inteiro->inserir(6, inteiro); inteiro->remover(inteiro, 2); NoBinario<int>* esq = inteiro->getEsquerda(); ASSERT_EQ(*(esq->getDado()), 5); ASSERT_EQ(*(esq->getDireita()->getDado()), 6); ASSERT_EQ(*(esq->getEsquerda()->getDado()), 4); } TEST_F(NoBinarioTest, remover2Sub) { inteiro->inserir(20, inteiro); inteiro->inserir(25, inteiro); inteiro->inserir(26, inteiro); inteiro->inserir(15, inteiro); inteiro->inserir(14, inteiro); inteiro->inserir(16, inteiro); inteiro->remover(inteiro, 20); NoBinario<int>* d = inteiro->getDireita(); ASSERT_TRUE(*(d->getDado()) == 25 || *(d->getDado()) == 16); NoBinario<int>* dd = d->getDireita(); NoBinario<int>* de = d->getEsquerda(); if (*(d->getDado()) == 25) { ASSERT_EQ(*(dd->getDado()), 26); ASSERT_EQ(*(de->getDado()), 15); ASSERT_EQ(dd->getEsquerda(), nullptr); ASSERT_EQ(dd->getDireita(), nullptr); NoBinario<int>* ded = de->getDireita(); NoBinario<int>* dee = de->getEsquerda(); ASSERT_EQ(*(ded->getDado()), 16); ASSERT_EQ(*(dee->getDado()), 14); ASSERT_EQ(ded->getEsquerda(), nullptr); ASSERT_EQ(ded->getDireita(), nullptr); ASSERT_EQ(dee->getEsquerda(), nullptr); ASSERT_EQ(dee->getDireita(), nullptr); } else { ASSERT_EQ(*(dd->getDado()), 25); ASSERT_EQ(*(de->getDado()), 15); NoBinario<int>* ddd = dd->getDireita(); NoBinario<int>* dde = dd->getEsquerda(); ASSERT_EQ(*(ddd->getDado()), 26); ASSERT_EQ(*(dde->getDado()), 14); ASSERT_EQ(ddd->getEsquerda(), nullptr); ASSERT_EQ(ddd->getDireita(), nullptr); ASSERT_EQ(dde->getEsquerda(), nullptr); ASSERT_EQ(dde->getDireita(), nullptr); } } TEST_F(NoBinarioTest, minimo) { int i; ASSERT_EQ(10, *(inteiro->minimo(inteiro)->getDado())); for (i = 9; i >= 0; i--) { ASSERT_NO_THROW(inteiro->inserir(i, inteiro)); ASSERT_EQ(i, *(inteiro->minimo(inteiro)->getDado())); } } TEST_F(NoBinarioTest, preOrdem) { ASSERT_NO_THROW(inteiro->inserir(8, inteiro)); ASSERT_NO_THROW(inteiro->inserir(9, inteiro)); ASSERT_NO_THROW(inteiro->inserir(11, inteiro)); ASSERT_NO_THROW(inteiro->inserir(12, inteiro)); ASSERT_NO_THROW(inteiro->preOrdem(inteiro)); std::vector<NoBinario<int>* > elementos = inteiro->getElementos(); ASSERT_EQ(10, *(elementos[0]->getDado())); ASSERT_EQ(8, *(elementos[1]->getDado())); ASSERT_EQ(9, *(elementos[2]->getDado())); ASSERT_EQ(11, *(elementos[3]->getDado())); ASSERT_EQ(12, *(elementos[4]->getDado())); } TEST_F(NoBinarioTest, emOrdem) { ASSERT_NO_THROW(inteiro->inserir(8, inteiro)); ASSERT_NO_THROW(inteiro->inserir(9, inteiro)); ASSERT_NO_THROW(inteiro->inserir(11, inteiro)); ASSERT_NO_THROW(inteiro->inserir(12, inteiro)); ASSERT_NO_THROW(inteiro->emOrdem(inteiro)); std::vector<NoBinario<int>* > elementos = inteiro->getElementos(); ASSERT_EQ(8, *(elementos[0]->getDado())); ASSERT_EQ(9, *(elementos[1]->getDado())); ASSERT_EQ(10, *(elementos[2]->getDado())); ASSERT_EQ(11, *(elementos[3]->getDado())); ASSERT_EQ(12, *(elementos[4]->getDado())); } TEST_F(NoBinarioTest, posOrdem) { ASSERT_NO_THROW(inteiro->inserir(8, inteiro)); ASSERT_NO_THROW(inteiro->inserir(9, inteiro)); ASSERT_NO_THROW(inteiro->inserir(11, inteiro)); ASSERT_NO_THROW(inteiro->inserir(12, inteiro)); ASSERT_NO_THROW(inteiro->posOrdem(inteiro)); std::vector<NoBinario<int>* > elementos = inteiro->getElementos(); ASSERT_EQ(9, *(elementos[0]->getDado())); ASSERT_EQ(8, *(elementos[1]->getDado())); ASSERT_EQ(12, *(elementos[2]->getDado())); ASSERT_EQ(11, *(elementos[3]->getDado())); ASSERT_EQ(10, *(elementos[4]->getDado())); }
31
70
0.608942
lucasjoao
f8e18e934c815584b42d24249fc25a873c31081c
140
cpp
C++
C语言程序设计基础/15.【图形】输出一行星号.cpp
xiabee/BIT-CS
5d8d8331e6b9588773991a872c259e430ef1eae1
[ "Apache-2.0" ]
63
2021-01-10T02:32:17.000Z
2022-03-30T04:08:38.000Z
C语言程序设计基础/15.【图形】输出一行星号.cpp
xiabee/BIT-CS
5d8d8331e6b9588773991a872c259e430ef1eae1
[ "Apache-2.0" ]
2
2021-06-09T05:38:58.000Z
2021-12-14T13:53:54.000Z
C语言程序设计基础/15.【图形】输出一行星号.cpp
xiabee/BIT-CS
5d8d8331e6b9588773991a872c259e430ef1eae1
[ "Apache-2.0" ]
20
2021-01-12T11:49:36.000Z
2022-03-26T11:04:58.000Z
#include <stdio.h> int main() { int n, i; scanf ("%d", &n); for (i = 1; i <= n; i++) { printf ("*"); } printf ("\n"); return 0; }
10.769231
25
0.428571
xiabee
f8e3c4478d822ef2a7afb75a556e32e84bf9387e
13,611
ipp
C++
src/cradle/imaging/sample.ipp
mghro/astroid-core
72736f64bed19ec3bb0e92ebee4d7cf09fc0399f
[ "MIT" ]
null
null
null
src/cradle/imaging/sample.ipp
mghro/astroid-core
72736f64bed19ec3bb0e92ebee4d7cf09fc0399f
[ "MIT" ]
3
2020-10-26T18:45:47.000Z
2020-10-26T18:46:06.000Z
src/cradle/imaging/sample.ipp
mghro/astroid-core
72736f64bed19ec3bb0e92ebee4d7cf09fc0399f
[ "MIT" ]
null
null
null
#include <cmath> #include <cradle/imaging/geometry.hpp> #include <cradle/imaging/iterator.hpp> namespace cradle { namespace impl { template<unsigned N, class T, class SP> optional<T> compute_raw_image_sample( image<N, T, SP> const& img, vector<N, double> const& p) { vector<N, double> image_p = transform_point(inverse(get_spatial_mapping(img)), p); vector<N, unsigned> index; for (unsigned i = 0; i < N; ++i) { index[i] = unsigned(std::floor(image_p[i])); if (index[i] >= img.size[i]) return optional<T>(); } return T(get_pixel_ref(img, index)); } template<unsigned N, class T, class SP> optional<typename replace_channel_type<T, double>::type> compute_image_sample(image<N, T, SP> const& img, vector<N, double> const& p) { auto sample = compute_raw_image_sample(img, p); if (!sample) { return optional<typename replace_channel_type<T, double>::type>(); } return apply_linear_function(img.value_mapping, sample.get()); } template<unsigned N> struct point_sampler { vector<N, double> p; optional<double> result; template<class Pixel, class SP> void operator()(image<N, Pixel, SP> const& img) { optional<Pixel> x = raw_image_sample(img, p); if (x) result = double(get(x)); else result = none; } }; template<unsigned N, class SP> optional<double> compute_raw_image_sample( image<N, variant, SP> const& img, vector<N, double> const& p) { impl::point_sampler<N> sampler; sampler.p = p; apply_fn_to_gray_variant(sampler, img); return sampler.result; } template<unsigned N, class SP> optional<double> compute_image_sample( image<N, variant, SP> const& img, vector<N, double> const& p) { auto sample = compute_raw_image_sample(img, p); if (!sample) return sample; return apply_linear_function(img.value_mapping, sample.get()); } } // namespace impl template<unsigned N, class T, class SP> optional<T> raw_image_sample(image<N, T, SP> const& img, vector<N, double> const& p) { return impl::compute_raw_image_sample(img, p); } template<unsigned N, class T, class SP> optional<typename replace_channel_type<T, double>::type> image_sample(image<N, T, SP> const& img, vector<N, double> const& p) { return impl::compute_image_sample(img, p); } namespace impl { template<unsigned N, class T, class SP, unsigned Axis> struct raw_interpolated_sampler { static optional<typename replace_channel_type<T, double>::type> apply( image<N, T, SP> const& img, vector<N, double> const& p, vector<N, unsigned>& index) { typedef optional<typename replace_channel_type<T, double>::type> return_type; double v = p[Axis] - 0.5, floor_v = std::floor(v); index[Axis] = unsigned(floor_v); if (index[Axis] < img.size[Axis] && index[Axis] + 1 < img.size[Axis]) { double f = v - floor_v; return_type sample1 = raw_interpolated_sampler<N, T, SP, Axis - 1>::apply( img, p, index); ++index[Axis]; return_type sample2 = raw_interpolated_sampler<N, T, SP, Axis - 1>::apply( img, p, index); if (sample1 && sample2) return sample1.get() * (1 - f) + sample2.get() * f; } else { index[Axis] = unsigned(std::floor(p[Axis])); if (index[Axis] < img.size[Axis]) { return raw_interpolated_sampler<N, T, SP, Axis - 1>::apply( img, p, index); } } return return_type(); } }; template<unsigned N, class T, class SP> struct raw_interpolated_sampler<N, T, SP, 0> { static optional<typename replace_channel_type<T, double>::type> apply( image<N, T, SP> const& img, vector<N, double> const& p, vector<N, unsigned>& index) { typedef optional<typename replace_channel_type<T, double>::type> return_type; double v = p[0] - 0.5, floor_v = std::floor(v); index[0] = unsigned(floor_v); if (index[0] < img.size[0] && index[0] + 1 < img.size[0]) { double f = v - floor_v; typename replace_channel_type<T, double>::type sample1 = channel_convert<double>(get_pixel_ref(img, index)); ++index[0]; typename replace_channel_type<T, double>::type sample2 = channel_convert<double>(get_pixel_ref(img, index)); return sample1 * (1 - f) + sample2 * f; } else { index[0] = unsigned(std::floor(p[0])); if (index[0] < img.size[0]) { return channel_convert<double>(get_pixel_ref(img, index)); } } return return_type(); } }; template<unsigned N, class T, class SP> optional<typename replace_channel_type<T, double>::type> compute_raw_interpolated_image_sample( image<N, T, SP> const& img, vector<N, double> const& p) { vector<N, double> image_p = transform_point(inverse(get_spatial_mapping(img)), p); vector<N, unsigned> index; return impl::raw_interpolated_sampler<N, T, SP, N - 1>::apply( img, image_p, index); } template<unsigned N, class T, class SP> optional<typename replace_channel_type<T, double>::type> compute_interpolated_image_sample( image<N, T, SP> const& img, vector<N, double> const& p) { auto sample = compute_raw_interpolated_image_sample(img, p); if (!sample) return sample; return apply_linear_function(img.value_mapping, sample.get()); } template<unsigned N> struct interpolated_point_sampler { vector<N, double> p; optional<double> result; template<class Pixel, class SP> void operator()(image<N, Pixel, SP> const& img) { result = compute_raw_interpolated_image_sample(img, p); } }; template<unsigned N, class SP> optional<double> compute_raw_interpolated_image_sample( image<N, variant, SP> const& img, vector<N, double> const& p) { impl::interpolated_point_sampler<N> sampler; sampler.p = p; apply_fn_to_gray_variant(sampler, img); return sampler.result; } template<unsigned N, class SP> optional<double> compute_interpolated_image_sample( image<N, variant, SP> const& img, vector<N, double> const& p) { auto sample = raw_interpolated_image_sample(img, p); if (!sample) return sample; return apply_linear_function(img.value_mapping, sample.get()); } } // namespace impl template<unsigned N, class T, class SP> optional<typename replace_channel_type<T, double>::type> raw_interpolated_image_sample( image<N, T, SP> const& img, vector<N, double> const& p) { return impl::compute_raw_interpolated_image_sample(img, p); } template<unsigned N, class T, class SP> optional<typename replace_channel_type<T, double>::type> interpolated_image_sample( image<N, T, SP> const& img, vector<N, double> const& p) { return impl::compute_interpolated_image_sample(img, p); } namespace impl { // stores information about which pixels to sample along each axis struct raw_region_sample_axis_info { // the index of the first pixel to include unsigned i_begin; // # of pixels to include unsigned count; // w_first is the weight of the first pixel (if count >= 1) // w_last is the weight of the last pixel (if count >= 2) // w_mid is the weight of the pixels in the middle (if count >= 3) double w_first, w_mid, w_last; }; template<unsigned N, class T, class SP, unsigned Axis> struct raw_region_sample { static void apply( typename replace_channel_type<T, double>::type& result, image<N, T, SP> const& img, raw_region_sample_axis_info const* axis_info, vector<N, unsigned>& index, double weight) { raw_region_sample_axis_info const& info = axis_info[Axis]; index[Axis] = info.i_begin; raw_region_sample<N, T, SP, Axis - 1>::apply( result, img, axis_info, index, weight * info.w_first); unsigned count = info.count - 1; while (count > 1) { ++index[Axis]; raw_region_sample<N, T, SP, Axis - 1>::apply( result, img, axis_info, index, weight * info.w_mid); --count; } if (count > 0) { ++index[Axis]; raw_region_sample<N, T, SP, Axis - 1>::apply( result, img, axis_info, index, weight * info.w_last); } } }; template<unsigned N, class T, class SP> struct raw_region_sample<N, T, SP, 0> { static void apply( typename replace_channel_type<T, double>::type& result, image<N, T, SP> const& img, raw_region_sample_axis_info const* axis_info, vector<N, unsigned>& index, double weight) { raw_region_sample_axis_info const& info = axis_info[0]; index[0] = info.i_begin; span_iterator<N, T, SP> i = get_axis_iterator(img, 0, index); result += typename replace_channel_type<T, double>::type(*i) * weight * info.w_first; ++i; unsigned count = info.count - 1; while (count > 1) { result += typename replace_channel_type<T, double>::type(*i) * weight * info.w_mid; ++i; --count; } if (count > 0) { result += typename replace_channel_type<T, double>::type(*i) * weight * info.w_last; ++i; } } }; template<unsigned N, class T, class SP> optional<typename replace_channel_type<T, double>::type> compute_raw_image_sample_over_box( image<N, T, SP> const& img, box<N, double> const& region) { matrix<N + 1, N + 1, double> inverse_spatial_mapping = inverse(get_spatial_mapping(img)); box<N, double> image_region; image_region.corner = transform_point(inverse_spatial_mapping, region.corner); image_region.size = transform_vector(inverse_spatial_mapping, region.size); impl::raw_region_sample_axis_info axis_info[N]; for (unsigned i = 0; i < N; ++i) { impl::raw_region_sample_axis_info& info = axis_info[i]; double low = double(std::floor(image_region.corner[i])); int i_begin = int(low); if (i_begin < 0) { i_begin = 0; info.w_first = 1; } else info.w_first = (low + 1) - double(image_region.corner[i]); double high = double(std::ceil(get_high_corner(image_region)[i])); int i_end = int(high); if (i_end > int(img.size[i])) { i_end = img.size[i]; info.w_last = 1; } else { info.w_last = double(get_high_corner(image_region)[i]) - (high - 1); } // region doesn't overlap the image along this axis if (i_begin >= i_end) { return optional<typename replace_channel_type<T, double>::type>(); } info.i_begin = i_begin; info.count = i_end - i_begin; double total_weight = info.w_first; if (info.count > 1) total_weight += info.w_last + (info.count - 2); double adjustment = 1 / total_weight; info.w_first *= adjustment; info.w_last *= adjustment; info.w_mid = adjustment; } typename replace_channel_type<T, double>::type result; fill_channels(result, 0); vector<N, unsigned> index; impl::raw_region_sample<N, T, SP, N - 1>::apply( result, img, axis_info, index, 1); return result; } template<unsigned N, class T, class SP> optional<typename replace_channel_type<T, double>::type> compute_image_sample_over_box( image<N, T, SP> const& img, box<N, double> const& region) { auto sample = compute_raw_image_sample_over_box(img, region); if (!sample) return sample; return apply_linear_function(img.value_mapping, sample.get()); } template<unsigned N> struct region_sampler { box<N, double> region; optional<double> result; template<class Pixel, class SP> void operator()(image<N, Pixel, SP> const& img) { result = compute_raw_image_sample_over_box(img, region); } }; template<unsigned N, class SP> optional<double> compute_raw_image_sample_over_box( image<N, variant, SP> const& img, box<N, double> const& region) { impl::region_sampler<N> sampler; sampler.region = region; apply_fn_to_gray_variant(sampler, img); return sampler.result; } // template<unsigned N, class SP> optional<double> compute_image_sample_over_box( image<N, variant, SP> const& img, box<N, double> const& region) { auto sample = compute_raw_image_sample_over_box(img, region); if (!sample) return sample; return apply_linear_function(img.value_mapping, sample.get()); } } // namespace impl template<unsigned N, class T, class SP> optional<typename replace_channel_type<T, double>::type> raw_image_sample_over_box( image<N, T, SP> const& img, box<N, double> const& region) { return impl::compute_raw_image_sample_over_box(img, region); } template<unsigned N, class T, class SP> optional<typename replace_channel_type<T, double>::type> image_sample_over_box(image<N, T, SP> const& img, box<N, double> const& region) { return impl::compute_image_sample_over_box(img, region); } } // namespace cradle
28.594538
79
0.62163
mghro
f8e3fb2e537d6eeb9622faf4add0b9a184901f12
2,991
cpp
C++
whycpp/src/impl/drawing.cpp
senior-sigan/WHY_CPP
f9e2d060a782b9d72fb2c9f3ce580af00eb40779
[ "MIT" ]
6
2019-01-10T12:06:04.000Z
2022-01-06T15:22:03.000Z
whycpp/src/impl/drawing.cpp
senior-sigan/WHY_CPP
f9e2d060a782b9d72fb2c9f3ce580af00eb40779
[ "MIT" ]
8
2019-02-22T09:14:34.000Z
2019-04-20T18:46:37.000Z
whycpp/src/impl/drawing.cpp
senior-sigan/WHY_CPP
f9e2d060a782b9d72fb2c9f3ce580af00eb40779
[ "MIT" ]
3
2019-03-22T09:01:52.000Z
2021-06-13T17:50:31.000Z
#include <whycpp/color.h> #include <whycpp/drawing.h> #include <whycpp/types.h> #include <algorithm> #include "../context.h" #include "../holders/sprites_holder.h" #include "../sprite.h" #include "../holders/video_memory_holder.h" i32 GetDisplayWidth(const Context &ctx) { return ctx.Get<VideoMemoryHolder>()->GetWidth(); } i32 GetDisplayHeight(const Context &ctx) { return ctx.Get<VideoMemoryHolder>()->GetHeight(); } void SetPixel(Context &ctx, i32 x, i32 y, const RGBA &color) { if (color.alpha == 0) return; ctx.Get<VideoMemoryHolder>()->Set(x, y, color); } const RGBA GetPixel(const Context &ctx, i32 x, i32 y) { return ctx.Get<VideoMemoryHolder>()->Get(x, y); } void DrawClearScreen(Context &ctx, const RGBA &color) { ctx.Get<VideoMemoryHolder>()->Fill(color); } void DrawLine(Context &ctx, i32 x0, i32 y0, i32 x1, i32 y1, const RGBA &color) { i32 dx = std::abs(x1 - x0), sx = x0 < x1 ? 1 : -1; i32 dy = std::abs(y1 - y0), sy = y0 < y1 ? 1 : -1; i32 err = (dx > dy ? dx : -dy) / 2; i32 e2; for (;;) { SetPixel(ctx, x0, y0, color); if (x0 == x1 && y0 == y1) break; e2 = err; if (e2 > -dx) { err -= dy; x0 += sx; } if (e2 < dy) { err += dx; y0 += sy; } } } void DrawRectFill(Context &ctx, i32 x, i32 y, i32 w, i32 h, const RGBA &color) { for (auto i = y; i < y + h; i++) { DrawLine(ctx, x, i, x + w - 1, i, color); } } void DrawRect(Context &ctx, i32 x, i32 y, i32 w, i32 h, const RGBA &color) { DrawLine(ctx, x, y, x + w, y, color); DrawLine(ctx, x, y, x, y + h, color); DrawLine(ctx, x + w, y, x + w, y + h, color); DrawLine(ctx, x, y + h, x + w, y + h, color); } void DrawCircle(Context &context, i32 x, i32 y, i32 radius, const RGBA &color) { i32 r = radius; i32 x_ = -r; i32 y_ = 0; i32 err = 2 - 2 * r; do { SetPixel(context, x - x_, y + y_, color); SetPixel(context, x + x_, y - y_, color); SetPixel(context, x - y_, y - x_, color); SetPixel(context, x + y_, y + x_, color); r = err; if (r <= y_) err += ++y_ * 2 + 1; if (r > x_ || err > y_) err += ++x_ * 2 + 1; } while (x_ < 0); } void DrawCircleFill(Context &context, i32 x, i32 y, i32 radius, const RGBA &color) { i32 r = radius; i32 x_ = -r; i32 y_ = 0; i32 err = 2 - 2 * r; do { for (i32 i = x + x_; i <= x - x_; i++) { SetPixel(context, i, y + y_, color); } for (i32 i = x + x_; i <= x - x_; i++) { SetPixel(context, i, y - y_, color); } r = err; if (r <= y_) err += ++y_ * 2 + 1; if (r > x_ || err > y_) err += ++x_ * 2 + 1; } while (x_ < 0); } void DrawSprite(Context &context, i32 sprite_id, i32 screen_x, i32 screen_y, i32 sheet_x, i32 sheet_y, i32 width, i32 height) { auto spr = context.Get<SpritesHolder>()->GetSprite(sprite_id); for (auto y = 0; y < height; y++) { for (auto x = 0; x < width; x++) { SetPixel(context, screen_x + x, screen_y + y, spr->Get(sheet_x + x, sheet_y + y)); } } }
29.323529
113
0.557339
senior-sigan
f8e5fdb06d9898450187a253886d2cb83ab0bcc2
1,813
cpp
C++
hphp/runtime/vm/srckey.cpp
abhishekgahlot/hiphop-php
5b367ac44a7a9a6e4c777ae0786d1c872d3ae0a9
[ "PHP-3.01", "Zend-2.0" ]
1
2015-11-05T19:26:02.000Z
2015-11-05T19:26:02.000Z
hphp/runtime/vm/srckey.cpp
abhishekgahlot/hiphop-php
5b367ac44a7a9a6e4c777ae0786d1c872d3ae0a9
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
hphp/runtime/vm/srckey.cpp
abhishekgahlot/hiphop-php
5b367ac44a7a9a6e4c777ae0786d1c872d3ae0a9
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/vm/srckey.h" namespace HPHP { void sktrace(SrcKey sk, const char *fmt, ...) { if (!Trace::enabled) { return; } // We don't want to print string literals, so don't pass the unit auto func = sk.func(); auto unit = sk.unit(); string s = instrToString((Op*)unit->at(sk.offset())); const char *filepath = "*anonFile*"; if (unit->filepath()->data() && strlen(unit->filepath()->data()) > 0) { filepath = unit->filepath()->data(); } Trace::trace("%s:%d in %s(id 0x%llx) %6d: %20s ", filepath, unit->getLineNumber(sk.offset()), func->isPseudoMain() ? "pseudoMain" : func->fullName()->data(), (unsigned long long)sk.getFuncId(), sk.offset(), s.c_str()); va_list a; va_start(a, fmt); Trace::vtrace(fmt, a); va_end(a); } }
41.204545
78
0.470491
abhishekgahlot
25c970e052812a625ab74eecf8f648da1c9aac35
10,901
cpp
C++
src/core/lib/core_serialization_new/serializationhandlers/collectionhandler.cpp
wgsyd/wgtf
d8cacb43e2c5d40080d33c18a8c2f5bd27d21bed
[ "BSD-3-Clause" ]
28
2016-06-03T05:28:25.000Z
2019-02-14T12:04:31.000Z
src/core/lib/core_serialization_new/serializationhandlers/collectionhandler.cpp
karajensen/wgtf
740397bcfdbc02bc574231579d57d7c9cd5cc26d
[ "BSD-3-Clause" ]
null
null
null
src/core/lib/core_serialization_new/serializationhandlers/collectionhandler.cpp
karajensen/wgtf
740397bcfdbc02bc574231579d57d7c9cd5cc26d
[ "BSD-3-Clause" ]
14
2016-06-03T05:52:27.000Z
2019-03-21T09:56:03.000Z
#include "collectionhandler.hpp" namespace wgt { CollectionHandler::CollectionHandler(const SerializationHandlerManager& handlerManager) : SerializationHandler("__CollectionHandler"), handlerManager_(handlerManager) { } bool CollectionHandler::write(const Variant& v, const NodePtr& node, bool writeType) { node->setHandlerName(handlerName_); if (writeType) { node->setType(collectionName_, strlen(collectionName_)); } bool success = false; Collection c; if (!v.tryCast<Collection>(c)) { return false; } if (c.empty()) { return true; } // Check that the key isn't a collection, since we can't serialize those. if (c.begin().key().canCast<Collection>()) { return false; } // Find and hold on to our handlers std::shared_ptr<SerializationHandler> keyHandler = nullptr; std::shared_ptr<SerializationHandler> valueHandler = nullptr; const MetaType* keyMetaType = MetaType::find(c.keyType().getName()); const MetaType* valueMetaType = MetaType::find(c.valueType().getName()); // If a type in the collection is Variant, then the handler can vary, so leave it as nullptr. if (keyMetaType != MetaType::get<Variant>()) { keyHandler = handlerManager_.findHandlerWrite(c.begin().key()); } if (valueMetaType != MetaType::get<Variant>()) { valueHandler = handlerManager_.findHandlerWrite(c.begin().value()); } // Create a base node for all the elements in the collection. auto baseNode = node->createEmptyChild(collectionBaseNodeName_, strlen(collectionBaseNodeName_)); // Iterate through all the objects in the collection for (auto iter = c.begin(); iter != c.end(); ++iter) { // Write the key, if it exists Variant key = iter.key(); if (!key.isVoid()) { // Create the key node std::unique_ptr<SerializationNode> keyNode; if (keyHandler.get() == nullptr) { // Variant type, go through the entire system keyNode = baseNode->createChildVariant(keyName_, strlen(keyName_), key); } else { // Non-Variant type, use our handler keyNode = baseNode->createEmptyChild(keyName_, strlen(keyName_)); if (!keyHandler->write(key, keyNode, false)) { return false; } } if (keyNode == nullptr) { return false; } // Write the value Variant value = iter.value(); if (!value.isVoid()) { // Create the value node std::unique_ptr<SerializationNode> valueNode; if (valueHandler.get() == nullptr) { // Variant type, go through the entire system valueNode = keyNode->createChildVariant(valueName_, strlen(valueName_), value); } else { // Non-Variant type, use our handler valueNode = keyNode->createEmptyChild(valueName_, strlen(valueName_)); if (!valueHandler->write(value, valueNode, false)) { return false; } } if (valueNode == nullptr) { return false; } } else { return false; } } else { return false; } } // Write the types and handlers last so that the serialized list can be iterated through intuitively // Container type const char* collectionContainerName = this->getReservedNames().collectionContainerType; auto containerTypeNode = node->createEmptyChild(collectionContainerName, strlen(collectionContainerName)); const char* collectionContainerType = c.impl()->containerType().getName(); containerTypeNode->setType(collectionContainerType, strlen(collectionContainerType)); // Key variant type const char* collectionKeyVName = this->getReservedNames().collectionKeyVariantType; auto keyVTypeNode = node->createEmptyChild(collectionKeyVName, strlen(collectionKeyVName)); const char* collectionKeyVType = c.keyType().getName(); keyVTypeNode->setType(collectionKeyVType, strlen(collectionKeyVType)); // Value variant type const char* collectionValueVName = this->getReservedNames().collectionValueVariantType; auto valueVTypeNode = node->createEmptyChild(collectionValueVName, strlen(collectionValueVName)); const char* collectionValueVType = c.valueType().getName(); valueVTypeNode->setType(collectionValueVType, strlen(collectionValueVType)); // Key internal type const char* collectionKeyIName = this->getReservedNames().collectionKeyInternalType; auto keyITypeNode = node->createEmptyChild(collectionKeyIName, strlen(collectionKeyIName)); const char* collectionKeyIType = keyHandler->getInternalTypeOf(c.begin().key(), node); keyITypeNode->setType(collectionKeyIType, strlen(collectionKeyIType)); // Value internal type const char* collectionValueIName = this->getReservedNames().collectionValueInternalType; auto valueITypeNode = node->createEmptyChild(collectionValueIName, strlen(collectionValueIName)); const char* collectionValueIType = valueHandler->getInternalTypeOf(c.begin().value(), node); valueITypeNode->setType(collectionValueIType, strlen(collectionValueIType)); // Key handler if (keyHandler.get() != nullptr) { const char* collectionKeyHandlerName = this->getReservedNames().collectionKeyHandler; auto keyHandlerNode = node->createEmptyChild(collectionKeyHandlerName, strlen(collectionKeyHandlerName)); const char* collectionKeyHandler = keyHandler->getName(); keyHandlerNode->setValueString(collectionKeyHandler, strlen(collectionKeyHandler)); } // Value handler if (valueHandler.get() != nullptr) { const char* collectionValueHandlerName = this->getReservedNames().collectionValueHandler; auto valueHandlerNode = node->createEmptyChild(collectionValueHandlerName, strlen(collectionValueHandlerName)); const char* collectionValueHandler = valueHandler->getName(); valueHandlerNode->setValueString(collectionValueHandler, strlen(collectionValueHandler)); } return true; } bool CollectionHandler::read(Variant& v, const NodePtr& node, const char* typeName) { // Check that we've been given a valid Variant if (v.isVoid() || v.type() == nullptr) { return false; } // Container, key, and value types TypeId containerType; TypeId keyVariantType; TypeId valueVariantType; std::string keyInternalType; std::string valueInternalType; // Container const char* containerName = this->getReservedNames().collectionContainerType; std::string containerTypeName = node->getChildNode(containerName, strlen(containerName))->getType(); containerType = TypeId(containerTypeName.c_str()); // Key variant type const char* keyVName = this->getReservedNames().collectionKeyVariantType; std::string keyVTypeName = node->getChildNode(keyVName, strlen(keyVName))->getType(); keyVariantType = TypeId(keyVTypeName.c_str()); // Value variant type const char* valueVName = this->getReservedNames().collectionValueVariantType; std::string valueVTypeName = node->getChildNode(valueVName, strlen(valueVName))->getType(); valueVariantType = TypeId(valueVTypeName.c_str()); // Key internal type const char* keyIName = this->getReservedNames().collectionKeyInternalType; keyInternalType = node->getChildNode(keyIName, strlen(keyIName))->getType(); // Value internal type const char* valueIName = this->getReservedNames().collectionValueInternalType; valueInternalType = node->getChildNode(valueIName, strlen(valueIName))->getType(); // Cast to a collection Collection c; if (!v.tryCast<Collection>(c)) { return false; } // Check that the types match if (strcmp(c.impl()->containerType().getName(), containerType.getName()) != 0) { return false; } // Get handlers std::shared_ptr<SerializationHandler> keyHandler = nullptr; std::shared_ptr<SerializationHandler> valueHandler = nullptr; if (MetaType::find(keyVariantType.getName()) != MetaType::get<Variant>()) { const char* keyHandlerName = this->getReservedNames().collectionKeyHandler; auto keyHandlerNode = node->getChildNode(keyHandlerName, strlen(keyHandlerName)); std::string keyHandlerString = keyHandlerNode->getValueString(); keyHandler = handlerManager_.findHandlerRead(node, keyHandlerString.c_str(), keyInternalType.c_str()); } if (MetaType::find(valueVariantType.getName()) != MetaType::get<Variant>()) { const char* valueHandlerName = this->getReservedNames().collectionValueHandler; auto valueHandlerNode = node->getChildNode(valueHandlerName, strlen(valueHandlerName)); std::string valueHandlerString = valueHandlerNode->getValueString(); valueHandler = handlerManager_.findHandlerRead(node, valueHandlerString.c_str(), valueInternalType.c_str()); } // Get the base node of the collection auto baseNode = node->getChildNode(collectionBaseNodeName_, strlen(collectionBaseNodeName_)); auto nodeChildren = baseNode->getAllChildren(); auto collectionIter = c.begin(); // Iterate through all the children until we reach the nodes for storing type data for (auto nodeIter = nodeChildren.begin(); nodeIter != nodeChildren.end(); ++nodeIter) { std::unique_ptr<SerializationNode>& currentNode = *nodeIter; Variant key = Variant(keyVariantType); // Assign key/value if (currentNode->getName() != keyName_) { return false; } // Read the key node if (keyHandler.get() == nullptr) { // Read as a Variant if (!currentNode->getValueVariant(key, keyVariantType.getName())) { return false; } } else { // Read with a handler, using the type supplied if (!keyHandler->read(key, currentNode, keyVariantType.getName())) { return false; } } // Insert/get the key, which creates the value for us. Collection::Iterator insertIter; if (c.canResize()) { insertIter = c.insert(key); } else { if (key != collectionIter.key()) { return false; } insertIter = collectionIter; ++collectionIter; } if (insertIter == c.end()) { return false; } Variant value = insertIter.value(); auto childNode = currentNode->getChildNode(valueName_, strlen(valueName_)); if (childNode == nullptr) { return false; } // Read the value node if (valueHandler.get() == nullptr) { // Read as a Variant if (!childNode->getValueVariant(value, valueVariantType.getName())) { return false; } } else { // Read with a handler, using the type supplied if (!valueHandler->read(value, childNode, valueVariantType.getName())) { return false; } } // If this collection doesn't support setting values, then it's invalid. if (!insertIter.setValue(value)) { return false; } } return true; } const char* CollectionHandler::getInternalTypeOf(const Variant& v, const NodePtr& node) const { return collectionName_; } bool CollectionHandler::canHandleWriteInternal(const Variant& v, bool writeType) { if (v.typeIs<Collection>() || v.canCast<Collection>()) { return true; } return false; } bool CollectionHandler::canHandleReadInternal(const NodePtr& node, const char* typeName) { std::string nodeType = typeName != nullptr ? typeName : node->getType(); if (nodeType == collectionName_) { return true; } return false; } } // end namespace wgt
31.234957
113
0.730942
wgsyd
25caea8cd2bdb42e2a2b0c79558eb63e0bd7c51e
19,146
cpp
C++
src/dagify.cpp
vgteam/libhandlegraph
a38d31f01d24a4b928bfa2fad2fe08a0b47528c5
[ "MIT" ]
16
2019-03-03T14:50:59.000Z
2022-03-13T21:07:32.000Z
src/dagify.cpp
vgteam/libhandlegraph
a38d31f01d24a4b928bfa2fad2fe08a0b47528c5
[ "MIT" ]
39
2019-03-01T04:16:06.000Z
2022-03-30T18:46:57.000Z
src/dagify.cpp
vgteam/libhandlegraph
a38d31f01d24a4b928bfa2fad2fe08a0b47528c5
[ "MIT" ]
3
2019-02-25T05:13:56.000Z
2021-11-01T20:32:53.000Z
/** * \file dagify.cpp * * Implements an algorithm to convert a single-stranded graph into a DAG */ //#define debug_dagify #include <vector> #include <unordered_set> #include <atomic> #include "handlegraph/expanding_overlay_graph.hpp" #include "handlegraph/algorithms/dagify.hpp" #include "handlegraph/algorithms/is_single_stranded.hpp" #include "handlegraph/algorithms/strongly_connected_components.hpp" #include "handlegraph/algorithms/eades_algorithm.hpp" namespace handlegraph { namespace algorithms { using namespace std; // TODO: ugly copypasta class SubHandleGraph : public ExpandingOverlayGraph { public: /// Initialize as empty subgraph of a super graph SubHandleGraph(const HandleGraph* super); /// Add a node from the super graph to the subgraph. Must be a handle to the /// super graph. No effect if the node is already included in the subgraph. /// Generally invalidates the results of any previous algorithms. void add_handle(const handle_t& handle); ////////////////////////// /// HandleGraph interface ////////////////////////// // Method to check if a node exists by ID bool has_node(nid_t node_id) const; /// Look up the handle for the node with the given ID in the given orientation handle_t get_handle(const nid_t& node_id, bool is_reverse = false) const; /// Get the ID from a handle nid_t get_id(const handle_t& handle) const; /// Get the orientation of a handle bool get_is_reverse(const handle_t& handle) const; /// Invert the orientation of a handle (potentially without getting its ID) handle_t flip(const handle_t& handle) const; /// Get the length of a node size_t get_length(const handle_t& handle) const; /// Get the sequence of a node, presented in the handle's local forward /// orientation. string get_sequence(const handle_t& handle) const; /// Loop over all the handles to next/previous (right/left) nodes. Passes /// them to a callback which returns false to stop iterating and true to /// continue. Returns true if we finished and false if we stopped early. bool follow_edges_impl(const handle_t& handle, bool go_left, const function<bool(const handle_t&)>& iteratee) const; /// Loop over all the nodes in the graph in their local forward /// orientations, in their internal stored order. Stop if the iteratee /// returns false. Can be told to run in parallel, in which case stopping /// after a false return value is on a best-effort basis and iteration /// order is not defined. bool for_each_handle_impl(const function<bool(const handle_t&)>& iteratee, bool parallel = false) const; /// Return the number of nodes in the graph size_t get_node_count() const; /// Return the smallest ID in the graph, or some smaller number if the /// smallest ID is unavailable. Return value is unspecified if the graph is empty. nid_t min_node_id() const; /// Return the largest ID in the graph, or some larger number if the /// largest ID is unavailable. Return value is unspecified if the graph is empty. nid_t max_node_id() const; /////////////////////////////////// /// ExpandingOverlayGraph interface /////////////////////////////////// /** * Returns the handle in the underlying graph that corresponds to a handle in the * overlay */ handle_t get_underlying_handle(const handle_t& handle) const; private: const HandleGraph* super = nullptr; unordered_set<nid_t> contents; // keep track of these separately rather than use an ordered set nid_t min_id = numeric_limits<nid_t>::max(); nid_t max_id = numeric_limits<nid_t>::min(); }; SubHandleGraph::SubHandleGraph(const HandleGraph* super) : super(super) { // nothing to do } void SubHandleGraph::add_handle(const handle_t& handle) { nid_t node_id = super->get_id(handle); min_id = min(node_id, min_id); max_id = max(node_id, max_id); contents.insert(node_id); } bool SubHandleGraph::has_node(nid_t node_id) const { return contents.count(node_id); } handle_t SubHandleGraph::get_handle(const nid_t& node_id, bool is_reverse) const { if (!contents.count(node_id)) { cerr << "error:[SubHandleGraph] subgraph does not contain node with ID " << node_id << endl; exit(1); } return super->get_handle(node_id, is_reverse); } nid_t SubHandleGraph::get_id(const handle_t& handle) const { return super->get_id(handle); } bool SubHandleGraph::get_is_reverse(const handle_t& handle) const { return super->get_is_reverse(handle); } handle_t SubHandleGraph::flip(const handle_t& handle) const { return super->flip(handle); } size_t SubHandleGraph::get_length(const handle_t& handle) const { return super->get_length(handle); } string SubHandleGraph::get_sequence(const handle_t& handle) const { return super->get_sequence(handle); } bool SubHandleGraph::follow_edges_impl(const handle_t& handle, bool go_left, const function<bool(const handle_t&)>& iteratee) const { // only let it travel along edges whose endpoints are in the subgraph bool keep_going = true; super->follow_edges(handle, go_left, [&](const handle_t& handle) { if (contents.count(super->get_id(handle))) { keep_going = iteratee(handle); } return keep_going; }); return keep_going; } bool SubHandleGraph::for_each_handle_impl(const function<bool(const handle_t&)>& iteratee, bool parallel) const { // non-parallel so we don't pull in any dependencies for (nid_t node_id : contents) { if (!iteratee(super->get_handle(node_id))) { return false; } } return true; } size_t SubHandleGraph::get_node_count() const { return contents.size(); } nid_t SubHandleGraph::min_node_id() const { return min_id; } nid_t SubHandleGraph::max_node_id() const { return max_id; } handle_t SubHandleGraph::get_underlying_handle(const handle_t& handle) const { return handle; } // TODO: SubHandleGraph port over unordered_map<nid_t, nid_t> dagify(const HandleGraph* graph, MutableHandleGraph* into, size_t min_preserved_path_length) { // initialize the translator from the dagified graph back to the original graph unordered_map<nid_t, nid_t> translator; // generate a canonical orientation across the graph vector<handle_t> orientation = single_stranded_orientation(graph); if (orientation.size() < graph->get_node_count()) { cerr << "error:[dagify] Dagify algorithm only valid on graphs with a single stranded orientation, consider using split_strands first" << endl; exit(1); } #ifdef debug_dagify cerr << "got canonical orientation:" << endl; for (const handle_t& h : orientation) { cerr << "\t" << graph->get_id(h) << (graph->get_is_reverse(h) ? "-" : "+") << endl; } #endif // mark the ones that whose canonical orientation is reversed unordered_set<nid_t> reversed_nodes; for (size_t i = 0; i < orientation.size(); i++) { if (graph->get_is_reverse(orientation[i])) { reversed_nodes.insert(graph->get_id(orientation[i])); } } // find the strongly connected components of the original graph vector<unordered_set<nid_t>> strong_components = strongly_connected_components(graph); #ifdef debug_dagify cerr << "got strongly connected components:" << endl; for (size_t i = 0; i < strong_components.size(); i++) { cerr << "\tcomponent " << i << endl; for (nid_t nid : strong_components[i]) { cerr << "\t\t" << nid << endl; } } #endif // duplicate strongly connected components into the dagified graph in such a way // that paths are preserved // a tracker for which SCC a node belongs to unordered_map<nid_t, size_t> component_of; // a map from a node in the original graph to all its copies (in order) in the // dagified graph unordered_map<handle_t, vector<handle_t>> injector; for (size_t i = 0; i < strong_components.size(); i++) { #ifdef debug_dagify cerr << "handling component " << i << endl; #endif // keep track of which nodes are in which component (for later) auto& component = strong_components[i]; for (nid_t node_id : component) { component_of[node_id] = i; } // figure out how many times we need to copy this SCC // wrap the SCC in a handle graph SubHandleGraph subgraph(graph); for (const nid_t& node_id : component) { subgraph.add_handle(graph->get_handle(node_id)); } // get a layout with a low FAS vector<handle_t> layout = eades_algorithm(&subgraph); // make sure the layout matches the canonical orientation of the graph if (graph->get_is_reverse(layout.front()) != reversed_nodes.count(graph->get_id(layout.front()))) { for (int64_t i = 0, j = layout.size() - 1; i < j; i++, j--) { auto tmp = layout[i]; layout[i] = subgraph.flip(layout[j]); layout[j] = subgraph.flip(tmp); } if (layout.size() % 2) { layout[layout.size() / 2] = subgraph.flip(layout[layout.size() / 2]); } } #ifdef debug_dagify cerr << "layout for component:" << endl; for (const handle_t& h : layout) { cerr << "\t" << graph->get_id(h) << (graph->get_is_reverse(h) ? "-" : "+") << endl; } #endif // record the ordering of the layout so we can identify backward edges unordered_map<handle_t, size_t> ordering; for (size_t i = 0; i < layout.size(); i++) { ordering[layout[i]] = i; } // mark the edges as either forward or backward relative to the layout vector<vector<size_t>> forward_edges(layout.size()); vector<pair<size_t, size_t>> backward_edges; subgraph.for_each_edge([&](const edge_t& edge) { // get the indices of the edge in the layout, making sure to match // the canonical orientation size_t i, j; auto iter = ordering.find(edge.first); if (iter != ordering.end()) { i = iter->second; j = ordering[edge.second]; } else { i = ordering[subgraph.flip(edge.second)]; j = ordering[subgraph.flip(edge.first)]; } // classify the edge as forward or backward if (i < j) { forward_edges[i].push_back(j); } else { backward_edges.emplace_back(i, j); } // always keep going return true; }); // check for each node whether we've duplicated the component enough times // to preserve its cycles // dynamic progamming structures that represent distances within the current // copy of the SCC and the next copy vector<int64_t> distances(layout.size(), numeric_limits<int64_t>::max()); vector<int64_t> next_distances(layout.size(), numeric_limits<int64_t>::max()); // init the distances so that we are measuring from the end of the heads of // backward edges (which cross to the next copy of the SCC) for (const pair<size_t, size_t>& bwd_edge : backward_edges) { handle_t handle = layout[bwd_edge.first]; distances[ordering[handle]] = -subgraph.get_length(handle); } // init the tracker that we use for the bail-out condition int64_t min_relaxed_dist = -1; // add copies until the minimum distance to the new copy is longer than the distance we're // trying to preserve for (size_t copy_num = 0; min_relaxed_dist < int64_t(min_preserved_path_length); copy_num++) { #ifdef debug_dagify cerr << "copy number " << copy_num << endl; #endif // do we need a new copy of this SCC to preserve paths? if (copy_num == injector[layout.front()].size()) { // we haven't added this copy of the connected component yet #ifdef debug_dagify cerr << "adding nodes for this copy" << endl; #endif // add the nodes for (const handle_t& original_handle : layout) { // create the node in the same foward orientation as the original handle_t new_handle = into->create_handle(graph->get_sequence(graph->forward(original_handle))); // use the handle locally in the same orientation as it is in the layout if (graph->get_is_reverse(original_handle)) { new_handle = into->flip(new_handle); } #ifdef debug_dagify cerr << "\t" << graph->get_id(original_handle) << " duplicated to " << into->get_id(new_handle) << endl; #endif // record the translation between the graphs translator[into->get_id(new_handle)] = graph->get_id(original_handle); injector[original_handle].push_back(new_handle); } // add the forward edges within this copy for (size_t i = 0; i < forward_edges.size(); i++) { handle_t from = injector[layout[i]].back(); for (const size_t& j : forward_edges[i]) { into->create_edge(from, injector[layout[j]].back()); #ifdef debug_dagify cerr << "\t\tfwd edge " << into->get_id(from) << (into->get_is_reverse(from) ? "-" : "+") << " -> " << into->get_id(injector[layout[j]].back()) << (into->get_is_reverse(injector[layout[j]].back()) ? "-" : "+") << endl; #endif } } // is there a previous copy? if (copy_num > 0) { // add the backward edges between the copies for (const pair<size_t, size_t>& bwd_edge : backward_edges) { const auto& from_copies = injector[layout[bwd_edge.first]]; into->create_edge(from_copies[from_copies.size() - 2], injector[layout[bwd_edge.second]].back()); #ifdef debug_dagify cerr << "\t\tbwd edge " << into->get_id(from_copies[from_copies.size() - 2]) << (into->get_is_reverse(from_copies[from_copies.size() - 2]) ? "-" : "+") << " -> " << into->get_id(injector[layout[bwd_edge.second]].back()) << (into->get_is_reverse(injector[layout[bwd_edge.second]].back()) ? "-" : "+") << endl; #endif } } } // we've finished adding the copy of the SCC that corresponds to this iteration // now we will do the dynamic programming to bound the distance to the next SCC // find the shortest path to the nodes, staying within this copy of the SCC for (size_t i = 0; i < distances.size(); i++) { // skip infinity to avoid overflow if (distances[i] == numeric_limits<int64_t>::max()) { continue; } int64_t dist_thru = distances[i] + subgraph.get_length(layout[i]); for (const size_t& j : forward_edges[i]) { distances[j] = min(distances[j], dist_thru); } } // now find the minimum distance to nodes in the next copy of the SCC (which // may not yet be created in the graph) min_relaxed_dist = numeric_limits<int64_t>::max(); for (const pair<size_t, size_t>& bwd_edge : backward_edges) { // skip infinity to avoid overflow if (distances[bwd_edge.first] == numeric_limits<int64_t>::max()) { continue; } int64_t dist_thru = distances[bwd_edge.first] + subgraph.get_length(layout[bwd_edge.first]); if (dist_thru < next_distances[bwd_edge.second]) { next_distances[bwd_edge.second] = dist_thru; // keep track of the shortest distance to the next copy min_relaxed_dist = min(min_relaxed_dist, dist_thru); } } #ifdef debug_dagify cerr << "distances within component" << endl; for (size_t i = 0; i < distances.size(); i++) { cerr << "\t" << graph->get_id(layout[i]) << (graph->get_is_reverse(layout[i]) ? "-" : "+") << " " << distances[i] << endl; } cerr << "distances to next component" << endl; for (size_t i = 0; i < next_distances.size(); i++) { cerr << "\t" << graph->get_id(layout[i]) << (graph->get_is_reverse(layout[i]) ? "-" : "+") << " " << next_distances[i] << endl; } #endif // initialize the DP structures for the next iteration distances = move(next_distances); next_distances.assign(distances.size(), numeric_limits<int64_t>::max()); } } #ifdef debug_dagify cerr << "adding edges between SCCs" << endl; #endif // add edges between the strongly connected components graph->for_each_edge([&](const edge_t& canonical_edge) { if (component_of[graph->get_id(canonical_edge.first)] != component_of[graph->get_id(canonical_edge.second)]) { // this edge is between SCCs // put the edge in the order of the orientation we've imposed on the graph so // we can index into the look structures we created edge_t edge = (graph->get_is_reverse(canonical_edge.first) != reversed_nodes.count(graph->get_id(canonical_edge.first)) ? edge_t(graph->flip(canonical_edge.second), graph->flip(canonical_edge.first)) : canonical_edge); // connect the last copy of the first node to all copies of the second const handle_t& from = injector[edge.first].back(); for (const handle_t& to : injector[edge.second]) { into->create_edge(from, to); #ifdef debug_dagify cerr << "\t" << into->get_id(from) << (into->get_is_reverse(from) ? "-" : "+") << " -> " << into->get_id(to) << (into->get_is_reverse(to) ? "-" : "+") << endl; #endif } } // always keep going return true; }); // return the ID translator return translator; } } }
39.721992
332
0.593753
vgteam
25d1824fb2cbe0e9da5dbffccab59beab8e79368
8,892
cpp
C++
thormang3_step_control_module/src/robotis_online_walking_plugin.cpp
thor-mang/ROBOTIS-THORMANG-MPC
6d5d6479ddab1bbcf0ff34e5cf6f98823da38cad
[ "BSD-3-Clause" ]
3
2018-01-30T16:03:20.000Z
2021-11-13T21:14:08.000Z
thormang3_step_control_module/src/robotis_online_walking_plugin.cpp
thor-mang/ROBOTIS-THORMANG-MPC
6d5d6479ddab1bbcf0ff34e5cf6f98823da38cad
[ "BSD-3-Clause" ]
null
null
null
thormang3_step_control_module/src/robotis_online_walking_plugin.cpp
thor-mang/ROBOTIS-THORMANG-MPC
6d5d6479ddab1bbcf0ff34e5cf6f98823da38cad
[ "BSD-3-Clause" ]
null
null
null
#include <thormang3_step_control_module/robotis_online_walking_plugin.h> #include <thormang3_walking_module/thormang3_online_walking.h> #include <thormang3_walking_module/walking_module.h> namespace thormang3 { using namespace vigir_footstep_planning; THORMANG3OnlineWalkingPlugin::THORMANG3OnlineWalkingPlugin() : StepControllerPlugin() , last_remaining_unreserved_steps_(0) , min_unreserved_steps_(2) { } THORMANG3OnlineWalkingPlugin::~THORMANG3OnlineWalkingPlugin() { } void THORMANG3OnlineWalkingPlugin::setStepPlanMsgPlugin(StepPlanMsgPlugin::Ptr plugin) { StepControllerPlugin::setStepPlanMsgPlugin(plugin); boost::unique_lock<boost::shared_mutex> lock(plugin_mutex_); thor_mang_step_plan_msg_plugin_ = boost::dynamic_pointer_cast<ThorMangStepPlanMsgPlugin>(plugin); if (!thor_mang_step_plan_msg_plugin_) ROS_ERROR("[THORMANG3OnlineWalkingPlugin] StepPlanMsgPlugin is not from type 'ThorMangStepPlanMsgPlugin'!"); } bool THORMANG3OnlineWalkingPlugin::updateStepPlan(const msgs::StepPlan& step_plan) { if (step_plan.steps.empty()) return true; // transform initial step plan (afterwards stitching will do that automatically for us) if (step_queue_->empty()) { const msgs::Step& step = step_plan.steps.front(); robotis_framework::StepData ref_step; initStepData(ref_step); /// TODO: use robotis reference step here? //robotis_framework::THORMANG3OnlineWalking::GetInstance()->GetReferenceStepDatafotAddition(&ref_step); geometry_msgs::Pose ref_pose; if (step.foot.foot_index == msgs::Foot::LEFT) thor_mang_footstep_planning::toRos(ref_step.position_data.left_foot_pose, ref_pose); else if (step.foot.foot_index == msgs::Foot::RIGHT) thor_mang_footstep_planning::toRos(ref_step.position_data.right_foot_pose, ref_pose); else { ROS_ERROR("[THORMANG3OnlineWalkingPlugin] updateStepPlan: First step of input step plan has unknown foot index."); return false; } // determine transformation to robotis frame tf::Transform transform = vigir_footstep_planning::StepPlan::getTransform(step.foot.pose, ref_pose); msgs::StepPlan step_plan_transformed = step_plan; vigir_footstep_planning::StepPlan::transformStepPlan(step_plan_transformed, transform); return StepControllerPlugin::updateStepPlan(step_plan_transformed); } else { /// TODO: Handle reverse spooling correctly return StepControllerPlugin::updateStepPlan(step_plan); } return false; } void THORMANG3OnlineWalkingPlugin::initWalk() { thormang3::THORMANG3OnlineWalking* online_walking = thormang3::THORMANG3OnlineWalking::getInstance(); if (online_walking->isRunning()) { ROS_ERROR("[THORMANG3OnlineWalkingPlugin] Can't start walking as walking engine is still running. This is likely a bug and should be fixed immediately!"); setState(FAILED); return; } //online_walking->initialize(); //online_walking->setInitialPose(); //online_walking->setInitalWaistYawAngle(); last_remaining_unreserved_steps_ = 0; // init feedback states msgs::ExecuteStepPlanFeedback feedback; feedback.header.stamp = ros::Time::now(); feedback.last_performed_step_index = -1; feedback.currently_executing_step_index = 0; feedback.first_changeable_step_index = 0; setFeedbackState(feedback); setState(ACTIVE); online_walking->start(); ROS_INFO("[THORMANG3OnlineWalkingPlugin] Starting walking."); } void THORMANG3OnlineWalkingPlugin::preProcess(const ros::TimerEvent& event) { StepControllerPlugin::preProcess(event); if (getState() != ACTIVE) return; thormang3::THORMANG3OnlineWalking* online_walking = thormang3::THORMANG3OnlineWalking::getInstance(); // first check if walking engine is still running if (!online_walking->isRunning()) { ROS_INFO("[THORMANG3OnlineWalkingPlugin] Walking engine has stopped unexpectedly. This is likely a bug and should be fixed immediately!"); setState(FAILED); return; } // checking current state of walking engine int remaining_unreserved_steps = online_walking->getNumofRemainingUnreservedStepData(); int executed_steps = std::max(last_remaining_unreserved_steps_ - remaining_unreserved_steps, 0); last_remaining_unreserved_steps_ = remaining_unreserved_steps; int needed_steps = min_unreserved_steps_ - remaining_unreserved_steps; msgs::ExecuteStepPlanFeedback feedback = getFeedbackState(); // step(s) has been performed recently feedback.header.stamp = ros::Time::now(); feedback.last_performed_step_index += executed_steps; feedback.currently_executing_step_index += executed_steps; if (needed_steps > 0) { step_queue_->clearDirtyFlag(); // check if further steps in queue are available int steps_remaining = std::max(0, (step_queue_->lastStepIndex() - feedback.first_changeable_step_index) + 1); // steps are available if (steps_remaining > 0) { needed_steps = std::min(needed_steps, steps_remaining); setNextStepIndexNeeded(getNextStepIndexNeeded()+needed_steps); feedback.first_changeable_step_index = getNextStepIndexNeeded()+1; } // queue has been completely flushed out and executed else { // check for successful execution of queue if (step_queue_->lastStepIndex() == feedback.last_performed_step_index) { ROS_INFO("[THORMANG3OnlineWalkingPlugin] Walking finished."); feedback.currently_executing_step_index = -1; feedback.first_changeable_step_index = -1; setFeedbackState(feedback); step_queue_->reset(); updateQueueFeedback(); setState(FINISHED); } } } setFeedbackState(feedback); } bool THORMANG3OnlineWalkingPlugin::executeStep(const msgs::Step& step) { /// TODO: flush step thormang3::THORMANG3OnlineWalking* online_walking = thormang3::THORMANG3OnlineWalking::getInstance(); // add initial step if (step.step_index == 0) { robotis_framework::StepData step_data; initStepData(step_data); /// TODO: use robotis reference step here? //online_walking->getReferenceStepDatafotAddition(&_refStepData); if (!online_walking->addStepData(step_data)) { ROS_INFO("[THORMANG3OnlineWalkingPlugin] executeStep: Error while adding initial step."); return false; } last_step_data_ = step_data; // add final step step_data.position_data.foot_z_swap = 0.0; step_data.position_data.body_z_swap = 0.0; step_data.position_data.moving_foot = thormang3_walking_module_msgs::StepPositionData::STANDING; step_data.time_data.walking_state = thormang3_walking_module_msgs::StepTimeData::IN_WALKING_ENDING; step_data.time_data.abs_step_time += 1.0; if (!online_walking->addStepData(step_data)) { ROS_INFO("[THORMANG3OnlineWalkingPlugin] executeStep: Error while adding (temp) final step."); return false; } } else { // get ref data robotis_framework::StepData ref_step_data; online_walking->getReferenceStepDatafotAddition(&ref_step_data); // remove final step to be updated online_walking->eraseLastStepData(); // add step /// TODO: use robotis reference step here? robotis_framework::StepData step_data = last_step_data_; step_data << step; /// TODO: compensate drift in z step_data.position_data.body_pose.z = ref_step_data.position_data.body_pose.z; if (step.foot.foot_index == msgs::Foot::LEFT) step_data.position_data.left_foot_pose.z = ref_step_data.position_data.right_foot_pose.z; else step_data.position_data.right_foot_pose.z = ref_step_data.position_data.left_foot_pose.z; if (!online_walking->addStepData(step_data)) { ROS_INFO("[THORMANG3OnlineWalkingPlugin] executeStep: Error while adding step %i.", step.step_index); return false; } last_step_data_ = step_data; // readd updated final step //step_data.position_data.foot_z_swap = 0.0; step_data.position_data.body_z_swap = 0.0; step_data.position_data.moving_foot = thormang3_walking_module_msgs::StepPositionData::STANDING; step_data.time_data.walking_state = thormang3_walking_module_msgs::StepTimeData::IN_WALKING_ENDING; step_data.time_data.abs_step_time += 1.6; if (!online_walking->addStepData(step_data)) { ROS_INFO("[THORMANG3OnlineWalkingPlugin] executeStep: Error while adding (temp) final step."); return false; } } last_remaining_unreserved_steps_ = online_walking->getNumofRemainingUnreservedStepData(); return true; } void THORMANG3OnlineWalkingPlugin::stop() { StepControllerPlugin::stop(); /// TODO: Stop when both feet on ground thormang3::THORMANG3OnlineWalking::getInstance()->stop(); } } // namespace #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(thormang3::THORMANG3OnlineWalkingPlugin, vigir_step_control::StepControllerPlugin)
33.055762
158
0.753711
thor-mang
25d1f31082b94445867fed6605391419691dffe0
899
hpp
C++
tasks/LedMatrixDisplay.hpp
PhischDotOrg/stm32f4-common
4b6b9c436018c89d3668c6ee107e97abb930bae2
[ "MIT" ]
1
2022-01-31T01:59:52.000Z
2022-01-31T01:59:52.000Z
tasks/LedMatrixDisplay.hpp
PhischDotOrg/stm32-common
4b6b9c436018c89d3668c6ee107e97abb930bae2
[ "MIT" ]
5
2020-04-13T21:55:12.000Z
2020-06-27T17:44:44.000Z
tasks/LedMatrixDisplay.hpp
PhischDotOrg/stm32f4-common
4b6b9c436018c89d3668c6ee107e97abb930bae2
[ "MIT" ]
null
null
null
/*- * $Copyright$ -*/ #ifndef _TASKS_LED_MATRIX_DISPLAY_HPP_3dcb329a_694a_48b4_8249_5ca9cb2ed9b4 #define _TASKS_LED_MATRIX_DISPLAY_HPP_3dcb329a_694a_48b4_8249_5ca9cb2ed9b4 #include "tasks/Task.hpp" #include <gpio/GpioPin.hpp> #include <uart/UartDevice.hpp> namespace tasks { template<typename LedMatrixT, typename UartT = uart::UartDevice, unsigned t_width = 8, unsigned t_height = 8> class LedMatrixDisplayT : public Task { private: UartT & m_uart; LedMatrixT & m_ledMatrix; const unsigned m_periodUs; virtual void run(void); public: LedMatrixDisplayT(const char * const p_name, UartT &p_uart, LedMatrixT &p_ledMatrix, const unsigned p_priority, const unsigned p_periodUs = 500); virtual ~LedMatrixDisplayT(); }; }; /* namespace tasks */ #include "LedMatrixDisplay.cpp" #endif /* _TASKS_LED_MATRIX_DISPLAY_HPP_3dcb329a_694a_48b4_8249_5ca9cb2ed9b4 */
26.441176
149
0.765295
PhischDotOrg
25d39d929f95332c75d0f8c7a56f050bd408de0a
609
hpp
C++
include/guidance/segregated_intersection_classification.hpp
AugustoQueiroz/pedalavel-backend
c7fa405ff6f6823bdc9d4bb857eddc7197be1f4f
[ "BSD-2-Clause" ]
null
null
null
include/guidance/segregated_intersection_classification.hpp
AugustoQueiroz/pedalavel-backend
c7fa405ff6f6823bdc9d4bb857eddc7197be1f4f
[ "BSD-2-Clause" ]
null
null
null
include/guidance/segregated_intersection_classification.hpp
AugustoQueiroz/pedalavel-backend
c7fa405ff6f6823bdc9d4bb857eddc7197be1f4f
[ "BSD-2-Clause" ]
1
2019-09-23T22:49:07.000Z
2019-09-23T22:49:07.000Z
#include "util/typedefs.hpp" #include <unordered_set> namespace osrm { namespace util { class NameTable; } namespace extractor { class NodeBasedGraphFactory; } namespace guidance { // Find all "segregated" edges, e.g. edges that can be skipped in turn instructions. // The main cases are: // - middle edges between two osm ways in one logic road (U-turn) // - staggered intersections (X-cross) // - square/circle intersections std::unordered_set<EdgeID> findSegregatedNodes(const extractor::NodeBasedGraphFactory &factory, const util::NameTable &names); } }
21.75
95
0.701149
AugustoQueiroz
25d41e95630190e43c50fefd8afcd9eaf11683a4
5,884
hxx
C++
include/itkBlockMatchingMultiResolutionIterationObserver.hxx
tbirdso/ITKUltrasound
fb5915978de73a71b0fc43b9ce1c9d32dfa19783
[ "Apache-2.0" ]
38
2015-01-20T14:16:22.000Z
2022-03-16T09:23:09.000Z
include/itkBlockMatchingMultiResolutionIterationObserver.hxx
thewtex/ITKUltrasound
9ab459466ffe155840fdf3de30aafb3660dba800
[ "Apache-2.0" ]
83
2015-08-05T14:09:42.000Z
2022-03-30T20:28:03.000Z
include/itkBlockMatchingMultiResolutionIterationObserver.hxx
thewtex/ITKUltrasound
9ab459466ffe155840fdf3de30aafb3660dba800
[ "Apache-2.0" ]
29
2015-03-27T23:23:20.000Z
2022-01-04T22:44:57.000Z
/*========================================================================= * * Copyright NumFOCUS * * 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. * *=========================================================================*/ #ifndef itkBlockMatchingMultiResolutionIterationObserver_hxx #define itkBlockMatchingMultiResolutionIterationObserver_hxx #include "itkBlockMatchingMultiResolutionIterationObserver.h" #include <iostream> #include <sstream> namespace itk { namespace BlockMatching { template <typename TMultiResolutionMethod> MultiResolutionIterationObserver<TMultiResolutionMethod>::MultiResolutionIterationObserver() { m_FixedImageWriter = FixedImageWriterType::New(); m_MovingImageWriter = MovingImageWriterType::New(); m_DisplacementWriter = DisplacementWriterType::New(); m_DisplacementComponentsFilter = DisplacementComponentsFilterType::New(); m_DisplacementComponentsWriter = DisplacementComponentsWriterType::New(); m_StrainFilter = StrainFilterType::New(); m_StrainWriter = StrainWriterType::New(); m_StrainWriter->SetInput(m_StrainFilter->GetOutput()); m_StrainComponentsFilter = StrainComponentsFilterType::New(); m_StrainComponentsFilter->SetInput(m_StrainFilter->GetOutput()); m_StrainComponentsWriter = StrainComponentsWriterType::New(); } template <typename TMultiResolutionMethod> MultiResolutionIterationObserver<TMultiResolutionMethod>::~MultiResolutionIterationObserver() { if (m_CSVFile.is_open()) { m_CSVFile.flush(); m_CSVFile.close(); } } template <typename TMultiResolutionMethod> void MultiResolutionIterationObserver<TMultiResolutionMethod>::Execute(itk::Object * object, const itk::EventObject & event) { Superclass::Execute(object, event); const unsigned long level = this->m_MultiResolutionMethod->GetCurrentLevel(); std::cout << "Current Level: " << level + 1; std::cout << " / " << this->m_MultiResolutionMethod->GetNumberOfLevels() << std::endl; if (!m_CSVFile.is_open()) { m_CSVFile.open((m_OutputFilePrefix + "_BlockRadius.csv").c_str()); if (!m_CSVFile.is_open()) throw std::runtime_error("Could not open multi-level status file."); m_CSVFile << "Level, Block Radius" << std::endl; } m_CSVFile << level << ", "; m_CSVFile << const_cast<typename Superclass::BlockRadiusCalculatorType *>(this->m_BlockRadiusCalculator.GetPointer()) ->Compute(level) << std::endl; // Skip the base level where the multilevel pyramid filter is not used. if (level < this->m_MultiResolutionMethod->GetNumberOfLevels()) { std::cout << "Writing fixed image..." << std::endl; std::ostringstream ostr; ostr << m_OutputFilePrefix << "_Level_" << level << "_FixedImage.mha"; this->m_FixedImageWriter->SetInput( const_cast<typename Superclass::FixedImagePyramidType *>(this->m_FixedImagePyramid.GetPointer()) ->GetOutput(level)); this->m_FixedImageWriter->SetFileName(ostr.str()); this->m_FixedImageWriter->Update(); std::cout << "Writing moving image..." << std::endl; ostr.str(""); ostr << m_OutputFilePrefix << "_Level_" << level << "_MovingImage.mha"; this->m_MovingImageWriter->SetInput( const_cast<typename Superclass::MovingImagePyramidType *>(this->m_MovingImagePyramid.GetPointer()) ->GetOutput(level)); this->m_MovingImageWriter->SetFileName(ostr.str()); this->m_MovingImageWriter->Update(); if (level > 0) { std::cout << "Writing displacement image..." << std::endl; ostr.str(""); ostr << m_OutputFilePrefix << "_Level_" << level << "_PreviousDisplacements.mha"; m_DisplacementWriter->SetInput(this->m_SearchRegionImageSource->GetPreviousDisplacements()); m_DisplacementWriter->SetFileName(ostr.str()); m_DisplacementWriter->Update(); m_DisplacementComponentsFilter->SetInput(this->m_SearchRegionImageSource->GetPreviousDisplacements()); ostr.str(""); ostr << m_OutputFilePrefix << "_Level_" << level << "_PreviousDisplacementComponent0.mha"; m_DisplacementComponentsWriter->SetFileName(ostr.str()); m_DisplacementComponentsWriter->SetInput(m_DisplacementComponentsFilter->GetOutput(0)); m_DisplacementComponentsWriter->Update(); ostr.str(""); ostr << m_OutputFilePrefix << "_Level_" << level << "_PreviousDisplacementComponent1.mha"; m_DisplacementComponentsWriter->SetFileName(ostr.str()); m_DisplacementComponentsWriter->SetInput(m_DisplacementComponentsFilter->GetOutput(1)); m_DisplacementComponentsWriter->Update(); std::cout << "Writing strain image..." << std::endl; m_StrainFilter->SetInput(this->m_SearchRegionImageSource->GetPreviousDisplacements()); ostr.str(""); ostr << m_OutputFilePrefix << "_Level_" << level << "_PreviousStrains.mha"; m_StrainWriter->SetFileName(ostr.str()); m_StrainWriter->Update(); for (unsigned int i = 0; i < 3; i++) { m_StrainComponentsWriter->SetInput(m_StrainComponentsFilter->GetOutput(i)); ostr.str(""); ostr << m_OutputFilePrefix << "_Level_" << level << "_PreviousStrainComponent"; ostr << i << ".mha"; m_StrainComponentsWriter->SetFileName(ostr.str()); m_StrainComponentsWriter->Update(); } } } } } // end namespace BlockMatching } // end namespace itk #endif
40.027211
119
0.700204
tbirdso
25d5669bc9f24f7f02b710f8f0878c16a6496c94
1,731
cpp
C++
console/src/boost_1_78_0/libs/describe/test/overloaded_test2.cpp
vany152/FilesHash
39f282807b7f1abc56dac389e8259ee3bb557a8d
[ "MIT" ]
106
2015-08-07T04:23:50.000Z
2020-12-27T18:25:15.000Z
console/src/boost_1_78_0/libs/describe/test/overloaded_test2.cpp
vany152/FilesHash
39f282807b7f1abc56dac389e8259ee3bb557a8d
[ "MIT" ]
130
2016-06-22T22:11:25.000Z
2020-11-29T20:24:09.000Z
console/src/boost_1_78_0/libs/describe/test/overloaded_test2.cpp
vany152/FilesHash
39f282807b7f1abc56dac389e8259ee3bb557a8d
[ "MIT" ]
41
2015-07-08T19:18:35.000Z
2021-01-14T16:39:56.000Z
// Copyright 2020 Peter Dimov // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt #include <boost/describe/members.hpp> #include <boost/describe/class.hpp> #include <boost/core/lightweight_test.hpp> #include <utility> class X { private: std::pair<int, int> p_; public: std::pair<int, int>& f() { return p_; } std::pair<int, int> const& f() const { return p_; } BOOST_DESCRIBE_CLASS(X, (), ((std::pair<int, int>& ()) f, (std::pair<int, int> const& () const) f), (), (p_)) }; #if !defined(BOOST_DESCRIBE_CXX14) #include <boost/config/pragma_message.hpp> BOOST_PRAGMA_MESSAGE("Skipping test because C++14 is not available") int main() {} #else #include <boost/mp11.hpp> int main() { using namespace boost::describe; using namespace boost::mp11; { using L1 = describe_members<X, mod_any_access>; BOOST_TEST_EQ( mp_size<L1>::value, 1 ); using D1 = mp_at_c<L1, 0>; BOOST_TEST_CSTR_EQ( D1::name, "p_" ); BOOST_TEST_EQ( D1::modifiers, mod_private ); X x; auto& p = x.*D1::pointer; using L2 = describe_members<X, mod_any_access | mod_function>; BOOST_TEST_EQ( mp_size<L2>::value, 2 ); using D2 = mp_at_c<L2, 0>; using D3 = mp_at_c<L2, 1>; BOOST_TEST_EQ( &(x.*D2::pointer)(), &p ); BOOST_TEST_CSTR_EQ( D2::name, "f" ); BOOST_TEST_EQ( D2::modifiers, mod_public | mod_function ); BOOST_TEST_EQ( &(x.*D3::pointer)(), &p ); BOOST_TEST_CSTR_EQ( D3::name, "f" ); BOOST_TEST_EQ( D3::modifiers, mod_public | mod_function ); } return boost::report_errors(); } #endif // !defined(BOOST_DESCRIBE_CXX14)
23.08
113
0.62565
vany152
25dabbbb9c66336a8a909ef3fe31761be685940e
1,886
cpp
C++
benchmarks/threadpool/benchmark.cpp
alexbriskin/taskflow
da69f8989f26f8ff7bc731dbafb2f6ce171934fc
[ "MIT" ]
null
null
null
benchmarks/threadpool/benchmark.cpp
alexbriskin/taskflow
da69f8989f26f8ff7bc731dbafb2f6ce171934fc
[ "MIT" ]
null
null
null
benchmarks/threadpool/benchmark.cpp
alexbriskin/taskflow
da69f8989f26f8ff7bc731dbafb2f6ce171934fc
[ "MIT" ]
null
null
null
#include <taskflow/taskflow.hpp> #include <chrono> #include "ThreadPool.hpp" ThreadPool* ThreadPool::singleton = nullptr; std::mutex ThreadPool::singleton_mutex; tf::Executor executor; class ChronoTimer { public: ChronoTimer(void) { } void start(void){ startTime = std::chrono::high_resolution_clock::now(); } void finish(std::string msg){ auto finish = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> elapsed = finish - startTime; printf("%s : %f ms\n",msg.c_str(), elapsed.count() * 1000); } private: std::chrono::high_resolution_clock::time_point startTime; }; void benchFunc(uint64_t loopLen){ float acc = 0; for (uint64_t k = 0; k < loopLen; ++k) acc += k; } void bench(uint32_t iter){ printf("Benchmark with %d iterations\n",iter); const uint64_t num_blocks = 1000; const uint64_t loopLen = 100; ChronoTimer timer; ThreadPool *pool = ThreadPool::get(); timer.start(); for (uint64_t it = 0; it < iter; ++it) { tf::Taskflow taskflow; tf::Task node[num_blocks]; for (uint64_t i = 0; i < num_blocks; i++) node[i] = taskflow.placeholder(); for (uint64_t i = 0; i < num_blocks; i++) { node[i].work([=]() { benchFunc(loopLen); }); } executor.run(taskflow).wait(); } timer.finish("taskflow: time in ms: "); timer.start(); for (uint64_t it = 0; it < iter; ++it) { std::vector<std::future<int>> results; for (uint64_t i = 0; i < num_blocks; i++) { results.emplace_back(pool->enqueue([=]() { benchFunc(loopLen); return 0; })); } for(auto& result : results) { result.get(); } } timer.finish("threadpool: time in ms: "); } int main() { for (uint32_t i = 0; i < 5; ++i) bench(100); for (uint32_t i = 0; i < 5; ++i) bench(50); for (uint32_t i = 0; i < 5; ++i) bench(20); for (uint32_t i = 0; i < 5; ++i) bench(10); for (uint32_t i = 0; i < 5; ++i) bench(5); }
22.452381
61
0.629905
alexbriskin
25db6ad72a6d8a018fff90d5533d6d667604fe69
3,776
hpp
C++
src/core/exponential.hpp
tp-ntouran/mocc
77d386cdf341b1a860599ff7c6e4017d46e0b102
[ "Apache-2.0" ]
11
2016-03-31T17:46:15.000Z
2022-02-14T01:07:56.000Z
src/core/exponential.hpp
tp-ntouran/mocc
77d386cdf341b1a860599ff7c6e4017d46e0b102
[ "Apache-2.0" ]
3
2016-04-04T16:40:47.000Z
2019-10-16T22:22:54.000Z
src/core/exponential.hpp
tp-ntouran/mocc
77d386cdf341b1a860599ff7c6e4017d46e0b102
[ "Apache-2.0" ]
3
2019-10-16T22:20:15.000Z
2019-11-28T11:59:03.000Z
/* Copyright 2016 Mitchell Young 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. */ #pragma once #include <algorithm> #include <array> #include <cassert> #include <cmath> #include "util/global_config.hpp" namespace mocc { /** * Base class defining a class of simple utility classes for computing * exponential functions. The base version uses the stock library call to * exp(), while derived versions can override this with more efficient table * lookups. */ class Exponential { public: Exponential() { } inline real_t exp(real_t v) const { return std::exp(v); } virtual real_t max_error() { return 0.0; } }; /* * This version of \ref Exponential uses a linear lookup table to speed up * the evaluations of \ref exp(). If the argument to \ref exp() is beyond * the domain of the table, it will fall back to the result of the standard * library \c exp() function. */ template <int N> class Exponential_Linear : public Exponential { public: Exponential_Linear(real_t min = -10.0, real_t max = 0.0) : min_(min), max_(max), space_((max - min_) / (real_t)(N)), rspace_(1.0 / space_) { for (int i = 0; i <= N; i++) { d_[i] = std::exp(min_ + i * space_); } } inline real_t exp(real_t v) const { if (v < min_ || v > max_) { std::cout << "Out-of-bounds exponential argument: " << v << std::endl; return std::exp(v); } int i = (v - min_) * rspace_; v -= space_ * i + min_; return d_[i] + (d_[i + 1] - d_[i]) * v * rspace_; } real_t max_error() { real_t max_error = 0.0; for (int i = 0; i < N; i++) { real_t x = min_ + space_ * (0.5 + i); real_t e = std::exp(x); real_t err = std::abs((this->exp(x) - e) / e); max_error = std::max(max_error, err); } return max_error; } /* * \brief Return the table value for the passed point index * * This is mostly useful for testing and debugging purposes. */ real_t operator[](int i) const { return d_[i]; } real_t dx() const { return space_; } protected: real_t min_; real_t max_; real_t space_; real_t rspace_; std::array<real_t, N + 1> d_; }; /** * Same as \ref Exponential_Linear, but without the check to make sure the * argument is within the limits of the table. This should only be used in * situations where one knows that the arguments to \ref exp() won't spill * the banks of the table. Even considering branch prediction, this manages * to shave a little more time off of the \ref exp() evaluations over \ref * Exponential_Linear. */ template <int N> class Exponential_UnsafeLinear : public Exponential_Linear<N> { Exponential_UnsafeLinear(real_t min = -10.0, real_t max = 0.0) : Exponential_Linear<N>(min, max) { return; } inline real_t exp(real_t v) const { int i = (v - this->min_) * this->rspace_; v -= this->space_ * i + this->min_; return this->d_[i] + (this->d_[i + 1] - this->d_[i]) * v * this->rspace_; } }; }
27.362319
80
0.601165
tp-ntouran
25dcaa63f88e96f8b8aea70cd7e38066eaa3cd88
2,362
cpp
C++
Algorithms/0993.CousinsInBinaryTree/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
Algorithms/0993.CousinsInBinaryTree/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
Algorithms/0993.CousinsInBinaryTree/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
#include <queue> #include "TreeNode.h" #include "TreeNodeUtils.h" #include "gtest/gtest.h" using CommonLib::TreeNode; namespace { struct NodeData { NodeData(TreeNode* current, size_t depth, TreeNode* parent) : Current(current), Depth(depth), Parent(parent) { } TreeNode* Current; size_t Depth; TreeNode* Parent; }; class Solution { public: bool isCousins(TreeNode* root, int x, int y) const { std::queue<NodeData> nodes; nodes.emplace(root, 0, nullptr); bool hasXValue = false; bool hasYValue = false; size_t currentDepth = 0; TreeNode* lastParent = nullptr; while (!nodes.empty()) { if (currentDepth != nodes.front().Depth) { hasXValue = false; hasYValue = false; currentDepth = nodes.front().Depth; lastParent = nullptr; } if (nodes.front().Current->val == x && ProcessValueEquality(nodes.front().Parent, hasXValue, hasYValue, &lastParent)) return true; if (nodes.front().Current->val == y && ProcessValueEquality(nodes.front().Parent, hasYValue, hasXValue, &lastParent)) return true; if (nodes.front().Current->left != nullptr) nodes.emplace(nodes.front().Current->left, nodes.front().Depth + 1, nodes.front().Current); if (nodes.front().Current->right != nullptr) nodes.emplace(nodes.front().Current->right, nodes.front().Depth + 1, nodes.front().Current); nodes.pop(); } return false; } private: bool ProcessValueEquality(TreeNode* parent, bool &hasValue, bool hasOtherValue, TreeNode** lastParent) const { if (hasOtherValue && *lastParent != parent) return true; hasValue = true; *lastParent = parent; return false; } }; } using CommonLib::Codec; namespace CousinsInBinaryTreeTask { TEST(SmallestStringStartingFromLeafTaskTests, Examples) { const Solution solution; ASSERT_EQ(false, solution.isCousins(Codec::createTree("[1,2,3,4]").get(), 4, 3)); ASSERT_EQ(true, solution.isCousins(Codec::createTree("[1,2,3,null,4,null,5]").get(), 5, 4)); ASSERT_EQ(false, solution.isCousins(Codec::createTree("[1,2,3,null,4]").get(), 2, 3)); } }
28.457831
129
0.600339
stdstring
25e0c3389da573d2eedb1433ce82a0f442dc3c7b
881
cpp
C++
UOJ/Goodbye Yiwei/B/code.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
UOJ/Goodbye Yiwei/B/code.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
UOJ/Goodbye Yiwei/B/code.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstring> #define maxn 100010 #define maxm 200010 using namespace std; int T,n,m; struct Graph{ int tot,head[maxn],to[maxm],next[maxm],du[maxn],mark[maxn]; void addedge(int a,int b){to[++tot]=b;next[tot]=head[a];head[a]=tot;++du[a];} void clear(){tot=0;memset(head,0,sizeof(head));memset(du,0,sizeof(du));memset(mark,0,sizeof(mark));} void solve(){ for(int k=1;k<=n;++k){ if(du[k]==1){mark[k]=1;continue;} for(int p=head[k];p;p=next[p])if(du[to[p]]==1){mark[k]=1;break;} } } }G; int main(){ scanf("%d",&T); while(T--){ scanf("%d%d",&n,&m); G.clear(); for(int i=1;i<=m;++i){ int u,v;scanf("%d%d",&u,&v); G.addedge(u,v);G.addedge(v,u); } G.solve(); int k=0; for(int i=1;i<=n;++i)if(G.mark[i])++k; printf("%d\n",k); for(int i=1;i<=n;++i)if(G.mark[i])printf("%d ",i);printf("\n"); } return 0; }
22.589744
101
0.578888
sjj118
25e3e10969df769bef5fb49031e2c4848fc1c2ea
1,122
hpp
C++
sources/Notebook.hpp
LiorBreitman8234/Ex2_cpp_b
53c8c2524d737e3121a749c3b1ff2ef4551de6cb
[ "MIT" ]
null
null
null
sources/Notebook.hpp
LiorBreitman8234/Ex2_cpp_b
53c8c2524d737e3121a749c3b1ff2ef4551de6cb
[ "MIT" ]
null
null
null
sources/Notebook.hpp
LiorBreitman8234/Ex2_cpp_b
53c8c2524d737e3121a749c3b1ff2ef4551de6cb
[ "MIT" ]
null
null
null
// // Created by bravo8234 on 20/03/2022. // #ifndef EX2_CPP_QA_NOTEBOOK_HPP #define EX2_CPP_QA_NOTEBOOK_HPP #include <iostream> #include <vector> #include <map> #include <unordered_map> #include <string> #include <stdexcept> #include "Page.hpp" #include "Direction.hpp" #define ROW_LENGTH 100 #define CHAR_UP_LIMIT 126 #define CHAR_LOW_LIMIT 32 namespace ariel { class Notebook { std::map<int, Page> pages; std::map<int, Page> &pagesRef; static int checkInputWrite(int page, int row, int column, const std::string &toWrite, Direction direction); static int checkInputReadAndErase(int page, int row, int column, int length, Direction direction); public: Notebook() : pages(std::map<int, Page>()), pagesRef(pages) {}; void write(int page, int row, int column, Direction direction, std::string toWrite); std::string read(int page, int row, int column, Direction direction, int length); void erase(int page, int row, int column, Direction direction, int length); void show(int page); }; } #endif //EX2_CPP_QA_NOTEBOOK_HPP
25.5
115
0.688948
LiorBreitman8234
25e45e9972c42667d5f0467baaa2ab2366b980c5
18,719
cpp
C++
src/incphp.cpp
StephanGocht/incphp
d92cd186d4bfb059140278b0adc2ec47de06f704
[ "MIT" ]
1
2021-03-08T08:08:03.000Z
2021-03-08T08:08:03.000Z
src/incphp.cpp
StephanGocht/incphp
d92cd186d4bfb059140278b0adc2ec47de06f704
[ "MIT" ]
null
null
null
src/incphp.cpp
StephanGocht/incphp
d92cd186d4bfb059140278b0adc2ec47de06f704
[ "MIT" ]
1
2017-08-29T07:09:09.000Z
2017-08-29T07:09:09.000Z
#include "incphp.h" #include <array> #include <iostream> #include <cmath> #include <set> #include "SatVariable.h" #include "LearnedClauseEvaluationDecorator.h" #include "tclap/CmdLine.h" #include "carj/carj.h" #include "carj/ScopedTimer.h" #include "ipasir/randomized_ipasir.h" #include "ipasir/ipasir_cpp.h" #include "ipasir/printer.h" #include "carj/logging.h" int neccessaryArgument = true; int defaultIsFalse = false; using json = nlohmann::json; TCLAP::CmdLine cmd( "This tool solves the pidgeon hole principle incrementally.", ' ', "0.1"); carj::CarjArg<TCLAP::SwitchArg, bool> addAssumed("A", "addAssumed", "Add assumed clauses.", cmd, defaultIsFalse); carj::CarjArg<TCLAP::SwitchArg, bool> fixedUpperBound("u", "fixedUpperBound", "Add upper bound as clauses.", cmd, defaultIsFalse); namespace CollectData { class MakespanAndTime { public: MakespanAndTime(unsigned makespan) { static auto& solves = carj::getCarj() .data["/incphp/result/solves"_json_pointer]; solves.push_back({}); solves.back()["makespan"] = makespan; LOG(INFO) << "makespan: " << makespan; timer = std::make_unique<carj::ScopedTimer>(solves.back()["time"]); } private: std::unique_ptr<carj::ScopedTimer> timer; }; } class DimSpecFixedPigeons { private: unsigned numPigeons; unsigned numLiteralsPerTime; /** * Variable representing that pigeon p is in hole h. * Note that hole is the same as time. */ int varPigeonInHole(unsigned p, unsigned h) { return numLiteralsPerTime * h + p + 1; } /** * Helper variable, which is true iff the pigeon sits in a future hole. * i.e. step created hole h, then pigeon sits in a hole added in step later */ int helperFutureHole(int p, int h) { return numLiteralsPerTime * h + numPigeons + p + 1; } void printClause(std::vector<int> clause) { for (int literal: clause) { std::cout << literal << " "; } std::cout << "0" << std::endl; } public: DimSpecFixedPigeons(unsigned _numPigeons): numPigeons(_numPigeons), numLiteralsPerTime(2 * _numPigeons) { } void print() { //i, u, g, t int numberOfClauses = 0; numberOfClauses = numPigeons; std::cout << "i cnf " << numLiteralsPerTime << " " << numberOfClauses << std::endl; for (unsigned i = 0; i < numPigeons; i++) { printClause({ varPigeonInHole(i, 0), helperFutureHole(i, 0) }); } numberOfClauses = (numPigeons - 1) * numPigeons / 2; std::cout << "u cnf " << numLiteralsPerTime << " " << numberOfClauses << std::endl; // at most one pigeon in hole of step for (unsigned i = 0; i < numPigeons; i++) { for (unsigned j = 0; j < i; j++) { printClause({-varPigeonInHole(i, 0) , -varPigeonInHole(j, 0)}); } } numberOfClauses = numPigeons; std::cout << "g cnf " << numLiteralsPerTime << " " << numberOfClauses << std::endl; for (unsigned i = 0; i < numPigeons; i++) { printClause({-helperFutureHole(i, 0)}); } numberOfClauses = 3 * numPigeons; std::cout << "t cnf " << 2 * numLiteralsPerTime << " " << numberOfClauses << std::endl; for (unsigned i = 0; i < numPigeons; i++) { // -> printClause({ -helperFutureHole(i, 0), varPigeonInHole(i, 1), helperFutureHole(i, 1), }); // <- // printClause({ // helperFutureHole(i, 0), // -varPigeonInHole(i, 1) // }); // printClause({ // helperFutureHole(i, 0), // -helperFutureHole(i, 1) // }); } } }; class VariableContainer { public: VariableContainer(unsigned _numPigeons): numPigeons(_numPigeons), allocator() { } virtual int pigeonInHole(unsigned pigeon, unsigned hole) = 0; virtual SatVariableAllocator& getAllocator() { return allocator; } virtual ~VariableContainer(){ } protected: unsigned numPigeons; private: SatVariableAllocator allocator; }; class BasicVariableContainer: public virtual VariableContainer { public: BasicVariableContainer(unsigned numPigeons): VariableContainer(numPigeons), P(VariableContainer::getAllocator().newVariable( numPigeons, numPigeons - 1)) { } virtual int pigeonInHole(unsigned pigeon, unsigned hole) { return P(pigeon, hole); } virtual ~BasicVariableContainer(){ } private: SatVariable<unsigned, unsigned> P; }; class ExtendedVariableContainer: public virtual VariableContainer { public: ExtendedVariableContainer(unsigned numPigeons): VariableContainer(numPigeons), P(VariableContainer::getAllocator().newVariable( numPigeons + 1, numPigeons, numPigeons - 1)) { } virtual int pigeonInHole(unsigned pigeon, unsigned hole) { return P(numPigeons, pigeon, hole); } virtual int pigeonInHole(unsigned layer, unsigned pigeon, unsigned hole) { return P(layer, pigeon, hole); } virtual ~ExtendedVariableContainer(){ } private: SatVariable<unsigned, unsigned, unsigned> P; }; class VariableContainer3SAT: public virtual VariableContainer { public: VariableContainer3SAT(unsigned numPigeons): VariableContainer(numPigeons), H(getAllocator().newVariable(numPigeons, numPigeons)) { } virtual int connector(unsigned pigeon, unsigned hole) { return H(pigeon, hole); } virtual ~VariableContainer3SAT(){ } private: SatVariable<unsigned, unsigned> H; }; class HelperVariableContainer: public virtual VariableContainer { public: HelperVariableContainer(unsigned numPigeons): VariableContainer(numPigeons), helperVar(getAllocator().newVariable(numPigeons)) { } virtual int helper(unsigned i) { return helperVar(i); } virtual ~HelperVariableContainer(){ } private: SatVariable<unsigned> helperVar; }; template <class T1, class T2> class ContainerCombinator: public virtual VariableContainer, public virtual T1, public virtual T2 { public: ContainerCombinator(unsigned numPigeons): VariableContainer(numPigeons), T1(numPigeons), T2(numPigeons) { } virtual ~ContainerCombinator(){ } }; class UniversalPHPEncoder { public: UniversalPHPEncoder( std::unique_ptr<ipasir::Ipasir> _solver, unsigned _numPigeons): UniversalPHPEncoder( std::move(_solver), std::make_unique<BasicVariableContainer>(_numPigeons), _numPigeons ) {} UniversalPHPEncoder( std::unique_ptr<ipasir::Ipasir> _solver, std::unique_ptr<VariableContainer> _var, unsigned _numPigeons): solver(std::move(_solver)), var(std::move(_var)), numPigeons(_numPigeons) { assert(numPigeons > 1); } virtual void addAtMostOnePigeonInHole(unsigned hole) { for (unsigned pigeonA = 1; pigeonA < numPigeons; pigeonA++) { for (unsigned pigeonB = 0; pigeonB < pigeonA; pigeonB++) { solver->addClause({ -var->pigeonInHole(pigeonA, hole), -var->pigeonInHole(pigeonB, hole) }); } } } virtual void addAtLeastOneHolePerPigeon( unsigned numHoles, unsigned activationLiteral = 0) { for (unsigned pigeon = 0; pigeon < numPigeons; pigeon++) { for (unsigned hole = 0; hole < numHoles; hole++) { solver->add(var->pigeonInHole(pigeon, hole)); } if (activationLiteral != 0) { solver->add(activationLiteral); } solver->add(0); } } virtual void solve(){ unsigned numHoles = numPigeons - 1; addAtLeastOneHolePerPigeon(numHoles); for (unsigned hole = 0; hole < numHoles; hole++) { addAtMostOnePigeonInHole(hole); } bool solved = (solver->solve() == ipasir::SolveResult::SAT); assert(!solved); } virtual VariableContainer* getVar() { return var.get(); } virtual ~UniversalPHPEncoder(){ } protected: std::unique_ptr<ipasir::Ipasir> solver; std::unique_ptr<VariableContainer> var; unsigned numPigeons; }; typedef ContainerCombinator<HelperVariableContainer, BasicVariableContainer> hvc; class SimpleIncrementalPHPEncoder: public UniversalPHPEncoder { public: SimpleIncrementalPHPEncoder( std::unique_ptr<ipasir::Ipasir> _solver, unsigned numPigeons): UniversalPHPEncoder( std::move(_solver), std::make_unique<hvc>(numPigeons), numPigeons ) { hvar = dynamic_cast<hvc*>(getVar()); } virtual void solve(){ bool solved; for (unsigned numHoles = 1; numHoles < numPigeons; numHoles++) { addAtMostOnePigeonInHole(numHoles - 1); addAtLeastOneHolePerPigeon(numHoles, hvar->helper(numHoles - 1)); { CollectData::MakespanAndTime m(numHoles); solver->assume(-hvar->helper(numHoles - 1)); solved = (solver->solve() == ipasir::SolveResult::SAT); assert(!solved); } } } virtual ~SimpleIncrementalPHPEncoder(){} private: hvc* hvar; }; typedef ContainerCombinator<VariableContainer3SAT, BasicVariableContainer> svc; class PHPEncoder3SAT: public UniversalPHPEncoder { public: PHPEncoder3SAT( std::unique_ptr<ipasir::Ipasir> _solver, unsigned _numPigeons): UniversalPHPEncoder( std::move(_solver), std::make_unique<svc>(_numPigeons), _numPigeons ) { } PHPEncoder3SAT( std::unique_ptr<ipasir::Ipasir> _solver, std::unique_ptr<VariableContainer3SAT> _var, unsigned _numPigeons): UniversalPHPEncoder( std::move(_solver), std::move(_var), _numPigeons ) { } virtual void addLowerBorder() { VariableContainer3SAT* var = dynamic_cast<VariableContainer3SAT*>(getVar()); for (unsigned p = 0; p < numPigeons; p++) { solver->addClause({ var->connector(p, 0)}); } } virtual void addBorders(bool forceUppberBound = false) { addLowerBorder(); if (forceUppberBound || fixedUpperBound.getValue()) { addUpperBorder(); } } virtual void addHole(unsigned hole) { VariableContainer3SAT* var = dynamic_cast<VariableContainer3SAT*>(getVar()); for (unsigned p = 0; p < numPigeons; p++) { solver->addClause({ -var->connector(p,hole), var->pigeonInHole(p, hole), var->connector(p, hole + 1) }); } addAtMostOnePigeonInHole(hole); } virtual void addUpperBorder() { VariableContainer3SAT* var = dynamic_cast<VariableContainer3SAT*>(getVar()); for (unsigned p = 0; p < numPigeons; p++) { solver->addClause({ -var->connector(p, numPigeons - 1)}); } } virtual void assumeAll(unsigned i) { VariableContainer3SAT* var = dynamic_cast<VariableContainer3SAT*>(getVar()); for (unsigned p = 0; p < numPigeons; p++) { solver->assume(-var->connector(p, i)); } bool solved = (solver->solve() == ipasir::SolveResult::SAT); assert(!solved); } virtual void solve() { solve(false); } virtual void solveIncremental() { solve(true); } virtual void solve(bool incremental){ addBorders(); for (unsigned numHoles = 1; numHoles < numPigeons; numHoles++) { addHole(numHoles - 1); if (incremental) { CollectData::MakespanAndTime m(numHoles); assumeAll(numHoles); } } if (!incremental) { unsigned numHoles = numPigeons - 1; CollectData::MakespanAndTime m(numHoles); assumeAll(numHoles); } } virtual ~PHPEncoder3SAT() {}; }; class AlternatePHPEncoder3SAT: public PHPEncoder3SAT { public: AlternatePHPEncoder3SAT( std::unique_ptr<ipasir::Ipasir> _solver, unsigned _numPigeons): PHPEncoder3SAT( std::move(_solver), std::make_unique<svc>(_numPigeons), _numPigeons ) { } virtual void assumeAll(unsigned numHoles) { VariableContainer3SAT* var = dynamic_cast<VariableContainer3SAT*>(getVar()); unsigned n = numPigeons; for (unsigned k = numPigeons; k >=numHoles + 1; k--) { // std::cout << "n: " << n << " k: " << k << std::endl; std::vector<bool> v(n); std::fill(v.begin(), v.begin() + k, true); do { for (unsigned i = 0; i < n; ++i) { if (v[i]) { solver->assume(-var->connector(i, numHoles)); // std::cout << i << " "; } } // std::cout << std::endl; bool unsat = (solver->solve() == ipasir::SolveResult::UNSAT); assert(unsat); if (unsat && addAssumed.getValue()) { for (unsigned i = 0; i < n; ++i) { if (v[i]) { solver->add(var->connector(i, numHoles)); // std::cout << i << " "; } } solver->add(0); } } while (std::prev_permutation(v.begin(), v.end())); } } }; typedef ContainerCombinator<ExtendedVariableContainer, VariableContainer3SAT> evc; class ExtendedPHPEncoder3SAT: public PHPEncoder3SAT { public: ExtendedPHPEncoder3SAT( std::unique_ptr<ipasir::Ipasir> _solver, unsigned _numPigeons): PHPEncoder3SAT( std::move(_solver), std::make_unique<evc>(_numPigeons), _numPigeons ) { } ExtendedPHPEncoder3SAT( std::unique_ptr<ipasir::Ipasir> _solver, std::unique_ptr<evc> _var, unsigned _numPigeons): PHPEncoder3SAT( std::move(_solver), std::move(_var), _numPigeons ) { } virtual void addExtendedResolutionClauses(){ ExtendedVariableContainer* var = dynamic_cast<ExtendedVariableContainer*>(getVar()); for (unsigned n = numPigeons; n > 2; n--) { for (unsigned i = 0; i < n - 1; i++) { for (unsigned j = 0; j < n - 2; j++) { solver->addClause({ var->pigeonInHole(n - 1, i, j), -var->pigeonInHole(n, i, j) }); solver->addClause({ var->pigeonInHole(n - 1, i, j), -var->pigeonInHole(n, i, n - 2), -var->pigeonInHole(n, n - 1, j) }); solver->addClause({ -var->pigeonInHole(n - 1, i, j), var->pigeonInHole(n, i, j), var->pigeonInHole(n, i, n - 2) }); solver->addClause({ -var->pigeonInHole(n - 1, i, j), var->pigeonInHole(n, i, j), var->pigeonInHole(n, n - 1, j) }); } } } } virtual void learnClauses(unsigned step){ unsigned sn = numPigeons; ExtendedVariableContainer* var = dynamic_cast<ExtendedVariableContainer*>(getVar()); // learn at most one for (unsigned h = 0; h < numPigeons - 1 - step; h++) { for (unsigned p = 1; p < numPigeons - step; p++) { for (unsigned j = 0; j < p; j++) { //carj::ScopedTimer timer((*solves.rbegin())["time"]); //LOG(INFO) << "var->pigeonInHole(" << sn - step << ", " << p << ", " << h << ")"; //LOG(INFO) << "var->pigeonInHole(" << sn - step << ", " << j << ", " << h << ")"; std::vector<int> clause({ -var->pigeonInHole(sn - step, p, h), -var->pigeonInHole(sn - step, j, h) }); for (int lit: clause) { solver->assume(-lit); } std::set<int> clauseLiterals; clauseLiterals.insert(clause.begin(),clause.end()); bool foundClause = false; solver->set_learn(2, [&foundClause, &clauseLiterals](int* learned) { std::set<int> learnedLiterals; while(*learned != 0) { learnedLiterals.insert(*learned); learned++; } foundClause |= (learnedLiterals == clauseLiterals); }); bool solved = (solver->solve() == ipasir::SolveResult::SAT); assert(!solved); solver->set_learn(0, [](int*){}); } } } // learn at least one for (unsigned p = 1; p < numPigeons - step; p++) { for (unsigned h = 0; h < numPigeons - 1 - step; h++) { //carj::ScopedTimer timer((*solves.rbegin())["time"]); //LOG(INFO) << "var->pigeonInHole(" << sn - step << ", " << p << ", " << h << ")"; //LOG(INFO) << "var->pigeonInHole(" << sn - step << ", " << j << ", " << h << ")"; solver->assume(-var->pigeonInHole(sn - step, p, h)); } bool solved = (solver->solve() == ipasir::SolveResult::SAT); assert(!solved); } } virtual void solve() { solve(false); } virtual void solveIncremental() { solve(true); } virtual void solve(bool incremental){ // solver->set_learn(10000, [](int* learned) { // for(;*learned != 0;learned++) { // std::cout << *learned << " "; // } // std::cout << std::endl; // }); bool solved; addBorders(true); for (unsigned numHoles = 1; numHoles < numPigeons; numHoles++) { addHole(numHoles - 1); } addExtendedResolutionClauses(); if (incremental) { for (unsigned step = 1; step < numPigeons; step++) { CollectData::MakespanAndTime m(step); learnClauses(step); } } solved = (solver->solve() == ipasir::SolveResult::SAT); assert(!solved); } virtual ~ExtendedPHPEncoder3SAT(){ } }; carj::TCarjArg<TCLAP::ValueArg, unsigned> numberOfPigeons("n", "numPigeons", "Number of pigeons", !neccessaryArgument, 1, "natural number", cmd); carj::CarjArg<TCLAP::SwitchArg, bool> dimspec("d", "dimspec", "Output dimspec.", cmd, defaultIsFalse); carj::CarjArg<TCLAP::SwitchArg, bool> print("p", "print", "Output as cnf.", cmd, defaultIsFalse); carj::CarjArg<TCLAP::SwitchArg, bool> extendedResolution("e", "extendedResolution", "Add extended resolution formulas.", cmd, defaultIsFalse); carj::CarjArg<TCLAP::SwitchArg, bool> incremental("i", "incremental", "Solve formual incrementally.", cmd, defaultIsFalse); carj::CarjArg<TCLAP::SwitchArg, bool> alternate("a", "alternate", "alternate mode", cmd, defaultIsFalse); carj::CarjArg<TCLAP::SwitchArg, bool> encoding3SAT("3", "3sat", "Encode PHP in 3 SAT CNF.", cmd, defaultIsFalse); carj::CarjArg<TCLAP::SwitchArg, bool> record("r", "record", "Record clause learning data.", cmd, defaultIsFalse); int incphp_main(int argc, const char **argv) { carj::init(argc, argv, cmd, "/incphp/parameters"); if (dimspec.getValue()) { DimSpecFixedPigeons dsfp(numberOfPigeons.getValue()); dsfp.print(); } else { std::unique_ptr<ipasir::Ipasir> solver; if (print.getValue()) { solver = std::make_unique<ipasir::Printer>(); } else { solver = std::make_unique<ipasir::Solver>(); } solver = std::make_unique<ipasir::RandomizedSolver>(std::move(solver)); if (record.getValue()) { solver = std::make_unique<LearnedClauseEvaluationDecorator>(std::move(solver)); } LOG(INFO) << "Using solver: " << solver->signature(); if (encoding3SAT.getValue()) { if (extendedResolution.getValue()) { std::unique_ptr<ExtendedPHPEncoder3SAT> encoder = std::make_unique<ExtendedPHPEncoder3SAT>( std::move(solver), numberOfPigeons.getValue()); if (incremental.getValue()) { encoder->solveIncremental(); } else { encoder->solve(); } } else { std::unique_ptr<PHPEncoder3SAT> encoder; if (alternate.getValue()) { encoder = std::make_unique<AlternatePHPEncoder3SAT>( std::move(solver), numberOfPigeons.getValue()); } else { encoder = std::make_unique<PHPEncoder3SAT>( std::move(solver), numberOfPigeons.getValue()); } if (incremental.getValue()) { encoder->solveIncremental(); } else { encoder->solve(); } } } else { if (extendedResolution.getValue()) { LOG(FATAL) << "Unsupported Option"; } if (incremental.getValue()) { SimpleIncrementalPHPEncoder encoder( std::move(solver), numberOfPigeons.getValue()); encoder.solve(); } else { UniversalPHPEncoder encoder( std::move(solver), numberOfPigeons.getValue()); encoder.solve(); } } } return 0; }
23.664981
87
0.653614
StephanGocht
25e63d36759d04c52f22d125bdc27220b637dd8f
548
cpp
C++
Boost/The Boost C++ Libraries/src/7.2.2/main.cpp
goodspeed24e/Programming
ae73fad022396ea03105aad83293facaeea561ae
[ "MIT" ]
1
2021-03-12T19:29:33.000Z
2021-03-12T19:29:33.000Z
Boost/The Boost C++ Libraries/src/7.2.2/main.cpp
goodspeed24e/Programming
ae73fad022396ea03105aad83293facaeea561ae
[ "MIT" ]
1
2019-03-13T01:36:12.000Z
2019-03-13T01:36:12.000Z
Boost/The Boost C++ Libraries/src/7.2.2/main.cpp
goodspeed24e/Programming
ae73fad022396ea03105aad83293facaeea561ae
[ "MIT" ]
null
null
null
#include <boost/asio.hpp> #include <iostream> void handler1(const boost::system::error_code &ec) { std::cout << "5 s." << std::endl; } void handler2(const boost::system::error_code &ec) { std::cout << "10 s." << std::endl; } int main() { boost::asio::io_service io_service; boost::asio::deadline_timer timer1(io_service, boost::posix_time::seconds(5)); timer1.async_wait(handler1); boost::asio::deadline_timer timer2(io_service, boost::posix_time::seconds(10)); timer2.async_wait(handler2); io_service.run(); }
24.909091
82
0.673358
goodspeed24e
25ef27291d8a3b3351f444dba989fa4c5149a5b0
14,474
cpp
C++
clients/cpp-pistache-server/generated/model/Hudson.cpp
cliffano/jenkins-api-clients-generator
522d02b3a130a29471df5ec1d3d22c822b3d0813
[ "MIT" ]
null
null
null
clients/cpp-pistache-server/generated/model/Hudson.cpp
cliffano/jenkins-api-clients-generator
522d02b3a130a29471df5ec1d3d22c822b3d0813
[ "MIT" ]
null
null
null
clients/cpp-pistache-server/generated/model/Hudson.cpp
cliffano/jenkins-api-clients-generator
522d02b3a130a29471df5ec1d3d22c822b3d0813
[ "MIT" ]
null
null
null
/** * Swaggy Jenkins * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ #include "Hudson.h" #include "Helpers.h" #include <sstream> namespace org::openapitools::server::model { Hudson::Hudson() { m__class = ""; m__classIsSet = false; m_AssignedLabelsIsSet = false; m_Mode = ""; m_ModeIsSet = false; m_NodeDescription = ""; m_NodeDescriptionIsSet = false; m_NodeName = ""; m_NodeNameIsSet = false; m_NumExecutors = 0; m_NumExecutorsIsSet = false; m_Description = ""; m_DescriptionIsSet = false; m_JobsIsSet = false; m_PrimaryViewIsSet = false; m_QuietingDown = false; m_QuietingDownIsSet = false; m_SlaveAgentPort = 0; m_SlaveAgentPortIsSet = false; m_UnlabeledLoadIsSet = false; m_UseCrumbs = false; m_UseCrumbsIsSet = false; m_UseSecurity = false; m_UseSecurityIsSet = false; m_ViewsIsSet = false; } void Hudson::validate() const { std::stringstream msg; if (!validate(msg)) { throw org::openapitools::server::helpers::ValidationException(msg.str()); } } bool Hudson::validate(std::stringstream& msg) const { return validate(msg, ""); } bool Hudson::validate(std::stringstream& msg, const std::string& pathPrefix) const { bool success = true; const std::string _pathPrefix = pathPrefix.empty() ? "Hudson" : pathPrefix; if (assignedLabelsIsSet()) { const std::vector<HudsonassignedLabels>& value = m_AssignedLabels; const std::string currentValuePath = _pathPrefix + ".assignedLabels"; { // Recursive validation of array elements const std::string oldValuePath = currentValuePath; int i = 0; for (const HudsonassignedLabels& value : value) { const std::string currentValuePath = oldValuePath + "[" + std::to_string(i) + "]"; success = value.validate(msg, currentValuePath + ".assignedLabels") && success; i++; } } } if (jobsIsSet()) { const std::vector<FreeStyleProject>& value = m_Jobs; const std::string currentValuePath = _pathPrefix + ".jobs"; { // Recursive validation of array elements const std::string oldValuePath = currentValuePath; int i = 0; for (const FreeStyleProject& value : value) { const std::string currentValuePath = oldValuePath + "[" + std::to_string(i) + "]"; success = value.validate(msg, currentValuePath + ".jobs") && success; i++; } } } if (viewsIsSet()) { const std::vector<AllView>& value = m_Views; const std::string currentValuePath = _pathPrefix + ".views"; { // Recursive validation of array elements const std::string oldValuePath = currentValuePath; int i = 0; for (const AllView& value : value) { const std::string currentValuePath = oldValuePath + "[" + std::to_string(i) + "]"; success = value.validate(msg, currentValuePath + ".views") && success; i++; } } } return success; } bool Hudson::operator==(const Hudson& rhs) const { return ((!r_classIsSet() && !rhs.r_classIsSet()) || (r_classIsSet() && rhs.r_classIsSet() && getClass() == rhs.getClass())) && ((!assignedLabelsIsSet() && !rhs.assignedLabelsIsSet()) || (assignedLabelsIsSet() && rhs.assignedLabelsIsSet() && getAssignedLabels() == rhs.getAssignedLabels())) && ((!modeIsSet() && !rhs.modeIsSet()) || (modeIsSet() && rhs.modeIsSet() && getMode() == rhs.getMode())) && ((!nodeDescriptionIsSet() && !rhs.nodeDescriptionIsSet()) || (nodeDescriptionIsSet() && rhs.nodeDescriptionIsSet() && getNodeDescription() == rhs.getNodeDescription())) && ((!nodeNameIsSet() && !rhs.nodeNameIsSet()) || (nodeNameIsSet() && rhs.nodeNameIsSet() && getNodeName() == rhs.getNodeName())) && ((!numExecutorsIsSet() && !rhs.numExecutorsIsSet()) || (numExecutorsIsSet() && rhs.numExecutorsIsSet() && getNumExecutors() == rhs.getNumExecutors())) && ((!descriptionIsSet() && !rhs.descriptionIsSet()) || (descriptionIsSet() && rhs.descriptionIsSet() && getDescription() == rhs.getDescription())) && ((!jobsIsSet() && !rhs.jobsIsSet()) || (jobsIsSet() && rhs.jobsIsSet() && getJobs() == rhs.getJobs())) && ((!primaryViewIsSet() && !rhs.primaryViewIsSet()) || (primaryViewIsSet() && rhs.primaryViewIsSet() && getPrimaryView() == rhs.getPrimaryView())) && ((!quietingDownIsSet() && !rhs.quietingDownIsSet()) || (quietingDownIsSet() && rhs.quietingDownIsSet() && isQuietingDown() == rhs.isQuietingDown())) && ((!slaveAgentPortIsSet() && !rhs.slaveAgentPortIsSet()) || (slaveAgentPortIsSet() && rhs.slaveAgentPortIsSet() && getSlaveAgentPort() == rhs.getSlaveAgentPort())) && ((!unlabeledLoadIsSet() && !rhs.unlabeledLoadIsSet()) || (unlabeledLoadIsSet() && rhs.unlabeledLoadIsSet() && getUnlabeledLoad() == rhs.getUnlabeledLoad())) && ((!useCrumbsIsSet() && !rhs.useCrumbsIsSet()) || (useCrumbsIsSet() && rhs.useCrumbsIsSet() && isUseCrumbs() == rhs.isUseCrumbs())) && ((!useSecurityIsSet() && !rhs.useSecurityIsSet()) || (useSecurityIsSet() && rhs.useSecurityIsSet() && isUseSecurity() == rhs.isUseSecurity())) && ((!viewsIsSet() && !rhs.viewsIsSet()) || (viewsIsSet() && rhs.viewsIsSet() && getViews() == rhs.getViews())) ; } bool Hudson::operator!=(const Hudson& rhs) const { return !(*this == rhs); } void to_json(nlohmann::json& j, const Hudson& o) { j = nlohmann::json(); if(o.r_classIsSet()) j["_class"] = o.m__class; if(o.assignedLabelsIsSet() || !o.m_AssignedLabels.empty()) j["assignedLabels"] = o.m_AssignedLabels; if(o.modeIsSet()) j["mode"] = o.m_Mode; if(o.nodeDescriptionIsSet()) j["nodeDescription"] = o.m_NodeDescription; if(o.nodeNameIsSet()) j["nodeName"] = o.m_NodeName; if(o.numExecutorsIsSet()) j["numExecutors"] = o.m_NumExecutors; if(o.descriptionIsSet()) j["description"] = o.m_Description; if(o.jobsIsSet() || !o.m_Jobs.empty()) j["jobs"] = o.m_Jobs; if(o.primaryViewIsSet()) j["primaryView"] = o.m_PrimaryView; if(o.quietingDownIsSet()) j["quietingDown"] = o.m_QuietingDown; if(o.slaveAgentPortIsSet()) j["slaveAgentPort"] = o.m_SlaveAgentPort; if(o.unlabeledLoadIsSet()) j["unlabeledLoad"] = o.m_UnlabeledLoad; if(o.useCrumbsIsSet()) j["useCrumbs"] = o.m_UseCrumbs; if(o.useSecurityIsSet()) j["useSecurity"] = o.m_UseSecurity; if(o.viewsIsSet() || !o.m_Views.empty()) j["views"] = o.m_Views; } void from_json(const nlohmann::json& j, Hudson& o) { if(j.find("_class") != j.end()) { j.at("_class").get_to(o.m__class); o.m__classIsSet = true; } if(j.find("assignedLabels") != j.end()) { j.at("assignedLabels").get_to(o.m_AssignedLabels); o.m_AssignedLabelsIsSet = true; } if(j.find("mode") != j.end()) { j.at("mode").get_to(o.m_Mode); o.m_ModeIsSet = true; } if(j.find("nodeDescription") != j.end()) { j.at("nodeDescription").get_to(o.m_NodeDescription); o.m_NodeDescriptionIsSet = true; } if(j.find("nodeName") != j.end()) { j.at("nodeName").get_to(o.m_NodeName); o.m_NodeNameIsSet = true; } if(j.find("numExecutors") != j.end()) { j.at("numExecutors").get_to(o.m_NumExecutors); o.m_NumExecutorsIsSet = true; } if(j.find("description") != j.end()) { j.at("description").get_to(o.m_Description); o.m_DescriptionIsSet = true; } if(j.find("jobs") != j.end()) { j.at("jobs").get_to(o.m_Jobs); o.m_JobsIsSet = true; } if(j.find("primaryView") != j.end()) { j.at("primaryView").get_to(o.m_PrimaryView); o.m_PrimaryViewIsSet = true; } if(j.find("quietingDown") != j.end()) { j.at("quietingDown").get_to(o.m_QuietingDown); o.m_QuietingDownIsSet = true; } if(j.find("slaveAgentPort") != j.end()) { j.at("slaveAgentPort").get_to(o.m_SlaveAgentPort); o.m_SlaveAgentPortIsSet = true; } if(j.find("unlabeledLoad") != j.end()) { j.at("unlabeledLoad").get_to(o.m_UnlabeledLoad); o.m_UnlabeledLoadIsSet = true; } if(j.find("useCrumbs") != j.end()) { j.at("useCrumbs").get_to(o.m_UseCrumbs); o.m_UseCrumbsIsSet = true; } if(j.find("useSecurity") != j.end()) { j.at("useSecurity").get_to(o.m_UseSecurity); o.m_UseSecurityIsSet = true; } if(j.find("views") != j.end()) { j.at("views").get_to(o.m_Views); o.m_ViewsIsSet = true; } } std::string Hudson::getClass() const { return m__class; } void Hudson::setClass(std::string const& value) { m__class = value; m__classIsSet = true; } bool Hudson::r_classIsSet() const { return m__classIsSet; } void Hudson::unset_class() { m__classIsSet = false; } std::vector<HudsonassignedLabels> Hudson::getAssignedLabels() const { return m_AssignedLabels; } void Hudson::setAssignedLabels(std::vector<HudsonassignedLabels> const& value) { m_AssignedLabels = value; m_AssignedLabelsIsSet = true; } bool Hudson::assignedLabelsIsSet() const { return m_AssignedLabelsIsSet; } void Hudson::unsetAssignedLabels() { m_AssignedLabelsIsSet = false; } std::string Hudson::getMode() const { return m_Mode; } void Hudson::setMode(std::string const& value) { m_Mode = value; m_ModeIsSet = true; } bool Hudson::modeIsSet() const { return m_ModeIsSet; } void Hudson::unsetMode() { m_ModeIsSet = false; } std::string Hudson::getNodeDescription() const { return m_NodeDescription; } void Hudson::setNodeDescription(std::string const& value) { m_NodeDescription = value; m_NodeDescriptionIsSet = true; } bool Hudson::nodeDescriptionIsSet() const { return m_NodeDescriptionIsSet; } void Hudson::unsetNodeDescription() { m_NodeDescriptionIsSet = false; } std::string Hudson::getNodeName() const { return m_NodeName; } void Hudson::setNodeName(std::string const& value) { m_NodeName = value; m_NodeNameIsSet = true; } bool Hudson::nodeNameIsSet() const { return m_NodeNameIsSet; } void Hudson::unsetNodeName() { m_NodeNameIsSet = false; } int32_t Hudson::getNumExecutors() const { return m_NumExecutors; } void Hudson::setNumExecutors(int32_t const value) { m_NumExecutors = value; m_NumExecutorsIsSet = true; } bool Hudson::numExecutorsIsSet() const { return m_NumExecutorsIsSet; } void Hudson::unsetNumExecutors() { m_NumExecutorsIsSet = false; } std::string Hudson::getDescription() const { return m_Description; } void Hudson::setDescription(std::string const& value) { m_Description = value; m_DescriptionIsSet = true; } bool Hudson::descriptionIsSet() const { return m_DescriptionIsSet; } void Hudson::unsetDescription() { m_DescriptionIsSet = false; } std::vector<FreeStyleProject> Hudson::getJobs() const { return m_Jobs; } void Hudson::setJobs(std::vector<FreeStyleProject> const& value) { m_Jobs = value; m_JobsIsSet = true; } bool Hudson::jobsIsSet() const { return m_JobsIsSet; } void Hudson::unsetJobs() { m_JobsIsSet = false; } AllView Hudson::getPrimaryView() const { return m_PrimaryView; } void Hudson::setPrimaryView(AllView const& value) { m_PrimaryView = value; m_PrimaryViewIsSet = true; } bool Hudson::primaryViewIsSet() const { return m_PrimaryViewIsSet; } void Hudson::unsetPrimaryView() { m_PrimaryViewIsSet = false; } bool Hudson::isQuietingDown() const { return m_QuietingDown; } void Hudson::setQuietingDown(bool const value) { m_QuietingDown = value; m_QuietingDownIsSet = true; } bool Hudson::quietingDownIsSet() const { return m_QuietingDownIsSet; } void Hudson::unsetQuietingDown() { m_QuietingDownIsSet = false; } int32_t Hudson::getSlaveAgentPort() const { return m_SlaveAgentPort; } void Hudson::setSlaveAgentPort(int32_t const value) { m_SlaveAgentPort = value; m_SlaveAgentPortIsSet = true; } bool Hudson::slaveAgentPortIsSet() const { return m_SlaveAgentPortIsSet; } void Hudson::unsetSlaveAgentPort() { m_SlaveAgentPortIsSet = false; } UnlabeledLoadStatistics Hudson::getUnlabeledLoad() const { return m_UnlabeledLoad; } void Hudson::setUnlabeledLoad(UnlabeledLoadStatistics const& value) { m_UnlabeledLoad = value; m_UnlabeledLoadIsSet = true; } bool Hudson::unlabeledLoadIsSet() const { return m_UnlabeledLoadIsSet; } void Hudson::unsetUnlabeledLoad() { m_UnlabeledLoadIsSet = false; } bool Hudson::isUseCrumbs() const { return m_UseCrumbs; } void Hudson::setUseCrumbs(bool const value) { m_UseCrumbs = value; m_UseCrumbsIsSet = true; } bool Hudson::useCrumbsIsSet() const { return m_UseCrumbsIsSet; } void Hudson::unsetUseCrumbs() { m_UseCrumbsIsSet = false; } bool Hudson::isUseSecurity() const { return m_UseSecurity; } void Hudson::setUseSecurity(bool const value) { m_UseSecurity = value; m_UseSecurityIsSet = true; } bool Hudson::useSecurityIsSet() const { return m_UseSecurityIsSet; } void Hudson::unsetUseSecurity() { m_UseSecurityIsSet = false; } std::vector<AllView> Hudson::getViews() const { return m_Views; } void Hudson::setViews(std::vector<AllView> const& value) { m_Views = value; m_ViewsIsSet = true; } bool Hudson::viewsIsSet() const { return m_ViewsIsSet; } void Hudson::unsetViews() { m_ViewsIsSet = false; } } // namespace org::openapitools::server::model
25.348511
175
0.626295
cliffano
25f26808a683224938ca9ecd5e1d20790c8c5e5d
4,241
cc
C++
chrome/browser/notifications/notification_exceptions_table_model_unittest.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-02-20T14:25:04.000Z
2019-12-13T13:58:28.000Z
chrome/browser/notifications/notification_exceptions_table_model_unittest.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-07-25T09:37:22.000Z
2017-08-04T07:18:56.000Z
chrome/browser/notifications/notification_exceptions_table_model_unittest.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-08-09T09:03:23.000Z
2020-05-26T09:14:49.000Z
// Copyright (c) 2011 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/notifications/notification_exceptions_table_model.h" #include "base/utf_string_conversions.h" #include "chrome/browser/notifications/desktop_notification_service_factory.h" #include "chrome/test/testing_profile.h" #include "content/browser/browser_thread.h" #include "content/browser/renderer_host/test_render_view_host.h" #include "grit/generated_resources.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/l10n/l10n_util.h" class NotificationExceptionsTableModelTest : public RenderViewHostTestHarness { public: NotificationExceptionsTableModelTest() : ui_thread_(BrowserThread::UI, MessageLoop::current()) { } virtual ~NotificationExceptionsTableModelTest() { } virtual void SetUp() { RenderViewHostTestHarness::SetUp(); service_ = DesktopNotificationServiceFactory::GetForProfile(profile()); ResetModel(); } virtual void TearDown() { model_.reset(NULL); RenderViewHostTestHarness::TearDown(); } virtual void ResetModel() { model_.reset(new NotificationExceptionsTableModel(service_)); } virtual void FillData() { service_->GrantPermission(GURL("http://e-allowed2.com")); service_->GrantPermission(GURL("http://allowed.com")); service_->DenyPermission(GURL("http://denied2.com")); service_->DenyPermission(GURL("http://denied.com")); service_->DenyPermission(GURL("http://f-denied3.com")); ResetModel(); } protected: BrowserThread ui_thread_; scoped_ptr<NotificationExceptionsTableModel> model_; DesktopNotificationService* service_; }; TEST_F(NotificationExceptionsTableModelTest, CanCreate) { EXPECT_EQ(0, model_->RowCount()); } TEST_F(NotificationExceptionsTableModelTest, RemoveAll) { FillData(); EXPECT_EQ(2u, service_->GetAllowedOrigins().size()); EXPECT_EQ(3u, service_->GetBlockedOrigins().size()); EXPECT_EQ(5, model_->RowCount()); model_->RemoveAll(); EXPECT_EQ(0, model_->RowCount()); EXPECT_EQ(0u, service_->GetAllowedOrigins().size()); EXPECT_EQ(0u, service_->GetBlockedOrigins().size()); } TEST_F(NotificationExceptionsTableModelTest, AlphabeticalOrder) { FillData(); EXPECT_EQ(5, model_->RowCount()); EXPECT_EQ(ASCIIToUTF16("allowed.com"), model_->GetText(0, IDS_EXCEPTIONS_HOSTNAME_HEADER)); EXPECT_EQ(l10n_util::GetStringUTF16(IDS_EXCEPTIONS_ALLOW_BUTTON), model_->GetText(0, IDS_EXCEPTIONS_ACTION_HEADER)); EXPECT_EQ(ASCIIToUTF16("denied.com"), model_->GetText(1, IDS_EXCEPTIONS_HOSTNAME_HEADER)); EXPECT_EQ(l10n_util::GetStringUTF16(IDS_EXCEPTIONS_BLOCK_BUTTON), model_->GetText(1, IDS_EXCEPTIONS_ACTION_HEADER)); EXPECT_EQ(ASCIIToUTF16("denied2.com"), model_->GetText(2, IDS_EXCEPTIONS_HOSTNAME_HEADER)); EXPECT_EQ(l10n_util::GetStringUTF16(IDS_EXCEPTIONS_BLOCK_BUTTON), model_->GetText(2, IDS_EXCEPTIONS_ACTION_HEADER)); EXPECT_EQ(ASCIIToUTF16("e-allowed2.com"), model_->GetText(3, IDS_EXCEPTIONS_HOSTNAME_HEADER)); EXPECT_EQ(l10n_util::GetStringUTF16(IDS_EXCEPTIONS_ALLOW_BUTTON), model_->GetText(3, IDS_EXCEPTIONS_ACTION_HEADER)); EXPECT_EQ(ASCIIToUTF16("f-denied3.com"), model_->GetText(4, IDS_EXCEPTIONS_HOSTNAME_HEADER)); EXPECT_EQ(l10n_util::GetStringUTF16(IDS_EXCEPTIONS_BLOCK_BUTTON), model_->GetText(4, IDS_EXCEPTIONS_ACTION_HEADER)); } TEST_F(NotificationExceptionsTableModelTest, RemoveRows) { FillData(); EXPECT_EQ(5, model_->RowCount()); { RemoveRowsTableModel::Rows rows; rows.insert(0); // allowed.com rows.insert(3); // e-allowed2.com model_->RemoveRows(rows); } EXPECT_EQ(3, model_->RowCount()); EXPECT_EQ(0u, service_->GetAllowedOrigins().size()); EXPECT_EQ(3u, service_->GetBlockedOrigins().size()); { RemoveRowsTableModel::Rows rows; rows.insert(0); rows.insert(1); rows.insert(2); model_->RemoveRows(rows); } EXPECT_EQ(0, model_->RowCount()); EXPECT_EQ(0u, service_->GetAllowedOrigins().size()); EXPECT_EQ(0u, service_->GetBlockedOrigins().size()); }
32.875969
79
0.735676
SlimKatLegacy
25f8faa529e071bca6ffcb8058685f2c30cb6c1c
9,203
cpp
C++
src/wxTTM/Tools/ListItem.cpp
ttm-tt/wxTTM
f9c75f05a564a0d82034412c1eb4c94d943e267f
[ "MIT" ]
null
null
null
src/wxTTM/Tools/ListItem.cpp
ttm-tt/wxTTM
f9c75f05a564a0d82034412c1eb4c94d943e267f
[ "MIT" ]
null
null
null
src/wxTTM/Tools/ListItem.cpp
ttm-tt/wxTTM
f9c75f05a564a0d82034412c1eb4c94d943e267f
[ "MIT" ]
null
null
null
/* Copyright (C) 2020 Christoph Theis */ // Basisklasse fuer Items in ListCtrl(Ex) #include "stdafx.h" #include "ListItem.h" #include "TmEntryStore.h" #include "Rec.h" // Abstand zwischen den Raendern des Rechtecks zum Text unsigned ListItem::offset = 2; // naNameWidth startet mit 2, bei jedem Listeneintrag wird aber ermittelt, // ob ein Nationenkuerzel nicht breiter ist. Irgendwann ist naNameWidth // dann die Mindestbreite, die erforderlich ist, um alle Nationenkuerzel // ohne kuerzen darstellen zu muessen. // Wechselt man da Turnier, bliebe naNameWidth erhalten, aber das kann man // in Kauf nehmen. Ebenso, dass evtl. am Anfang einmal falsch gezeichnet wird. unsigned ListItem::naNameWidth = 2; unsigned ListItem::plNrWidth = 2; unsigned ListItem::tmNameWidth = 2; int ListItem::CompareFunction(const ListItem *item1, const ListItem *item2, int col) { if (!item1) return (item2 ? +1 : 0); if (!item2) return (item1 ? -1 : 0); return item1->Compare(item2, col); } ListItem::~ListItem() { } // ----------------------------------------------------------------------- // Vergleich zweiter Items int ListItem::Compare(const ListItem *itemPtr, int col) const { return m_id - itemPtr->m_id; } // ----------------------------------------------------------------------- // Inkrementelle Suche bool ListItem::HasString(const wxString &str) const { return false; } // ----------------------------------------------------------------------- void ListItem::DrawString(wxDC *pDC, wxRect &rect, const wxString &str, unsigned fmt) { if (rect.GetLeft() >= rect.GetRight()) return; // fmt |= DT_SINGLELINE | DT_NOPREFIX | DT_NOCLIP | DT_VCENTER; wxArrayString tmp = wxStringTokenize(str, "\n"); if (tmp.GetCount() == 0) tmp.Add(""); int lH = rect.GetHeight() / tmp.GetCount(); for (unsigned i = 0; i < tmp.GetCount(); i++) { wxRect line = rect; line.SetTop (rect.GetTop() + i * lH); line.SetHeight(lH); wxString shortStr = MakeShortString(pDC, tmp[i], line); pDC->DrawLabel(shortStr, line, fmt | wxALIGN_CENTER_VERTICAL); } } // ----------------------------------------------------------------------- void ListItem::DrawImage(wxDC *pDC, wxRect &rect, const wxBitmap &img) { pDC->DrawLabel(wxEmptyString, img, rect, wxALIGN_CENTER); } // ----------------------------------------------------------------------- void ListItem::DrawPlayer(wxDC *pDC, wxRect &rect, const PlRec &pl, bool showNaName) { if (!pl.plNr) return; wxRect rcNr = rect; // StartNr wxRect rcName = rect; // Spielername wxRect rcAssoc = rect; // Verband unsigned cW = pDC->GetTextExtent("M").GetWidth(); unsigned needed; needed = (unsigned) pDC->GetTextExtent(wxString::Format("%d", pl.plNr)).GetWidth(); needed += 2 * offset; plNrWidth = std::max(plNrWidth, (needed + cW - 1) / cW); rcNr.SetRight(rcNr.GetLeft() + plNrWidth * cW); rcName.SetLeft(rcNr.GetRight()); if (showNaName) { if (*pl.naName) { // Die minimale Breite (in Einheiten von cw) ermitteln, die fuer den Verband noetig ist. needed = (unsigned) pDC->GetTextExtent(pl.naName).GetWidth(); needed += 2 * offset; naNameWidth = std::max(naNameWidth, (needed + cW - 1) / cW); } rcAssoc.SetLeft(rcAssoc.GetRight() - naNameWidth * cW); rcName.SetRight(rcAssoc.GetLeft()); } rcNr.SetLeft(rcNr.GetLeft() + offset); rcNr.SetRight(rcNr.GetRight() - offset); rcName.SetLeft(rcName.GetLeft() + offset); rcName.SetRight(rcName.GetRight() - offset); rcAssoc.SetLeft(rcAssoc.GetLeft() + offset); rcAssoc.SetRight(rcAssoc.GetRight() - offset); wxChar buf[130]; if (!*pl.psName.psFirst || wxStrlen(pl.psName.psFirst) == 1 && wxIsspace(*pl.psName.psFirst)) wxSprintf(buf, "%s", pl.psName.psLast); else wxSprintf(buf, "%s, %s", pl.psName.psLast, pl.psName.psFirst); if (pl.plNr) DrawLong(pDC, rcNr, pl.plNr); if (*pl.psName.psLast) { DrawString(pDC, rcName, buf); if (showNaName) DrawString(pDC, rcAssoc, pl.naName); } } void ListItem::DrawTeam(wxDC *pDC, wxRect &rect, const TmTeam &tm, bool showNaName) { if (!*tm.tmName && !*tm.tmDesc) return; wxRect rcName = rect; // Abkuerzung wxRect rcDesc = rect; // Name wxRect rcAssoc = rect; // Verband unsigned cW = pDC->GetTextExtent("M").GetWidth(); // Die minimale Breite (in Einheiten von cw) ermitteln, die fuer den Verband noetig ist. if (*tm.naName) { int needed = pDC->GetTextExtent(tm.naName).GetWidth(); needed += 2 * offset; naNameWidth = std::max(naNameWidth, (needed + cW - 1) / cW); } // Breite fuer das Mannschaftskuerzel berechnen if (*tm.tmName) { int needed = pDC->GetTextExtent(tm.tmName).GetWidth(); needed += 2 * offset; tmNameWidth = std::max(tmNameWidth, (needed + cW - 1) / cW); } // Die gleiche Breite fuer das Mannschaftskuerzel annehmen. rcName.SetRight(rcName.GetLeft() + tmNameWidth * cW); rcDesc.SetLeft(rcName.GetRight()); if (showNaName) { rcAssoc.SetLeft(rcAssoc.GetRight() - naNameWidth * cW); rcAssoc.SetRight(rect.GetRight()); rcDesc.SetRight(rcAssoc.GetLeft()); } rcName.SetLeft(rcName.GetLeft() + offset); rcName.SetRight(rcName.GetRight() - offset); rcDesc.SetLeft(rcDesc.GetLeft() + offset); rcDesc.SetRight(rcDesc.GetRight() - offset); rcAssoc.SetLeft(rcAssoc.GetLeft() + offset); rcAssoc.SetRight(rcAssoc.GetRight() - offset); DrawString(pDC, rcName, tm.tmName); DrawString(pDC, rcDesc, tm.tmDesc); if (showNaName) DrawString(pDC, rcAssoc, tm.naName); } void ListItem::DrawGroup(wxDC *pDC, wxRect &rect, const TmGroup &gr) { if (!gr.grID) { DrawStringCentered(pDC, rect, _("T.B.D.")); return; } wxRect rcName = rect; // Group name wxRect rcDesc = rect; // Group desc wxRect rcPos = rect; // Position unsigned cW = pDC->GetTextExtent("M").GetWidth(); // Die minimale Breite (in Einheiten von cw) ermitteln, die fuer den Verband noetig ist. if (*gr.grName) { int needed = pDC->GetTextExtent(gr.grName).GetWidth(); needed += 2 * offset; naNameWidth = std::max(naNameWidth, (needed + cW - 1) / cW); } rcDesc.SetLeft(rcName.GetLeft() + naNameWidth * cW); rcName.SetRight(rcDesc.GetLeft()); rcPos.SetLeft(rcPos.GetRight() - naNameWidth * cW); rcDesc.SetRight(rcPos.GetLeft()); rcName.SetLeft(rcName.GetLeft() + offset); rcName.SetRight(rcName.GetRight() - offset); rcDesc.SetLeft(rcDesc.GetLeft() + offset); rcDesc.SetRight(rcDesc.GetRight() - offset); rcPos.SetLeft(rcPos.GetLeft() + offset); rcPos.SetRight(rcPos.GetRight() - offset); DrawString(pDC, rcName, gr.grName); DrawString(pDC, rcDesc, gr.grDesc); if (gr.grPos) DrawLong(pDC, rcPos, gr.grPos, wxALIGN_LEFT); } void ListItem::DrawEntry(wxDC *pDC, wxRect &rect, const TmEntry &tm, bool showNaName) { switch (tm.team.cpType) { case CP_SINGLE : DrawPlayer(pDC, rect, tm.team.pl, showNaName); break; case CP_DOUBLE : case CP_MIXED : { wxRect tmp = rect; tmp.SetBottom(rect.GetTop() + rect.GetHeight() / 2); DrawPlayer(pDC, tmp, tm.team.pl, showNaName); tmp.SetTop(tmp.GetBottom()); tmp.SetBottom(rect.GetBottom()); DrawPlayer(pDC, tmp, tm.team.bd, showNaName); break; } case CP_TEAM : DrawTeam(pDC, rect, tm.team.tm, showNaName); break; case CP_GROUP : DrawGroup(pDC, rect, tm.team.gr); break; default : break; } } void ListItem::DrawResult(wxDC *pDC, wxRect &rect, short resA, short resX) { wxRect rc = rect; rc.SetLeft(rc.GetLeft() + offset); rc.SetRight(rc.GetRight() - offset); wxChar buf[10]; wxSprintf(buf, "%2i : %2i", resA, resX); DrawString(pDC, rc, buf); } // ----------------------------------------------------------------------- // String verkuerzen, bis er in das Rechteck passt wxString ListItem::MakeShortString(wxDC *pDC, const wxString &str, const wxRect &rect) { static const wxChar strDots[] = wxT("..."); static wxChar strShort[MAX_PATH]; static wxChar strNull[] = wxT(""); if (rect.GetLeft() >= rect.GetRight()) return strNull; int len = wxStrlen(str); if( len == 0 || pDC->GetTextExtent(str).GetWidth() <= rect.GetWidth() ) { return str; } wxStrncpy(strShort, str, MAX_PATH); strShort[MAX_PATH-1] = 0; if (len > MAX_PATH-1) len = MAX_PATH-1; int nAddLen = pDC->GetTextExtent(strDots).GetWidth(); for(int i = len - 1; i > 0; i--) { strShort[i] = wxChar(); if ( (pDC->GetTextExtent(strShort).GetWidth() + nAddLen) <= rect.GetWidth() ) { break; } } wxStrcat(strShort, strDots); return strShort; } // ----------------------------------------------------------------------- void ListItem::MeasureItem(LPMEASUREITEMSTRUCT lpMIS) { return; } bool ListItem::DrawSeparatingLine() { return false; } // ----------------------------------------------------------------------- wxString ListItem::BeginEditColumn(int col) const { return wxString(); } void ListItem::EndEditColumn(int col, const wxString &value) { // Nothing }
25.282967
94
0.613822
ttm-tt
25faa2f355c5d2cc93d5c975578b8dc3a2d1201e
3,886
cpp
C++
tests/unit/TextChat_test.cpp
truthiswill/sdk
00ace479a434b2d5c329cfe4f7178392fcfd1cdb
[ "BSD-2-Clause" ]
1
2022-02-24T03:44:47.000Z
2022-02-24T03:44:47.000Z
tests/unit/TextChat_test.cpp
akjkmeagabase/sdk
fdff0e09e6ab384c9694d4c4d10c34e6a225c1e6
[ "BSD-2-Clause" ]
null
null
null
tests/unit/TextChat_test.cpp
akjkmeagabase/sdk
fdff0e09e6ab384c9694d4c4d10c34e6a225c1e6
[ "BSD-2-Clause" ]
null
null
null
/** * (c) 2019 by Mega Limited, Wellsford, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. */ #include <gtest/gtest.h> #include <mega/megaclient.h> #include <mega/megaapp.h> #include <mega/types.h> #include "DefaultedFileSystemAccess.h" #include "utils.h" #ifdef ENABLE_CHAT namespace { class MockFileSystemAccess : public mt::DefaultedFileSystemAccess { }; void checkTextChats(const mega::TextChat& exp, const mega::TextChat& act) { ASSERT_EQ(exp.id, act.id); ASSERT_EQ(exp.priv, act.priv); ASSERT_EQ(exp.shard, act.shard); ASSERT_EQ(*exp.userpriv, *act.userpriv); ASSERT_EQ(exp.group, act.group); ASSERT_EQ(exp.title, act.title); ASSERT_EQ(exp.ou, act.ou); ASSERT_EQ(exp.ts, act.ts); ASSERT_EQ(exp.attachedNodes, act.attachedNodes); ASSERT_EQ(exp.isFlagSet(0), act.isFlagSet(0)); ASSERT_EQ(exp.publicchat, act.publicchat); ASSERT_EQ(exp.unifiedKey, act.unifiedKey); } } TEST(TextChat, serialize_unserialize) { mega::MegaApp app; auto client = mt::makeClient(app); mega::TextChat tc; tc.id = 1; tc.priv = mega::PRIV_STANDARD; tc.shard = 2; tc.userpriv = new mega::userpriv_vector; tc.userpriv->emplace_back(3, mega::PRIV_MODERATOR); tc.userpriv->emplace_back(4, mega::PRIV_RO); tc.group = true; tc.title = "foo"; tc.ou = 5; tc.ts = 6; tc.attachedNodes[7].insert(8); tc.attachedNodes[7].insert(9); tc.attachedNodes[8].insert(10); tc.setFlag(true, 0); tc.publicchat = true; tc.unifiedKey = "bar"; std::string d; ASSERT_TRUE(tc.serialize(&d)); auto newTc = mega::TextChat::unserialize(client.get(), &d); checkTextChats(tc, *newTc); } TEST(TextChat, unserialize_32bit) { mega::MegaApp app; auto client = mt::makeClient(app); mega::TextChat tc; tc.id = 1; tc.priv = mega::PRIV_STANDARD; tc.shard = 2; tc.userpriv = new mega::userpriv_vector; tc.userpriv->emplace_back(3, mega::PRIV_MODERATOR); tc.userpriv->emplace_back(4, mega::PRIV_RO); tc.group = true; tc.title = "foo"; tc.ou = 5; tc.ts = 6; tc.attachedNodes[7].insert(8); tc.attachedNodes[7].insert(9); tc.attachedNodes[8].insert(10); tc.setFlag(true, 0); tc.publicchat = true; tc.unifiedKey = "bar"; // This is the result of serialization on 32bit Windows const std::array<char, 125> rawData = { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x00, 0x66, 0x6f, 0x6f, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x62, 0x61, 0x72 }; std::string d(rawData.data(), rawData.size()); auto newTc = mega::TextChat::unserialize(client.get(), &d); checkTextChats(tc, *newTc); } #endif
30.359375
79
0.653371
truthiswill
25fcf11745a446cb8ddc224fe08418b05228c89a
16,735
hpp
C++
examples/cpuid/libcpuid/include/cpuid/cpuid.hpp
DrPizza/jsm
d5fc0a6c1e579bbb15c546aa3b76012ad93bc7ef
[ "MIT" ]
1
2021-06-29T06:46:34.000Z
2021-06-29T06:46:34.000Z
examples/cpuid/libcpuid/include/cpuid/cpuid.hpp
DrPizza/jsm
d5fc0a6c1e579bbb15c546aa3b76012ad93bc7ef
[ "MIT" ]
null
null
null
examples/cpuid/libcpuid/include/cpuid/cpuid.hpp
DrPizza/jsm
d5fc0a6c1e579bbb15c546aa3b76012ad93bc7ef
[ "MIT" ]
null
null
null
#ifndef CPUID_HPP #define CPUID_HPP #include <cstddef> #include <array> #include <map> #include <gsl/gsl> #include <fmt/format.h> #include "suffixes.hpp" #if defined(_MSC_VER) #define UNREACHABLE() __assume(0) #else #define UNREACHABLE() __builtin_unreachable() #endif namespace cpuid { enum struct leaf_type : std::uint32_t { basic_info = 0x0000'0000_u32, version_info = 0x0000'0001_u32, cache_and_tlb = 0x0000'0002_u32, serial_number = 0x0000'0003_u32, deterministic_cache = 0x0000'0004_u32, monitor_mwait = 0x0000'0005_u32, thermal_and_power = 0x0000'0006_u32, extended_features = 0x0000'0007_u32, reserved_1 = 0x0000'0008_u32, direct_cache_access = 0x0000'0009_u32, performance_monitoring = 0x0000'000a_u32, extended_topology = 0x0000'000b_u32, reserved_2 = 0x0000'000c_u32, extended_state = 0x0000'000d_u32, reserved_3 = 0x0000'000e_u32, rdt_monitoring = 0x0000'000f_u32, rdt_allocation = 0x0000'0010_u32, reserved_4 = 0x0000'0011_u32, sgx_info = 0x0000'0012_u32, reserved_5 = 0x0000'0013_u32, processor_trace = 0x0000'0014_u32, time_stamp_counter = 0x0000'0015_u32, processor_frequency = 0x0000'0016_u32, system_on_chip_vendor = 0x0000'0017_u32, deterministic_tlb = 0x0000'0018_u32, reserved_6 = 0x0000'0019_u32, reserved_7 = 0x0000'001a_u32, pconfig = 0x0000'001b_u32, reserved_8 = 0x0000'001c_u32, reserved_9 = 0x0000'001d_u32, reserved_10 = 0x0000'001e_u32, extended_topology_v2 = 0x0000'001f_u32, hypervisor_limit = 0x4000'0000_u32, hyper_v_signature = 0x4000'0001_u32, hyper_v_system_identity = 0x4000'0002_u32, hyper_v_features = 0x4000'0003_u32, hyper_v_enlightenment_recs = 0x4000'0004_u32, hyper_v_implementation_limits = 0x4000'0005_u32, hyper_v_implementation_hardware = 0x4000'0006_u32, hyper_v_root_cpu_management = 0x4000'0007_u32, hyper_v_shared_virtual_memory = 0x4000'0008_u32, hyper_v_nested_hypervisor = 0x4000'0009_u32, hyper_v_nested_features = 0x4000'000a_u32, xen_limit = 0x4000'0000_u32, xen_limit_offset = 0x4000'0100_u32, xen_version = 0x4000'0001_u32, xen_version_offset = 0x4000'0101_u32, xen_features = 0x4000'0002_u32, xen_features_offset = 0x4000'0102_u32, xen_time = 0x4000'0003_u32, xen_time_offset = 0x4000'0103_u32, xen_hvm_features = 0x4000'0004_u32, xen_hvm_features_offset = 0x4000'0104_u32, xen_pv_features = 0x4000'0005_u32, xen_pv_features_offset = 0x4000'0105_u32, vmware_timing = 0x4000'0010_u32, kvm_features = 0x4000'0001_u32, extended_limit = 0x8000'0000_u32, extended_signature_and_features = 0x8000'0001_u32, brand_string_0 = 0x8000'0002_u32, brand_string_1 = 0x8000'0003_u32, brand_string_2 = 0x8000'0004_u32, l1_cache_identifiers = 0x8000'0005_u32, l2_cache_identifiers = 0x8000'0006_u32, ras_advanced_power_management = 0x8000'0007_u32, address_limits = 0x8000'0008_u32, reserved_11 = 0x8000'0009_u32, secure_virtual_machine = 0x8000'000a_u32, extended_reserved_1 = 0x8000'000b_u32, extended_reserved_2 = 0x8000'000c_u32, extended_reserved_3 = 0x8000'000d_u32, extended_reserved_4 = 0x8000'000e_u32, extended_reserved_5 = 0x8000'000f_u32, extended_reserved_6 = 0x8000'0010_u32, extended_reserved_7 = 0x8000'0011_u32, extended_reserved_8 = 0x8000'0012_u32, extended_reserved_9 = 0x8000'0013_u32, extended_reserved_10 = 0x8000'0014_u32, extended_reserved_11 = 0x8000'0015_u32, extended_reserved_12 = 0x8000'0016_u32, extended_reserved_13 = 0x8000'0017_u32, extended_reserved_14 = 0x8000'0018_u32, tlb_1g_identifiers = 0x8000'0019_u32, performance_optimization = 0x8000'001a_u32, instruction_based_sampling = 0x8000'001b_u32, lightweight_profiling = 0x8000'001c_u32, cache_properties = 0x8000'001d_u32, extended_apic = 0x8000'001e_u32, encrypted_memory = 0x8000'001f_u32, none = 0x0000'0000_u32, }; constexpr inline leaf_type operator++(leaf_type& lhs) { lhs = static_cast<leaf_type>(static_cast<std::uint32_t>(lhs) + 1); return lhs; } constexpr inline leaf_type operator+=(leaf_type& lhs, std::uint32_t rhs) { lhs = static_cast<leaf_type>(static_cast<std::uint32_t>(lhs) + rhs); return lhs; } constexpr inline leaf_type operator+(const leaf_type& lhs, std::uint32_t rhs) { return static_cast<leaf_type>(static_cast<std::uint32_t>(lhs) + rhs); } enum struct subleaf_type : std::uint32_t { main = 0x0000'0000_u32, extended_features_main = 0x0000'0000_u32, extended_state_main = 0x0000'0000_u32, extended_state_sub = 0x0000'0001_u32, rdt_monitoring_main = 0x0000'0000_u32, rdt_monitoring_l3 = 0x0000'0001_u32, rdt_allocation_main = 0x0000'0000_u32, rdt_cat_l3 = 0x0000'0001_u32, rdt_cat_l2 = 0x0000'0002_u32, rdt_mba = 0x0000'0003_u32, sgx_capabilities = 0x0000'0000_u32, sgx_attributes = 0x0000'0001_u32, processor_trace_main = 0x0000'0000_u32, processor_trace_sub = 0x0000'0001_u32, system_on_chip_vendor_main = 0x0000'0000_u32, system_on_chip_vendor_sub = 0x0000'0001_u32, deterministic_address_translation_main = 0x0000'0000_u32, deterministic_address_translation_sub = 0x0000'0001_u32, xen_time_main = 0x0000'0000_u32, xen_time_tsc_offset = 0x0000'0001_u32, xen_time_host = 0x0000'0002_u32, none = 0x0000'0000_u32, }; constexpr inline subleaf_type operator++(subleaf_type& lhs) { lhs = static_cast<subleaf_type>(static_cast<std::uint32_t>(lhs) + 1); return lhs; } constexpr inline subleaf_type operator+=(subleaf_type& lhs, std::uint32_t offset) { lhs = static_cast<subleaf_type>(static_cast<std::uint32_t>(lhs) + offset); return lhs; } enum register_type : std::uint8_t { eax, ebx, ecx, edx, }; constexpr inline register_type operator++(register_type& lhs) { lhs = static_cast<register_type>(static_cast<std::uint8_t>(lhs) + 1); return lhs; } enum vendor_type : std::uint32_t { unknown = 0x0000'0000_u32, // silicon amd = 0x0000'0001_u32, centaur = 0x0000'0002_u32, cyrix = 0x0000'0004_u32, intel = 0x0000'0008_u32, transmeta = 0x0000'0010_u32, nat_semi = 0x0000'0020_u32, nexgen = 0x0000'0040_u32, rise = 0x0000'0080_u32, sis = 0x0000'0100_u32, umc = 0x0000'0200_u32, via = 0x0000'0400_u32, vortex = 0x0000'0800_u32, // hypervisors bhyve = 0x0001'0000_u32, kvm = 0x0002'0000_u32, hyper_v = 0x0004'0000_u32, parallels = 0x0008'0000_u32, vmware = 0x0010'0000_u32, xen_hvm = 0x0020'0000_u32, xen_viridian = xen_hvm | hyper_v, qemu = 0x0040'0000_u32, // for filtering any_silicon = 0x0000'0fff_u32, any_hypervisor = 0x007f'0000_u32, any = 0xffff'ffff_u32, }; constexpr inline vendor_type operator|(const vendor_type& lhs, const vendor_type& rhs) { return static_cast<vendor_type>(static_cast<std::uint32_t>(lhs) | static_cast<std::uint32_t>(rhs)); } constexpr inline vendor_type operator&(const vendor_type& lhs, const vendor_type& rhs) { return static_cast<vendor_type>(static_cast<std::uint32_t>(lhs) & static_cast<std::uint32_t>(rhs)); } inline std::string to_string(vendor_type vendor) { std::string silicon; std::string hypervisor; switch(vendor & vendor_type::any_silicon) { case vendor_type::amd: silicon = "AMD"; break; case vendor_type::centaur: silicon = "Centaur"; break; case vendor_type::cyrix: silicon = "Cyrix"; break; case vendor_type::intel: silicon = "Intel"; break; case vendor_type::transmeta: silicon = "Transmeta"; break; case vendor_type::nat_semi: silicon = "National Semiconductor"; break; case vendor_type::nexgen: silicon = "NexGen"; break; case vendor_type::rise: silicon = "Rise"; break; case vendor_type::sis: silicon = "SiS"; break; case vendor_type::umc: silicon = "UMC"; break; case vendor_type::via: silicon = "VIA"; break; case vendor_type::vortex: silicon = "Vortex"; break; default: silicon = "Unknown"; break; } switch(vendor & vendor_type::any_hypervisor) { case vendor_type::bhyve: hypervisor = "bhyve"; break; case vendor_type::kvm: hypervisor = "KVM"; break; case vendor_type::hyper_v: hypervisor = "Hyper-V"; break; case vendor_type::parallels: hypervisor = "Parallels"; break; case vendor_type::vmware: hypervisor = "VMware"; break; case vendor_type::xen_hvm: hypervisor = "Xen HVM"; break; case vendor_type::xen_viridian: hypervisor = "Xen HVM with Viridian Extensions"; break; case vendor_type::qemu: hypervisor = "QEMU"; break; default: hypervisor = ""; } return hypervisor.size() != 0 ? hypervisor + " on " + silicon : silicon; } using register_set_t = std::array<std::uint32_t, 4>; using subleaves_t = std::map<subleaf_type, register_set_t>; using leaves_t = std::map<leaf_type, subleaves_t>; vendor_type get_vendor_from_name(const register_set_t& regs); struct id_info_t { std::uint32_t brand_id : 8; std::uint32_t cache_line_size : 8; std::uint32_t maximum_addressable_ids : 8; std::uint32_t initial_apic_id : 8; }; struct split_model_t { std::uint32_t stepping : 4; std::uint32_t model : 4; std::uint32_t family : 4; std::uint32_t type : 2; std::uint32_t reserved_1 : 2; std::uint32_t extended_model : 4; std::uint32_t extended_family : 8; std::uint32_t reserved_2 : 4; }; struct model_t { std::uint32_t stepping; std::uint32_t model; std::uint32_t family; }; inline bool operator==(const model_t& lhs, const model_t& rhs) noexcept { return lhs.stepping == rhs.stepping && lhs.model == rhs.model && lhs.family == rhs.family; } struct cpu_t { std::uint32_t apic_id; vendor_type vendor; model_t model; leaves_t leaves; }; inline bool operator==(const cpu_t& lhs, const cpu_t& rhs) noexcept { return lhs.apic_id == rhs.apic_id && lhs.vendor == rhs.vendor && lhs.model == rhs.model && lhs.leaves == rhs.leaves; } register_set_t cpuid(leaf_type leaf, subleaf_type subleaf) noexcept; void print_generic(fmt::memory_buffer& out, const cpu_t& cpu, leaf_type leaf, subleaf_type subleaf); enum struct file_format { native, etallen, libcpuid, aida64, cpuinfo }; std::map<std::uint32_t, cpu_t> enumerate_file(std::istream& fin, file_format format); std::map<std::uint32_t, cpu_t> enumerate_processors(bool brute_force, bool skip_vendor_check, bool skip_feature_check); void print_dump(fmt::memory_buffer& out, std::map<std::uint32_t, cpu_t> logical_cpus, file_format format); void print_leaf(fmt::memory_buffer& out, const cpu_t& cpu, leaf_type leaf, bool skip_vendor_check, bool skip_feature_check); void print_leaves(fmt::memory_buffer& out, const cpu_t& cpu, bool skip_vendor_check, bool skip_feature_check); struct flag_spec_t { std::uint32_t selector_eax = 0_u32; std::uint32_t selector_ecx = 0_u32; register_type flag_register = eax; std::string flag_name = ""; std::uint32_t flag_start = 0xffff'ffff_u32; std::uint32_t flag_end = 0xffff'ffff_u32; }; void print_single_flag(fmt::memory_buffer& out, const cpu_t& cpu, const flag_spec_t& flag_description); flag_spec_t parse_flag_spec(const std::string& flag_description); std::string to_string(const flag_spec_t& spec); inline bool operator==(const flag_spec_t& lhs, const flag_spec_t& rhs) noexcept { return std::tie(lhs.selector_eax, lhs.selector_ecx, lhs.flag_register, lhs.flag_name, lhs.flag_start, lhs.flag_end) == std::tie(rhs.selector_eax, rhs.selector_ecx, rhs.flag_register, rhs.flag_name, rhs.flag_start, rhs.flag_end); } struct cache_instance_t { std::vector<std::uint32_t> sharing_ids; }; struct cache_t { std::uint32_t level; std::uint32_t type; std::uint32_t ways; std::uint32_t sets; std::uint32_t line_size; std::uint32_t line_partitions; std::uint32_t total_size; bool fully_associative; bool direct_mapped; bool complex_addressed; bool self_initializing; bool invalidates_lower_levels; bool inclusive; std::uint32_t sharing_mask; std::map<std::uint32_t, cache_instance_t> instances; }; inline bool operator<(const cache_t& lhs, const cache_t& rhs) noexcept { return lhs.level != rhs.level ? lhs.level < rhs.level : lhs.type != rhs.type ? lhs.type < rhs.type : lhs.total_size < rhs.total_size; } enum class level_type : std::uint32_t { invalid = 0_u32, smt = 1_u32, core = 2_u32, module = 3_u32, tile = 4_u32, die = 5_u32, node = 0xffff'fffe_u32, package = 0xffff'ffff_u32 }; struct level_description_t { level_type level; std::uint32_t shift_distance; std::uint32_t select_mask; }; struct logical_core_t { std::uint32_t full_apic_id; std::uint32_t smt_id; std::uint32_t core_id; std::uint32_t package_id; std::vector<std::uint32_t> non_shared_cache_ids; std::vector<std::uint32_t> shared_cache_ids; }; struct physical_core_t { std::map<std::uint32_t, logical_core_t> logical_cores; }; struct module_t { std::map<std::uint32_t, physical_core_t> physical_cores; }; struct tile_t { std::map<std::uint32_t, module_t> modules; }; struct die_t { std::map<std::uint32_t, tile_t> tiles; }; struct node_t { std::map<std::uint32_t, physical_core_t> physical_cores; }; struct package_t { std::map<std::uint32_t, physical_core_t> physical_cores; //std::map<std::uint32_t, die_t> dies; //std::map<std::uint32_t, node_t> nodes; }; struct system_t { vendor_type vendor; std::uint32_t smt_mask_width; std::uint32_t core_mask_width; std::uint32_t module_mask_width; std::uint32_t tile_mask_width; std::uint32_t die_mask_width; std::vector<std::uint32_t> x2_apic_ids; std::vector<cache_t> all_caches; std::vector<logical_core_t> all_cores; std::map<std::uint32_t, package_t> packages; std::set<level_type> valid_levels; }; system_t build_topology(const std::map<std::uint32_t, cpu_t>& logical_cpus); void print_topology(fmt::memory_buffer& out, const system_t& machine); } #endif
32.685547
126
0.612668
DrPizza
25fd2c2620a37d779238ed3ac882ec1e28b9c71f
231,883
cpp
C++
Core/SoarKernel/src/semantic_memory/semantic_memory.cpp
Bryan-Stearns/Soar
969f4fec676293b459ed552ad096549519800534
[ "BSD-2-Clause" ]
1
2021-03-03T23:20:23.000Z
2021-03-03T23:20:23.000Z
Core/SoarKernel/src/semantic_memory/semantic_memory.cpp
Bryan-Stearns/Soar
969f4fec676293b459ed552ad096549519800534
[ "BSD-2-Clause" ]
null
null
null
Core/SoarKernel/src/semantic_memory/semantic_memory.cpp
Bryan-Stearns/Soar
969f4fec676293b459ed552ad096549519800534
[ "BSD-2-Clause" ]
1
2021-03-03T23:20:25.000Z
2021-03-03T23:20:25.000Z
/************************************************************************* * PLEASE SEE THE FILE "COPYING" (INCLUDED WITH THIS SOFTWARE PACKAGE) * FOR LICENSE AND COPYRIGHT INFORMATION. *************************************************************************/ /************************************************************************* * * file: semantic_memory.cpp * * ======================================================================= * Description : Various functions for Soar-SMem * ======================================================================= */ #include "semantic_memory.h" #include "agent.h" #include "condition.h" #include "debug.h" #include "decide.h" #include "ebc.h" #include "instantiation.h" #include "lexer.h" #include "rhs.h" #include "semantic_memory_math_queries.h" #include "test.h" #include "preference.h" #include "print.h" #include "slot.h" #include "symbol.h" #include "working_memory.h" #include "working_memory_activation.h" #include "xml.h" #include <list> #include <map> #include <queue> #include <utility> #include <ctype.h> #include <fstream> #include <algorithm> ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // Bookmark strings to help navigate the code ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // parameters smem::param // stats smem::stats // timers smem::timers // statements smem::statements // wmes smem::wmes // variables smem::var // temporal hash smem::hash // activation smem::act // long-term identifiers smem::lti // storage smem::storage // non-cue-based retrieval smem::ncb // cue-based retrieval smem::cbr // initialization smem::init // parsing smem::parse // api smem::api // visualization smem::viz ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // Parameter Functions (smem::params) ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// smem_param_container::smem_param_container(agent* new_agent): soar_module::param_container(new_agent) { // learning learning = new soar_module::boolean_param("learning", off, new soar_module::f_predicate<boolean>()); add(learning); // database database = new soar_module::constant_param<db_choices>("database", memory, new soar_module::f_predicate<db_choices>()); database->add_mapping(memory, "memory"); database->add_mapping(file, "file"); add(database); // append database or dump data on init append_db = new soar_module::boolean_param("append", on, new soar_module::f_predicate<boolean>()); add(append_db); // path path = new smem_path_param("path", "", new soar_module::predicate<const char*>(), new soar_module::f_predicate<const char*>(), thisAgent); add(path); // auto-commit lazy_commit = new soar_module::boolean_param("lazy-commit", on, new smem_db_predicate<boolean>(thisAgent)); add(lazy_commit); // timers timers = new soar_module::constant_param<soar_module::timer::timer_level>("timers", soar_module::timer::zero, new soar_module::f_predicate<soar_module::timer::timer_level>()); timers->add_mapping(soar_module::timer::zero, "off"); timers->add_mapping(soar_module::timer::one, "one"); timers->add_mapping(soar_module::timer::two, "two"); timers->add_mapping(soar_module::timer::three, "three"); add(timers); // page_size page_size = new soar_module::constant_param<page_choices>("page-size", page_8k, new smem_db_predicate<page_choices>(thisAgent)); page_size->add_mapping(page_1k, "1k"); page_size->add_mapping(page_2k, "2k"); page_size->add_mapping(page_4k, "4k"); page_size->add_mapping(page_8k, "8k"); page_size->add_mapping(page_16k, "16k"); page_size->add_mapping(page_32k, "32k"); page_size->add_mapping(page_64k, "64k"); add(page_size); // cache_size cache_size = new soar_module::integer_param("cache-size", 10000, new soar_module::gt_predicate<int64_t>(1, true), new smem_db_predicate<int64_t>(thisAgent)); add(cache_size); // opt opt = new soar_module::constant_param<opt_choices>("optimization", opt_speed, new smem_db_predicate<opt_choices>(thisAgent)); opt->add_mapping(opt_safety, "safety"); opt->add_mapping(opt_speed, "performance"); add(opt); // thresh thresh = new soar_module::integer_param("thresh", 100, new soar_module::predicate<int64_t>(), new smem_db_predicate<int64_t>(thisAgent)); add(thresh); // merge merge = new soar_module::constant_param<merge_choices>("merge", merge_add, new soar_module::f_predicate<merge_choices>()); merge->add_mapping(merge_none, "none"); merge->add_mapping(merge_add, "add"); add(merge); // activate_on_query activate_on_query = new soar_module::boolean_param("activate-on-query", on, new soar_module::f_predicate<boolean>()); add(activate_on_query); // activation_mode activation_mode = new soar_module::constant_param<act_choices>("activation-mode", act_recency, new soar_module::f_predicate<act_choices>()); activation_mode->add_mapping(act_recency, "recency"); activation_mode->add_mapping(act_frequency, "frequency"); activation_mode->add_mapping(act_base, "base-level"); add(activation_mode); // base_decay base_decay = new soar_module::decimal_param("base-decay", 0.5, new soar_module::gt_predicate<double>(0, false), new soar_module::f_predicate<double>()); add(base_decay); // base_update_policy base_update = new soar_module::constant_param<base_update_choices>("base-update-policy", bupt_stable, new soar_module::f_predicate<base_update_choices>()); base_update->add_mapping(bupt_stable, "stable"); base_update->add_mapping(bupt_naive, "naive"); base_update->add_mapping(bupt_incremental, "incremental"); add(base_update); // incremental update thresholds base_incremental_threshes = new soar_module::int_set_param("base-incremental-threshes", new soar_module::f_predicate< int64_t >()); add(base_incremental_threshes); // mirroring mirroring = new soar_module::boolean_param("mirroring", off, new smem_db_predicate< boolean >(thisAgent)); add(mirroring); } // /* This is a test of whether or not the SMEM database with no version number is the one that smem_update_schema_one_to_two can convert. It tests for the existence of a table name to determine if this is the old version. */ inline bool smem_version_one(agent* thisAgent) { double check_num_tables; thisAgent->smem_db->sql_simple_get_float("SELECT count(type) FROM sqlite_master WHERE type='table' AND name='smem7_signature'", check_num_tables); if (check_num_tables == 0) { return false; } return true; } smem_path_param::smem_path_param(const char* new_name, const char* new_value, soar_module::predicate<const char*>* new_val_pred, soar_module::predicate<const char*>* new_prot_pred, agent* new_agent): soar_module::string_param(new_name, new_value, new_val_pred, new_prot_pred), thisAgent(new_agent) {} void smem_path_param::set_value(const char* new_value) { /* The first time path is set, we check that the the database is the right version, * so you can warn someone before they try to use it that conversion will take some * time. That way, they can then switch to another before dedicating that time. */ value->assign(new_value); const char* db_path; db_path = thisAgent->smem_params->path->get_value(); bool attempt_connection_here = thisAgent->smem_db->get_status() == soar_module::disconnected; if (attempt_connection_here) { thisAgent->smem_db->connect(db_path); } if (thisAgent->smem_db->get_status() == soar_module::problem) { print_sysparam_trace(thisAgent, 0, "Semantic memory database Error: %s\n", thisAgent->smem_db->get_errmsg()); } else { // temporary queries for one-time init actions soar_module::sqlite_statement* temp_q = NULL; // If the database is on file, make sure the database contents use the current schema // If it does not, switch to memory-based database if (strcmp(db_path, ":memory:")) // Only worry about database version if writing to disk { bool sql_is_new; std::string schema_version; if (thisAgent->smem_db->sql_is_new_db(sql_is_new)) { if (!sql_is_new) { // Check if table exists already temp_q = new soar_module::sqlite_statement(thisAgent->smem_db, "CREATE TABLE IF NOT EXISTS versions (system TEXT PRIMARY KEY,version_number TEXT)"); temp_q->prepare(); if (temp_q->get_status() == soar_module::ready) { if (!thisAgent->smem_db->sql_simple_get_string("SELECT version_number FROM versions WHERE system = 'smem_schema'", schema_version)) { if (smem_version_one(thisAgent)) { print(thisAgent, "...You have selected a database with an old version.\n" "...If you proceed, the database will be converted to a\n" "...new version when the database is initialized.\n" "...Conversion can take a large amount of time with large databases.\n"); } } } } } } delete temp_q; temp_q = NULL; } if (attempt_connection_here) { thisAgent->smem_db->disconnect(); } } // template <typename T> smem_db_predicate<T>::smem_db_predicate(agent* new_agent): soar_module::agent_predicate<T>(new_agent) {} template <typename T> bool smem_db_predicate<T>::operator()(T /*val*/) { return (this->thisAgent->smem_db->get_status() == soar_module::connected); } bool smem_enabled(agent* thisAgent) { return (thisAgent->smem_params->learning->get_value() == on); } ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // Statistic Functions (smem::stats) ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// smem_stat_container::smem_stat_container(agent* new_agent): soar_module::stat_container(new_agent) { // db-lib-version db_lib_version = new smem_db_lib_version_stat(thisAgent, "db-lib-version", NULL, new soar_module::predicate< const char* >()); add(db_lib_version); // mem-usage mem_usage = new smem_mem_usage_stat(thisAgent, "mem-usage", 0, new soar_module::predicate<int64_t>()); add(mem_usage); // mem-high mem_high = new smem_mem_high_stat(thisAgent, "mem-high", 0, new soar_module::predicate<int64_t>()); add(mem_high); // // expansions expansions = new soar_module::integer_stat("retrieves", 0, new soar_module::f_predicate<int64_t>()); add(expansions); // cue-based-retrievals cbr = new soar_module::integer_stat("queries", 0, new soar_module::f_predicate<int64_t>()); add(cbr); // stores stores = new soar_module::integer_stat("stores", 0, new soar_module::f_predicate<int64_t>()); add(stores); // activations act_updates = new soar_module::integer_stat("act_updates", 0, new soar_module::f_predicate<int64_t>()); add(act_updates); // mirrors mirrors = new soar_module::integer_stat("mirrors", 0, new soar_module::f_predicate<int64_t>()); add(mirrors); // // chunks chunks = new soar_module::integer_stat("nodes", 0, new smem_db_predicate< int64_t >(thisAgent)); add(chunks); // slots slots = new soar_module::integer_stat("edges", 0, new smem_db_predicate< int64_t >(thisAgent)); add(slots); } // smem_db_lib_version_stat::smem_db_lib_version_stat(agent* new_agent, const char* new_name, const char* new_value, soar_module::predicate< const char* >* new_prot_pred): soar_module::primitive_stat< const char* >(new_name, new_value, new_prot_pred), thisAgent(new_agent) {} const char* smem_db_lib_version_stat::get_value() { return thisAgent->smem_db->lib_version(); } // smem_mem_usage_stat::smem_mem_usage_stat(agent* new_agent, const char* new_name, int64_t new_value, soar_module::predicate<int64_t>* new_prot_pred): soar_module::integer_stat(new_name, new_value, new_prot_pred), thisAgent(new_agent) {} int64_t smem_mem_usage_stat::get_value() { return thisAgent->smem_db->memory_usage(); } // smem_mem_high_stat::smem_mem_high_stat(agent* new_agent, const char* new_name, int64_t new_value, soar_module::predicate<int64_t>* new_prot_pred): soar_module::integer_stat(new_name, new_value, new_prot_pred), thisAgent(new_agent) {} int64_t smem_mem_high_stat::get_value() { return thisAgent->smem_db->memory_highwater(); } ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // Timer Functions (smem::timers) ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// smem_timer_container::smem_timer_container(agent* new_agent): soar_module::timer_container(new_agent) { // one total = new smem_timer("_total", thisAgent, soar_module::timer::one); add(total); // two storage = new smem_timer("smem_storage", thisAgent, soar_module::timer::two); add(storage); ncb_retrieval = new smem_timer("smem_ncb_retrieval", thisAgent, soar_module::timer::two); add(ncb_retrieval); query = new smem_timer("smem_query", thisAgent, soar_module::timer::two); add(query); api = new smem_timer("smem_api", thisAgent, soar_module::timer::two); add(api); init = new smem_timer("smem_init", thisAgent, soar_module::timer::two); add(init); hash = new smem_timer("smem_hash", thisAgent, soar_module::timer::two); add(hash); act = new smem_timer("three_activation", thisAgent, soar_module::timer::three); add(act); } // smem_timer_level_predicate::smem_timer_level_predicate(agent* new_agent): soar_module::agent_predicate<soar_module::timer::timer_level>(new_agent) {} bool smem_timer_level_predicate::operator()(soar_module::timer::timer_level val) { return (thisAgent->smem_params->timers->get_value() >= val); } // smem_timer::smem_timer(const char* new_name, agent* new_agent, soar_module::timer::timer_level new_level): soar_module::timer(new_name, new_agent, new_level, new smem_timer_level_predicate(new_agent)) {} ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // Statement Functions (smem::statements) ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// void smem_statement_container::create_tables() { add_structure("CREATE TABLE IF NOT EXISTS versions (system TEXT PRIMARY KEY,version_number TEXT)"); add_structure("CREATE TABLE smem_persistent_variables (variable_id INTEGER PRIMARY KEY,variable_value INTEGER)"); add_structure("CREATE TABLE smem_symbols_type (s_id INTEGER PRIMARY KEY, symbol_type INTEGER)"); add_structure("CREATE TABLE smem_symbols_integer (s_id INTEGER PRIMARY KEY, symbol_value INTEGER)"); add_structure("CREATE TABLE smem_symbols_float (s_id INTEGER PRIMARY KEY, symbol_value REAL)"); add_structure("CREATE TABLE smem_symbols_string (s_id INTEGER PRIMARY KEY, symbol_value TEXT)"); add_structure("CREATE TABLE smem_lti (lti_id INTEGER PRIMARY KEY, soar_letter INTEGER, soar_number INTEGER, total_augmentations INTEGER, activation_value REAL, activations_total INTEGER, activations_last INTEGER, activations_first INTEGER)"); add_structure("CREATE TABLE smem_activation_history (lti_id INTEGER PRIMARY KEY, t1 INTEGER, t2 INTEGER, t3 INTEGER, t4 INTEGER, t5 INTEGER, t6 INTEGER, t7 INTEGER, t8 INTEGER, t9 INTEGER, t10 INTEGER)"); add_structure("CREATE TABLE smem_augmentations (lti_id INTEGER, attribute_s_id INTEGER, value_constant_s_id INTEGER, value_lti_id INTEGER, activation_value REAL)"); add_structure("CREATE TABLE smem_attribute_frequency (attribute_s_id INTEGER PRIMARY KEY, edge_frequency INTEGER)"); add_structure("CREATE TABLE smem_wmes_constant_frequency (attribute_s_id INTEGER, value_constant_s_id INTEGER, edge_frequency INTEGER)"); add_structure("CREATE TABLE smem_wmes_lti_frequency (attribute_s_id INTEGER, value_lti_id INTEGER, edge_frequency INTEGER)"); add_structure("CREATE TABLE smem_ascii (ascii_num INTEGER PRIMARY KEY, ascii_chr TEXT)"); // adding an ascii table just to make lti queries easier when inspecting database { add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (65,'A')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (66,'B')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (67,'C')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (68,'D')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (69,'E')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (70,'F')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (71,'G')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (72,'H')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (73,'I')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (74,'J')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (75,'K')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (76,'L')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (77,'M')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (78,'N')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (79,'O')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (80,'P')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (81,'Q')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (82,'R')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (83,'S')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (84,'T')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (85,'U')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (86,'V')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (87,'W')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (88,'X')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (89,'Y')"); add_structure("INSERT OR IGNORE INTO smem_ascii (ascii_num, ascii_chr) VALUES (90,'Z')"); } } void smem_statement_container::create_indices() { add_structure("CREATE UNIQUE INDEX smem_symbols_int_const ON smem_symbols_integer (symbol_value)"); add_structure("CREATE UNIQUE INDEX smem_symbols_float_const ON smem_symbols_float (symbol_value)"); add_structure("CREATE UNIQUE INDEX smem_symbols_str_const ON smem_symbols_string (symbol_value)"); add_structure("CREATE UNIQUE INDEX smem_lti_letter_num ON smem_lti (soar_letter, soar_number)"); add_structure("CREATE INDEX smem_lti_t ON smem_lti (activations_last)"); add_structure("CREATE INDEX smem_augmentations_parent_attr_val_lti ON smem_augmentations (lti_id, attribute_s_id, value_constant_s_id, value_lti_id)"); add_structure("CREATE INDEX smem_augmentations_attr_val_lti_cycle ON smem_augmentations (attribute_s_id, value_constant_s_id, value_lti_id, activation_value)"); add_structure("CREATE INDEX smem_augmentations_attr_cycle ON smem_augmentations (attribute_s_id, activation_value)"); add_structure("CREATE UNIQUE INDEX smem_wmes_constant_frequency_attr_val ON smem_wmes_constant_frequency (attribute_s_id, value_constant_s_id)"); add_structure("CREATE UNIQUE INDEX smem_ct_lti_attr_val ON smem_wmes_lti_frequency (attribute_s_id, value_lti_id)"); } void smem_statement_container::drop_tables(agent* new_agent) { new_agent->smem_db->sql_execute("DROP TABLE IF EXISTS smem_persistent_variables"); new_agent->smem_db->sql_execute("DROP TABLE IF EXISTS smem_symbols_type"); new_agent->smem_db->sql_execute("DROP TABLE IF EXISTS smem_symbols_integer"); new_agent->smem_db->sql_execute("DROP TABLE IF EXISTS smem_symbols_float"); new_agent->smem_db->sql_execute("DROP TABLE IF EXISTS smem_symbols_string"); new_agent->smem_db->sql_execute("DROP TABLE IF EXISTS smem_lti"); new_agent->smem_db->sql_execute("DROP TABLE IF EXISTS smem_activation_history"); new_agent->smem_db->sql_execute("DROP TABLE IF EXISTS smem_augmentations"); new_agent->smem_db->sql_execute("DROP TABLE IF EXISTS smem_attribute_frequency"); new_agent->smem_db->sql_execute("DROP TABLE IF EXISTS smem_wmes_constant_frequency"); new_agent->smem_db->sql_execute("DROP TABLE IF EXISTS smem_wmes_lti_frequency"); new_agent->smem_db->sql_execute("DROP TABLE IF EXISTS smem_ascii"); } smem_statement_container::smem_statement_container(agent* new_agent): soar_module::sqlite_statement_container(new_agent->smem_db) { soar_module::sqlite_database* new_db = new_agent->smem_db; // Delete all entries from the tables in the database if append setting is off if (new_agent->smem_params->append_db->get_value() == off) { print_sysparam_trace(new_agent, 0, "Erasing contents of semantic memory database. (append = off)\n"); drop_tables(new_agent); } create_tables(); create_indices(); // Update the version number add_structure("REPLACE INTO versions (system, version_number) VALUES ('smem_schema'," SMEM_SCHEMA_VERSION ")"); begin = new soar_module::sqlite_statement(new_db, "BEGIN"); add(begin); commit = new soar_module::sqlite_statement(new_db, "COMMIT"); add(commit); rollback = new soar_module::sqlite_statement(new_db, "ROLLBACK"); add(rollback); // var_get = new soar_module::sqlite_statement(new_db, "SELECT variable_value FROM smem_persistent_variables WHERE variable_id=?"); add(var_get); var_set = new soar_module::sqlite_statement(new_db, "UPDATE smem_persistent_variables SET variable_value=? WHERE variable_id=?"); add(var_set); var_create = new soar_module::sqlite_statement(new_db, "INSERT INTO smem_persistent_variables (variable_id,variable_value) VALUES (?,?)"); add(var_create); // hash_rev_int = new soar_module::sqlite_statement(new_db, "SELECT symbol_value FROM smem_symbols_integer WHERE s_id=?"); add(hash_rev_int); hash_rev_float = new soar_module::sqlite_statement(new_db, "SELECT symbol_value FROM smem_symbols_float WHERE s_id=?"); add(hash_rev_float); hash_rev_str = new soar_module::sqlite_statement(new_db, "SELECT symbol_value FROM smem_symbols_string WHERE s_id=?"); add(hash_rev_str); hash_rev_type = new soar_module::sqlite_statement(new_db, "SELECT symbol_type FROM smem_symbols_type WHERE s_id=?"); add(hash_rev_type); hash_get_int = new soar_module::sqlite_statement(new_db, "SELECT s_id FROM smem_symbols_integer WHERE symbol_value=?"); add(hash_get_int); hash_get_float = new soar_module::sqlite_statement(new_db, "SELECT s_id FROM smem_symbols_float WHERE symbol_value=?"); add(hash_get_float); hash_get_str = new soar_module::sqlite_statement(new_db, "SELECT s_id FROM smem_symbols_string WHERE symbol_value=?"); add(hash_get_str); hash_add_type = new soar_module::sqlite_statement(new_db, "INSERT INTO smem_symbols_type (symbol_type) VALUES (?)"); add(hash_add_type); hash_add_int = new soar_module::sqlite_statement(new_db, "INSERT INTO smem_symbols_integer (s_id,symbol_value) VALUES (?,?)"); add(hash_add_int); hash_add_float = new soar_module::sqlite_statement(new_db, "INSERT INTO smem_symbols_float (s_id,symbol_value) VALUES (?,?)"); add(hash_add_float); hash_add_str = new soar_module::sqlite_statement(new_db, "INSERT INTO smem_symbols_string (s_id,symbol_value) VALUES (?,?)"); add(hash_add_str); // lti_add = new soar_module::sqlite_statement(new_db, "INSERT INTO smem_lti (soar_letter,soar_number,total_augmentations,activation_value,activations_total,activations_last,activations_first) VALUES (?,?,?,?,?,?,?)"); add(lti_add); lti_get = new soar_module::sqlite_statement(new_db, "SELECT lti_id FROM smem_lti WHERE soar_letter=? AND soar_number=?"); add(lti_get); lti_letter_num = new soar_module::sqlite_statement(new_db, "SELECT soar_letter, soar_number FROM smem_lti WHERE lti_id=?"); add(lti_letter_num); lti_max = new soar_module::sqlite_statement(new_db, "SELECT soar_letter, MAX(soar_number) FROM smem_lti GROUP BY soar_letter"); add(lti_max); lti_access_get = new soar_module::sqlite_statement(new_db, "SELECT activations_total, activations_last, activations_first FROM smem_lti WHERE lti_id=?"); add(lti_access_get); lti_access_set = new soar_module::sqlite_statement(new_db, "UPDATE smem_lti SET activations_total=?, activations_last=?, activations_first=? WHERE lti_id=?"); add(lti_access_set); lti_get_t = new soar_module::sqlite_statement(new_db, "SELECT lti_id FROM smem_lti WHERE activations_last=?"); add(lti_get_t); // web_add = new soar_module::sqlite_statement(new_db, "INSERT INTO smem_augmentations (lti_id, attribute_s_id, value_constant_s_id, value_lti_id, activation_value) VALUES (?,?,?,?,?)"); add(web_add); web_truncate = new soar_module::sqlite_statement(new_db, "DELETE FROM smem_augmentations WHERE lti_id=?"); add(web_truncate); web_expand = new soar_module::sqlite_statement(new_db, "SELECT tsh_a.symbol_type AS attr_type, tsh_a.s_id AS attr_hash, vcl.symbol_type AS value_type, vcl.s_id AS value_hash, vcl.soar_letter AS value_letter, vcl.soar_number AS value_num, vcl.value_lti_id AS value_lti FROM ((smem_augmentations w LEFT JOIN smem_symbols_type tsh_v ON w.value_constant_s_id=tsh_v.s_id) vc LEFT JOIN smem_lti AS lti ON vc.value_lti_id=lti.lti_id) vcl INNER JOIN smem_symbols_type tsh_a ON vcl.attribute_s_id=tsh_a.s_id WHERE vcl.lti_id=?"); add(web_expand); // web_all = new soar_module::sqlite_statement(new_db, "SELECT attribute_s_id, value_constant_s_id, value_lti_id FROM smem_augmentations WHERE lti_id=?"); add(web_all); // web_attr_all = new soar_module::sqlite_statement(new_db, "SELECT lti_id, activation_value FROM smem_augmentations w WHERE attribute_s_id=? ORDER BY activation_value DESC"); add(web_attr_all); web_const_all = new soar_module::sqlite_statement(new_db, "SELECT lti_id, activation_value FROM smem_augmentations w WHERE attribute_s_id=? AND value_constant_s_id=? AND value_lti_id=" SMEM_AUGMENTATIONS_NULL_STR " ORDER BY activation_value DESC"); add(web_const_all); web_lti_all = new soar_module::sqlite_statement(new_db, "SELECT lti_id, activation_value FROM smem_augmentations w WHERE attribute_s_id=? AND value_constant_s_id=" SMEM_AUGMENTATIONS_NULL_STR " AND value_lti_id=? ORDER BY activation_value DESC"); add(web_lti_all); // web_attr_child = new soar_module::sqlite_statement(new_db, "SELECT lti_id, value_constant_s_id FROM smem_augmentations WHERE lti_id=? AND attribute_s_id=?"); add(web_attr_child); web_const_child = new soar_module::sqlite_statement(new_db, "SELECT lti_id, value_constant_s_id FROM smem_augmentations WHERE lti_id=? AND attribute_s_id=? AND value_constant_s_id=?"); add(web_const_child); web_lti_child = new soar_module::sqlite_statement(new_db, "SELECT lti_id, value_constant_s_id FROM smem_augmentations WHERE lti_id=? AND attribute_s_id=? AND value_constant_s_id=" SMEM_AUGMENTATIONS_NULL_STR " AND value_lti_id=?"); add(web_lti_child); // attribute_frequency_check = new soar_module::sqlite_statement(new_db, "SELECT edge_frequency FROM smem_attribute_frequency WHERE attribute_s_id=?"); add(attribute_frequency_check); wmes_constant_frequency_check = new soar_module::sqlite_statement(new_db, "SELECT edge_frequency FROM smem_wmes_constant_frequency WHERE attribute_s_id=? AND value_constant_s_id=?"); add(wmes_constant_frequency_check); wmes_lti_frequency_check = new soar_module::sqlite_statement(new_db, "SELECT edge_frequency FROM smem_wmes_lti_frequency WHERE attribute_s_id=? AND value_lti_id=?"); add(wmes_lti_frequency_check); // attribute_frequency_add = new soar_module::sqlite_statement(new_db, "INSERT INTO smem_attribute_frequency (attribute_s_id, edge_frequency) VALUES (?,1)"); add(attribute_frequency_add); wmes_constant_frequency_add = new soar_module::sqlite_statement(new_db, "INSERT INTO smem_wmes_constant_frequency (attribute_s_id, value_constant_s_id, edge_frequency) VALUES (?,?,1)"); add(wmes_constant_frequency_add); wmes_lti_frequency_add = new soar_module::sqlite_statement(new_db, "INSERT INTO smem_wmes_lti_frequency (attribute_s_id, value_lti_id, edge_frequency) VALUES (?,?,1)"); add(wmes_lti_frequency_add); // attribute_frequency_update = new soar_module::sqlite_statement(new_db, "UPDATE smem_attribute_frequency SET edge_frequency = edge_frequency + ? WHERE attribute_s_id=?"); add(attribute_frequency_update); wmes_constant_frequency_update = new soar_module::sqlite_statement(new_db, "UPDATE smem_wmes_constant_frequency SET edge_frequency = edge_frequency + ? WHERE attribute_s_id=? AND value_constant_s_id=?"); add(wmes_constant_frequency_update); wmes_lti_frequency_update = new soar_module::sqlite_statement(new_db, "UPDATE smem_wmes_lti_frequency SET edge_frequency = edge_frequency + ? WHERE attribute_s_id=? AND value_lti_id=?"); add(wmes_lti_frequency_update); // attribute_frequency_get = new soar_module::sqlite_statement(new_db, "SELECT edge_frequency FROM smem_attribute_frequency WHERE attribute_s_id=?"); add(attribute_frequency_get); wmes_constant_frequency_get = new soar_module::sqlite_statement(new_db, "SELECT edge_frequency FROM smem_wmes_constant_frequency WHERE attribute_s_id=? AND value_constant_s_id=?"); add(wmes_constant_frequency_get); wmes_lti_frequency_get = new soar_module::sqlite_statement(new_db, "SELECT edge_frequency FROM smem_wmes_lti_frequency WHERE attribute_s_id=? AND value_lti_id=?"); add(wmes_lti_frequency_get); // act_set = new soar_module::sqlite_statement(new_db, "UPDATE smem_augmentations SET activation_value=? WHERE lti_id=?"); add(act_set); act_lti_child_ct_get = new soar_module::sqlite_statement(new_db, "SELECT total_augmentations FROM smem_lti WHERE lti_id=?"); add(act_lti_child_ct_get); act_lti_child_ct_set = new soar_module::sqlite_statement(new_db, "UPDATE smem_lti SET total_augmentations=? WHERE lti_id=?"); add(act_lti_child_ct_set); act_lti_set = new soar_module::sqlite_statement(new_db, "UPDATE smem_lti SET activation_value=? WHERE lti_id=?"); add(act_lti_set); act_lti_get = new soar_module::sqlite_statement(new_db, "SELECT activation_value FROM smem_lti WHERE lti_id=?"); add(act_lti_get); history_get = new soar_module::sqlite_statement(new_db, "SELECT t1,t2,t3,t4,t5,t6,t7,t8,t9,t10 FROM smem_activation_history WHERE lti_id=?"); add(history_get); history_push = new soar_module::sqlite_statement(new_db, "UPDATE smem_activation_history SET t10=t9,t9=t8,t8=t7,t8=t7,t7=t6,t6=t5,t5=t4,t4=t3,t3=t2,t2=t1,t1=? WHERE lti_id=?"); add(history_push); history_add = new soar_module::sqlite_statement(new_db, "INSERT INTO smem_activation_history (lti_id,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10) VALUES (?,?,0,0,0,0,0,0,0,0,0)"); add(history_add); // vis_lti = new soar_module::sqlite_statement(new_db, "SELECT lti_id, soar_letter, soar_number, activation_value FROM smem_lti ORDER BY soar_letter ASC, soar_number ASC"); add(vis_lti); vis_lti_act = new soar_module::sqlite_statement(new_db, "SELECT activation_value FROM smem_lti WHERE lti_id=?"); add(vis_lti_act); vis_value_const = new soar_module::sqlite_statement(new_db, "SELECT lti_id, tsh1.symbol_type AS attr_type, tsh1.s_id AS attr_hash, tsh2.symbol_type AS val_type, tsh2.s_id AS val_hash FROM smem_augmentations w, smem_symbols_type tsh1, smem_symbols_type tsh2 WHERE (w.attribute_s_id=tsh1.s_id) AND (w.value_constant_s_id=tsh2.s_id)"); add(vis_value_const); vis_value_lti = new soar_module::sqlite_statement(new_db, "SELECT lti_id, tsh.symbol_type AS attr_type, tsh.s_id AS attr_hash, value_lti_id FROM smem_augmentations w, smem_symbols_type tsh WHERE (w.attribute_s_id=tsh.s_id) AND (value_lti_id<>" SMEM_AUGMENTATIONS_NULL_STR ")"); add(vis_value_lti); } ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // WME Functions (smem::wmes) ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// smem_wme_list* smem_get_direct_augs_of_id(Symbol* id, tc_number tc = NIL) { slot* s; wme* w; smem_wme_list* return_val = new smem_wme_list; // augs only exist for identifiers if (id->is_identifier()) { if (tc != NIL) { if (tc == id->tc_num) { return return_val; } else { id->tc_num = tc; } } // impasse wmes for (w = id->id->impasse_wmes; w != NIL; w = w->next) { if (!w->acceptable) { return_val->push_back(w); } } // input wmes for (w = id->id->input_wmes; w != NIL; w = w->next) { return_val->push_back(w); } // regular wmes for (s = id->id->slots; s != NIL; s = s->next) { for (w = s->wmes; w != NIL; w = w->next) { if (!w->acceptable) { return_val->push_back(w); } } } } return return_val; } inline void _smem_process_buffered_wme_list(agent* thisAgent, Symbol* state, wme_set& cue_wmes, symbol_triple_list& my_list, bool meta) { if (my_list.empty()) { return; } instantiation* inst = make_architectural_instantiation(thisAgent, state, &cue_wmes, &my_list); for (preference* pref = inst->preferences_generated; pref;) { // add the preference to temporary memory if (add_preference_to_tm(thisAgent, pref)) { // and add it to the list of preferences to be removed // when the goal is removed insert_at_head_of_dll(state->id->preferences_from_goal, pref, all_of_goal_next, all_of_goal_prev); pref->on_goal_list = true; if (meta) { // if this is a meta wme, then it is completely local // to the state and thus we will manually remove it // (via preference removal) when the time comes state->id->smem_info->smem_wmes->push_back(pref); } } else { if (pref->reference_count == 0) { preference* previous = pref; pref = pref->inst_next; possibly_deallocate_preference_and_clones(thisAgent, previous); continue; } } pref = pref->inst_next; } if (!meta) { // otherwise, we submit the fake instantiation to backtracing // such as to potentially produce justifications that can follow // it to future adventures (potentially on new states) instantiation* my_justification_list = NIL; dprint(DT_MILESTONES, "Calling chunk instantiation from _smem_process_buffered_wme_list...\n"); thisAgent->ebChunker->set_learning_for_instantiation(inst); thisAgent->ebChunker->build_chunk_or_justification(inst, &my_justification_list); // if any justifications are created, assert their preferences manually // (copied mainly from assert_new_preferences with respect to our circumstances) if (my_justification_list != NIL) { preference* just_pref = NIL; instantiation* next_justification = NIL; for (instantiation* my_justification = my_justification_list; my_justification != NIL; my_justification = next_justification) { next_justification = my_justification->next; if (my_justification->in_ms) { insert_at_head_of_dll(my_justification->prod->instantiations, my_justification, next, prev); } for (just_pref = my_justification->preferences_generated; just_pref != NIL;) { if (add_preference_to_tm(thisAgent, just_pref)) { if (wma_enabled(thisAgent)) { wma_activate_wmes_in_pref(thisAgent, just_pref); } } else { if (just_pref->reference_count == 0) { preference* previous = just_pref; just_pref = just_pref->inst_next; possibly_deallocate_preference_and_clones(thisAgent, previous); continue; } } just_pref = just_pref->inst_next; } } } } } inline void smem_process_buffered_wmes(agent* thisAgent, Symbol* state, wme_set& cue_wmes, symbol_triple_list& meta_wmes, symbol_triple_list& retrieval_wmes) { _smem_process_buffered_wme_list(thisAgent, state, cue_wmes, meta_wmes, true); _smem_process_buffered_wme_list(thisAgent, state, cue_wmes, retrieval_wmes, false); } inline void smem_buffer_add_wme(agent* thisAgent, symbol_triple_list& my_list, Symbol* id, Symbol* attr, Symbol* value) { my_list.push_back(new symbol_triple(id, attr, value)); symbol_add_ref(thisAgent, id); symbol_add_ref(thisAgent, attr); symbol_add_ref(thisAgent, value); } ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // Variable Functions (smem::var) // // Variables are key-value pairs stored in the database // that are necessary to maintain a store between // multiple runs of Soar. // ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // gets an SMem variable from the database inline bool smem_variable_get(agent* thisAgent, smem_variable_key variable_id, int64_t* variable_value) { soar_module::exec_result status; soar_module::sqlite_statement* var_get = thisAgent->smem_stmts->var_get; var_get->bind_int(1, variable_id); status = var_get->execute(); if (status == soar_module::row) { (*variable_value) = var_get->column_int(0); } var_get->reinitialize(); return (status == soar_module::row); } // sets an existing SMem variable in the database inline void smem_variable_set(agent* thisAgent, smem_variable_key variable_id, int64_t variable_value) { soar_module::sqlite_statement* var_set = thisAgent->smem_stmts->var_set; var_set->bind_int(1, variable_value); var_set->bind_int(2, variable_id); var_set->execute(soar_module::op_reinit); } // creates a new SMem variable in the database inline void smem_variable_create(agent* thisAgent, smem_variable_key variable_id, int64_t variable_value) { soar_module::sqlite_statement* var_create = thisAgent->smem_stmts->var_create; var_create->bind_int(1, variable_id); var_create->bind_int(2, variable_value); var_create->execute(soar_module::op_reinit); } ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // Temporal Hash Functions (smem::hash) // // The rete has symbol hashing, but the values are // reliable only for the lifetime of a symbol. This // isn't good for SMem. Hence, we implement a simple // lookup table. // // Note the hashing functions for the symbol types are // very similar, but with enough differences that I // separated them out for clarity. // ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// inline smem_hash_id smem_temporal_hash_add_type(agent* thisAgent, byte symbol_type) { thisAgent->smem_stmts->hash_add_type->bind_int(1, symbol_type); thisAgent->smem_stmts->hash_add_type->execute(soar_module::op_reinit); return static_cast<smem_hash_id>(thisAgent->smem_db->last_insert_rowid()); } inline smem_hash_id smem_temporal_hash_int(agent* thisAgent, int64_t val, bool add_on_fail = true) { smem_hash_id return_val = NIL; // search first thisAgent->smem_stmts->hash_get_int->bind_int(1, val); if (thisAgent->smem_stmts->hash_get_int->execute() == soar_module::row) { return_val = static_cast<smem_hash_id>(thisAgent->smem_stmts->hash_get_int->column_int(0)); } thisAgent->smem_stmts->hash_get_int->reinitialize(); // if fail and supposed to add if (!return_val && add_on_fail) { // type first return_val = smem_temporal_hash_add_type(thisAgent, INT_CONSTANT_SYMBOL_TYPE); // then content thisAgent->smem_stmts->hash_add_int->bind_int(1, return_val); thisAgent->smem_stmts->hash_add_int->bind_int(2, val); thisAgent->smem_stmts->hash_add_int->execute(soar_module::op_reinit); } return return_val; } inline smem_hash_id smem_temporal_hash_float(agent* thisAgent, double val, bool add_on_fail = true) { smem_hash_id return_val = NIL; // search first thisAgent->smem_stmts->hash_get_float->bind_double(1, val); if (thisAgent->smem_stmts->hash_get_float->execute() == soar_module::row) { return_val = static_cast<smem_hash_id>(thisAgent->smem_stmts->hash_get_float->column_int(0)); } thisAgent->smem_stmts->hash_get_float->reinitialize(); // if fail and supposed to add if (!return_val && add_on_fail) { // type first return_val = smem_temporal_hash_add_type(thisAgent, FLOAT_CONSTANT_SYMBOL_TYPE); // then content thisAgent->smem_stmts->hash_add_float->bind_int(1, return_val); thisAgent->smem_stmts->hash_add_float->bind_double(2, val); thisAgent->smem_stmts->hash_add_float->execute(soar_module::op_reinit); } return return_val; } inline smem_hash_id smem_temporal_hash_str(agent* thisAgent, char* val, bool add_on_fail = true) { smem_hash_id return_val = NIL; // search first thisAgent->smem_stmts->hash_get_str->bind_text(1, static_cast<const char*>(val)); if (thisAgent->smem_stmts->hash_get_str->execute() == soar_module::row) { return_val = static_cast<smem_hash_id>(thisAgent->smem_stmts->hash_get_str->column_int(0)); } thisAgent->smem_stmts->hash_get_str->reinitialize(); // if fail and supposed to add if (!return_val && add_on_fail) { // type first return_val = smem_temporal_hash_add_type(thisAgent, STR_CONSTANT_SYMBOL_TYPE); // then content thisAgent->smem_stmts->hash_add_str->bind_int(1, return_val); thisAgent->smem_stmts->hash_add_str->bind_text(2, static_cast<const char*>(val)); thisAgent->smem_stmts->hash_add_str->execute(soar_module::op_reinit); } return return_val; } // returns a temporally unique integer representing a symbol constant smem_hash_id smem_temporal_hash(agent* thisAgent, Symbol* sym, bool add_on_fail = true) { smem_hash_id return_val = NIL; //////////////////////////////////////////////////////////////////////////// thisAgent->smem_timers->hash->start(); //////////////////////////////////////////////////////////////////////////// if (sym->is_constant()) { if ((!sym->smem_hash) || (sym->smem_valid != thisAgent->smem_validation)) { sym->smem_hash = NIL; sym->smem_valid = thisAgent->smem_validation; switch (sym->symbol_type) { case STR_CONSTANT_SYMBOL_TYPE: return_val = smem_temporal_hash_str(thisAgent, sym->sc->name, add_on_fail); break; case INT_CONSTANT_SYMBOL_TYPE: return_val = smem_temporal_hash_int(thisAgent, sym->ic->value, add_on_fail); break; case FLOAT_CONSTANT_SYMBOL_TYPE: return_val = smem_temporal_hash_float(thisAgent, sym->fc->value, add_on_fail); break; } // cache results for later re-use sym->smem_hash = return_val; sym->smem_valid = thisAgent->smem_validation; } return_val = sym->smem_hash; } //////////////////////////////////////////////////////////////////////////// thisAgent->smem_timers->hash->stop(); //////////////////////////////////////////////////////////////////////////// return return_val; } inline int64_t smem_reverse_hash_int(agent* thisAgent, smem_hash_id hash_value) { int64_t return_val = NIL; thisAgent->smem_stmts->hash_rev_int->bind_int(1, hash_value); soar_module::exec_result res = thisAgent->smem_stmts->hash_rev_int->execute(); (void)res; // quells compiler warning assert(res == soar_module::row); return_val = thisAgent->smem_stmts->hash_rev_int->column_int(0); thisAgent->smem_stmts->hash_rev_int->reinitialize(); return return_val; } inline double smem_reverse_hash_float(agent* thisAgent, smem_hash_id hash_value) { double return_val = NIL; thisAgent->smem_stmts->hash_rev_float->bind_int(1, hash_value); soar_module::exec_result res = thisAgent->smem_stmts->hash_rev_float->execute(); (void)res; // quells compiler warning assert(res == soar_module::row); return_val = thisAgent->smem_stmts->hash_rev_float->column_double(0); thisAgent->smem_stmts->hash_rev_float->reinitialize(); return return_val; } inline void smem_reverse_hash_str(agent* thisAgent, smem_hash_id hash_value, std::string& dest) { thisAgent->smem_stmts->hash_rev_str->bind_int(1, hash_value); soar_module::exec_result res = thisAgent->smem_stmts->hash_rev_str->execute(); (void)res; // quells compiler warning assert(res == soar_module::row); dest.assign(thisAgent->smem_stmts->hash_rev_str->column_text(0)); thisAgent->smem_stmts->hash_rev_str->reinitialize(); } inline Symbol* smem_reverse_hash(agent* thisAgent, byte symbol_type, smem_hash_id hash_value) { Symbol* return_val = NULL; std::string dest; switch (symbol_type) { case STR_CONSTANT_SYMBOL_TYPE: smem_reverse_hash_str(thisAgent, hash_value, dest); return_val = make_str_constant(thisAgent, const_cast<char*>(dest.c_str())); break; case INT_CONSTANT_SYMBOL_TYPE: return_val = make_int_constant(thisAgent, smem_reverse_hash_int(thisAgent, hash_value)); break; case FLOAT_CONSTANT_SYMBOL_TYPE: return_val = make_float_constant(thisAgent, smem_reverse_hash_float(thisAgent, hash_value)); break; default: return_val = NULL; break; } return return_val; } ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // Activation Functions (smem::act) ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// inline double smem_lti_calc_base(agent* thisAgent, smem_lti_id lti, int64_t time_now, uint64_t n = 0, uint64_t activations_first = 0) { double sum = 0.0; double d = thisAgent->smem_params->base_decay->get_value(); uint64_t t_k; uint64_t t_n = (time_now - activations_first); if (n == 0) { thisAgent->smem_stmts->lti_access_get->bind_int(1, lti); thisAgent->smem_stmts->lti_access_get->execute(); n = thisAgent->smem_stmts->lti_access_get->column_int(0); activations_first = thisAgent->smem_stmts->lti_access_get->column_int(2); thisAgent->smem_stmts->lti_access_get->reinitialize(); } // get all history thisAgent->smem_stmts->history_get->bind_int(1, lti); thisAgent->smem_stmts->history_get->execute(); { int available_history = static_cast<int>((SMEM_ACT_HISTORY_ENTRIES < n) ? (SMEM_ACT_HISTORY_ENTRIES) : (n)); t_k = static_cast<uint64_t>(time_now - thisAgent->smem_stmts->history_get->column_int(available_history - 1)); for (int i = 0; i < available_history; i++) { sum += pow(static_cast<double>(time_now - thisAgent->smem_stmts->history_get->column_int(i)), static_cast<double>(-d)); } } thisAgent->smem_stmts->history_get->reinitialize(); // if available history was insufficient, approximate rest if (n > SMEM_ACT_HISTORY_ENTRIES) { double apx_numerator = (static_cast<double>(n - SMEM_ACT_HISTORY_ENTRIES) * (pow(static_cast<double>(t_n), 1.0 - d) - pow(static_cast<double>(t_k), 1.0 - d))); double apx_denominator = ((1.0 - d) * static_cast<double>(t_n - t_k)); sum += (apx_numerator / apx_denominator); } return ((sum > 0) ? (log(sum)) : (SMEM_ACT_LOW)); } // activates a new or existing long-term identifier // note: optional num_edges parameter saves us a lookup // just when storing a new chunk (default is a // big number that should never come up naturally // and if it does, satisfies thresholding behavior). inline double smem_lti_activate(agent* thisAgent, smem_lti_id lti, bool add_access, uint64_t num_edges = SMEM_ACT_MAX) { //////////////////////////////////////////////////////////////////////////// thisAgent->smem_timers->act->start(); //////////////////////////////////////////////////////////////////////////// int64_t time_now; if (add_access) { time_now = thisAgent->smem_max_cycle++; if ((thisAgent->smem_params->activation_mode->get_value() == smem_param_container::act_base) && (thisAgent->smem_params->base_update->get_value() == smem_param_container::bupt_incremental)) { int64_t time_diff; for (std::set< int64_t >::iterator b = thisAgent->smem_params->base_incremental_threshes->set_begin(); b != thisAgent->smem_params->base_incremental_threshes->set_end(); b++) { if (*b > 0) { time_diff = (time_now - *b); if (time_diff > 0) { std::list< smem_lti_id > to_update; thisAgent->smem_stmts->lti_get_t->bind_int(1, time_diff); while (thisAgent->smem_stmts->lti_get_t->execute() == soar_module::row) { to_update.push_back(static_cast< smem_lti_id >(thisAgent->smem_stmts->lti_get_t->column_int(0))); } thisAgent->smem_stmts->lti_get_t->reinitialize(); for (std::list< smem_lti_id >::iterator it = to_update.begin(); it != to_update.end(); it++) { smem_lti_activate(thisAgent, (*it), false); } } } } } } else { time_now = thisAgent->smem_max_cycle; thisAgent->smem_stats->act_updates->set_value(thisAgent->smem_stats->act_updates->get_value() + 1); } // access information uint64_t prev_access_n = 0; uint64_t prev_access_t = 0; uint64_t prev_access_1 = 0; { // get old (potentially useful below) { thisAgent->smem_stmts->lti_access_get->bind_int(1, lti); thisAgent->smem_stmts->lti_access_get->execute(); prev_access_n = thisAgent->smem_stmts->lti_access_get->column_int(0); prev_access_t = thisAgent->smem_stmts->lti_access_get->column_int(1); prev_access_1 = thisAgent->smem_stmts->lti_access_get->column_int(2); thisAgent->smem_stmts->lti_access_get->reinitialize(); } // set new if (add_access) { thisAgent->smem_stmts->lti_access_set->bind_int(1, (prev_access_n + 1)); thisAgent->smem_stmts->lti_access_set->bind_int(2, time_now); thisAgent->smem_stmts->lti_access_set->bind_int(3, ((prev_access_n == 0) ? (time_now) : (prev_access_1))); thisAgent->smem_stmts->lti_access_set->bind_int(4, lti); thisAgent->smem_stmts->lti_access_set->execute(soar_module::op_reinit); } } // get new activation value (depends upon bias) double new_activation = 0.0; smem_param_container::act_choices act_mode = thisAgent->smem_params->activation_mode->get_value(); if (act_mode == smem_param_container::act_recency) { new_activation = static_cast<double>(time_now); } else if (act_mode == smem_param_container::act_frequency) { new_activation = static_cast<double>(prev_access_n + ((add_access) ? (1) : (0))); } else if (act_mode == smem_param_container::act_base) { if (prev_access_n == 0) { if (add_access) { thisAgent->smem_stmts->history_add->bind_int(1, lti); thisAgent->smem_stmts->history_add->bind_int(2, time_now); thisAgent->smem_stmts->history_add->execute(soar_module::op_reinit); } new_activation = 0; } else { if (add_access) { thisAgent->smem_stmts->history_push->bind_int(1, time_now); thisAgent->smem_stmts->history_push->bind_int(2, lti); thisAgent->smem_stmts->history_push->execute(soar_module::op_reinit); } new_activation = smem_lti_calc_base(thisAgent, lti, time_now + ((add_access) ? (1) : (0)), prev_access_n + ((add_access) ? (1) : (0)), prev_access_1); } } // get number of augmentations (if not supplied) if (num_edges == SMEM_ACT_MAX) { thisAgent->smem_stmts->act_lti_child_ct_get->bind_int(1, lti); thisAgent->smem_stmts->act_lti_child_ct_get->execute(); num_edges = thisAgent->smem_stmts->act_lti_child_ct_get->column_int(0); thisAgent->smem_stmts->act_lti_child_ct_get->reinitialize(); } // only if augmentation count is less than threshold do we associate with edges if (num_edges < static_cast<uint64_t>(thisAgent->smem_params->thresh->get_value())) { // activation_value=? WHERE lti=? thisAgent->smem_stmts->act_set->bind_double(1, new_activation); thisAgent->smem_stmts->act_set->bind_int(2, lti); thisAgent->smem_stmts->act_set->execute(soar_module::op_reinit); } // always associate activation with lti { // activation_value=? WHERE lti=? thisAgent->smem_stmts->act_lti_set->bind_double(1, new_activation); thisAgent->smem_stmts->act_lti_set->bind_int(2, lti); thisAgent->smem_stmts->act_lti_set->execute(soar_module::op_reinit); } //////////////////////////////////////////////////////////////////////////// thisAgent->smem_timers->act->stop(); //////////////////////////////////////////////////////////////////////////// return new_activation; } ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // Long-Term Identifier Functions (smem::lti) ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// void _smem_lti_from_test(test t, std::set<Symbol*>* valid_ltis) { if (!t) { return; } if (t->type == EQUALITY_TEST) { if ((t->data.referent->symbol_type == IDENTIFIER_SYMBOL_TYPE) && (t->data.referent->id->smem_lti != NIL)) { valid_ltis->insert(t->data.referent); } return; } { if (t->type == CONJUNCTIVE_TEST) { for (cons* c = t->data.conjunct_list; c != NIL; c = c->rest) { _smem_lti_from_test(static_cast<test>(c->first), valid_ltis); } } } } // copied primarily from add_all_variables_in_rhs_value void _smem_lti_from_rhs_value(rhs_value rv, std::set<Symbol*>* valid_ltis) { if (rhs_value_is_symbol(rv)) { Symbol* sym = rhs_value_to_symbol(rv); if ((sym->symbol_type == IDENTIFIER_SYMBOL_TYPE) && (sym->id->smem_lti != NIL)) { valid_ltis->insert(sym); } } else { list* fl = rhs_value_to_funcall_list(rv); for (cons* c = fl->rest; c != NIL; c = c->rest) { _smem_lti_from_rhs_value(static_cast<rhs_value>(c->first), valid_ltis); } } } // instance of hash_table_callback_fn2 bool smem_count_ltis(agent* /*thisAgent*/, void* item, void* userdata) { Symbol* id = static_cast<symbol_struct*>(item); if (id->id->smem_lti != NIL) { uint64_t* counter = reinterpret_cast<uint64_t*>(userdata); (*counter)++; } return false; } // gets the lti id for an existing lti soar_letter/number pair (or NIL if failure) smem_lti_id smem_lti_get_id(agent* thisAgent, char name_letter, uint64_t name_number) { smem_lti_id return_val = NIL; // getting lti ids requires an open semantic database smem_attach(thisAgent); // soar_letter=? AND number=? thisAgent->smem_stmts->lti_get->bind_int(1, static_cast<uint64_t>(name_letter)); thisAgent->smem_stmts->lti_get->bind_int(2, static_cast<uint64_t>(name_number)); if (thisAgent->smem_stmts->lti_get->execute() == soar_module::row) { return_val = thisAgent->smem_stmts->lti_get->column_int(0); } thisAgent->smem_stmts->lti_get->reinitialize(); return return_val; } // adds a new lti id for a soar_letter/number pair inline smem_lti_id smem_lti_add_id(agent* thisAgent, char name_letter, uint64_t name_number) { smem_lti_id return_val; // create lti: soar_letter, number, total_augmentations, activation_value, activations_total, activations_last, activations_first thisAgent->smem_stmts->lti_add->bind_int(1, static_cast<uint64_t>(name_letter)); thisAgent->smem_stmts->lti_add->bind_int(2, static_cast<uint64_t>(name_number)); thisAgent->smem_stmts->lti_add->bind_int(3, static_cast<uint64_t>(0)); thisAgent->smem_stmts->lti_add->bind_double(4, static_cast<double>(0)); thisAgent->smem_stmts->lti_add->bind_int(5, static_cast<uint64_t>(0)); thisAgent->smem_stmts->lti_add->bind_int(6, static_cast<uint64_t>(0)); thisAgent->smem_stmts->lti_add->bind_int(7, static_cast<uint64_t>(0)); thisAgent->smem_stmts->lti_add->execute(soar_module::op_reinit); return_val = static_cast<smem_lti_id>(thisAgent->smem_db->last_insert_rowid()); // increment stat thisAgent->smem_stats->chunks->set_value(thisAgent->smem_stats->chunks->get_value() + 1); return return_val; } // makes a non-long-term identifier into a long-term identifier inline smem_lti_id smem_lti_soar_add(agent* thisAgent, Symbol* id) { if ((id->is_identifier()) && (id->id->smem_lti == NIL)) { // try to find existing lti id->id->smem_lti = smem_lti_get_id(thisAgent, id->id->name_letter, id->id->name_number); // if doesn't exist, add if (id->id->smem_lti == NIL) { id->id->smem_lti = smem_lti_add_id(thisAgent, id->id->name_letter, id->id->name_number); id->id->smem_time_id = thisAgent->epmem_stats->time->get_value(); id->id->smem_valid = thisAgent->epmem_validation; epmem_schedule_promotion(thisAgent, id); } } return id->id->smem_lti; } // returns a reference to an lti Symbol* smem_lti_soar_make(agent* thisAgent, smem_lti_id lti, char name_letter, uint64_t name_number, goal_stack_level level) { Symbol* return_val; // try to find existing return_val = find_identifier(thisAgent, name_letter, name_number); // otherwise create if (return_val == NIL) { return_val = make_new_identifier(thisAgent, name_letter, level, name_number); } else { symbol_add_ref(thisAgent, return_val); if ((return_val->id->level == SMEM_LTI_UNKNOWN_LEVEL) && (level != SMEM_LTI_UNKNOWN_LEVEL)) { return_val->id->level = level; return_val->id->promotion_level = level; } } // set lti field irrespective return_val->id->smem_lti = lti; return return_val; } void smem_reset_id_counters(agent* thisAgent) { if (thisAgent->smem_db->get_status() == soar_module::connected) { // soar_letter, max while (thisAgent->smem_stmts->lti_max->execute() == soar_module::row) { uint64_t name_letter = static_cast<uint64_t>(thisAgent->smem_stmts->lti_max->column_int(0)); uint64_t letter_max = static_cast<uint64_t>(thisAgent->smem_stmts->lti_max->column_int(1)); // shift to alphabet name_letter -= static_cast<uint64_t>('A'); // get count uint64_t* letter_ct = & thisAgent->id_counter[ name_letter ]; // adjust if necessary if ((*letter_ct) <= letter_max) { (*letter_ct) = (letter_max + 1); } } thisAgent->smem_stmts->lti_max->reinitialize(); } } ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // Storage Functions (smem::storage) ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// inline smem_slot* smem_make_slot(smem_slot_map* slots, Symbol* attr) { smem_slot** s = & (*slots)[ attr ]; if (!(*s)) { (*s) = new smem_slot; } return (*s); } void smem_disconnect_chunk(agent* thisAgent, smem_lti_id lti_id) { // adjust attr, attr/value counts { uint64_t pair_count = 0; smem_lti_id child_attr = 0; std::set<smem_lti_id> distinct_attr; // pairs first, accumulate distinct attributes and pair count thisAgent->smem_stmts->web_all->bind_int(1, lti_id); while (thisAgent->smem_stmts->web_all->execute() == soar_module::row) { pair_count++; child_attr = thisAgent->smem_stmts->web_all->column_int(0); distinct_attr.insert(child_attr); // null -> attr/lti if (thisAgent->smem_stmts->web_all->column_int(1) != SMEM_AUGMENTATIONS_NULL) { // adjust in opposite direction ( adjust, attribute, const ) thisAgent->smem_stmts->wmes_constant_frequency_update->bind_int(1, -1); thisAgent->smem_stmts->wmes_constant_frequency_update->bind_int(2, child_attr); thisAgent->smem_stmts->wmes_constant_frequency_update->bind_int(3, thisAgent->smem_stmts->web_all->column_int(1)); thisAgent->smem_stmts->wmes_constant_frequency_update->execute(soar_module::op_reinit); } else { // adjust in opposite direction ( adjust, attribute, lti ) thisAgent->smem_stmts->wmes_lti_frequency_update->bind_int(1, -1); thisAgent->smem_stmts->wmes_lti_frequency_update->bind_int(2, child_attr); thisAgent->smem_stmts->wmes_lti_frequency_update->bind_int(3, thisAgent->smem_stmts->web_all->column_int(2)); thisAgent->smem_stmts->wmes_lti_frequency_update->execute(soar_module::op_reinit); } } thisAgent->smem_stmts->web_all->reinitialize(); // now attributes for (std::set<smem_lti_id>::iterator a = distinct_attr.begin(); a != distinct_attr.end(); a++) { // adjust in opposite direction ( adjust, attribute ) thisAgent->smem_stmts->attribute_frequency_update->bind_int(1, -1); thisAgent->smem_stmts->attribute_frequency_update->bind_int(2, *a); thisAgent->smem_stmts->attribute_frequency_update->execute(soar_module::op_reinit); } // update local statistic thisAgent->smem_stats->slots->set_value(thisAgent->smem_stats->slots->get_value() - pair_count); } // disconnect { thisAgent->smem_stmts->web_truncate->bind_int(1, lti_id); thisAgent->smem_stmts->web_truncate->execute(soar_module::op_reinit); } } void smem_store_chunk(agent* thisAgent, smem_lti_id lti_id, smem_slot_map* children, bool remove_old_children = true, Symbol* print_id = NULL, bool activate = true) { // if remove children, disconnect chunk -> no existing edges // else, need to query number of existing edges uint64_t existing_edges = 0; if (remove_old_children) { smem_disconnect_chunk(thisAgent, lti_id); // provide trace output if (thisAgent->sysparams[ TRACE_SMEM_SYSPARAM ] && (print_id)) { char buf[256]; snprintf_with_symbols(thisAgent, buf, 256, "<=SMEM: (%y ^* *)\n", print_id); print(thisAgent, buf); xml_generate_warning(thisAgent, buf); } } else { thisAgent->smem_stmts->act_lti_child_ct_get->bind_int(1, lti_id); thisAgent->smem_stmts->act_lti_child_ct_get->execute(); existing_edges = static_cast<uint64_t>(thisAgent->smem_stmts->act_lti_child_ct_get->column_int(0)); thisAgent->smem_stmts->act_lti_child_ct_get->reinitialize(); } // get new edges // if didn't disconnect, entails lookups in existing edges std::set<smem_hash_id> attr_new; std::set< std::pair<smem_hash_id, smem_hash_id> > const_new; std::set< std::pair<smem_hash_id, smem_lti_id> > lti_new; { smem_slot_map::iterator s; smem_slot::iterator v; smem_hash_id attr_hash = 0; smem_hash_id value_hash = 0; smem_lti_id value_lti = 0; for (s = children->begin(); s != children->end(); s++) { attr_hash = smem_temporal_hash(thisAgent, s->first); if (remove_old_children) { attr_new.insert(attr_hash); } else { // lti_id, attribute_s_id thisAgent->smem_stmts->web_attr_child->bind_int(1, lti_id); thisAgent->smem_stmts->web_attr_child->bind_int(2, attr_hash); if (thisAgent->smem_stmts->web_attr_child->execute(soar_module::op_reinit) != soar_module::row) { attr_new.insert(attr_hash); } } for (v = s->second->begin(); v != s->second->end(); v++) { if ((*v)->val_const.val_type == value_const_t) { value_hash = smem_temporal_hash(thisAgent, (*v)->val_const.val_value); if (remove_old_children) { const_new.insert(std::make_pair(attr_hash, value_hash)); } else { // lti_id, attribute_s_id, val_const thisAgent->smem_stmts->web_const_child->bind_int(1, lti_id); thisAgent->smem_stmts->web_const_child->bind_int(2, attr_hash); thisAgent->smem_stmts->web_const_child->bind_int(3, value_hash); if (thisAgent->smem_stmts->web_const_child->execute(soar_module::op_reinit) != soar_module::row) { const_new.insert(std::make_pair(attr_hash, value_hash)); } } // provide trace output if (thisAgent->sysparams[ TRACE_SMEM_SYSPARAM ] && (print_id)) { char buf[256]; snprintf_with_symbols(thisAgent, buf, 256, "=>SMEM: (%y ^%y %y)\n", print_id, s->first, (*v)->val_const.val_value); print(thisAgent, buf); xml_generate_warning(thisAgent, buf); } } else { value_lti = (*v)->val_lti.val_value->lti_id; if (value_lti == NIL) { value_lti = smem_lti_add_id(thisAgent, (*v)->val_lti.val_value->lti_letter, (*v)->val_lti.val_value->lti_number); (*v)->val_lti.val_value->lti_id = value_lti; if ((*v)->val_lti.val_value->soar_id != NIL) { (*v)->val_lti.val_value->soar_id->id->smem_lti = value_lti; (*v)->val_lti.val_value->soar_id->id->smem_time_id = thisAgent->epmem_stats->time->get_value(); (*v)->val_lti.val_value->soar_id->id->smem_valid = thisAgent->epmem_validation; epmem_schedule_promotion(thisAgent, (*v)->val_lti.val_value->soar_id); } } if (remove_old_children) { lti_new.insert(std::make_pair(attr_hash, value_lti)); } else { // lti_id, attribute_s_id, val_lti thisAgent->smem_stmts->web_lti_child->bind_int(1, lti_id); thisAgent->smem_stmts->web_lti_child->bind_int(2, attr_hash); thisAgent->smem_stmts->web_lti_child->bind_int(3, value_lti); if (thisAgent->smem_stmts->web_lti_child->execute(soar_module::op_reinit) != soar_module::row) { lti_new.insert(std::make_pair(attr_hash, value_lti)); } } // provide trace output if (thisAgent->sysparams[ TRACE_SMEM_SYSPARAM ] && (print_id)) { char buf[256]; snprintf_with_symbols(thisAgent, buf, 256, "=>SMEM: (%y ^%y %y)\n", print_id, s->first, (*v)->val_lti.val_value->soar_id); print(thisAgent, buf); xml_generate_warning(thisAgent, buf); } } } } } // activation function assumes proper thresholding state // thus, consider four cases of augmentation counts (w.r.t. thresh) // 1. before=below, after=below: good (activation will update smem_augmentations) // 2. before=below, after=above: need to update smem_augmentations->inf // 3. before=after, after=below: good (activation will update smem_augmentations, free transition) // 4. before=after, after=after: good (activation won't touch smem_augmentations) // // hence, we detect + handle case #2 here uint64_t new_edges = (existing_edges + const_new.size() + lti_new.size()); bool after_above; double web_act = static_cast<double>(SMEM_ACT_MAX); { uint64_t thresh = static_cast<uint64_t>(thisAgent->smem_params->thresh->get_value()); after_above = (new_edges >= thresh); // if before below if (existing_edges < thresh) { if (after_above) { // update smem_augmentations to inf thisAgent->smem_stmts->act_set->bind_double(1, web_act); thisAgent->smem_stmts->act_set->bind_int(2, lti_id); thisAgent->smem_stmts->act_set->execute(soar_module::op_reinit); } } } // update edge counter { thisAgent->smem_stmts->act_lti_child_ct_set->bind_int(1, new_edges); thisAgent->smem_stmts->act_lti_child_ct_set->bind_int(2, lti_id); thisAgent->smem_stmts->act_lti_child_ct_set->execute(soar_module::op_reinit); } // now we can safely activate the lti if (activate) { double lti_act = smem_lti_activate(thisAgent, lti_id, true, new_edges); if (!after_above) { web_act = lti_act; } } // insert new edges, update counters { // attr/const pairs { for (std::set< std::pair< smem_hash_id, smem_hash_id > >::iterator p = const_new.begin(); p != const_new.end(); p++) { // insert { // lti_id, attribute_s_id, val_const, value_lti_id, activation_value thisAgent->smem_stmts->web_add->bind_int(1, lti_id); thisAgent->smem_stmts->web_add->bind_int(2, p->first); thisAgent->smem_stmts->web_add->bind_int(3, p->second); thisAgent->smem_stmts->web_add->bind_int(4, SMEM_AUGMENTATIONS_NULL); thisAgent->smem_stmts->web_add->bind_double(5, web_act); thisAgent->smem_stmts->web_add->execute(soar_module::op_reinit); } // update counter { // check if counter exists (and add if does not): attribute_s_id, val thisAgent->smem_stmts->wmes_constant_frequency_check->bind_int(1, p->first); thisAgent->smem_stmts->wmes_constant_frequency_check->bind_int(2, p->second); if (thisAgent->smem_stmts->wmes_constant_frequency_check->execute(soar_module::op_reinit) != soar_module::row) { thisAgent->smem_stmts->wmes_constant_frequency_add->bind_int(1, p->first); thisAgent->smem_stmts->wmes_constant_frequency_add->bind_int(2, p->second); thisAgent->smem_stmts->wmes_constant_frequency_add->execute(soar_module::op_reinit); } else { // adjust count (adjustment, attribute_s_id, val) thisAgent->smem_stmts->wmes_constant_frequency_update->bind_int(1, 1); thisAgent->smem_stmts->wmes_constant_frequency_update->bind_int(2, p->first); thisAgent->smem_stmts->wmes_constant_frequency_update->bind_int(3, p->second); thisAgent->smem_stmts->wmes_constant_frequency_update->execute(soar_module::op_reinit); } } } } // attr/lti pairs { for (std::set< std::pair< smem_hash_id, smem_lti_id > >::iterator p = lti_new.begin(); p != lti_new.end(); p++) { // insert { // lti_id, attribute_s_id, val_const, value_lti_id, activation_value thisAgent->smem_stmts->web_add->bind_int(1, lti_id); thisAgent->smem_stmts->web_add->bind_int(2, p->first); thisAgent->smem_stmts->web_add->bind_int(3, SMEM_AUGMENTATIONS_NULL); thisAgent->smem_stmts->web_add->bind_int(4, p->second); thisAgent->smem_stmts->web_add->bind_double(5, web_act); thisAgent->smem_stmts->web_add->execute(soar_module::op_reinit); } // update counter { // check if counter exists (and add if does not): attribute_s_id, val thisAgent->smem_stmts->wmes_lti_frequency_check->bind_int(1, p->first); thisAgent->smem_stmts->wmes_lti_frequency_check->bind_int(2, p->second); if (thisAgent->smem_stmts->wmes_lti_frequency_check->execute(soar_module::op_reinit) != soar_module::row) { thisAgent->smem_stmts->wmes_lti_frequency_add->bind_int(1, p->first); thisAgent->smem_stmts->wmes_lti_frequency_add->bind_int(2, p->second); thisAgent->smem_stmts->wmes_lti_frequency_add->execute(soar_module::op_reinit); } else { // adjust count (adjustment, attribute_s_id, lti) thisAgent->smem_stmts->wmes_lti_frequency_update->bind_int(1, 1); thisAgent->smem_stmts->wmes_lti_frequency_update->bind_int(2, p->first); thisAgent->smem_stmts->wmes_lti_frequency_update->bind_int(3, p->second); thisAgent->smem_stmts->wmes_lti_frequency_update->execute(soar_module::op_reinit); } } } } // update attribute count { for (std::set< smem_hash_id >::iterator a = attr_new.begin(); a != attr_new.end(); a++) { // check if counter exists (and add if does not): attribute_s_id thisAgent->smem_stmts->attribute_frequency_check->bind_int(1, *a); if (thisAgent->smem_stmts->attribute_frequency_check->execute(soar_module::op_reinit) != soar_module::row) { thisAgent->smem_stmts->attribute_frequency_add->bind_int(1, *a); thisAgent->smem_stmts->attribute_frequency_add->execute(soar_module::op_reinit); } else { // adjust count (adjustment, attribute_s_id) thisAgent->smem_stmts->attribute_frequency_update->bind_int(1, 1); thisAgent->smem_stmts->attribute_frequency_update->bind_int(2, *a); thisAgent->smem_stmts->attribute_frequency_update->execute(soar_module::op_reinit); } } } // update local edge count { thisAgent->smem_stats->slots->set_value(thisAgent->smem_stats->slots->get_value() + (const_new.size() + lti_new.size())); } } } void smem_soar_store(agent* thisAgent, Symbol* id, smem_storage_type store_type = store_level, tc_number tc = NIL) { // transitive closure only matters for recursive storage if ((store_type == store_recursive) && (tc == NIL)) { tc = get_new_tc_number(thisAgent); } smem_sym_list shorties; // get level smem_wme_list* children = smem_get_direct_augs_of_id(id, tc); smem_wme_list::iterator w; // make the target an lti, so intermediary data structure has lti_id // (takes care of short-term id self-referencing) smem_lti_soar_add(thisAgent, id); // encode this level { smem_sym_to_chunk_map sym_to_chunk; smem_sym_to_chunk_map::iterator c_p; smem_chunk** c; smem_slot_map slots; smem_slot_map::iterator s_p; smem_slot::iterator v_p; smem_slot* s; smem_chunk_value* v; for (w = children->begin(); w != children->end(); w++) { // get slot s = smem_make_slot(&(slots), (*w)->attr); // create value, per type v = new smem_chunk_value; if ((*w)->value->is_constant()) { v->val_const.val_type = value_const_t; v->val_const.val_value = (*w)->value; } else { v->val_lti.val_type = value_lti_t; // try to find existing chunk c = & sym_to_chunk[(*w)->value ]; // if doesn't exist, add; else use existing if (!(*c)) { (*c) = new smem_chunk; (*c)->lti_id = (*w)->value->id->smem_lti; (*c)->lti_letter = (*w)->value->id->name_letter; (*c)->lti_number = (*w)->value->id->name_number; (*c)->slots = NULL; (*c)->soar_id = (*w)->value; // only traverse to short-term identifiers if ((store_type == store_recursive) && ((*c)->lti_id == NIL)) { shorties.push_back((*c)->soar_id); } } v->val_lti.val_value = (*c); } // add value to slot s->push_back(v); } smem_store_chunk(thisAgent, id->id->smem_lti, &(slots), true, id); // clean up { // de-allocate slots for (s_p = slots.begin(); s_p != slots.end(); s_p++) { for (v_p = s_p->second->begin(); v_p != s_p->second->end(); v_p++) { delete(*v_p); } delete s_p->second; } // de-allocate chunks for (c_p = sym_to_chunk.begin(); c_p != sym_to_chunk.end(); c_p++) { delete c_p->second; } delete children; } } // recurse as necessary for (smem_sym_list::iterator shorty = shorties.begin(); shorty != shorties.end(); shorty++) { smem_soar_store(thisAgent, (*shorty), store_recursive, tc); } } ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // Non-Cue-Based Retrieval Functions (smem::ncb) ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// void smem_install_memory(agent* thisAgent, Symbol* state, smem_lti_id lti_id, Symbol* lti, bool activate_lti, symbol_triple_list& meta_wmes, symbol_triple_list& retrieval_wmes, smem_install_type install_type = wm_install, uint64_t depth = 1, std::set<smem_lti_id>* visited = NULL) { //////////////////////////////////////////////////////////////////////////// thisAgent->smem_timers->ncb_retrieval->start(); //////////////////////////////////////////////////////////////////////////// // get the ^result header for this state Symbol* result_header = NULL; if (install_type == wm_install) { result_header = state->id->smem_result_header; } // get identifier if not known bool lti_created_here = false; if (lti == NIL && install_type == wm_install) { soar_module::sqlite_statement* q = thisAgent->smem_stmts->lti_letter_num; q->bind_int(1, lti_id); q->execute(); lti = smem_lti_soar_make(thisAgent, lti_id, static_cast<char>(q->column_int(0)), static_cast<uint64_t>(q->column_int(1)), result_header->id->level); q->reinitialize(); lti_created_here = true; } // activate lti if (activate_lti) { smem_lti_activate(thisAgent, lti_id, true); } // point retrieved to lti if (install_type == wm_install) { if (visited == NULL) { smem_buffer_add_wme(thisAgent, meta_wmes, result_header, thisAgent->smem_sym_retrieved, lti); } else { smem_buffer_add_wme(thisAgent, meta_wmes, result_header, thisAgent->smem_sym_depth_retrieved, lti); } } if (lti_created_here) { // if the identifier was created above we need to // remove a single ref count AFTER the wme // is added (such as to not deallocate the symbol // prematurely) symbol_remove_ref(thisAgent, lti); } bool triggered = false; // if no children, then retrieve children // merge may override this behavior if (((thisAgent->smem_params->merge->get_value() == smem_param_container::merge_add) || ((lti->id->impasse_wmes == NIL) && (lti->id->input_wmes == NIL) && (lti->id->slots == NIL))) || (install_type == fake_install)) //(The final bit is if this is being called by the remove command.) { if (visited == NULL) { triggered = true; visited = new std::set<smem_lti_id>; } soar_module::sqlite_statement* expand_q = thisAgent->smem_stmts->web_expand; Symbol* attr_sym; Symbol* value_sym; // get direct children: attr_type, attr_hash, value_type, value_hash, value_letter, value_num, value_lti expand_q->bind_int(1, lti_id); std::set<Symbol*> children; while (expand_q->execute() == soar_module::row) { // make the identifier symbol irrespective of value type attr_sym = smem_reverse_hash(thisAgent, static_cast<byte>(expand_q->column_int(0)), static_cast<smem_hash_id>(expand_q->column_int(1))); // identifier vs. constant if (expand_q->column_int(6) != SMEM_AUGMENTATIONS_NULL) { value_sym = smem_lti_soar_make(thisAgent, static_cast<smem_lti_id>(expand_q->column_int(6)), static_cast<char>(expand_q->column_int(4)), static_cast<uint64_t>(expand_q->column_int(5)), lti->id->level); if (depth > 1) { children.insert(value_sym); } } else { value_sym = smem_reverse_hash(thisAgent, static_cast<byte>(expand_q->column_int(2)), static_cast<smem_hash_id>(expand_q->column_int(3))); } // add wme smem_buffer_add_wme(thisAgent, retrieval_wmes, lti, attr_sym, value_sym); // deal with ref counts - attribute/values are always created in this function // (thus an extra ref count is set before adding a wme) symbol_remove_ref(thisAgent, attr_sym); symbol_remove_ref(thisAgent, value_sym); } expand_q->reinitialize(); //Attempt to find children for the case of depth. std::set<Symbol*>::iterator iterator; std::set<Symbol*>::iterator end = children.end(); for (iterator = children.begin(); iterator != end; ++iterator) { if (visited->find((*iterator)->id->smem_lti) == visited->end()) { visited->insert((*iterator)->id->smem_lti); smem_install_memory(thisAgent, state, (*iterator)->id->smem_lti, (*iterator), (thisAgent->smem_params->activate_on_query->get_value() == on), meta_wmes, retrieval_wmes, install_type, depth - 1, visited); } } } if (triggered) { delete visited; } //////////////////////////////////////////////////////////////////////////// thisAgent->smem_timers->ncb_retrieval->stop(); //////////////////////////////////////////////////////////////////////////// } ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // Cue-Based Retrieval Functions (smem::cbr) ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// inline soar_module::sqlite_statement* smem_setup_web_crawl(agent* thisAgent, smem_weighted_cue_element* el) { soar_module::sqlite_statement* q = NULL; // first, point to correct query and setup // query-specific parameters if (el->element_type == attr_t) { // attribute_s_id=? q = thisAgent->smem_stmts->web_attr_all; } else if (el->element_type == value_const_t) { // attribute_s_id=? AND value_constant_s_id=? q = thisAgent->smem_stmts->web_const_all; q->bind_int(2, el->value_hash); } else if (el->element_type == value_lti_t) { // attribute_s_id=? AND value_lti_id=? q = thisAgent->smem_stmts->web_lti_all; q->bind_int(2, el->value_lti); } // all require hash as first parameter q->bind_int(1, el->attr_hash); return q; } inline bool _smem_process_cue_wme(agent* thisAgent, wme* w, bool pos_cue, smem_prioritized_weighted_cue& weighted_pq, MathQuery* mathQuery) { bool good_wme = true; smem_weighted_cue_element* new_cue_element; smem_hash_id attr_hash; smem_hash_id value_hash; smem_lti_id value_lti; smem_cue_element_type element_type; soar_module::sqlite_statement* q = NULL; { // we only have to do hard work if attr_hash = smem_temporal_hash(thisAgent, w->attr, false); if (attr_hash != NIL) { if (w->value->is_constant() && mathQuery == NIL) { value_lti = NIL; value_hash = smem_temporal_hash(thisAgent, w->value, false); element_type = value_const_t; if (value_hash != NIL) { q = thisAgent->smem_stmts->wmes_constant_frequency_get; q->bind_int(1, attr_hash); q->bind_int(2, value_hash); } else if (pos_cue) { good_wme = false; } else { //This would be a negative query that smem has no hash for. This means that //there is no way it could be in any of the results, and we don't //need to continue processing it, let alone use it in the search. --ACN return true; } } else { //If we get here on a math query, the value may not be an identifier if (w->value->symbol_type == IDENTIFIER_SYMBOL_TYPE) { value_lti = w->value->id->smem_lti; } else { value_lti = 0; } value_hash = NIL; if (value_lti == NIL) { q = thisAgent->smem_stmts->attribute_frequency_get; q->bind_int(1, attr_hash); element_type = attr_t; } else { q = thisAgent->smem_stmts->wmes_lti_frequency_get; q->bind_int(1, attr_hash); q->bind_int(2, value_lti); element_type = value_lti_t; } } if (good_wme) { if (q->execute() == soar_module::row) { new_cue_element = new smem_weighted_cue_element; new_cue_element->weight = q->column_int(0); new_cue_element->attr_hash = attr_hash; new_cue_element->value_hash = value_hash; new_cue_element->value_lti = value_lti; new_cue_element->cue_element = w; new_cue_element->element_type = element_type; new_cue_element->pos_element = pos_cue; new_cue_element->mathElement = mathQuery; weighted_pq.push(new_cue_element); new_cue_element = NULL; } else { if (pos_cue) { good_wme = false; } } q->reinitialize(); } } else { if (pos_cue) { good_wme = false; } } } //If we brought in a math query and didn't use it if (!good_wme && mathQuery != NIL) { delete mathQuery; } return good_wme; } //this returns a pair with <needFullSearch, goodCue> std::pair<bool, bool>* processMathQuery(agent* thisAgent, Symbol* mathQuery, smem_prioritized_weighted_cue* weighted_pq) { bool needFullSearch = false; //Use this set to track when certain elements have been added, so we don't add them twice std::set<Symbol*> uniqueMathQueryElements; std::pair<bool, bool>* result = new std::pair<bool, bool>(true, true); smem_wme_list* cue = smem_get_direct_augs_of_id(mathQuery); for (smem_wme_list::iterator cue_p = cue->begin(); cue_p != cue->end(); cue_p++) { smem_wme_list* cueTypes = smem_get_direct_augs_of_id((*cue_p)->value); if (cueTypes->empty()) { //This would be an attribute without a query type attached result->first = false; result->second = false; break; } else { for (smem_wme_list::iterator cueType = cueTypes->begin(); cueType != cueTypes->end(); cueType++) { if ((*cueType)->attr == thisAgent->smem_sym_math_query_less) { if ((*cueType)->value->symbol_type == FLOAT_CONSTANT_SYMBOL_TYPE) { _smem_process_cue_wme(thisAgent, (*cue_p), true, *weighted_pq, new MathQueryLess((*cueType)->value->fc->value)); } else if ((*cueType)->value->symbol_type == INT_CONSTANT_SYMBOL_TYPE) { _smem_process_cue_wme(thisAgent, (*cue_p), true, *weighted_pq, new MathQueryLess((*cueType)->value->ic->value)); } else { //There isn't a valid value to compare against result->first = false; result->second = false; break; } } else if ((*cueType)->attr == thisAgent->smem_sym_math_query_greater) { if ((*cueType)->value->symbol_type == FLOAT_CONSTANT_SYMBOL_TYPE) { _smem_process_cue_wme(thisAgent, (*cue_p), true, *weighted_pq, new MathQueryGreater((*cueType)->value->fc->value)); } else if ((*cueType)->value->symbol_type == INT_CONSTANT_SYMBOL_TYPE) { _smem_process_cue_wme(thisAgent, (*cue_p), true, *weighted_pq, new MathQueryGreater((*cueType)->value->ic->value)); } else { //There isn't a valid value to compare against result->first = false; result->second = false; break; } } else if ((*cueType)->attr == thisAgent->smem_sym_math_query_less_or_equal) { if ((*cueType)->value->symbol_type == FLOAT_CONSTANT_SYMBOL_TYPE) { _smem_process_cue_wme(thisAgent, (*cue_p), true, *weighted_pq, new MathQueryLessOrEqual((*cueType)->value->fc->value)); } else if ((*cueType)->value->symbol_type == INT_CONSTANT_SYMBOL_TYPE) { _smem_process_cue_wme(thisAgent, (*cue_p), true, *weighted_pq, new MathQueryLessOrEqual((*cueType)->value->ic->value)); } else { //There isn't a valid value to compare against result->first = false; result->second = false; break; } } else if ((*cueType)->attr == thisAgent->smem_sym_math_query_greater_or_equal) { if ((*cueType)->value->symbol_type == FLOAT_CONSTANT_SYMBOL_TYPE) { _smem_process_cue_wme(thisAgent, (*cue_p), true, *weighted_pq, new MathQueryGreaterOrEqual((*cueType)->value->fc->value)); } else if ((*cueType)->value->symbol_type == INT_CONSTANT_SYMBOL_TYPE) { _smem_process_cue_wme(thisAgent, (*cue_p), true, *weighted_pq, new MathQueryGreaterOrEqual((*cueType)->value->ic->value)); } else { //There isn't a valid value to compare against result->first = false; result->second = false; break; } } else if ((*cueType)->attr == thisAgent->smem_sym_math_query_max) { if (uniqueMathQueryElements.find(thisAgent->smem_sym_math_query_max) != uniqueMathQueryElements.end()) { //Only one max at a time result->first = false; result->second = false; break; } else { uniqueMathQueryElements.insert(thisAgent->smem_sym_math_query_max); } needFullSearch = true; _smem_process_cue_wme(thisAgent, (*cue_p), true, *weighted_pq, new MathQueryMax()); } else if ((*cueType)->attr == thisAgent->smem_sym_math_query_min) { if (uniqueMathQueryElements.find(thisAgent->smem_sym_math_query_min) != uniqueMathQueryElements.end()) { //Only one min at a time result->first = false; result->second = false; break; } else { uniqueMathQueryElements.insert(thisAgent->smem_sym_math_query_min); } needFullSearch = true; _smem_process_cue_wme(thisAgent, (*cue_p), true, *weighted_pq, new MathQueryMin()); } } } delete cueTypes; } delete cue; if (result->second) { result->first = needFullSearch; return result; } return result; } smem_lti_id smem_process_query(agent* thisAgent, Symbol* state, Symbol* query, Symbol* negquery, Symbol* mathQuery, smem_lti_set* prohibit, wme_set& cue_wmes, symbol_triple_list& meta_wmes, symbol_triple_list& retrieval_wmes, smem_query_levels query_level = qry_full, uint64_t number_to_retrieve = 1, std::list<smem_lti_id>* match_ids = NIL, uint64_t depth = 1, smem_install_type install_type = wm_install) { smem_weighted_cue_list weighted_cue; bool good_cue = true; //This is used when doing math queries that need to look at more that just the first valid element bool needFullSearch = false; soar_module::sqlite_statement* q = NULL; std::list<smem_lti_id> temp_list; if (query_level == qry_full) { match_ids = &(temp_list); } smem_lti_id king_id = NIL; //////////////////////////////////////////////////////////////////////////// thisAgent->smem_timers->query->start(); //////////////////////////////////////////////////////////////////////////// // prepare query stats { smem_prioritized_weighted_cue weighted_pq; // positive cue - always { smem_wme_list* cue = smem_get_direct_augs_of_id(query); if (cue->empty()) { good_cue = false; } for (smem_wme_list::iterator cue_p = cue->begin(); cue_p != cue->end(); cue_p++) { cue_wmes.insert((*cue_p)); if (good_cue) { good_cue = _smem_process_cue_wme(thisAgent, (*cue_p), true, weighted_pq, NIL); } } delete cue; } //Look through while were here, so that we can make sure the attributes we need are in the results if (mathQuery != NIL && good_cue) { std::pair<bool, bool>* mpr = processMathQuery(thisAgent, mathQuery, &weighted_pq); needFullSearch = mpr->first; good_cue = mpr->second; delete mpr; } // negative cue - if present if (negquery) { smem_wme_list* cue = smem_get_direct_augs_of_id(negquery); for (smem_wme_list::iterator cue_p = cue->begin(); cue_p != cue->end(); cue_p++) { cue_wmes.insert((*cue_p)); if (good_cue) { good_cue = _smem_process_cue_wme(thisAgent, (*cue_p), false, weighted_pq, NIL); } } delete cue; } // if valid cue, transfer priority queue to list if (good_cue) { while (!weighted_pq.empty()) { weighted_cue.push_back(weighted_pq.top()); weighted_pq.pop(); } } // else deallocate priority queue contents else { while (!weighted_pq.empty()) { smem_prioritized_weighted_cue::value_type top = weighted_pq.top(); weighted_pq.pop(); if (top->mathElement != NIL) { delete top->mathElement; } delete top; /*if(weighted_pq.top()->mathElement != NIL){ delete weighted_pq.top()->mathElement; } delete weighted_pq.top(); weighted_pq.pop();*/ } } } // only search if the cue was valid if (good_cue && !weighted_cue.empty()) { // by definition, the first positive-cue element dictates the candidate set smem_weighted_cue_list::iterator cand_set; smem_weighted_cue_list::iterator next_element; for (next_element = weighted_cue.begin(); next_element != weighted_cue.end(); next_element++) { if ((*next_element)->pos_element) { cand_set = next_element; break; } } soar_module::sqlite_statement* q2 = NULL; smem_lti_set::iterator prohibit_p; smem_lti_id cand; bool good_cand; if (thisAgent->smem_params->activation_mode->get_value() == smem_param_container::act_base) { // naive base-level updates means update activation of // every candidate in the minimal list before the // confirmation walk if (thisAgent->smem_params->base_update->get_value() == smem_param_container::bupt_naive) { q = smem_setup_web_crawl(thisAgent, (*cand_set)); // queue up distinct lti's to update // - set because queries could contain wilds // - not in loop because the effects of activation may actually // alter the resultset of the query (isolation???) std::set< smem_lti_id > to_update; while (q->execute() == soar_module::row) { to_update.insert(q->column_int(0)); } for (std::set< smem_lti_id >::iterator it = to_update.begin(); it != to_update.end(); it++) { smem_lti_activate(thisAgent, (*it), false); } q->reinitialize(); } } // setup first query, which is sorted on activation already q = smem_setup_web_crawl(thisAgent, (*cand_set)); thisAgent->lastCue = new agent::BasicWeightedCue((*cand_set)->cue_element, (*cand_set)->weight); // this becomes the minimal set to walk (till match or fail) if (q->execute() == soar_module::row) { smem_prioritized_activated_lti_queue plentiful_parents; bool more_rows = true; bool use_db = false; bool has_feature = false; while (more_rows && (q->column_double(1) == static_cast<double>(SMEM_ACT_MAX))) { thisAgent->smem_stmts->act_lti_get->bind_int(1, q->column_int(0)); thisAgent->smem_stmts->act_lti_get->execute(); plentiful_parents.push(std::make_pair< double, smem_lti_id >(thisAgent->smem_stmts->act_lti_get->column_double(0), q->column_int(0))); thisAgent->smem_stmts->act_lti_get->reinitialize(); more_rows = (q->execute() == soar_module::row); } bool first_element = false; while (((match_ids->size() < number_to_retrieve) || (needFullSearch)) && ((more_rows) || (!plentiful_parents.empty()))) { // choose next candidate (db vs. priority queue) { use_db = false; if (!more_rows) { use_db = false; } else if (plentiful_parents.empty()) { use_db = true; } else { use_db = (q->column_double(1) > plentiful_parents.top().first); } if (use_db) { cand = q->column_int(0); more_rows = (q->execute() == soar_module::row); } else { cand = plentiful_parents.top().second; plentiful_parents.pop(); } } // if not prohibited, submit to the remaining cue elements prohibit_p = prohibit->find(cand); if (prohibit_p == prohibit->end()) { good_cand = true; for (next_element = weighted_cue.begin(); next_element != weighted_cue.end() && good_cand; next_element++) { // don't need to check the generating list //If the cand_set is a math query, we care about more than its existence if ((*next_element) == (*cand_set) && (*next_element)->mathElement == NIL) { continue; } if ((*next_element)->element_type == attr_t) { // parent=? AND attribute_s_id=? q2 = thisAgent->smem_stmts->web_attr_child; } else if ((*next_element)->element_type == value_const_t) { // parent=? AND attribute_s_id=? AND value_constant_s_id=? q2 = thisAgent->smem_stmts->web_const_child; q2->bind_int(3, (*next_element)->value_hash); } else if ((*next_element)->element_type == value_lti_t) { // parent=? AND attribute_s_id=? AND value_lti_id=? q2 = thisAgent->smem_stmts->web_lti_child; q2->bind_int(3, (*next_element)->value_lti); } // all require own id, attribute q2->bind_int(1, cand); q2->bind_int(2, (*next_element)->attr_hash); has_feature = (q2->execute() == soar_module::row); bool mathQueryMet = false; if ((*next_element)->mathElement != NIL && has_feature) { do { smem_hash_id valueHash = q2->column_int(2 - 1); thisAgent->smem_stmts->hash_rev_type->bind_int(1, valueHash); if (thisAgent->smem_stmts->hash_rev_type->execute() != soar_module::row) { good_cand = false; } else { switch (thisAgent->smem_stmts->hash_rev_type->column_int(1 - 1)) { case FLOAT_CONSTANT_SYMBOL_TYPE: mathQueryMet |= (*next_element)->mathElement->valueIsAcceptable(smem_reverse_hash_float(thisAgent, valueHash)); break; case INT_CONSTANT_SYMBOL_TYPE: mathQueryMet |= (*next_element)->mathElement->valueIsAcceptable(smem_reverse_hash_int(thisAgent, valueHash)); break; } } thisAgent->smem_stmts->hash_rev_type->reinitialize(); } while (q2->execute() == soar_module::row); good_cand = mathQueryMet; } else { good_cand = (((*next_element)->pos_element) ? (has_feature) : (!has_feature)); } //In CSoar this needs to happen before the break, or the query might not be ready next time q2->reinitialize(); if (!good_cand) { break; } } if (good_cand) { king_id = cand; first_element = true; match_ids->push_back(cand); prohibit->insert(cand); } if (good_cand && first_element) { for (smem_weighted_cue_list::iterator wce = weighted_cue.begin(); wce != weighted_cue.end(); wce++) { if ((*wce)->mathElement != NIL) { (*wce)->mathElement->commit(); } } } else if (first_element) { for (smem_weighted_cue_list::iterator wce = weighted_cue.begin(); wce != weighted_cue.end(); wce++) { if ((*wce)->mathElement != NIL) { (*wce)->mathElement->rollback(); } } } } } // if (!match_ids->empty()) // { // king_id = match_ids->front(); // } } q->reinitialize(); // clean weighted cue for (next_element = weighted_cue.begin(); next_element != weighted_cue.end(); next_element++) { if ((*next_element)->mathElement != NIL) { delete(*next_element)->mathElement; } delete(*next_element); } } // reconstruction depends upon level if (query_level == qry_full) { // produce results if (king_id != NIL) { // success! smem_buffer_add_wme(thisAgent, meta_wmes, state->id->smem_result_header, thisAgent->smem_sym_success, query); if (negquery) { smem_buffer_add_wme(thisAgent, meta_wmes, state->id->smem_result_header, thisAgent->smem_sym_success, negquery); } //////////////////////////////////////////////////////////////////////////// thisAgent->smem_timers->query->stop(); //////////////////////////////////////////////////////////////////////////// smem_install_memory(thisAgent, state, king_id, NIL, (thisAgent->smem_params->activate_on_query->get_value() == on), meta_wmes, retrieval_wmes, install_type, depth); } else { smem_buffer_add_wme(thisAgent, meta_wmes, state->id->smem_result_header, thisAgent->smem_sym_failure, query); if (negquery) { smem_buffer_add_wme(thisAgent, meta_wmes, state->id->smem_result_header, thisAgent->smem_sym_failure, negquery); } //////////////////////////////////////////////////////////////////////////// thisAgent->smem_timers->query->stop(); //////////////////////////////////////////////////////////////////////////// } } else { //////////////////////////////////////////////////////////////////////////// thisAgent->smem_timers->query->stop(); //////////////////////////////////////////////////////////////////////////// } return king_id; } ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // Initialization (smem::init) ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// void smem_clear_result(agent* thisAgent, Symbol* state) { preference* pref; while (!state->id->smem_info->smem_wmes->empty()) { pref = state->id->smem_info->smem_wmes->back(); state->id->smem_info->smem_wmes->pop_back(); if (pref->in_tm) { remove_preference_from_tm(thisAgent, pref); } } } // performs cleanup when a state is removed void smem_reset(agent* thisAgent, Symbol* state) { if (state == NULL) { state = thisAgent->top_goal; } while (state) { smem_data* data = state->id->smem_info; data->last_cmd_time[0] = 0; data->last_cmd_time[1] = 0; data->last_cmd_count[0] = 0; data->last_cmd_count[1] = 0; // this will be called after prefs from goal are already removed, // so just clear out result stack data->smem_wmes->clear(); state = state->id->lower_goal; } } void smem_switch_to_memory_db(agent* thisAgent, std::string& buf) { print_sysparam_trace(thisAgent, 0, buf.c_str()); thisAgent->smem_db->disconnect(); thisAgent->smem_params->database->set_value(smem_param_container::memory); smem_init_db(thisAgent); } inline void smem_update_schema_one_to_two(agent* thisAgent) { thisAgent->smem_db->sql_execute("BEGIN TRANSACTION"); thisAgent->smem_db->sql_execute("CREATE TABLE smem_symbols_type (s_id INTEGER PRIMARY KEY,symbol_type INTEGER)"); thisAgent->smem_db->sql_execute("INSERT INTO smem_symbols_type (s_id, symbol_type) SELECT id, sym_type FROM smem7_symbols_type"); thisAgent->smem_db->sql_execute("DROP TABLE smem7_symbols_type"); thisAgent->smem_db->sql_execute("CREATE TABLE smem_symbols_string (s_id INTEGER PRIMARY KEY,symbol_value TEXT)"); thisAgent->smem_db->sql_execute("INSERT INTO smem_symbols_string (s_id, symbol_value) SELECT id, sym_const FROM smem7_symbols_str"); thisAgent->smem_db->sql_execute("DROP TABLE smem7_symbols_str"); thisAgent->smem_db->sql_execute("CREATE TABLE smem_symbols_integer (s_id INTEGER PRIMARY KEY,symbol_value INTEGER)"); thisAgent->smem_db->sql_execute("INSERT INTO smem_symbols_integer (s_id, symbol_value) SELECT id, sym_const FROM smem7_symbols_int"); thisAgent->smem_db->sql_execute("DROP TABLE smem7_symbols_int"); thisAgent->smem_db->sql_execute("CREATE TABLE smem_ascii (ascii_num INTEGER PRIMARY KEY,ascii_chr TEXT)"); thisAgent->smem_db->sql_execute("INSERT INTO smem_ascii (ascii_num, ascii_chr) SELECT ascii_num, ascii_num FROM smem7_ascii"); thisAgent->smem_db->sql_execute("DROP TABLE smem7_ascii"); thisAgent->smem_db->sql_execute("CREATE TABLE smem_symbols_float (s_id INTEGER PRIMARY KEY,symbol_value REAL)"); thisAgent->smem_db->sql_execute("INSERT INTO smem_symbols_float (s_id, symbol_value) SELECT id, sym_const FROM smem7_symbols_float"); thisAgent->smem_db->sql_execute("DROP TABLE smem7_symbols_float"); thisAgent->smem_db->sql_execute("CREATE TABLE smem_lti (lti_id INTEGER PRIMARY KEY,soar_letter INTEGER,soar_number INTEGER,total_augmentations INTEGER,activation_value REAL,activations_total INTEGER,activations_last INTEGER,activations_first INTEGER)"); thisAgent->smem_db->sql_execute("INSERT INTO smem_lti (lti_id, soar_letter, soar_number, total_augmentations, activation_value, activations_total, activations_last, activations_first) SELECT id, letter, num, child_ct, act_value, access_n, access_t, access_1 FROM smem7_lti"); thisAgent->smem_db->sql_execute("DROP TABLE smem7_lti"); thisAgent->smem_db->sql_execute("CREATE TABLE smem_activation_history (lti_id INTEGER PRIMARY KEY,t1 INTEGER,t2 INTEGER,t3 INTEGER,t4 INTEGER,t5 INTEGER,t6 INTEGER,t7 INTEGER,t8 INTEGER,t9 INTEGER,t10 INTEGER)"); thisAgent->smem_db->sql_execute("INSERT INTO smem_activation_history (lti_id, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10) SELECT id, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10 FROM smem7_history"); thisAgent->smem_db->sql_execute("DROP TABLE smem7_history"); thisAgent->smem_db->sql_execute("CREATE TABLE smem_augmentations (lti_id INTEGER,attribute_s_id INTEGER,value_constant_s_id INTEGER,value_lti_id INTEGER,activation_value REAL)"); thisAgent->smem_db->sql_execute("INSERT INTO smem_augmentations (lti_id, attribute_s_id, value_constant_s_id, value_lti_id, activation_value) SELECT parent_id, attr, val_const, val_lti, act_value FROM smem7_web"); thisAgent->smem_db->sql_execute("DROP TABLE smem7_web"); thisAgent->smem_db->sql_execute("CREATE TABLE smem_attribute_frequency (attribute_s_id INTEGER PRIMARY KEY,edge_frequency INTEGER)"); thisAgent->smem_db->sql_execute("INSERT INTO smem_attribute_frequency (attribute_s_id, edge_frequency) SELECT attr, ct FROM smem7_ct_attr"); thisAgent->smem_db->sql_execute("DROP TABLE smem7_ct_attr"); thisAgent->smem_db->sql_execute("CREATE TABLE smem_wmes_constant_frequency (attribute_s_id INTEGER,value_constant_s_id INTEGER,edge_frequency INTEGER)"); thisAgent->smem_db->sql_execute("INSERT INTO smem_wmes_constant_frequency (attribute_s_id, value_constant_s_id, edge_frequency) SELECT attr, val_const, ct FROM smem7_ct_const"); thisAgent->smem_db->sql_execute("DROP TABLE smem7_ct_const"); thisAgent->smem_db->sql_execute("CREATE TABLE smem_wmes_lti_frequency (attribute_s_id INTEGER,value_lti_id INTEGER,edge_frequency INTEGER)"); thisAgent->smem_db->sql_execute("INSERT INTO smem_wmes_lti_frequency (attribute_s_id, value_lti_id, edge_frequency) SELECT attr, val_lti, ct FROM smem7_ct_lti"); thisAgent->smem_db->sql_execute("DROP TABLE smem7_ct_lti"); thisAgent->smem_db->sql_execute("CREATE TABLE smem_persistent_variables (variable_id INTEGER PRIMARY KEY,variable_value INTEGER)"); thisAgent->smem_db->sql_execute("INSERT INTO smem_persistent_variables (variable_id, variable_value) SELECT id, value FROM smem7_vars"); thisAgent->smem_db->sql_execute("DROP TABLE smem7_vars"); thisAgent->smem_db->sql_execute("CREATE TABLE IF NOT EXISTS versions (system TEXT PRIMARY KEY,version_number TEXT)"); thisAgent->smem_db->sql_execute("INSERT INTO versions (system, version_number) VALUES ('smem_schema','2.0')"); thisAgent->smem_db->sql_execute("DROP TABLE smem7_signature"); thisAgent->smem_db->sql_execute("CREATE UNIQUE INDEX smem_symbols_int_const ON smem_symbols_integer (symbol_value)"); thisAgent->smem_db->sql_execute("CREATE UNIQUE INDEX smem_ct_lti_attr_val ON smem_wmes_lti_frequency (attribute_s_id, value_lti_id)"); thisAgent->smem_db->sql_execute("CREATE UNIQUE INDEX smem_symbols_float_const ON smem_symbols_float (symbol_value)"); thisAgent->smem_db->sql_execute("CREATE UNIQUE INDEX smem_symbols_str_const ON smem_symbols_string (symbol_value)"); thisAgent->smem_db->sql_execute("CREATE UNIQUE INDEX smem_lti_letter_num ON smem_lti (soar_letter,soar_number)"); thisAgent->smem_db->sql_execute("CREATE INDEX smem_lti_t ON smem_lti (activations_last)"); thisAgent->smem_db->sql_execute("CREATE INDEX smem_augmentations_parent_attr_val_lti ON smem_augmentations (lti_id, attribute_s_id, value_constant_s_id,value_lti_id)"); thisAgent->smem_db->sql_execute("CREATE INDEX smem_augmentations_attr_val_lti_cycle ON smem_augmentations (attribute_s_id, value_constant_s_id, value_lti_id, activation_value)"); thisAgent->smem_db->sql_execute("CREATE INDEX smem_augmentations_attr_cycle ON smem_augmentations (attribute_s_id, activation_value)"); thisAgent->smem_db->sql_execute("CREATE UNIQUE INDEX smem_wmes_constant_frequency_attr_val ON smem_wmes_constant_frequency (attribute_s_id, value_constant_s_id)"); thisAgent->smem_db->sql_execute("COMMIT"); } // opens the SQLite database and performs all initialization required for the current mode void smem_init_db(agent* thisAgent) { if (thisAgent->smem_db->get_status() != soar_module::disconnected) { return; } //////////////////////////////////////////////////////////////////////////// thisAgent->smem_timers->init->start(); //////////////////////////////////////////////////////////////////////////// const char* db_path; bool tabula_rasa = false; if (thisAgent->smem_params->database->get_value() == smem_param_container::memory) { db_path = ":memory:"; tabula_rasa = true; print_sysparam_trace(thisAgent, TRACE_SMEM_SYSPARAM, "Initializing semantic memory database in cpu memory.\n"); } else { db_path = thisAgent->smem_params->path->get_value(); print_sysparam_trace(thisAgent, TRACE_SMEM_SYSPARAM, "Initializing semantic memory memory database at %s\n", db_path); } // attempt connection thisAgent->smem_db->connect(db_path); if (thisAgent->smem_db->get_status() == soar_module::problem) { print_sysparam_trace(thisAgent, 0, "Semantic memory database Error: %s\n", thisAgent->smem_db->get_errmsg()); } else { // temporary queries for one-time init actions soar_module::sqlite_statement* temp_q = NULL; // If the database is on file, make sure the database contents use the current schema // If it does not, switch to memory-based database if (strcmp(db_path, ":memory:")) // Check if database mode is to a file { bool switch_to_memory, sql_is_new; std::string schema_version, version_error_message; /* -- Set switch_to_memory true in case we have any errors with the database -- */ switch_to_memory = true; if (thisAgent->smem_db->sql_is_new_db(sql_is_new)) { if (sql_is_new) { print_sysparam_trace(thisAgent, TRACE_SMEM_SYSPARAM, "...semantic memory database is new.\n"); switch_to_memory = false; tabula_rasa = true; } else { // Check if table exists already temp_q = new soar_module::sqlite_statement(thisAgent->smem_db, "CREATE TABLE IF NOT EXISTS versions (system TEXT PRIMARY KEY,version_number TEXT)"); temp_q->prepare(); if (temp_q->get_status() == soar_module::ready) { if (thisAgent->smem_db->sql_simple_get_string("SELECT version_number FROM versions WHERE system = 'smem_schema'", schema_version)) { if (schema_version != SMEM_SCHEMA_VERSION) { version_error_message.assign("...Error: Cannot load semantic memory database with schema version "); version_error_message.append(schema_version.c_str()); version_error_message.append(".\n...Please convert old semantic memory database or start a new database by " "setting a new database file path.\n...Switching to memory-based database.\n"); } else { print_sysparam_trace(thisAgent, TRACE_SMEM_SYSPARAM, "...version of semantic memory database ok.\n"); switch_to_memory = false; tabula_rasa = false; } } else { version_error_message.assign("...Error: Cannot read version number from file-based semantic memory database.\n"); if (smem_version_one(thisAgent)) { version_error_message.assign("...Version of semantic memory database is old.\n" "...Converting to version 2.0.\n"); smem_update_schema_one_to_two(thisAgent); switch_to_memory = false; tabula_rasa = false; delete temp_q; temp_q = NULL; } else { version_error_message.assign("...Switching to memory-based database.\n"); } } } else // Non-empty database exists with no version table. Probably schema 1.0 { if (smem_version_one(thisAgent)) { version_error_message.assign("...Version of semantic memory database is old.\n" "...Converting to version 2.0.\n"); smem_update_schema_one_to_two(thisAgent); switch_to_memory = false; tabula_rasa = false; delete temp_q; temp_q = NULL; } else { version_error_message.assign("...Error: Cannot load a semantic memory database with an old schema version.\n...Please convert " "old semantic memory database or start a new database by setting a new database file path.\n...Switching " "to memory-based database.\n"); } } delete temp_q; temp_q = NULL; } } else { version_error_message.assign("...Error: Cannot read database meta info from file-based semantic memory database.\n" "...Switching to memory-based database.\n"); } if (switch_to_memory) { // Memory mode will be set on, database will be disconnected to and then init_db // will be called again to reinitialize database. smem_switch_to_memory_db(thisAgent, version_error_message); return; } } // apply performance options { // page_size { switch (thisAgent->smem_params->page_size->get_value()) { case (smem_param_container::page_1k): thisAgent->smem_db->sql_execute("PRAGMA page_size = 1024"); break; case (smem_param_container::page_2k): thisAgent->smem_db->sql_execute("PRAGMA page_size = 2048"); break; case (smem_param_container::page_4k): thisAgent->smem_db->sql_execute("PRAGMA page_size = 4096"); break; case (smem_param_container::page_8k): thisAgent->smem_db->sql_execute("PRAGMA page_size = 8192"); break; case (smem_param_container::page_16k): thisAgent->smem_db->sql_execute("PRAGMA page_size = 16384"); break; case (smem_param_container::page_32k): thisAgent->smem_db->sql_execute("PRAGMA page_size = 32768"); break; case (smem_param_container::page_64k): thisAgent->smem_db->sql_execute("PRAGMA page_size = 65536"); break; } } // cache_size { std::string cache_sql("PRAGMA cache_size = "); char* str = thisAgent->smem_params->cache_size->get_string(); cache_sql.append(str); free(str); str = NULL; thisAgent->smem_db->sql_execute(cache_sql.c_str()); } // optimization if (thisAgent->smem_params->opt->get_value() == smem_param_container::opt_speed) { // synchronous - don't wait for writes to complete (can corrupt the db in case unexpected crash during transaction) thisAgent->smem_db->sql_execute("PRAGMA synchronous = OFF"); // journal_mode - no atomic transactions (can result in database corruption if crash during transaction) thisAgent->smem_db->sql_execute("PRAGMA journal_mode = OFF"); // locking_mode - no one else can view the database after our first write thisAgent->smem_db->sql_execute("PRAGMA locking_mode = EXCLUSIVE"); } } // update validation count thisAgent->smem_validation++; // setup common structures/queries thisAgent->smem_stmts = new smem_statement_container(thisAgent); if (tabula_rasa || (thisAgent->smem_params->append_db->get_value() == off)) { thisAgent->smem_stmts->structure(); } // initialize queries given database structure thisAgent->smem_stmts->prepare(); // initialize persistent variables if (tabula_rasa || (thisAgent->smem_params->append_db->get_value() == off)) { thisAgent->smem_stmts->begin->execute(soar_module::op_reinit); { // max cycle thisAgent->smem_max_cycle = static_cast<int64_t>(1); smem_variable_create(thisAgent, var_max_cycle, 1); // number of nodes thisAgent->smem_stats->chunks->set_value(0); smem_variable_create(thisAgent, var_num_nodes, 0); // number of edges thisAgent->smem_stats->slots->set_value(0); smem_variable_create(thisAgent, var_num_edges, 0); // threshold (from user parameter value) smem_variable_create(thisAgent, var_act_thresh, static_cast<int64_t>(thisAgent->smem_params->thresh->get_value())); // activation mode (from user parameter value) smem_variable_create(thisAgent, var_act_mode, static_cast<int64_t>(thisAgent->smem_params->activation_mode->get_value())); } thisAgent->smem_stmts->commit->execute(soar_module::op_reinit); } else { int64_t temp; // max cycle smem_variable_get(thisAgent, var_max_cycle, &(thisAgent->smem_max_cycle)); // number of nodes smem_variable_get(thisAgent, var_num_nodes, &(temp)); thisAgent->smem_stats->chunks->set_value(temp); // number of edges smem_variable_get(thisAgent, var_num_edges, &(temp)); thisAgent->smem_stats->slots->set_value(temp); // threshold smem_variable_get(thisAgent, var_act_thresh, &(temp)); thisAgent->smem_params->thresh->set_value(temp); // activation mode smem_variable_get(thisAgent, var_act_mode, &(temp)); thisAgent->smem_params->activation_mode->set_value(static_cast< smem_param_container::act_choices >(temp)); } // reset identifier counters smem_reset_id_counters(thisAgent); // if lazy commit, then we encapsulate the entire lifetime of the agent in a single transaction if (thisAgent->smem_params->lazy_commit->get_value() == on) { thisAgent->smem_stmts->begin->execute(soar_module::op_reinit); } } //////////////////////////////////////////////////////////////////////////// thisAgent->smem_timers->init->stop(); //////////////////////////////////////////////////////////////////////////// } void smem_attach(agent* thisAgent) { if (thisAgent->smem_db->get_status() == soar_module::disconnected) { smem_init_db(thisAgent); } } inline void _smem_close_vars(agent* thisAgent) { // store max cycle for future use of the smem database smem_variable_set(thisAgent, var_max_cycle, thisAgent->smem_max_cycle); // store num nodes/edges for future use of the smem database smem_variable_set(thisAgent, var_num_nodes, thisAgent->smem_stats->chunks->get_value()); smem_variable_set(thisAgent, var_num_edges, thisAgent->smem_stats->slots->get_value()); } // performs cleanup operations when the database needs to be closed (end soar, manual close, etc) void smem_close(agent* thisAgent) { if (thisAgent->smem_db->get_status() == soar_module::connected) { _smem_close_vars(thisAgent); // if lazy, commit if (thisAgent->smem_params->lazy_commit->get_value() == on) { thisAgent->smem_stmts->commit->execute(soar_module::op_reinit); } // de-allocate common statements delete thisAgent->smem_stmts; delete thisAgent->lastCue; // close the database thisAgent->smem_db->disconnect(); } } void smem_reinit_cmd(agent* thisAgent) { smem_close(thisAgent); // smem_init_db(thisAgent); } void smem_reinit(agent* thisAgent) { if (thisAgent->smem_db->get_status() == soar_module::connected) { if (thisAgent->smem_params->append_db->get_value() == off) { smem_close(thisAgent); smem_init_db(thisAgent); } } } ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // Parsing (smem::parse) ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// void smem_deallocate_chunk(agent* thisAgent, smem_chunk* chunk, bool free_chunk = true) { if (chunk) { // proceed to slots if (chunk->slots) { smem_slot_map::iterator s; smem_slot::iterator v; // iterate over slots while (!chunk->slots->empty()) { s = chunk->slots->begin(); // proceed to slot contents if (s->second) { // iterate over each value for (v = s->second->begin(); v != s->second->end(); v = s->second->erase(v)) { // de-allocation of value is dependent upon type if ((*v)->val_const.val_type == value_const_t) { symbol_remove_ref(thisAgent, (*v)->val_const.val_value); } else { // we never deallocate the lti chunk, as we assume // it will exist elsewhere for deallocation // delete (*s)->val_lti.val_value; } delete(*v); } delete s->second; } // deallocate attribute for each corresponding value symbol_remove_ref(thisAgent, s->first); chunk->slots->erase(s); } // remove slots delete chunk->slots; chunk->slots = NULL; } // remove chunk itself if (free_chunk) { delete chunk; chunk = NULL; } } } inline std::string* smem_parse_lti_name(agent* thisAgent, soar::Lexeme* lexeme, char* id_letter, uint64_t* id_number) { std::string* return_val = new std::string; if ((*lexeme).type == IDENTIFIER_LEXEME) { std::string soar_number; to_string((*lexeme).id_number, soar_number); return_val->append(1, (*lexeme).id_letter); return_val->append(soar_number); (*id_letter) = (*lexeme).id_letter; (*id_number) = (*lexeme).id_number; char counter_index = (*id_letter - static_cast<char>('A')); if (*id_number >= thisAgent->id_counter[counter_index]) { thisAgent->id_counter[counter_index] = *id_number + 1; } } else { return_val->assign((*lexeme).string()); (*id_letter) = static_cast<char>(toupper((*lexeme).string()[1])); (*id_number) = 0; } return return_val; } inline Symbol* smem_parse_constant_attr(agent* thisAgent, soar::Lexeme* lexeme) { Symbol* return_val = NIL; if ((*lexeme).type == STR_CONSTANT_LEXEME) { return_val = make_str_constant(thisAgent, static_cast<const char*>((*lexeme).string())); } else if ((*lexeme).type == INT_CONSTANT_LEXEME) { return_val = make_int_constant(thisAgent, (*lexeme).int_val); } else if ((*lexeme).type == FLOAT_CONSTANT_LEXEME) { return_val = make_float_constant(thisAgent, (*lexeme).float_val); } return return_val; } bool smem_parse_chunk(agent* thisAgent, soar::Lexer* lexer, smem_str_to_chunk_map* chunks, smem_chunk_set* newbies) { bool return_val = false; smem_chunk* new_chunk = new smem_chunk; new_chunk->slots = NULL; std::string* chunk_name = NULL; char temp_letter; uint64_t temp_number; bool good_at; // consume left paren lexer->get_lexeme(); if ((lexer->current_lexeme.type == AT_LEXEME) || (lexer->current_lexeme.type == IDENTIFIER_LEXEME) || (lexer->current_lexeme.type == VARIABLE_LEXEME)) { good_at = true; if (lexer->current_lexeme.type == AT_LEXEME) { lexer->get_lexeme(); good_at = (lexer->current_lexeme.type == IDENTIFIER_LEXEME); } if (good_at) { // save identifier chunk_name = smem_parse_lti_name(thisAgent, &(lexer->current_lexeme), &(temp_letter), &(temp_number)); new_chunk->lti_letter = temp_letter; new_chunk->lti_number = temp_number; new_chunk->lti_id = NIL; new_chunk->soar_id = NIL; new_chunk->slots = new smem_slot_map; // consume id lexer->get_lexeme(); // uint64_t intermediate_counter = 1; smem_chunk* intermediate_parent; smem_chunk* temp_chunk; std::string temp_key; std::string* temp_key2; Symbol* chunk_attr; smem_chunk_value* chunk_value; smem_slot* s; // populate slots while (lexer->current_lexeme.type == UP_ARROW_LEXEME) { intermediate_parent = new_chunk; // go on to attribute lexer->get_lexeme(); // get the appropriate constant type chunk_attr = smem_parse_constant_attr(thisAgent, &(lexer->current_lexeme)); // if constant attribute, proceed to value if (chunk_attr != NIL) { // consume attribute lexer->get_lexeme(); // support for dot notation: // when we encounter a dot, instantiate // the previous attribute as a temporary // identifier and use that as the parent while (lexer->current_lexeme.type == PERIOD_LEXEME) { // create a new chunk temp_chunk = new smem_chunk; temp_chunk->lti_letter = ((chunk_attr->symbol_type == STR_CONSTANT_SYMBOL_TYPE) ? (static_cast<char>(static_cast<int>(chunk_attr->sc->name[0]))) : ('X')); temp_chunk->lti_number = (intermediate_counter++); temp_chunk->lti_id = NIL; temp_chunk->slots = new smem_slot_map; temp_chunk->soar_id = NIL; // add it as a child to the current parent chunk_value = new smem_chunk_value; chunk_value->val_lti.val_type = value_lti_t; chunk_value->val_lti.val_value = temp_chunk; s = smem_make_slot(intermediate_parent->slots, chunk_attr); s->push_back(chunk_value); // create a key guaranteed to be unique std::string temp_key3; to_string(temp_chunk->lti_number, temp_key3); temp_key.assign("<"); temp_key.append(1, temp_chunk->lti_letter); temp_key.append("#"); temp_key.append(temp_key3); temp_key.append(">"); // insert the new chunk (*chunks)[ temp_key ] = temp_chunk; // definitely a new chunk newbies->insert(temp_chunk); // the new chunk is our parent for this set of values (or further dots) intermediate_parent = temp_chunk; temp_chunk = NULL; // get the next attribute lexer->get_lexeme(); chunk_attr = smem_parse_constant_attr(thisAgent, &(lexer->current_lexeme)); // consume attribute lexer->get_lexeme(); } if (chunk_attr != NIL) { bool first_value = true; do { // value by type chunk_value = NIL; if (lexer->current_lexeme.type == STR_CONSTANT_LEXEME) { chunk_value = new smem_chunk_value; chunk_value->val_const.val_type = value_const_t; chunk_value->val_const.val_value = make_str_constant(thisAgent, static_cast<const char*>(lexer->current_lexeme.string())); } else if (lexer->current_lexeme.type == INT_CONSTANT_LEXEME) { chunk_value = new smem_chunk_value; chunk_value->val_const.val_type = value_const_t; chunk_value->val_const.val_value = make_int_constant(thisAgent, lexer->current_lexeme.int_val); } else if (lexer->current_lexeme.type == FLOAT_CONSTANT_LEXEME) { chunk_value = new smem_chunk_value; chunk_value->val_const.val_type = value_const_t; chunk_value->val_const.val_value = make_float_constant(thisAgent, lexer->current_lexeme.float_val); } else if ((lexer->current_lexeme.type == AT_LEXEME) || (lexer->current_lexeme.type == IDENTIFIER_LEXEME) || (lexer->current_lexeme.type == VARIABLE_LEXEME)) { good_at = true; if (lexer->current_lexeme.type == AT_LEXEME) { lexer->get_lexeme(); good_at = (lexer->current_lexeme.type == IDENTIFIER_LEXEME); } if (good_at) { // create new value chunk_value = new smem_chunk_value; chunk_value->val_lti.val_type = value_lti_t; // get key temp_key2 = smem_parse_lti_name(thisAgent, &(lexer->current_lexeme), &(temp_letter), &(temp_number)); // search for an existing chunk smem_str_to_chunk_map::iterator p = chunks->find((*temp_key2)); // if exists, point; else create new if (p != chunks->end()) { chunk_value->val_lti.val_value = p->second; } else { // create new chunk temp_chunk = new smem_chunk; temp_chunk->lti_id = NIL; temp_chunk->lti_letter = temp_letter; temp_chunk->lti_number = temp_number; temp_chunk->lti_id = NIL; temp_chunk->slots = NIL; temp_chunk->soar_id = NIL; // associate with value chunk_value->val_lti.val_value = temp_chunk; // add to chunks (*chunks)[(*temp_key2) ] = temp_chunk; // possibly a newbie (could be a self-loop) newbies->insert(temp_chunk); } delete temp_key2; } } if (chunk_value != NIL) { // consume lexer->get_lexeme(); // add to appropriate slot s = smem_make_slot(intermediate_parent->slots, chunk_attr); if (first_value && !s->empty()) { // in the case of a repeated attribute, remove ref here to avoid leak symbol_remove_ref(thisAgent, chunk_attr); } s->push_back(chunk_value); // if this was the last attribute if (lexer->current_lexeme.type == R_PAREN_LEXEME) { return_val = true; lexer->get_lexeme(); chunk_value = NIL; } first_value = false; } } while (chunk_value != NIL); } } } } else { delete new_chunk; } } else { delete new_chunk; } if (return_val) { // search for an existing chunk (occurs if value comes before id) smem_chunk** p = & (*chunks)[(*chunk_name) ]; if (!(*p)) { (*p) = new_chunk; // a newbie! newbies->insert(new_chunk); } else { // transfer slots if (!(*p)->slots) { // if none previously, can just use (*p)->slots = new_chunk->slots; new_chunk->slots = NULL; } else { // otherwise, copy smem_slot_map::iterator ss_p; smem_slot::iterator s_p; smem_slot* source_slot; smem_slot* target_slot; // for all slots for (ss_p = new_chunk->slots->begin(); ss_p != new_chunk->slots->end(); ss_p++) { target_slot = smem_make_slot((*p)->slots, ss_p->first); source_slot = ss_p->second; // for all values in the slot for (s_p = source_slot->begin(); s_p != source_slot->end(); s_p++) { // copy each value target_slot->push_back((*s_p)); } // once copied, we no longer need the slot delete source_slot; } // we no longer need the slots delete new_chunk->slots; new_chunk->slots = NULL; } // contents are new newbies->insert((*p)); // deallocate smem_deallocate_chunk(thisAgent, new_chunk); } } else { newbies->clear(); } // de-allocate id name if (chunk_name) { delete chunk_name; } return return_val; } bool smem_parse_chunks(agent* thisAgent, const char* chunks_str, std::string** err_msg) { bool return_val = false; uint64_t clause_count = 0; // parsing chunks requires an open semantic database smem_attach(thisAgent); soar::Lexer lexer(thisAgent, chunks_str); bool good_chunk = true; smem_str_to_chunk_map chunks; smem_str_to_chunk_map::iterator c_old; smem_chunk_set newbies; smem_chunk_set::iterator c_new; // consume next token lexer.get_lexeme(); if (lexer.current_lexeme.type != L_PAREN_LEXEME) { good_chunk = false; } // while there are chunks to consume while ((lexer.current_lexeme.type == L_PAREN_LEXEME) && (good_chunk)) { good_chunk = smem_parse_chunk(thisAgent, &lexer, &(chunks), &(newbies)); if (good_chunk) { // add all newbie lti's as appropriate for (c_new = newbies.begin(); c_new != newbies.end(); c_new++) { if ((*c_new)->lti_id == NIL) { // deal differently with variable vs. lti if ((*c_new)->lti_number == NIL) { // add a new lti id (we have a guarantee this won't be in Soar's WM) (*c_new)->lti_number = (thisAgent->id_counter[(*c_new)->lti_letter - static_cast<char>('A') ]++); (*c_new)->lti_id = smem_lti_add_id(thisAgent, (*c_new)->lti_letter, (*c_new)->lti_number); } else { // should ALWAYS be the case (it's a newbie and we've initialized lti_id to NIL) if ((*c_new)->lti_id == NIL) { // get existing (*c_new)->lti_id = smem_lti_get_id(thisAgent, (*c_new)->lti_letter, (*c_new)->lti_number); // if doesn't exist, add it if ((*c_new)->lti_id == NIL) { (*c_new)->lti_id = smem_lti_add_id(thisAgent, (*c_new)->lti_letter, (*c_new)->lti_number); // this could affect an existing identifier in Soar's WM Symbol* id_parent = find_identifier(thisAgent, (*c_new)->lti_letter, (*c_new)->lti_number); if (id_parent != NIL) { // if so we make it an lti manually id_parent->id->smem_lti = (*c_new)->lti_id; id_parent->id->smem_time_id = thisAgent->epmem_stats->time->get_value(); id_parent->id->smem_valid = thisAgent->epmem_validation; epmem_schedule_promotion(thisAgent, id_parent); } } } } } } // add all newbie contents (append, as opposed to replace, children) for (c_new = newbies.begin(); c_new != newbies.end(); c_new++) { if ((*c_new)->slots != NIL) { smem_store_chunk(thisAgent, (*c_new)->lti_id, (*c_new)->slots, false); } } // deallocate *contents* of all newbies (need to keep around name->id association for future chunks) for (c_new = newbies.begin(); c_new != newbies.end(); c_new++) { smem_deallocate_chunk(thisAgent, (*c_new), false); } // increment clause counter clause_count++; // clear newbie list newbies.clear(); } }; return_val = good_chunk; // deallocate all chunks { for (c_old = chunks.begin(); c_old != chunks.end(); c_old++) { smem_deallocate_chunk(thisAgent, c_old->second, true); } } // produce error message on failure if (!return_val) { std::string num; to_string(clause_count, num); (*err_msg)->append("Error parsing clause #"); (*err_msg)->append(num); } return return_val; } /* The following function is supposed to read in the lexemes * and turn them into the cue wme for a call to smem_process_query. * This is intended to be run from the command line and does not yet have * full functionality. It doesn't work with mathqueries, for example. * This is for debugging purposes. * -Steven 23-7-2014 */ bool smem_parse_cues(agent* thisAgent, const char* chunks_str, std::string** err_msg, std::string** result_message, uint64_t number_to_retrieve) { uint64_t clause_count = 0; // This is counting up the number of parsed clauses // so that there is a pointer to a failure location. //Parsing requires an open semantic database. smem_attach(thisAgent); soar::Lexer lexer(thisAgent, chunks_str); bool good_cue = true; // This is a success or failure flag that will be checked periodically // and indicates whether or not we can call smem_process_query. std::map<std::string, Symbol*> cue_ids; //I want to keep track of previous references when adding a new element to the cue. //consume next token. lexer.get_lexeme(); good_cue = lexer.current_lexeme.type == L_PAREN_LEXEME; Symbol* root_cue_id = NIL; //This is the id that gets passed to smem_process_query. //It's main purpose is to contain augmentations Symbol* negative_cues = NULL; //This is supposed to contain the negative augmentations. bool trigger_first = true; //Just for managing my loop. bool minus_ever = false; //Did a negative cue ever show up? bool first_attribute = true; //Want to make sure there is a positive attribute to begin with. // While there is parsing to be done: while ((lexer.current_lexeme.type == L_PAREN_LEXEME) && good_cue) { //First, consume the left paren. lexer.get_lexeme(); if (trigger_first) { good_cue = lexer.current_lexeme.type == VARIABLE_LEXEME; if (good_cue) { root_cue_id = make_new_identifier(thisAgent, (char) lexer.current_lexeme.string()[1], 1); cue_ids[lexer.current_lexeme.string()] = root_cue_id; negative_cues = make_new_identifier(thisAgent, (char) lexer.current_lexeme.string()[1], 1); } else { (*err_msg)->append("Error: The cue must be a variable.\n");//Spit out that the cue must be a variable. break; } trigger_first = false; } else { //If this isn't the first time around, then this better be the same as the root_cue_id variable. good_cue = cue_ids[lexer.current_lexeme.string()] == root_cue_id; if (!good_cue) { (*err_msg)->append("Error: Additional clauses must share same variable.\n");//Spit out that additional clauses must share the same variable as the original cue variable. break; } } if (good_cue) { //Consume the root_cue_id lexer.get_lexeme(); Symbol* attribute; slot* temp_slot; //Now, we process the attributes of the cue id contained in this clause. bool minus = false; //Loop as long as positive or negative cues keep popping up. while (good_cue && (lexer.current_lexeme.type == UP_ARROW_LEXEME || lexer.current_lexeme.type == MINUS_LEXEME)) { if (lexer.current_lexeme.type == MINUS_LEXEME) { minus_ever = true; if (first_attribute) { good_cue = false; break; } lexer.get_lexeme(); good_cue = lexer.current_lexeme.type == UP_ARROW_LEXEME; minus = true; } else { minus = false; } lexer.get_lexeme();//Consume the up arrow and move on to the attribute. if (lexer.current_lexeme.type == VARIABLE_LEXEME) { //SMem doesn't suppose variable attributes ... YET. good_cue = false; break; } // TODO: test to make sure this is good. Previously there was no test // for the type of the lexeme so passing a "(" caused a segfault when making the slot. attribute = smem_parse_constant_attr(thisAgent, &(lexer.current_lexeme)); if (attribute == NIL) { good_cue = false; break; } Symbol* value; wme* temp_wme; if (minus) { temp_slot = make_slot(thisAgent, negative_cues, attribute); } else { temp_slot = make_slot(thisAgent, root_cue_id, attribute); //Make a slot for this attribute, or return slot it already has. } //consume the attribute. lexer.get_lexeme(); bool hasAddedValue = false; do //Add value by type { value = NIL; if (lexer.current_lexeme.type == STR_CONSTANT_LEXEME) { value = make_str_constant(thisAgent, static_cast<const char*>(lexer.current_lexeme.string())); lexer.get_lexeme(); } else if (lexer.current_lexeme.type == INT_CONSTANT_LEXEME) { value = make_int_constant(thisAgent, lexer.current_lexeme.int_val); lexer.get_lexeme(); } else if (lexer.current_lexeme.type == FLOAT_CONSTANT_LEXEME) { value = make_float_constant(thisAgent, lexer.current_lexeme.float_val); lexer.get_lexeme(); } else if (lexer.current_lexeme.type == AT_LEXEME) { //If the LTI isn't recognized, then it cannot be a good cue. lexer.get_lexeme(); smem_lti_id value_id = smem_lti_get_id(thisAgent, lexer.current_lexeme.id_letter, lexer.current_lexeme.id_number); if (value_id == NIL) { good_cue = false; (*err_msg)->append("Error: LTI was not found.\n"); break; } else { value = smem_lti_soar_make(thisAgent, value_id, lexer.current_lexeme.id_letter, lexer.current_lexeme.id_number, SMEM_LTI_UNKNOWN_LEVEL); } lexer.get_lexeme(); } else if (lexer.current_lexeme.type == VARIABLE_LEXEME || lexer.current_lexeme.type == IDENTIFIER_LEXEME) { std::map<std::basic_string<char>, Symbol*>::iterator value_iterator; value_iterator = cue_ids.find(lexer.current_lexeme.string()); if (value_iterator == cue_ids.end()) { value = make_new_identifier(thisAgent, (char) lexer.current_lexeme.string()[0], 1); cue_ids[lexer.current_lexeme.string()] = value; //Keep track of created symbols for deletion later. } lexer.get_lexeme(); } else { if (((lexer.current_lexeme.type == R_PAREN_LEXEME || lexer.current_lexeme.type == UP_ARROW_LEXEME) || lexer.current_lexeme.type == MINUS_LEXEME) && hasAddedValue) { //good_cue = true; break; } else { good_cue = false; break; } } if (value != NIL && good_cue) { //Value might be nil, but R_paren or next attribute could make it a good cue. hasAddedValue = true; if (minus) { temp_wme = make_wme(thisAgent, negative_cues, attribute, value, false); } else { temp_wme = make_wme(thisAgent, root_cue_id, attribute, value, false); } insert_at_head_of_dll(temp_slot->wmes, temp_wme, next, prev); //Put the wme in the slow for the attribute. } } while (value != NIL); //Loop until there are no more value lexemes to add to that attribute. first_attribute = false; } } else { break; } while (lexer.current_lexeme.type == R_PAREN_LEXEME) { lexer.get_lexeme(); } clause_count++; trigger_first = false; //It is no longer the first clause. } if (!good_cue) { std::string num; to_string(clause_count, num); (*err_msg)->append("Error parsing clause #"); (*err_msg)->append(num + "."); } else { smem_lti_set* prohibit = new smem_lti_set; wme_set cue_wmes; symbol_triple_list meta_wmes; symbol_triple_list retrieval_wmes; (*result_message) = new std::string(); std::list<smem_lti_id> match_ids; smem_process_query(thisAgent, NIL, root_cue_id, minus_ever ? negative_cues : NIL, NIL, prohibit, cue_wmes, meta_wmes, retrieval_wmes, qry_search, number_to_retrieve, &(match_ids), 1, fake_install); if (!match_ids.empty()) { for (std::list<smem_lti_id>::const_iterator id = match_ids.begin(), end = match_ids.end(); id != end; ++id) { smem_print_lti(thisAgent, (*id), 1, *result_message); //"1" is the depth. } } else { (*result_message)->append("SMem| No results for query."); } delete prohibit; } /* * Below is the clean-up */ if (root_cue_id != NIL) { slot* s; for (s = root_cue_id->id->slots; s != NIL; s = s->next) { //Remove all wme's from the slot. wme* delete_wme; for (delete_wme = s->wmes; delete_wme != NIL; delete_wme = delete_wme->next) { symbol_remove_ref(thisAgent, delete_wme->value); deallocate_wme(thisAgent, delete_wme); } s->wmes = NIL; symbol_remove_ref(thisAgent, s->attr); mark_slot_for_possible_removal(thisAgent, s); }//End of for-slots loop. root_cue_id->id->slots = NIL; for (s = negative_cues->id->slots; s != NIL; s = s->next) { //Remove all wme's from the slot. wme* delete_wme; for (delete_wme = s->wmes; delete_wme != NIL; delete_wme = delete_wme->next) { symbol_remove_ref(thisAgent, delete_wme->value); deallocate_wme(thisAgent, delete_wme); } s->wmes = NIL; symbol_remove_ref(thisAgent, s->attr); mark_slot_for_possible_removal(thisAgent, s); }//End of for-slots loop. negative_cues->id->slots = NIL; symbol_remove_ref(thisAgent, root_cue_id);//gets rid of cue id. symbol_remove_ref(thisAgent, negative_cues);//gets rid of negative cues id. } return good_cue; } void initialize_smem_chunk_value_lti(smem_chunk_value_lti& lti) { lti.val_type = smem_cue_element_type_none; lti.val_value = NULL; } void initialize_smem_chunk_value_constant(smem_chunk_value_constant& constant) { constant.val_type = smem_cue_element_type_none; constant.val_value = NULL; } /* * This is intended to allow the user to remove part or all of information stored on a LTI. * (All attributes, selected attributes, or just values from particular attributes.) */ bool smem_parse_remove(agent* thisAgent, const char* chunks_str, std::string** err_msg, std::string** result_message, bool force) { //TODO: need to fix so that err_msg and result_message are actually used or not passed. bool good_command = true; //parsing chunks requires an open semantic database smem_attach(thisAgent); soar::Lexer lexer(thisAgent, chunks_str); lexer.get_lexeme(); if (lexer.current_lexeme.type == L_PAREN_LEXEME) { lexer.get_lexeme();//Consumes the left paren } if (lexer.current_lexeme.type == AT_LEXEME && good_command) { lexer.get_lexeme(); } good_command = lexer.current_lexeme.type == IDENTIFIER_LEXEME; smem_lti_id lti_id = 0; if (good_command) { lti_id = smem_lti_get_id(thisAgent, lexer.current_lexeme.id_letter, lexer.current_lexeme.id_number); } else { (*err_msg)->append("Error: No LTI found for that letter and number.\n"); } symbol_triple_list retrieval_wmes; symbol_triple_list meta_wmes; if (good_command && lti_id != NIL) { Symbol* lti = smem_lti_soar_make(thisAgent, lti_id, lexer.current_lexeme.id_letter, lexer.current_lexeme.id_number, SMEM_LTI_UNKNOWN_LEVEL); lexer.get_lexeme();//Consume the identifier. smem_slot_map children; if (lexer.current_lexeme.type == UP_ARROW_LEXEME) { //Now that we know we have a good lti, we can do a NCBR so that we know what attributes and values we can delete. //"--force" will ignore attempts to delete that which isn't there, while the default will be to stop and report back. smem_install_memory(thisAgent, NIL, lti_id, lti, false, meta_wmes, retrieval_wmes, fake_install); //First, we'll create the slot_map according to retrieval_wmes, then we'll remove what we encounter during parsing. symbol_triple_list::iterator triple_ptr_iter; smem_slot* temp_slot; for (triple_ptr_iter = retrieval_wmes.begin(); triple_ptr_iter != retrieval_wmes.end(); triple_ptr_iter++) { if (children.count((*triple_ptr_iter)->attr)) //If the attribute is already in the map. { temp_slot = (children.find((*triple_ptr_iter)->attr)->second); smem_chunk_value* temp_val = new smem_chunk_value; if ((*triple_ptr_iter)->value->symbol_type == IDENTIFIER_SYMBOL_TYPE) { //If the chunk was retrieved and it is an identifier it is lti. smem_chunk_value_lti temp_lti; smem_chunk_value_constant temp_const; initialize_smem_chunk_value_lti(temp_lti); initialize_smem_chunk_value_constant(temp_const); temp_val->val_const = temp_const; temp_val->val_const.val_type = value_lti_t; temp_val->val_lti = temp_lti; temp_val->val_lti.val_type = value_lti_t; smem_chunk* temp_chunk = new smem_chunk; temp_chunk->lti_id = (*triple_ptr_iter)->value->id->smem_lti; temp_chunk->lti_letter = (*triple_ptr_iter)->value->id->name_letter; temp_chunk->lti_number = (*triple_ptr_iter)->value->id->name_number; temp_chunk->soar_id = (*triple_ptr_iter)->value; temp_val->val_lti.val_value = temp_chunk; } else //If the value is not an identifier, then it is a "constant". { smem_chunk_value_constant temp_const; smem_chunk_value_lti temp_lti; initialize_smem_chunk_value_lti(temp_lti); initialize_smem_chunk_value_constant(temp_const); temp_val->val_lti = temp_lti; temp_val->val_lti.val_type = value_const_t; temp_val->val_const.val_type = value_const_t; temp_val->val_const.val_value = (*triple_ptr_iter)->value; } (*temp_slot).push_back(temp_val); } else //If the attribute is not in the map and we need to make a slot. { temp_slot = new smem_slot; smem_chunk_value* temp_val = new smem_chunk_value; if ((*triple_ptr_iter)->value->symbol_type == IDENTIFIER_SYMBOL_TYPE) { //If the chunk was retrieved and it is an identifier it is lti. smem_chunk_value_lti temp_lti; smem_chunk_value_constant temp_const; initialize_smem_chunk_value_lti(temp_lti); initialize_smem_chunk_value_constant(temp_const); temp_val->val_const = temp_const; temp_val->val_const.val_type = value_lti_t; temp_val->val_lti = temp_lti; temp_val->val_lti.val_type = value_lti_t; smem_chunk* temp_chunk = new smem_chunk; temp_chunk->lti_id = (*triple_ptr_iter)->value->id->smem_lti; temp_chunk->lti_letter = (*triple_ptr_iter)->value->id->name_letter; temp_chunk->lti_number = (*triple_ptr_iter)->value->id->name_number; temp_chunk->soar_id = (*triple_ptr_iter)->value; temp_val->val_lti.val_value = temp_chunk; } else //If the value is nt an identifier, then it is a "constant". { smem_chunk_value_constant temp_const; smem_chunk_value_lti temp_lti; initialize_smem_chunk_value_lti(temp_lti); initialize_smem_chunk_value_constant(temp_const); temp_val->val_lti = temp_lti; temp_val->val_lti.val_type = value_const_t; temp_val->val_const.val_type = value_const_t; temp_val->val_const.val_value = (*triple_ptr_iter)->value; } (*temp_slot).push_back(temp_val); children[(*triple_ptr_iter)->attr] = temp_slot; } } //Now we process attributes one at a time. while (lexer.current_lexeme.type == UP_ARROW_LEXEME && (good_command || force)) { lexer.get_lexeme();// Consume the up arrow. Symbol* attribute = NIL; if (lexer.current_lexeme.type == STR_CONSTANT_LEXEME) { attribute = find_str_constant(thisAgent, static_cast<const char*>(lexer.current_lexeme.string())); } else if (lexer.current_lexeme.type == INT_CONSTANT_LEXEME) { attribute = find_int_constant(thisAgent, lexer.current_lexeme.int_val); } else if (lexer.current_lexeme.type == FLOAT_CONSTANT_LEXEME) { attribute = find_float_constant(thisAgent, lexer.current_lexeme.float_val); } if (attribute == NIL) { good_command = false; (*err_msg)->append("Error: Attribute was not found.\n"); } else { lexer.get_lexeme();//Consume the attribute. good_command = true; } if (good_command && (lexer.current_lexeme.type != UP_ARROW_LEXEME && lexer.current_lexeme.type != R_PAREN_LEXEME)) //If there are values. { Symbol* value; do //Add value by type { value = NIL; if (lexer.current_lexeme.type == STR_CONSTANT_LEXEME) { value = find_str_constant(thisAgent, static_cast<const char*>(lexer.current_lexeme.string())); lexer.get_lexeme(); } else if (lexer.current_lexeme.type == INT_CONSTANT_LEXEME) { value = find_int_constant(thisAgent, lexer.current_lexeme.int_val); lexer.get_lexeme(); } else if (lexer.current_lexeme.type == FLOAT_CONSTANT_LEXEME) { value = find_float_constant(thisAgent, lexer.current_lexeme.float_val); lexer.get_lexeme(); } else if (lexer.current_lexeme.type == AT_LEXEME) { lexer.get_lexeme(); if (lexer.current_lexeme.type == IDENTIFIER_LEXEME) { value = find_identifier(thisAgent, lexer.current_lexeme.id_letter, lexer.current_lexeme.id_number); lexer.get_lexeme(); } else { (*err_msg)->append("Error: '@' should be followed by an identifier.\n"); good_command = false; break; } } else { good_command = (lexer.current_lexeme.type == R_PAREN_LEXEME || lexer.current_lexeme.type == UP_ARROW_LEXEME); if (!good_command) { (*err_msg)->append("Error: Expected ')' or '^'.\n... The value was likely not found.\n"); } } if (value != NIL && good_command) //Value might be nil, but that can be just fine. { //Given a value for this attribute, we have a symbol triple to remove. smem_slot::iterator values; for (values = (children.find(attribute))->second->begin(); values != (children.find(attribute))->second->end(); values++) { if (value->symbol_type == IDENTIFIER_SYMBOL_TYPE && (*values)->val_lti.val_type == value_lti_t) { if ((*values)->val_lti.val_value->soar_id == value) { delete(*values)->val_lti.val_value; delete *values; (*(children.find(attribute))).second->erase(values); break; } } else if (value->symbol_type != IDENTIFIER_SYMBOL_TYPE && (*values)->val_const.val_type == value_const_t) { if ((*values)->val_const.val_value == value) { delete *values; (*(children.find(attribute))).second->erase(values); break; } } } if (values == (children.find(attribute))->second->end()) { (*err_msg)->append("Error: Value does not exist on attribute.\n"); } } else { if ((good_command && !force) && (lexer.current_lexeme.type != R_PAREN_LEXEME && lexer.current_lexeme.type != UP_ARROW_LEXEME)) { (*err_msg)->append("Error: Attribute contained a value that could not be found.\n"); break; } } } while (good_command && (value != NIL || !(lexer.current_lexeme.type == R_PAREN_LEXEME || lexer.current_lexeme.type == UP_ARROW_LEXEME))); } else if (good_command && children.find(attribute) != children.end()) //If we didn't have any values, then we just get rid of everything on the attribute. { smem_slot* result = (children.find(attribute))->second; smem_slot::iterator values, end = result->end(); for (values = (children.find(attribute))->second->begin(); values != end; values++) { delete *values; } children.erase(attribute); } if (force) { while ((lexer.current_lexeme.type != EOF_LEXEME && lexer.current_lexeme.type != UP_ARROW_LEXEME) && lexer.current_lexeme.type != R_PAREN_LEXEME) //Loop until the lexeme is EOF, another ^, or ")". { lexer.get_lexeme(); } } } } if (good_command && lexer.current_lexeme.type == R_PAREN_LEXEME) { smem_store_chunk(thisAgent, lti_id, &(children), true, NULL, false); } else if (good_command) { (*err_msg)->append("Error: Expected a ')'.\n"); } //Clean up. smem_slot_map::iterator attributes, end = children.end(); for (attributes = children.begin(); attributes != end; attributes++) { smem_slot* result = (children.find(attributes->first))->second; smem_slot::iterator values, end = result->end(); for (values = result->begin(); values != end; values++) { if ((*values)->val_lti.val_type == value_lti_t) { delete(*values)->val_lti.val_value; } delete *values; } delete attributes->second; } symbol_triple_list::iterator triple_iterator, end2 = retrieval_wmes.end(); for (triple_iterator = retrieval_wmes.begin(); triple_iterator != end2; triple_iterator++) { symbol_remove_ref(thisAgent, (*triple_iterator)->id); symbol_remove_ref(thisAgent, (*triple_iterator)->attr); symbol_remove_ref(thisAgent, (*triple_iterator)->value); delete *triple_iterator; } symbol_remove_ref(thisAgent, lti); } return good_command; } ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // API Implementation (smem::api) ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// void smem_respond_to_cmd(agent* thisAgent, bool store_only) { smem_attach(thisAgent); // start at the bottom and work our way up // (could go in the opposite direction as well) Symbol* state = thisAgent->bottom_goal; smem_wme_list* wmes; smem_wme_list* cmds; smem_wme_list::iterator w_p; symbol_triple_list meta_wmes; symbol_triple_list retrieval_wmes; wme_set cue_wmes; Symbol* query; Symbol* negquery; Symbol* retrieve; Symbol* math; uint64_t depth; smem_sym_list prohibit; smem_sym_list store; enum path_type { blank_slate, cmd_bad, cmd_retrieve, cmd_query, cmd_store } path; unsigned int time_slot = ((store_only) ? (1) : (0)); uint64_t wme_count; bool new_cue; tc_number tc; Symbol* parent_sym; std::queue<Symbol*> syms; int parent_level; std::queue<int> levels; bool do_wm_phase = false; bool mirroring_on = (thisAgent->smem_params->mirroring->get_value() == on); //Free this up as soon as we start a phase that allows queries if(!store_only){ delete thisAgent->lastCue; thisAgent->lastCue = NULL; } while (state != NULL) { //////////////////////////////////////////////////////////////////////////// thisAgent->smem_timers->api->start(); //////////////////////////////////////////////////////////////////////////// // make sure this state has had some sort of change to the cmd // NOTE: we only care one-level deep! new_cue = false; wme_count = 0; cmds = NIL; { tc = get_new_tc_number(thisAgent); // initialize BFS at command syms.push(state->id->smem_cmd_header); levels.push(0); while (!syms.empty()) { // get state parent_sym = syms.front(); syms.pop(); parent_level = levels.front(); levels.pop(); // get children of the current identifier wmes = smem_get_direct_augs_of_id(parent_sym, tc); { for (w_p = wmes->begin(); w_p != wmes->end(); w_p++) { if (((store_only) && ((parent_level != 0) || ((*w_p)->attr == thisAgent->smem_sym_store))) || ((!store_only) && ((parent_level != 0) || ((*w_p)->attr != thisAgent->smem_sym_store)))) { wme_count++; if ((*w_p)->timetag > state->id->smem_info->last_cmd_time[ time_slot ]) { new_cue = true; state->id->smem_info->last_cmd_time[ time_slot ] = (*w_p)->timetag; } if (((*w_p)->value->symbol_type == IDENTIFIER_SYMBOL_TYPE) && (parent_level == 0) && (((*w_p)->attr == thisAgent->smem_sym_query) || ((*w_p)->attr == thisAgent->smem_sym_store))) { syms.push((*w_p)->value); levels.push(parent_level + 1); } } } // free space from aug list if (cmds == NIL) { cmds = wmes; } else { delete wmes; } } } // see if any WMEs were removed if (state->id->smem_info->last_cmd_count[ time_slot ] != wme_count) { new_cue = true; state->id->smem_info->last_cmd_count[ time_slot ] = wme_count; } if (new_cue) { // clear old results smem_clear_result(thisAgent, state); do_wm_phase = true; } } // a command is issued if the cue is new // and there is something on the cue if (new_cue && wme_count) { cue_wmes.clear(); meta_wmes.clear(); retrieval_wmes.clear(); // initialize command vars retrieve = NIL; query = NIL; negquery = NIL; math = NIL; store.clear(); prohibit.clear(); path = blank_slate; depth = 1; // process top-level symbols for (w_p = cmds->begin(); w_p != cmds->end(); w_p++) { cue_wmes.insert((*w_p)); if (path != cmd_bad) { // collect information about known commands if ((*w_p)->attr == thisAgent->smem_sym_retrieve) { if (((*w_p)->value->symbol_type == IDENTIFIER_SYMBOL_TYPE) && (path == blank_slate)) { retrieve = (*w_p)->value; path = cmd_retrieve; } else { path = cmd_bad; } } else if ((*w_p)->attr == thisAgent->smem_sym_query) { if (((*w_p)->value->symbol_type == IDENTIFIER_SYMBOL_TYPE) && ((path == blank_slate) || (path == cmd_query)) && (query == NIL)) { query = (*w_p)->value; path = cmd_query; } else { path = cmd_bad; } } else if ((*w_p)->attr == thisAgent->smem_sym_negquery) { if (((*w_p)->value->symbol_type == IDENTIFIER_SYMBOL_TYPE) && ((path == blank_slate) || (path == cmd_query)) && (negquery == NIL)) { negquery = (*w_p)->value; path = cmd_query; } else { path = cmd_bad; } } else if ((*w_p)->attr == thisAgent->smem_sym_prohibit) { if (((*w_p)->value->symbol_type == IDENTIFIER_SYMBOL_TYPE) && ((path == blank_slate) || (path == cmd_query)) && ((*w_p)->value->id->smem_lti != NIL)) { prohibit.push_back((*w_p)->value); path = cmd_query; } else { path = cmd_bad; } } else if ((*w_p)->attr == thisAgent->smem_sym_math_query) { if (((*w_p)->value->symbol_type == IDENTIFIER_SYMBOL_TYPE) && ((path == blank_slate) || (path == cmd_query)) && (math == NIL)) { math = (*w_p)->value; path = cmd_query; } else { path = cmd_bad; } } else if ((*w_p)->attr == thisAgent->smem_sym_store) { if (((*w_p)->value->symbol_type == IDENTIFIER_SYMBOL_TYPE) && ((path == blank_slate) || (path == cmd_store))) { store.push_back((*w_p)->value); path = cmd_store; } else { path = cmd_bad; } } else if ((*w_p)->attr == thisAgent->smem_sym_depth) { if ((*w_p)->value->symbol_type == INT_CONSTANT_SYMBOL_TYPE) { depth = ((*w_p)->value->ic->value > 0) ? (*w_p)->value->ic->value : 1; } else { path = cmd_bad; } } else { path = cmd_bad; } } } // if on path 3 must have query/neg-query if ((path == cmd_query) && (query == NULL)) { path = cmd_bad; } // must be on a path if (path == blank_slate) { path = cmd_bad; } //////////////////////////////////////////////////////////////////////////// thisAgent->smem_timers->api->stop(); //////////////////////////////////////////////////////////////////////////// // process command if (path != cmd_bad) { // performing any command requires an initialized database smem_attach(thisAgent); // retrieve if (path == cmd_retrieve) { if (retrieve->id->smem_lti == NIL) { // retrieve is not pointing to an lti! smem_buffer_add_wme(thisAgent, meta_wmes, state->id->smem_result_header, thisAgent->smem_sym_failure, retrieve); } else { // status: success smem_buffer_add_wme(thisAgent, meta_wmes, state->id->smem_result_header, thisAgent->smem_sym_success, retrieve); // install memory directly onto the retrieve identifier smem_install_memory(thisAgent, state, retrieve->id->smem_lti, retrieve, true, meta_wmes, retrieval_wmes, wm_install, depth); // add one to the expansions stat thisAgent->smem_stats->expansions->set_value(thisAgent->smem_stats->expansions->get_value() + 1); } } // query else if (path == cmd_query) { smem_lti_set prohibit_lti; smem_sym_list::iterator sym_p; for (sym_p = prohibit.begin(); sym_p != prohibit.end(); sym_p++) { prohibit_lti.insert((*sym_p)->id->smem_lti); } smem_process_query(thisAgent, state, query, negquery, math, &(prohibit_lti), cue_wmes, meta_wmes, retrieval_wmes, qry_full, 1, NIL, depth, wm_install); // add one to the cbr stat thisAgent->smem_stats->cbr->set_value(thisAgent->smem_stats->cbr->get_value() + 1); } else if (path == cmd_store) { smem_sym_list::iterator sym_p; //////////////////////////////////////////////////////////////////////////// thisAgent->smem_timers->storage->start(); //////////////////////////////////////////////////////////////////////////// // start transaction (if not lazy) if (thisAgent->smem_params->lazy_commit->get_value() == off) { thisAgent->smem_stmts->begin->execute(soar_module::op_reinit); } for (sym_p = store.begin(); sym_p != store.end(); sym_p++) { smem_soar_store(thisAgent, (*sym_p), ((mirroring_on) ? (store_recursive) : (store_level))); // status: success smem_buffer_add_wme(thisAgent, meta_wmes, state->id->smem_result_header, thisAgent->smem_sym_success, (*sym_p)); // add one to the store stat thisAgent->smem_stats->stores->set_value(thisAgent->smem_stats->stores->get_value() + 1); } // commit transaction (if not lazy) if (thisAgent->smem_params->lazy_commit->get_value() == off) { thisAgent->smem_stmts->commit->execute(soar_module::op_reinit); } //////////////////////////////////////////////////////////////////////////// thisAgent->smem_timers->storage->stop(); //////////////////////////////////////////////////////////////////////////// } } else { smem_buffer_add_wme(thisAgent, meta_wmes, state->id->smem_result_header, thisAgent->smem_sym_bad_cmd, state->id->smem_cmd_header); } if (!meta_wmes.empty() || !retrieval_wmes.empty()) { // process preference assertion en masse smem_process_buffered_wmes(thisAgent, state, cue_wmes, meta_wmes, retrieval_wmes); // clear cache { symbol_triple_list::iterator mw_it; for (mw_it = retrieval_wmes.begin(); mw_it != retrieval_wmes.end(); mw_it++) { symbol_remove_ref(thisAgent, (*mw_it)->id); symbol_remove_ref(thisAgent, (*mw_it)->attr); symbol_remove_ref(thisAgent, (*mw_it)->value); delete(*mw_it); } retrieval_wmes.clear(); for (mw_it = meta_wmes.begin(); mw_it != meta_wmes.end(); mw_it++) { symbol_remove_ref(thisAgent, (*mw_it)->id); symbol_remove_ref(thisAgent, (*mw_it)->attr); symbol_remove_ref(thisAgent, (*mw_it)->value); delete(*mw_it); } meta_wmes.clear(); } // process wm changes on this state do_wm_phase = true; } // clear cue wmes cue_wmes.clear(); } else { //////////////////////////////////////////////////////////////////////////// thisAgent->smem_timers->api->stop(); //////////////////////////////////////////////////////////////////////////// } // free space from aug list delete cmds; state = state->id->higher_goal; } if (store_only && mirroring_on && (!thisAgent->smem_changed_ids->empty())) { //////////////////////////////////////////////////////////////////////////// thisAgent->smem_timers->storage->start(); //////////////////////////////////////////////////////////////////////////// // start transaction (if not lazy) if (thisAgent->smem_params->lazy_commit->get_value() == off) { thisAgent->smem_stmts->begin->execute(soar_module::op_reinit); } for (smem_pooled_symbol_set::iterator it = thisAgent->smem_changed_ids->begin(); it != thisAgent->smem_changed_ids->end(); it++) { // require that the lti has at least one augmentation if ((*it)->id->slots) { smem_soar_store(thisAgent, (*it), store_recursive); // add one to the mirrors stat thisAgent->smem_stats->mirrors->set_value(thisAgent->smem_stats->mirrors->get_value() + 1); } symbol_remove_ref(thisAgent, (*it)); } // commit transaction (if not lazy) if (thisAgent->smem_params->lazy_commit->get_value() == off) { thisAgent->smem_stmts->commit->execute(soar_module::op_reinit); } // clear symbol set thisAgent->smem_changed_ids->clear(); //////////////////////////////////////////////////////////////////////////// thisAgent->smem_timers->storage->stop(); //////////////////////////////////////////////////////////////////////////// } if (do_wm_phase) { thisAgent->smem_ignore_changes = true; do_working_memory_phase(thisAgent); thisAgent->smem_ignore_changes = false; } } void smem_go(agent* thisAgent, bool store_only) { thisAgent->smem_timers->total->start(); #ifndef SMEM_EXPERIMENT smem_respond_to_cmd(thisAgent, store_only); #else // SMEM_EXPERIMENT #endif // SMEM_EXPERIMENT thisAgent->smem_timers->total->stop(); } bool smem_backup_db(agent* thisAgent, const char* file_name, std::string* err) { bool return_val = false; if (thisAgent->smem_db->get_status() == soar_module::connected) { _smem_close_vars(thisAgent); if (thisAgent->smem_params->lazy_commit->get_value() == on) { thisAgent->smem_stmts->commit->execute(soar_module::op_reinit); } return_val = thisAgent->smem_db->backup(file_name, err); if (thisAgent->smem_params->lazy_commit->get_value() == on) { thisAgent->smem_stmts->begin->execute(soar_module::op_reinit); } } else { err->assign("Semantic database is not currently connected."); } return return_val; } ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // Visualization (smem::viz) ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// void smem_visualize_store(agent* thisAgent, std::string* return_val) { // header return_val->append("digraph smem {"); return_val->append("\n"); // LTIs return_val->append("node [ shape = doublecircle ];"); return_val->append("\n"); std::map< smem_lti_id, std::string > lti_names; std::map< smem_lti_id, std::string >::iterator n_p; { soar_module::sqlite_statement* q; smem_lti_id lti_id; char lti_letter; uint64_t lti_number; std::string* lti_name; std::string temp_str; int64_t temp_int; double temp_double; // id, soar_letter, number q = thisAgent->smem_stmts->vis_lti; while (q->execute() == soar_module::row) { lti_id = q->column_int(0); lti_letter = static_cast<char>(q->column_int(1)); lti_number = static_cast<uint64_t>(q->column_int(2)); lti_name = & lti_names[ lti_id ]; lti_name->push_back(lti_letter); to_string(lti_number, temp_str); lti_name->append(temp_str); return_val->append((*lti_name)); return_val->append(" [ label=\""); return_val->append((*lti_name)); return_val->append("\\n["); temp_double = q->column_double(3); to_string(temp_double, temp_str, 3, true); if (temp_double >= 0) { return_val->append("+"); } return_val->append(temp_str); return_val->append("]\""); return_val->append(" ];"); return_val->append("\n"); } q->reinitialize(); if (!lti_names.empty()) { // terminal nodes first { std::map< smem_lti_id, std::list<std::string> > lti_terminals; std::map< smem_lti_id, std::list<std::string> >::iterator t_p; std::list<std::string>::iterator a_p; std::list<std::string>* my_terminals; std::list<std::string>::size_type terminal_num; return_val->append("\n"); // proceed to terminal nodes return_val->append("node [ shape = plaintext ];"); return_val->append("\n"); // lti_id, attr_type, attr_hash, val_type, val_hash q = thisAgent->smem_stmts->vis_value_const; while (q->execute() == soar_module::row) { lti_id = q->column_int(0); my_terminals = & lti_terminals[ lti_id ]; lti_name = & lti_names[ lti_id ]; // parent prefix return_val->append((*lti_name)); return_val->append("_"); // terminal count terminal_num = my_terminals->size(); to_string(terminal_num, temp_str); return_val->append(temp_str); // prepare for value return_val->append(" [ label = \""); // output value { switch (q->column_int(3)) { case STR_CONSTANT_SYMBOL_TYPE: smem_reverse_hash_str(thisAgent, q->column_int(4), temp_str); break; case INT_CONSTANT_SYMBOL_TYPE: temp_int = smem_reverse_hash_int(thisAgent, q->column_int(4)); to_string(temp_int, temp_str); break; case FLOAT_CONSTANT_SYMBOL_TYPE: temp_double = smem_reverse_hash_float(thisAgent, q->column_int(4)); to_string(temp_double, temp_str); break; default: temp_str.clear(); break; } return_val->append(temp_str); } // store terminal (attribute for edge label) { switch (q->column_int(1)) { case STR_CONSTANT_SYMBOL_TYPE: smem_reverse_hash_str(thisAgent, q->column_int(2), temp_str); break; case INT_CONSTANT_SYMBOL_TYPE: temp_int = smem_reverse_hash_int(thisAgent, q->column_int(2)); to_string(temp_int, temp_str); break; case FLOAT_CONSTANT_SYMBOL_TYPE: temp_double = smem_reverse_hash_float(thisAgent, q->column_int(2)); to_string(temp_double, temp_str); break; default: temp_str.clear(); break; } my_terminals->push_back(temp_str); } // footer return_val->append("\" ];"); return_val->append("\n"); } q->reinitialize(); // output edges { unsigned int terminal_counter; for (n_p = lti_names.begin(); n_p != lti_names.end(); n_p++) { t_p = lti_terminals.find(n_p->first); if (t_p != lti_terminals.end()) { terminal_counter = 0; for (a_p = t_p->second.begin(); a_p != t_p->second.end(); a_p++) { return_val->append(n_p->second); return_val ->append(" -> "); return_val->append(n_p->second); return_val->append("_"); to_string(terminal_counter, temp_str); return_val->append(temp_str); return_val->append(" [ label=\""); return_val->append((*a_p)); return_val->append("\" ];"); return_val->append("\n"); terminal_counter++; } } } } } // then links to other LTIs { // lti_id, attr_type, attr_hash, value_lti_id q = thisAgent->smem_stmts->vis_value_lti; while (q->execute() == soar_module::row) { // source lti_id = q->column_int(0); lti_name = & lti_names[ lti_id ]; return_val->append((*lti_name)); return_val->append(" -> "); // destination lti_id = q->column_int(3); lti_name = & lti_names[ lti_id ]; return_val->append((*lti_name)); return_val->append(" [ label =\""); // output attribute { switch (q->column_int(1)) { case STR_CONSTANT_SYMBOL_TYPE: smem_reverse_hash_str(thisAgent, q->column_int(2), temp_str); break; case INT_CONSTANT_SYMBOL_TYPE: temp_int = smem_reverse_hash_int(thisAgent, q->column_int(2)); to_string(temp_int, temp_str); break; case FLOAT_CONSTANT_SYMBOL_TYPE: temp_double = smem_reverse_hash_float(thisAgent, q->column_int(2)); to_string(temp_double, temp_str); break; default: temp_str.clear(); break; } return_val->append(temp_str); } // footer return_val->append("\" ];"); return_val->append("\n"); } q->reinitialize(); } } } // footer return_val->append("}"); return_val->append("\n"); } void smem_visualize_lti(agent* thisAgent, smem_lti_id lti_id, unsigned int depth, std::string* return_val) { // buffer std::string return_val2; soar_module::sqlite_statement* expand_q = thisAgent->smem_stmts->web_expand; uint64_t child_counter; std::string temp_str; std::string temp_str2; int64_t temp_int; double temp_double; std::queue<smem_vis_lti*> bfs; smem_vis_lti* new_lti; smem_vis_lti* parent_lti; std::map< smem_lti_id, smem_vis_lti* > close_list; std::map< smem_lti_id, smem_vis_lti* >::iterator cl_p; // header return_val->append("digraph smem_lti {"); return_val->append("\n"); // root { new_lti = new smem_vis_lti; new_lti->lti_id = lti_id; new_lti->level = 0; // fake former linkage { soar_module::sqlite_statement* lti_q = thisAgent->smem_stmts->lti_letter_num; // get just this lti lti_q->bind_int(1, lti_id); lti_q->execute(); // soar_letter new_lti->lti_name.push_back(static_cast<char>(lti_q->column_int(0))); // number temp_int = lti_q->column_int(1); to_string(temp_int, temp_str); new_lti->lti_name.append(temp_str); // done with lookup lti_q->reinitialize(); } bfs.push(new_lti); close_list.insert(std::make_pair(lti_id, new_lti)); new_lti = NULL; } // optionally depth-limited breadth-first-search of children while (!bfs.empty()) { parent_lti = bfs.front(); bfs.pop(); child_counter = 0; // get direct children: attr_type, attr_hash, value_type, value_hash, value_letter, value_num, value_lti expand_q->bind_int(1, parent_lti->lti_id); while (expand_q->execute() == soar_module::row) { // identifier vs. constant if (expand_q->column_int(6) != SMEM_AUGMENTATIONS_NULL) { new_lti = new smem_vis_lti; new_lti->lti_id = expand_q->column_int(6); new_lti->level = (parent_lti->level + 1); // add node { // soar_letter new_lti->lti_name.push_back(static_cast<char>(expand_q->column_int(4))); // number temp_int = expand_q->column_int(5); to_string(temp_int, temp_str); new_lti->lti_name.append(temp_str); } // add linkage { // get attribute switch (expand_q->column_int(0)) { case STR_CONSTANT_SYMBOL_TYPE: smem_reverse_hash_str(thisAgent, expand_q->column_int(1), temp_str); break; case INT_CONSTANT_SYMBOL_TYPE: temp_int = smem_reverse_hash_int(thisAgent, expand_q->column_int(1)); to_string(temp_int, temp_str); break; case FLOAT_CONSTANT_SYMBOL_TYPE: temp_double = smem_reverse_hash_float(thisAgent, expand_q->column_int(1)); to_string(temp_double, temp_str); break; default: temp_str.clear(); break; } // output linkage return_val2.append(parent_lti->lti_name); return_val2.append(" -> "); return_val2.append(new_lti->lti_name); return_val2.append(" [ label = \""); return_val2.append(temp_str); return_val2.append("\" ];"); return_val2.append("\n"); } // prevent looping { cl_p = close_list.find(new_lti->lti_id); if (cl_p == close_list.end()) { close_list.insert(std::make_pair(new_lti->lti_id, new_lti)); if ((depth == 0) || (new_lti->level < depth)) { bfs.push(new_lti); } } else { delete new_lti; } } new_lti = NULL; } else { // add value node { // get node name { temp_str2.assign(parent_lti->lti_name); temp_str2.append("_"); to_string(child_counter, temp_str); temp_str2.append(temp_str); } // get value switch (expand_q->column_int(2)) { case STR_CONSTANT_SYMBOL_TYPE: smem_reverse_hash_str(thisAgent, expand_q->column_int(3), temp_str); break; case INT_CONSTANT_SYMBOL_TYPE: temp_int = smem_reverse_hash_int(thisAgent, expand_q->column_int(3)); to_string(temp_int, temp_str); break; case FLOAT_CONSTANT_SYMBOL_TYPE: temp_double = smem_reverse_hash_float(thisAgent, expand_q->column_int(3)); to_string(temp_double, temp_str); break; default: temp_str.clear(); break; } // output node return_val2.append("node [ shape = plaintext ];"); return_val2.append("\n"); return_val2.append(temp_str2); return_val2.append(" [ label=\""); return_val2.append(temp_str); return_val2.append("\" ];"); return_val2.append("\n"); } // add linkage { // get attribute switch (expand_q->column_int(0)) { case STR_CONSTANT_SYMBOL_TYPE: smem_reverse_hash_str(thisAgent, expand_q->column_int(1), temp_str); break; case INT_CONSTANT_SYMBOL_TYPE: temp_int = smem_reverse_hash_int(thisAgent, expand_q->column_int(1)); to_string(temp_int, temp_str); break; case FLOAT_CONSTANT_SYMBOL_TYPE: temp_double = smem_reverse_hash_float(thisAgent, expand_q->column_int(1)); to_string(temp_double, temp_str); break; default: temp_str.clear(); break; } // output linkage return_val2.append(parent_lti->lti_name); return_val2.append(" -> "); return_val2.append(temp_str2); return_val2.append(" [ label = \""); return_val2.append(temp_str); return_val2.append("\" ];"); return_val2.append("\n"); } child_counter++; } } expand_q->reinitialize(); } // footer return_val2.append("}"); return_val2.append("\n"); // handle lti nodes at once { soar_module::sqlite_statement* act_q = thisAgent->smem_stmts->vis_lti_act; return_val->append("node [ shape = doublecircle ];"); return_val->append("\n"); for (cl_p = close_list.begin(); cl_p != close_list.end(); cl_p++) { return_val->append(cl_p->second->lti_name); return_val->append(" [ label=\""); return_val->append(cl_p->second->lti_name); return_val->append("\\n["); act_q->bind_int(1, cl_p->first); if (act_q->execute() == soar_module::row) { temp_double = act_q->column_double(0); to_string(temp_double, temp_str, 3, true); if (temp_double >= 0) { return_val->append("+"); } return_val->append(temp_str); } act_q->reinitialize(); return_val->append("]\""); return_val->append(" ];"); return_val->append("\n"); delete cl_p->second; } } // transfer buffer after nodes return_val->append(return_val2); } inline std::set< smem_lti_id > _smem_print_lti(agent* thisAgent, smem_lti_id lti_id, char lti_letter, uint64_t lti_number, double lti_act, std::string* return_val, std::list<uint64_t>* history = NIL) { std::set< smem_lti_id > next; std::string temp_str, temp_str2, temp_str3; int64_t temp_int; double temp_double; std::map< std::string, std::list< std::string > > augmentations; std::map< std::string, std::list< std::string > >::iterator lti_slot; std::list< std::string >::iterator slot_val; smem_attach(thisAgent); soar_module::sqlite_statement* expand_q = thisAgent->smem_stmts->web_expand; return_val->append("(@"); return_val->push_back(lti_letter); to_string(lti_number, temp_str); return_val->append(temp_str); bool possible_id, possible_ic, possible_fc, possible_sc, possible_var, is_rereadable; // get direct children: attr_type, attr_hash, value_type, value_hash, value_letter, value_num, value_lti expand_q->bind_int(1, lti_id); while (expand_q->execute() == soar_module::row) { // get attribute switch (expand_q->column_int(0)) { case STR_CONSTANT_SYMBOL_TYPE: { smem_reverse_hash_str(thisAgent, expand_q->column_int(1), temp_str); if (count(temp_str.begin(), temp_str.end(), ' ') > 0) { temp_str.insert(0, "|"); temp_str += '|'; break; } soar::Lexer::determine_possible_symbol_types_for_string(temp_str.c_str(), strlen(temp_str.c_str()), &possible_id, &possible_var, &possible_sc, &possible_ic, &possible_fc, &is_rereadable); bool has_angle_bracket = temp_str[0] == '<' || temp_str[temp_str.length() - 1] == '>'; if ((!possible_sc) || possible_var || possible_ic || possible_fc || (!is_rereadable) || has_angle_bracket) { /* BUGBUG if in context where id's could occur, should check possible_id flag here also */ temp_str.insert(0, "|"); temp_str += '|'; } break; } case INT_CONSTANT_SYMBOL_TYPE: temp_int = smem_reverse_hash_int(thisAgent, expand_q->column_int(1)); to_string(temp_int, temp_str); break; case FLOAT_CONSTANT_SYMBOL_TYPE: temp_double = smem_reverse_hash_float(thisAgent, expand_q->column_int(1)); to_string(temp_double, temp_str); break; default: temp_str.clear(); break; } // identifier vs. constant if (expand_q->column_int(6) != SMEM_AUGMENTATIONS_NULL) { temp_str2.clear(); temp_str2.push_back('@'); // soar_letter temp_str2.push_back(static_cast<char>(expand_q->column_int(4))); // number temp_int = expand_q->column_int(5); to_string(temp_int, temp_str3); temp_str2.append(temp_str3); // add to next next.insert(static_cast< smem_lti_id >(expand_q->column_int(6))); } else { switch (expand_q->column_int(2)) { case STR_CONSTANT_SYMBOL_TYPE: { smem_reverse_hash_str(thisAgent, expand_q->column_int(3), temp_str2); if (count(temp_str2.begin(), temp_str2.end(), ' ') > 0) { temp_str2.insert(0, "|"); temp_str2 += '|'; break; } soar::Lexer::determine_possible_symbol_types_for_string(temp_str2.c_str(), temp_str2.length(), &possible_id, &possible_var, &possible_sc, &possible_ic, &possible_fc, &is_rereadable); bool has_angle_bracket = temp_str2[0] == '<' || temp_str2[temp_str2.length() - 1] == '>'; if ((!possible_sc) || possible_var || possible_ic || possible_fc || (!is_rereadable) || has_angle_bracket) { /* BUGBUG if in context where id's could occur, should check possible_id flag here also */ temp_str2.insert(0, "|"); temp_str2 += '|'; } break; } case INT_CONSTANT_SYMBOL_TYPE: temp_int = smem_reverse_hash_int(thisAgent, expand_q->column_int(3)); to_string(temp_int, temp_str2); break; case FLOAT_CONSTANT_SYMBOL_TYPE: temp_double = smem_reverse_hash_float(thisAgent, expand_q->column_int(3)); to_string(temp_double, temp_str2); break; default: temp_str2.clear(); break; } } augmentations[ temp_str ].push_back(temp_str2); } expand_q->reinitialize(); // output augmentations nicely { for (lti_slot = augmentations.begin(); lti_slot != augmentations.end(); lti_slot++) { return_val->append(" ^"); return_val->append(lti_slot->first); for (slot_val = lti_slot->second.begin(); slot_val != lti_slot->second.end(); slot_val++) { return_val->append(" "); return_val->append((*slot_val)); } } } augmentations.clear(); return_val->append(" ["); to_string(lti_act, temp_str, 3, true); if (lti_act >= 0) { return_val->append("+"); } return_val->append(temp_str); return_val->append("]"); return_val->append(")\n"); if (history != NIL) { std::ostringstream temp_string; return_val->append("SMem Access Cycle History\n"); return_val->append("[-"); for (std::list<uint64_t>::iterator history_item = (*history).begin(); history_item != (*history).end(); ++history_item) { if (history_item != (*history).begin()) { return_val->append(", -"); } temp_string << ((int64_t)thisAgent->smem_max_cycle - (int64_t)*history_item); return_val->append(temp_string.str()); temp_string.str(""); } return_val->append("]\n"); } return next; } void smem_print_store(agent* thisAgent, std::string* return_val) { // id, soar_letter, number soar_module::sqlite_statement* q = thisAgent->smem_stmts->vis_lti; while (q->execute() == soar_module::row) { _smem_print_lti(thisAgent, q->column_int(0), static_cast<char>(q->column_int(1)), static_cast<uint64_t>(q->column_int(2)), q->column_double(3), return_val); } q->reinitialize(); } void smem_print_lti(agent* thisAgent, smem_lti_id lti_id, uint64_t depth, std::string* return_val, bool history) { std::set< smem_lti_id > visited; std::pair< std::set< smem_lti_id >::iterator, bool > visited_ins_result; std::queue< std::pair< smem_lti_id, unsigned int > > to_visit; std::pair< smem_lti_id, unsigned int > c; std::set< smem_lti_id > next; std::set< smem_lti_id >::iterator next_it; soar_module::sqlite_statement* lti_q = thisAgent->smem_stmts->lti_letter_num; soar_module::sqlite_statement* act_q = thisAgent->smem_stmts->vis_lti_act; soar_module::sqlite_statement* hist_q = thisAgent->smem_stmts->history_get; soar_module::sqlite_statement* lti_access_q = thisAgent->smem_stmts->lti_access_get; unsigned int i; // initialize queue/set to_visit.push(std::make_pair(lti_id, 1u)); visited.insert(lti_id); while (!to_visit.empty()) { c = to_visit.front(); to_visit.pop(); // output leading spaces ala depth for (i = 1; i < c.second; i++) { return_val->append(" "); } // get lti info { lti_q->bind_int(1, c.first); lti_q->execute(); act_q->bind_int(1, c.first); act_q->execute(); //Look up activation history. std::list<uint64_t> access_history; if (history) { lti_access_q->bind_int(1, c.first); lti_access_q->execute(); uint64_t n = lti_access_q->column_int(0); lti_access_q->reinitialize(); hist_q->bind_int(1, c.first); hist_q->execute(); for (int i = 0; i < n && i < 10; ++i) //10 because of the length of the history record kept for smem. { if (thisAgent->smem_stmts->history_get->column_int(i) != 0) { access_history.push_back(hist_q->column_int(i)); } } hist_q->reinitialize(); } if (history && !access_history.empty()) { next = _smem_print_lti(thisAgent, c.first, static_cast<char>(lti_q->column_int(0)), static_cast<uint64_t>(lti_q->column_int(1)), act_q->column_double(0), return_val, &(access_history)); } else { next = _smem_print_lti(thisAgent, c.first, static_cast<char>(lti_q->column_int(0)), static_cast<uint64_t>(lti_q->column_int(1)), act_q->column_double(0), return_val); } // done with lookup lti_q->reinitialize(); act_q->reinitialize(); // consider further depth if (c.second < depth) { for (next_it = next.begin(); next_it != next.end(); next_it++) { visited_ins_result = visited.insert((*next_it)); if (visited_ins_result.second) { to_visit.push(std::make_pair((*next_it), c.second + 1u)); } } } } } }
39.952274
524
0.532083
Bryan-Stearns
25fd87249c385e2b459e6d3fc0275a6b65d9b193
44,878
cpp
C++
source/backend/shape/bezier.cpp
acekiller/povray
ae6837fb8625bb9ca00830f8871c90c87dd21b75
[ "Zlib" ]
1
2015-06-21T05:27:57.000Z
2015-06-21T05:27:57.000Z
source/backend/shape/bezier.cpp
binji/povray
ae6837fb8625bb9ca00830f8871c90c87dd21b75
[ "Zlib" ]
null
null
null
source/backend/shape/bezier.cpp
binji/povray
ae6837fb8625bb9ca00830f8871c90c87dd21b75
[ "Zlib" ]
null
null
null
/******************************************************************************* * bezier.cpp * * This module implements the code for Bezier bicubic patch shapes * * This file was written by Alexander Enzmann. He wrote the code for * bezier bicubic patches and generously provided us these enhancements. * * from Persistence of Vision Ray Tracer ('POV-Ray') version 3.7. * Copyright 1991-2003 Persistence of Vision Team * Copyright 2003-2009 Persistence of Vision Raytracer Pty. Ltd. * --------------------------------------------------------------------------- * NOTICE: This source code file is provided so that users may experiment * with enhancements to POV-Ray and to port the software to platforms other * than those supported by the POV-Ray developers. There are strict rules * regarding how you are permitted to use this file. These rules are contained * in the distribution and derivative versions licenses which should have been * provided with this file. * * These licences may be found online, linked from the end-user license * agreement that is located at http://www.povray.org/povlegal.html * --------------------------------------------------------------------------- * POV-Ray is based on the popular DKB raytracer version 2.12. * DKBTrace was originally written by David K. Buck. * DKBTrace Ver 2.0-2.12 were written by David K. Buck & Aaron A. Collins. * --------------------------------------------------------------------------- * $File: //depot/povray/smp/source/backend/shape/bezier.cpp $ * $Revision: #26 $ * $Change: 5103 $ * $DateTime: 2010/08/22 06:58:49 $ * $Author: clipka $ *******************************************************************************/ /********************************************************************************* * NOTICE * * This file is part of a BETA-TEST version of POV-Ray version 3.7. It is not * final code. Use of this source file is governed by both the standard POV-Ray * licences referred to in the copyright header block above this notice, and the * following additional restrictions numbered 1 through 4 below: * * 1. This source file may not be re-distributed without the written permission * of Persistence of Vision Raytracer Pty. Ltd. * * 2. This notice may not be altered or removed. * * 3. Binaries generated from this source file by individuals for their own * personal use may not be re-distributed without the written permission * of Persistence of Vision Raytracer Pty. Ltd. Such personal-use binaries * are not required to have a timeout, and thus permission is granted in * these circumstances only to disable the timeout code contained within * the beta software. * * 4. Binaries generated from this source file for use within an organizational * unit (such as, but not limited to, a company or university) may not be * distributed beyond the local organizational unit in which they were made, * unless written permission is obtained from Persistence of Vision Raytracer * Pty. Ltd. Additionally, the timeout code implemented within the beta may * not be disabled or otherwise bypassed in any manner. * * The following text is not part of the above conditions and is provided for * informational purposes only. * * The purpose of the no-redistribution clause is to attempt to keep the * circulating copies of the beta source fresh. The only authorized distribution * point for the source code is the POV-Ray website and Perforce server, where * the code will be kept up to date with recent fixes. Additionally the beta * timeout code mentioned above has been a standard part of POV-Ray betas since * version 1.0, and is intended to reduce bug reports from old betas as well as * keep any circulating beta binaries relatively fresh. * * All said, however, the POV-Ray developers are open to any reasonable request * for variations to the above conditions and will consider them on a case-by-case * basis. * * Additionally, the developers request your co-operation in fixing bugs and * generally improving the program. If submitting a bug-fix, please ensure that * you quote the revision number of the file shown above in the copyright header * (see the '$Revision:' field). This ensures that it is possible to determine * what specific copy of the file you are working with. The developers also would * like to make it known that until POV-Ray 3.7 is out of beta, they would prefer * to emphasize the provision of bug fixes over the addition of new features. * * Persons wishing to enhance this source are requested to take the above into * account. It is also strongly suggested that such enhancements are started with * a recent copy of the source. * * The source code page (see http://www.povray.org/beta/source/) sets out the * conditions under which the developers are willing to accept contributions back * into the primary source tree. Please refer to those conditions prior to making * any changes to this source, if you wish to submit those changes for inclusion * with POV-Ray. * *********************************************************************************/ // frame.h must always be the first POV file included (pulls in platform config) #include "backend/frame.h" #include "backend/math/vector.h" #include "backend/shape/bezier.h" #include "backend/math/matrices.h" #include "backend/scene/objects.h" #include "backend/scene/threaddata.h" #include "base/pov_err.h" #include <algorithm> // this must be the last file included #include "base/povdebug.h" namespace pov { /***************************************************************************** * Local preprocessor defines ******************************************************************************/ const DBL BEZIER_EPSILON = 1.0e-10; const DBL BEZIER_TOLERANCE = 1.0e-5; /***************************************************************************** * * FUNCTION * * create_new_bezier_node * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ BEZIER_NODE *BicubicPatch::create_new_bezier_node() { BEZIER_NODE *Node = (BEZIER_NODE *)POV_MALLOC(sizeof(BEZIER_NODE), "bezier node"); Node->Data_Ptr = NULL; return (Node); } /***************************************************************************** * * FUNCTION * * create_bezier_vertex_block * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ BEZIER_VERTICES *BicubicPatch::create_bezier_vertex_block() { BEZIER_VERTICES *Vertices; Vertices = (BEZIER_VERTICES *)POV_MALLOC(sizeof(BEZIER_VERTICES), "bezier vertices"); return (Vertices); } /***************************************************************************** * * FUNCTION * * create_bezier_child_block * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ BEZIER_CHILDREN *BicubicPatch::create_bezier_child_block() { BEZIER_CHILDREN *Children; Children = (BEZIER_CHILDREN *)POV_MALLOC(sizeof(BEZIER_CHILDREN), "bezier children"); return (Children); } /***************************************************************************** * * FUNCTION * * bezier_tree_builder * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ BEZIER_NODE *BicubicPatch::bezier_tree_builder(const VECTOR (*Patch)[4][4], DBL u0, DBL u1, DBL v0, DBL v1, int depth, int& max_depth_reached) { VECTOR Lower_Left[4][4], Lower_Right[4][4]; VECTOR Upper_Left[4][4], Upper_Right[4][4]; BEZIER_CHILDREN *Children; BEZIER_VERTICES *Vertices; BEZIER_NODE *Node = create_new_bezier_node(); if (depth > max_depth_reached) { max_depth_reached = depth; } /* Build the bounding sphere for this subpatch. */ bezier_bounding_sphere(Patch, Node->Center, &(Node->Radius_Squared)); /* * If the patch is close to being flat, then just perform * a ray-plane intersection test. */ if (flat_enough(Patch)) { /* The patch is now flat enough to simply store the corners. */ Node->Node_Type = BEZIER_LEAF_NODE; Vertices = create_bezier_vertex_block(); Assign_Vector(Vertices->Vertices[0], (*Patch)[0][0]); Assign_Vector(Vertices->Vertices[1], (*Patch)[0][3]); Assign_Vector(Vertices->Vertices[2], (*Patch)[3][3]); Assign_Vector(Vertices->Vertices[3], (*Patch)[3][0]); Vertices->uvbnds[0] = u0; Vertices->uvbnds[1] = u1; Vertices->uvbnds[2] = v0; Vertices->uvbnds[3] = v1; Node->Data_Ptr = (void *)Vertices; } else { if (depth >= U_Steps) { if (depth >= V_Steps) { /* We are at the max recursion depth. Just store corners. */ Node->Node_Type = BEZIER_LEAF_NODE; Vertices = create_bezier_vertex_block(); Assign_Vector(Vertices->Vertices[0], (*Patch)[0][0]); Assign_Vector(Vertices->Vertices[1], (*Patch)[0][3]); Assign_Vector(Vertices->Vertices[2], (*Patch)[3][3]); Assign_Vector(Vertices->Vertices[3], (*Patch)[3][0]); Vertices->uvbnds[0] = u0; Vertices->uvbnds[1] = u1; Vertices->uvbnds[2] = v0; Vertices->uvbnds[3] = v1; Node->Data_Ptr = (void *)Vertices; } else { bezier_split_up_down(Patch, (VECTOR(*)[4][4])Lower_Left, (VECTOR(*)[4][4])Upper_Left); Node->Node_Type = BEZIER_INTERIOR_NODE; Children = create_bezier_child_block(); Children->Children[0] = bezier_tree_builder((VECTOR(*)[4][4])Lower_Left, u0, u1, v0, (v0 + v1) / 2.0, depth + 1, max_depth_reached); Children->Children[1] = bezier_tree_builder((VECTOR(*)[4][4])Upper_Left, u0, u1, (v0 + v1) / 2.0, v1, depth + 1, max_depth_reached); Node->Count = 2; Node->Data_Ptr = (void *)Children; } } else { if (depth >= V_Steps) { bezier_split_left_right(Patch, (VECTOR(*)[4][4])Lower_Left, (VECTOR(*)[4][4])Lower_Right); Node->Node_Type = BEZIER_INTERIOR_NODE; Children = create_bezier_child_block(); Children->Children[0] = bezier_tree_builder((VECTOR(*)[4][4])Lower_Left, u0, (u0 + u1) / 2.0, v0, v1, depth + 1, max_depth_reached); Children->Children[1] = bezier_tree_builder((VECTOR(*)[4][4])Lower_Right, (u0 + u1) / 2.0, u1, v0, v1, depth + 1, max_depth_reached); Node->Count = 2; Node->Data_Ptr = (void *)Children; } else { bezier_split_left_right(Patch, (VECTOR(*)[4][4])Lower_Left, (VECTOR(*)[4][4])Lower_Right); bezier_split_up_down((VECTOR(*)[4][4])Lower_Left, (VECTOR(*)[4][4])Lower_Left, (VECTOR(*)[4][4])Upper_Left); bezier_split_up_down((VECTOR(*)[4][4])Lower_Right, (VECTOR(*)[4][4])Lower_Right, (VECTOR(*)[4][4])Upper_Right); Node->Node_Type = BEZIER_INTERIOR_NODE; Children = create_bezier_child_block(); Children->Children[0] = bezier_tree_builder((VECTOR(*)[4][4])Lower_Left, u0, (u0 + u1) / 2.0, v0, (v0 + v1) / 2.0, depth + 1, max_depth_reached); Children->Children[1] = bezier_tree_builder((VECTOR(*)[4][4])Upper_Left, u0, (u0 + u1) / 2.0, (v0 + v1) / 2.0, v1, depth + 1, max_depth_reached); Children->Children[2] = bezier_tree_builder((VECTOR(*)[4][4])Lower_Right, (u0 + u1) / 2.0, u1, v0, (v0 + v1) / 2.0, depth + 1, max_depth_reached); Children->Children[3] = bezier_tree_builder((VECTOR(*)[4][4])Upper_Right, (u0 + u1) / 2.0, u1, (v0 + v1) / 2.0, v1, depth + 1, max_depth_reached); Node->Count = 4; Node->Data_Ptr = (void *)Children; } } } return (Node); } /***************************************************************************** * * FUNCTION * * bezier_value * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * Determine the position and normal at a single coordinate * point (u, v) on a Bezier patch. * * CHANGES * * - * ******************************************************************************/ void BicubicPatch::bezier_value(const VECTOR (*cp)[4][4], DBL u0, DBL v0, VECTOR P, VECTOR N) { const DBL C[] = { 1.0, 3.0, 3.0, 1.0 }; int i, j; DBL c, t, ut, vt; DBL u[4], uu[4], v[4], vv[4]; DBL du[4], duu[4], dv[4], dvv[4]; DBL squared_u1, squared_v1; VECTOR U1, V1; /* Calculate binomial coefficients times coordinate positions. */ u[0] = 1.0; uu[0] = 1.0; du[0] = 0.0; duu[0] = 0.0; v[0] = 1.0; vv[0] = 1.0; dv[0] = 0.0; dvv[0] = 0.0; for (i = 1; i < 4; i++) { u[i] = u[i - 1] * u0; uu[i] = uu[i - 1] * (1.0 - u0); v[i] = v[i - 1] * v0; vv[i] = vv[i - 1] * (1.0 - v0); du[i] = i * u[i - 1]; duu[i] = -i * uu[i - 1]; dv[i] = i * v[i - 1]; dvv[i] = -i * vv[i - 1]; } /* Now evaluate position and tangents based on control points. */ Make_Vector(P, 0, 0, 0); Make_Vector(U1, 0, 0, 0); Make_Vector(V1, 0, 0, 0); for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { c = C[i] * C[j]; ut = u[i] * uu[3 - i]; vt = v[j] * vv[3 - j]; t = c * ut * vt; VAddScaledEq(P, t, (*cp)[i][j]); t = c * vt * (du[i] * uu[3 - i] + u[i] * duu[3 - i]); VAddScaledEq(U1, t, (*cp)[i][j]); t = c * ut * (dv[j] * vv[3 - j] + v[j] * dvv[3 - j]); VAddScaledEq(V1, t, (*cp)[i][j]); } } /* Make the normal from the cross product of the tangents. */ VCross(N, U1, V1); VDot(t, N, N); squared_u1 = VSumSqr(U1); squared_v1 = VSumSqr(V1); if (t > (BEZIER_EPSILON * squared_u1 * squared_v1)) { t = 1.0 / sqrt(t); VScaleEq(N, t); } else { Make_Vector(N, 1, 0, 0); } } /***************************************************************************** * * FUNCTION * * subpatch_normal * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * Calculate the normal to a subpatch (triangle) return the vector * <1.0 0.0 0.0> if the triangle is degenerate. * * CHANGES * * - * ******************************************************************************/ bool BicubicPatch::subpatch_normal(const VECTOR v1, const VECTOR v2, const VECTOR v3, VECTOR Result, DBL *d) { VECTOR V1, V2; DBL squared_v1, squared_v2; DBL Length; VSub(V1, v1, v2); VSub(V2, v3, v2); VCross(Result, V1, V2); Length = VSumSqr(Result); squared_v1 = VSumSqr(V1); squared_v2 = VSumSqr(V2); if (Length <= (BEZIER_EPSILON * squared_v1 * squared_v2)) { Make_Vector(Result, 1.0, 0.0, 0.0); *d = -1.0 * v1[X]; return false; } else { Length = sqrt(Length); VInverseScale(Result, Result, Length); VDot(*d, Result, v1); *d = 0.0 - *d; return true; } } /***************************************************************************** * * FUNCTION * * intersect_subpatch * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ bool BicubicPatch::intersect_subpatch(const Ray &ray, const VECTOR V1[3], const DBL uu[3], const DBL vv[3], DBL *Depth, VECTOR P, VECTOR N, DBL *u, DBL *v) const { DBL squared_b0, squared_b1; DBL d, n, a, b, r; VECTOR Q, T1; VECTOR B[3], IB[3], NN[3]; VSub(B[0], V1[1], V1[0]); VSub(B[1], V1[2], V1[0]); VCross(B[2], B[0], B[1]); VDot(d, B[2], B[2]); squared_b0 = VSumSqr(B[0]); squared_b1 = VSumSqr(B[1]); if (d <= (BEZIER_EPSILON * squared_b1 * squared_b0)) { return false; } d = 1.0 / sqrt(d); VScaleEq(B[2], d); /* Degenerate triangle. */ if (!MInvers3(B, IB)) { return false; } VDot(d, ray.Direction, IB[2]); if (fabs(d) < BEZIER_EPSILON) { return false; } VSub(Q, V1[0], ray.Origin); VDot(n, Q, IB[2]); *Depth = n / d; if (*Depth < BEZIER_TOLERANCE) { return false; } VScale(T1, ray.Direction, *Depth); VAdd(P, ray.Origin, T1); VSub(Q, P, V1[0]); VDot(a, Q, IB[0]); VDot(b, Q, IB[1]); if ((a < 0.0) || (b < 0.0) || (a + b > 1.0)) { return false; } r = 1.0 - a - b; Make_Vector(N, 0.0, 0.0, 0.0); bezier_value((VECTOR(*)[4][4])&Control_Points, uu[0], vv[0], T1, NN[0]); bezier_value((VECTOR(*)[4][4])&Control_Points, uu[1], vv[1], T1, NN[1]); bezier_value((VECTOR(*)[4][4])&Control_Points, uu[2], vv[2], T1, NN[2]); VScale(T1, NN[0], r); VAddEq(N, T1); VScale(T1, NN[1], a); VAddEq(N, T1); VScale(T1, NN[2], b); VAddEq(N, T1); *u = r * uu[0] + a * uu[1] + b * uu[2]; *v = r * vv[0] + a * vv[1] + b * vv[2]; VDot(d, N, N); if (d > BEZIER_EPSILON) { d = 1.0 / sqrt(d); VScaleEq(N, d); } else { Make_Vector(N, 1, 0, 0); } return true; } /***************************************************************************** * * FUNCTION * * find_average * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * Find a sphere that contains all of the points in the list "vectors". * * CHANGES * * - * ******************************************************************************/ void BicubicPatch::find_average(int vector_count, const VECTOR *vectors, VECTOR center, DBL *radius) { int i; DBL r0, r1, xc = 0, yc = 0, zc = 0; DBL x0, y0, z0; for (i = 0; i < vector_count; i++) { xc += vectors[i][X]; yc += vectors[i][Y]; zc += vectors[i][Z]; } xc /= (DBL)vector_count; yc /= (DBL)vector_count; zc /= (DBL)vector_count; r0 = 0.0; for (i = 0; i < vector_count; i++) { x0 = vectors[i][X] - xc; y0 = vectors[i][Y] - yc; z0 = vectors[i][Z] - zc; r1 = x0 * x0 + y0 * y0 + z0 * z0; if (r1 > r0) { r0 = r1; } } Make_Vector(center, xc, yc, zc); *radius = r0; } /***************************************************************************** * * FUNCTION * * spherical_bounds_check * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ bool BicubicPatch::spherical_bounds_check(const Ray &ray, const VECTOR center, DBL radius) { DBL x, y, z, dist1, dist2; x = center[X] - ray.Origin[X]; y = center[Y] - ray.Origin[Y]; z = center[Z] - ray.Origin[Z]; dist1 = x * x + y * y + z * z; if (dist1 < radius) { /* ray starts inside sphere - assume it intersects. */ return true; } else { dist2 = x*ray.Direction[X] + y*ray.Direction[Y] + z*ray.Direction[Z]; dist2 *= dist2; if ((dist2 > 0) && ((dist1 - dist2) <= (radius + BEZIER_EPSILON) )) { return true; } } return false; } /***************************************************************************** * * FUNCTION * * bezier_bounding_sphere * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * Find a sphere that bounds all of the control points of a Bezier patch. * The values returned are: the center of the bounding sphere, and the * square of the radius of the bounding sphere. * * CHANGES * * - * ******************************************************************************/ void BicubicPatch::bezier_bounding_sphere(const VECTOR (*Patch)[4][4], VECTOR center, DBL *radius) { int i, j; DBL r0, r1, xc = 0, yc = 0, zc = 0; DBL x0, y0, z0; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { xc += (*Patch)[i][j][X]; yc += (*Patch)[i][j][Y]; zc += (*Patch)[i][j][Z]; } } xc /= 16.0; yc /= 16.0; zc /= 16.0; r0 = 0.0; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { x0 = (*Patch)[i][j][X] - xc; y0 = (*Patch)[i][j][Y] - yc; z0 = (*Patch)[i][j][Z] - zc; r1 = x0 * x0 + y0 * y0 + z0 * z0; if (r1 > r0) { r0 = r1; } } } Make_Vector(center, xc, yc, zc); *radius = r0; } /***************************************************************************** * * FUNCTION * * Precompute_Patch_Values * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * Precompute grid points and normals for a bezier patch. * * CHANGES * * - * ******************************************************************************/ void BicubicPatch::Precompute_Patch_Values() { int i, j; VECTOR cp[16]; VECTOR(*Patch_Ptr)[4][4] = (VECTOR(*)[4][4]) Control_Points; int max_depth_reached = 0; /* Calculate the bounding sphere for the entire patch. */ for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { Assign_Vector(cp[4*i + j], Control_Points[i][j]); } } find_average(16, cp, Bounding_Sphere_Center, &Bounding_Sphere_Radius); if (Patch_Type == 1) { if (Node_Tree != NULL) { bezier_tree_deleter(Node_Tree); } Node_Tree = bezier_tree_builder(Patch_Ptr, 0.0, 1.0, 0.0, 1.0, 0, max_depth_reached); } } /***************************************************************************** * * FUNCTION * * point_plane_distance * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * Determine the distance from a point to a plane. * * CHANGES * * - * ******************************************************************************/ DBL BicubicPatch::point_plane_distance(const VECTOR p, const VECTOR n, DBL d) { DBL temp1, temp2; VDot(temp1, p, n); temp1 += d; VLength(temp2, n); if (fabs(temp2) < EPSILON) { return (0.0); } temp1 /= temp2; return (temp1); } /***************************************************************************** * * FUNCTION * * bezier_subpatch_intersect * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ int BicubicPatch::bezier_subpatch_intersect(const Ray &ray, const VECTOR (*Patch)[4][4], DBL u0, DBL u1, DBL v0, DBL v1, IStack& Depth_Stack, TraceThreadData *Thread) { int cnt = 0; VECTOR V1[3]; DBL u, v, Depth; DBL uu[3], vv[3]; VECTOR P, N; UV_VECT UV; DBL uv_point[2], tpoint[2]; Assign_Vector(V1[0], (*Patch)[0][0]); Assign_Vector(V1[1], (*Patch)[0][3]); Assign_Vector(V1[2], (*Patch)[3][3]); uu[0] = u0; uu[1] = u0; uu[2] = u1; vv[0] = v0; vv[1] = v1; vv[2] = v1; if (intersect_subpatch(ray, V1, uu, vv, &Depth, P, N, &u, &v)) { /* transform current point from uv space to texture space */ uv_point[0] = v; uv_point[1] = u; Compute_Texture_UV(uv_point, ST, tpoint); UV[U] = tpoint[0]; UV[V] = tpoint[1]; Depth_Stack->push(Intersection(Depth, P, N, UV, this)); cnt++; } Assign_Vector(V1[1], V1[2]); Assign_Vector(V1[2], (*Patch)[3][0]); uu[1] = uu[2]; uu[2] = u1; vv[1] = vv[2]; vv[2] = v0; if (intersect_subpatch(ray, V1, uu, vv, &Depth, P, N, &u, &v)) { /* transform current point from uv space to texture space */ uv_point[0] = v; uv_point[1] = u; Compute_Texture_UV(uv_point, ST, tpoint); UV[U] = tpoint[0]; UV[V] = tpoint[1]; Depth_Stack->push(Intersection(Depth, P, N, UV, this)); cnt++; } return (cnt); } /***************************************************************************** * * FUNCTION * * bezier_split_left_right * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ void BicubicPatch::bezier_split_left_right(const VECTOR (*Patch)[4][4], VECTOR (*Left_Patch)[4][4], VECTOR (*Right_Patch)[4][4]) { int i, j; VECTOR Half; VECTOR Temp1[4], Temp2[4]; for (i = 0; i < 4; i++) { Assign_Vector(Temp1[0], (*Patch)[0][i]); VHalf(Temp1[1], (*Patch)[0][i], (*Patch)[1][i]); VHalf(Half, (*Patch)[1][i], (*Patch)[2][i]); VHalf(Temp1[2], Temp1[1], Half); VHalf(Temp2[2], (*Patch)[2][i], (*Patch)[3][i]); VHalf(Temp2[1], Half, Temp2[2]); VHalf(Temp1[3], Temp1[2], Temp2[1]); Assign_Vector(Temp2[0], Temp1[3]); Assign_Vector(Temp2[3], (*Patch)[3][i]); for (j = 0; j < 4; j++) { Assign_Vector((*Left_Patch)[j][i], Temp1[j]); Assign_Vector((*Right_Patch)[j][i], Temp2[j]); } } } /***************************************************************************** * * FUNCTION * * bezier_split_up_down * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ void BicubicPatch::bezier_split_up_down(const VECTOR (*Patch)[4][4], VECTOR (*Bottom_Patch)[4][4], VECTOR (*Top_Patch)[4][4]) { int i, j; VECTOR Temp1[4], Temp2[4]; VECTOR Half; for (i = 0; i < 4; i++) { Assign_Vector(Temp1[0], (*Patch)[i][0]); VHalf(Temp1[1], (*Patch)[i][0], (*Patch)[i][1]); VHalf(Half, (*Patch)[i][1], (*Patch)[i][2]); VHalf(Temp1[2], Temp1[1], Half); VHalf(Temp2[2], (*Patch)[i][2], (*Patch)[i][3]); VHalf(Temp2[1], Half, Temp2[2]); VHalf(Temp1[3], Temp1[2], Temp2[1]); Assign_Vector(Temp2[0], Temp1[3]); Assign_Vector(Temp2[3], (*Patch)[i][3]); for (j = 0; j < 4; j++) { Assign_Vector((*Bottom_Patch)[i][j], Temp1[j]); Assign_Vector((*Top_Patch)[i][j] , Temp2[j]); } } } /***************************************************************************** * * FUNCTION * * determine_subpatch_flatness * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * See how close to a plane a subpatch is, the patch must have at least * three distinct vertices. A negative result from this function indicates * that a degenerate value of some sort was encountered. * * CHANGES * * - * ******************************************************************************/ DBL BicubicPatch::determine_subpatch_flatness(const VECTOR (*Patch)[4][4]) { int i, j; DBL d, dist, temp1; VECTOR n, TempV; VECTOR vertices[4]; Assign_Vector(vertices[0], (*Patch)[0][0]); Assign_Vector(vertices[1], (*Patch)[0][3]); VSub(TempV, vertices[0], vertices[1]); VLength(temp1, TempV); if (fabs(temp1) < EPSILON) { /* * Degenerate in the V direction for U = 0. This is ok if the other * two corners are distinct from the lower left corner - I'm sure there * are cases where the corners coincide and the middle has good values, * but that is somewhat pathalogical and won't be considered. */ Assign_Vector(vertices[1], (*Patch)[3][3]); VSub(TempV, vertices[0], vertices[1]); VLength(temp1, TempV); if (fabs(temp1) < EPSILON) { return (-1.0); } Assign_Vector(vertices[2], (*Patch)[3][0]); VSub(TempV, vertices[0], vertices[1]); VLength(temp1, TempV); if (fabs(temp1) < EPSILON) { return (-1.0); } VSub(TempV, vertices[1], vertices[2]); VLength(temp1, TempV); if (fabs(temp1) < EPSILON) { return (-1.0); } } else { Assign_Vector(vertices[2], (*Patch)[3][0]); VSub(TempV, vertices[0], vertices[1]); VLength(temp1, TempV); if (fabs(temp1) < EPSILON) { Assign_Vector(vertices[2], (*Patch)[3][3]); VSub(TempV, vertices[0], vertices[2]); VLength(temp1, TempV); if (fabs(temp1) < EPSILON) { return (-1.0); } VSub(TempV, vertices[1], vertices[2]); VLength(temp1, TempV); if (fabs(temp1) < EPSILON) { return (-1.0); } } else { VSub(TempV, vertices[1], vertices[2]); VLength(temp1, TempV); if (fabs(temp1) < EPSILON) { return (-1.0); } } } /* * Now that a good set of candidate points has been found, * find the plane equations for the patch. */ if (subpatch_normal(vertices[0], vertices[1], vertices[2], n, &d)) { /* * Step through all vertices and see what the maximum * distance from the plane happens to be. */ dist = 0.0; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { temp1 = fabs(point_plane_distance(((*Patch)[i][j]), n, d)); if (temp1 > dist) { dist = temp1; } } } return (dist); } else { /* Debug_Info("Subpatch normal failed in determine_subpatch_flatness\n"); */ return (-1.0); } } /***************************************************************************** * * FUNCTION * * flat_enough * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ bool BicubicPatch::flat_enough(const VECTOR (*Patch)[4][4]) const { DBL Dist; Dist = determine_subpatch_flatness(Patch); if (Dist < 0.0) { return false; } else { if (Dist < Flatness_Value) { return true; } else { return false; } } } /***************************************************************************** * * FUNCTION * * bezier_subdivider * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ int BicubicPatch::bezier_subdivider(const Ray &ray, const VECTOR (*Patch)[4][4], DBL u0, DBL u1, DBL v0, DBL v1, int recursion_depth, IStack& Depth_Stack, TraceThreadData *Thread) { int cnt = 0; DBL ut, vt, radius; VECTOR Lower_Left[4][4], Lower_Right[4][4]; VECTOR Upper_Left[4][4], Upper_Right[4][4]; VECTOR center; /* * Make sure the ray passes through a sphere bounding * the control points of the patch. */ bezier_bounding_sphere(Patch, center, &radius); if (!spherical_bounds_check(ray, center, radius)) { return (0); } /* * If the patch is close to being flat, then just * perform a ray-plane intersection test. */ if (flat_enough(Patch)) return bezier_subpatch_intersect(ray, Patch, u0, u1, v0, v1, Depth_Stack, Thread); if (recursion_depth >= U_Steps) { if (recursion_depth >= V_Steps) { return bezier_subpatch_intersect(ray, Patch, u0, u1, v0, v1, Depth_Stack, Thread); } else { bezier_split_up_down(Patch, (VECTOR(*)[4][4])Lower_Left, (VECTOR(*)[4][4])Upper_Left); vt = (v1 + v0) / 2.0; cnt += bezier_subdivider(ray, (VECTOR(*)[4][4])Lower_Left, u0, u1, v0, vt, recursion_depth + 1, Depth_Stack, Thread); cnt += bezier_subdivider(ray, (VECTOR(*)[4][4])Upper_Left, u0, u1, vt, v1, recursion_depth + 1, Depth_Stack, Thread); } } else { if (recursion_depth >= V_Steps) { bezier_split_left_right(Patch, (VECTOR(*)[4][4])Lower_Left, (VECTOR(*)[4][4])Lower_Right); ut = (u1 + u0) / 2.0; cnt += bezier_subdivider(ray, (VECTOR(*)[4][4])Lower_Left, u0, ut, v0, v1, recursion_depth + 1, Depth_Stack, Thread); cnt += bezier_subdivider(ray, (VECTOR(*)[4][4])Lower_Right, ut, u1, v0, v1, recursion_depth + 1, Depth_Stack, Thread); } else { ut = (u1 + u0) / 2.0; vt = (v1 + v0) / 2.0; bezier_split_left_right(Patch, (VECTOR(*)[4][4])Lower_Left, (VECTOR(*)[4][4])Lower_Right); bezier_split_up_down((VECTOR(*)[4][4])Lower_Left, (VECTOR(*)[4][4])Lower_Left, (VECTOR(*)[4][4])Upper_Left) ; bezier_split_up_down((VECTOR(*)[4][4])Lower_Right, (VECTOR(*)[4][4])Lower_Right, (VECTOR(*)[4][4])Upper_Right); cnt += bezier_subdivider(ray, (VECTOR(*)[4][4])Lower_Left, u0, ut, v0, vt, recursion_depth + 1, Depth_Stack, Thread); cnt += bezier_subdivider(ray, (VECTOR(*)[4][4])Upper_Left, u0, ut, vt, v1, recursion_depth + 1, Depth_Stack, Thread); cnt += bezier_subdivider(ray, (VECTOR(*)[4][4])Lower_Right, ut, u1, v0, vt, recursion_depth + 1, Depth_Stack, Thread); cnt += bezier_subdivider(ray, (VECTOR(*)[4][4])Upper_Right, ut, u1, vt, v1, recursion_depth + 1, Depth_Stack, Thread); } } return (cnt); } /***************************************************************************** * * FUNCTION * * bezier_tree_deleter * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ void BicubicPatch::bezier_tree_deleter(BEZIER_NODE *Node) { int i; BEZIER_CHILDREN *Children; /* If this is an interior node then continue the descent. */ if (Node->Node_Type == BEZIER_INTERIOR_NODE) { Children = (BEZIER_CHILDREN *)Node->Data_Ptr; for (i = 0; i < Node->Count; i++) { bezier_tree_deleter(Children->Children[i]); } POV_FREE(Children); } else { if (Node->Node_Type == BEZIER_LEAF_NODE) { /* Free the memory used for the vertices. */ POV_FREE(Node->Data_Ptr); } } /* Free the memory used for the node. */ POV_FREE(Node); } /***************************************************************************** * * FUNCTION * * bezier_tree_walker * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ int BicubicPatch::bezier_tree_walker(const Ray &ray, const BEZIER_NODE *Node, IStack& Depth_Stack, TraceThreadData *Thread) { int i, cnt = 0; DBL Depth, u, v; DBL uu[3], vv[3]; VECTOR N, P; VECTOR V1[3]; UV_VECT UV; DBL uv_point[2], tpoint[2]; const BEZIER_CHILDREN *Children; const BEZIER_VERTICES *Vertices; /* * Make sure the ray passes through a sphere bounding * the control points of the patch. */ if (!spherical_bounds_check(ray, Node->Center, Node->Radius_Squared)) { return (0); } /* * If this is an interior node then continue the descent, * else do a check against the vertices. */ if (Node->Node_Type == BEZIER_INTERIOR_NODE) { Children = (const BEZIER_CHILDREN *)Node->Data_Ptr; for (i = 0; i < Node->Count; i++) { cnt += bezier_tree_walker(ray, Children->Children[i], Depth_Stack, Thread); } } else if (Node->Node_Type == BEZIER_LEAF_NODE) { Vertices = (const BEZIER_VERTICES *)Node->Data_Ptr; Assign_Vector(V1[0], Vertices->Vertices[0]); Assign_Vector(V1[1], Vertices->Vertices[1]); Assign_Vector(V1[2], Vertices->Vertices[2]); uu[0] = Vertices->uvbnds[0]; uu[1] = Vertices->uvbnds[0]; uu[2] = Vertices->uvbnds[1]; vv[0] = Vertices->uvbnds[2]; vv[1] = Vertices->uvbnds[3]; vv[2] = Vertices->uvbnds[3]; /* * Triangulate this subpatch, then check for * intersections in the triangles. */ if (intersect_subpatch( ray, V1, uu, vv, &Depth, P, N, &u, &v)) { /* transform current point from uv space to texture space */ uv_point[0] = v; uv_point[1] = u; Compute_Texture_UV(uv_point, ST, tpoint); UV[U] = tpoint[0]; UV[V] = tpoint[1]; Depth_Stack->push(Intersection(Depth, P, N, UV, this)); cnt++; } Assign_Vector(V1[1], V1[2]); Assign_Vector(V1[2], Vertices->Vertices[3]); uu[1] = uu[2]; uu[2] = Vertices->uvbnds[1]; vv[1] = vv[2]; vv[2] = Vertices->uvbnds[2]; if (intersect_subpatch(ray, V1, uu, vv, &Depth, P, N, &u, &v)) { /* transform current point from object space to texture space */ uv_point[0] = v; uv_point[1] = u; Compute_Texture_UV(uv_point, ST, tpoint); UV[U] = tpoint[0]; UV[V] = tpoint[1]; Depth_Stack->push(Intersection(Depth, P, N, UV, this)); cnt++; } } else { throw POV_EXCEPTION_STRING("Bad Node type in bezier_tree_walker()."); } return (cnt); } /***************************************************************************** * * FUNCTION * * intersect_bicubic_patch0 * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ int BicubicPatch::intersect_bicubic_patch0(const Ray &ray, IStack& Depth_Stack, TraceThreadData *Thread) { const VECTOR(*Patch)[4][4] = &Control_Points; return (bezier_subdivider(ray, Patch, 0.0, 1.0, 0.0, 1.0, 0, Depth_Stack, Thread)); } /***************************************************************************** * * FUNCTION * * All_Bicubic_Patch_Intersections * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ bool BicubicPatch::All_Intersections(const Ray& ray, IStack& Depth_Stack, TraceThreadData *Thread) { int Found, cnt = 0; Found = false; Thread->Stats()[Ray_Bicubic_Tests]++; switch (Patch_Type) { case 0: cnt = intersect_bicubic_patch0(ray, Depth_Stack, Thread); break; case 1: cnt = bezier_tree_walker(ray, Node_Tree, Depth_Stack, Thread); break; default: throw POV_EXCEPTION_STRING("Bad patch type in All_Bicubic_Patch_Intersections."); } if (cnt > 0) { Thread->Stats()[Ray_Bicubic_Tests_Succeeded]++; Found = true; } return (Found); } /***************************************************************************** * * FUNCTION * * Inside_Bicubic_Patch * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * A patch is not a solid, so an inside test doesn't make sense. * * CHANGES * * - * ******************************************************************************/ bool BicubicPatch::Inside(const VECTOR, TraceThreadData *) const { return false; } /***************************************************************************** * * FUNCTION * * Bicubic_Patch_Normal * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ void BicubicPatch::Normal(VECTOR Result, Intersection *Inter, TraceThreadData *Thread) const { /* Use preocmputed normal. */ Assign_Vector(Result, Inter->INormal); } /***************************************************************************** * * FUNCTION * * Translate_Bicubic_Patch * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ void BicubicPatch::Translate(const VECTOR Vector, const TRANSFORM *) { int i, j; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { VAdd(Control_Points[i][j], Control_Points[i][j], Vector); } } Precompute_Patch_Values(); Compute_BBox(); } /***************************************************************************** * * FUNCTION * * Rotate_Bicubic_Patch * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ void BicubicPatch::Rotate(const VECTOR, const TRANSFORM *tr) { Transform(tr); } /***************************************************************************** * * FUNCTION * * Scale_Bicubic_Patch * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ void BicubicPatch::Scale(const VECTOR Vector, const TRANSFORM *) { int i, j; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { VEvaluate(Control_Points[i][j], Control_Points[i][j], Vector); } } Precompute_Patch_Values(); Compute_BBox(); } /***************************************************************************** * * FUNCTION * * Transform_Bicubic_Patch * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ void BicubicPatch::Transform(const TRANSFORM *tr) { int i, j; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { MTransPoint(Control_Points[i][j], Control_Points[i][j], tr); } } Precompute_Patch_Values(); Compute_BBox(); } /***************************************************************************** * * FUNCTION * * Invert_Bicubic_Patch * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * Inversion of a patch really doesn't make sense. * * CHANGES * * - * ******************************************************************************/ void BicubicPatch::Invert() { } /***************************************************************************** * * FUNCTION * * Create_Bicubic_Patch * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ BicubicPatch::BicubicPatch() : ObjectBase(BICUBIC_PATCH_OBJECT) { Patch_Type = - 1; U_Steps = 0; V_Steps = 0; Flatness_Value = 0.0; accuracy = 0.01; Node_Tree = NULL; Weights = NULL; /* * NOTE: Control_Points[4][4] is initialized in Parse_Bicubic_Patch. * Bounding_Sphere_Center,Bounding_Sphere_Radius, Normal_Vector[], and * IPoint[] are initialized in Precompute_Patch_Values. */ /* set the default uv-mapping coordinates */ ST[0][U] = 0; ST[0][V] = 0; ST[1][U] = 1; ST[1][V] = 0; ST[2][U] = 1; ST[2][V] = 1; ST[3][U] = 0; ST[3][V] = 1; } /***************************************************************************** * * FUNCTION * * Copy_Bicubic_Patch * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ ObjectPtr BicubicPatch::Copy() { int i, j; BicubicPatch *New = new BicubicPatch(); int m, h; /* Do not do *New = *Old so that Precompute works right */ New->Patch_Type = Patch_Type; New->U_Steps = U_Steps; New->V_Steps = V_Steps; if ( Weights != NULL ) { New->Weights = (WEIGHTS *)POV_MALLOC( sizeof(WEIGHTS),"bicubic patch" ); POV_MEMCPY( New->Weights, Weights, sizeof(WEIGHTS) ); } for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { Assign_Vector(New->Control_Points[i][j], Control_Points[i][j]); } } New->Flatness_Value = Flatness_Value; New->Precompute_Patch_Values(); /* copy the mapping */ for (m = 0; m < 4; m++) { for (h = 0; h < 3; h++) { New->ST[m][h] = ST[m][h]; } } return (New); } /***************************************************************************** * * FUNCTION * * Destroy_Bicubic_Patch * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Alexander Enzmann * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ BicubicPatch::~BicubicPatch() { if (Patch_Type == 1) { if (Node_Tree != NULL) { bezier_tree_deleter(Node_Tree); } } if ( Weights != NULL ) POV_FREE(Weights); } /***************************************************************************** * * FUNCTION * * Compute_Bicubic_Patch_BBox * * INPUT * * Bicubic_Patch - Bicubic patch * * OUTPUT * * Bicubic_Patch * * RETURNS * * AUTHOR * * Dieter Bayer * * DESCRIPTION * * Calculate the bounding box of a bicubic patch. * * CHANGES * * Aug 1994 : Creation. * ******************************************************************************/ void BicubicPatch::Compute_BBox() { int i, j; VECTOR Min, Max; Make_Vector(Min, BOUND_HUGE, BOUND_HUGE, BOUND_HUGE); Make_Vector(Max, -BOUND_HUGE, -BOUND_HUGE, -BOUND_HUGE); for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { Min[X] = min(Min[X], Control_Points[i][j][X]); Min[Y] = min(Min[Y], Control_Points[i][j][Y]); Min[Z] = min(Min[Z], Control_Points[i][j][Z]); Max[X] = max(Max[X], Control_Points[i][j][X]); Max[Y] = max(Max[Y], Control_Points[i][j][Y]); Max[Z] = max(Max[Z], Control_Points[i][j][Z]); } } Make_BBox_from_min_max(BBox, Min, Max); } /***************************************************************************** * * FUNCTION * * Bicubic_Patch_UVCoord * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Nathan Kopp * * DESCRIPTION * * - * * CHANGES * * - * ******************************************************************************/ void BicubicPatch::UVCoord(UV_VECT Result, const Intersection *Inter, TraceThreadData *Thread) const { /* Use preocmputed uv coordinates. */ Assign_UV_Vect(Result, Inter->Iuv); } /***************************************************************************** * * FUNCTION * * Compute_UV_Point * * INPUT * * OUTPUT * * RETURNS * * AUTHOR * * Mike Hough * * DESCRIPTION * * Transform p from uv space to texture space (point t) using the * shape's ST mapping * * CHANGES * * - * ******************************************************************************/ void BicubicPatch::Compute_Texture_UV(const UV_VECT p, const UV_VECT st[4], UV_VECT t) { UV_VECT u1, u2; u1[0] = st[0][0] + p[0] * (st[1][0] - st[0][0]); u1[1] = st[0][1] + p[0] * (st[1][1] - st[0][1]); u2[0] = st[3][0] + p[0] * (st[2][0] - st[3][0]); u2[1] = st[3][1] + p[0] * (st[2][1] - st[3][1]); t[0] = u1[0] + p[1] * (u2[0] - u1[0]); t[1] = u1[1] + p[1] * (u2[1] - u1[1]); } }
19.088898
182
0.533246
acekiller
d308603b4cafc4b003b92fad971055b67b738aff
5,336
cpp
C++
samples/stm32l011xx/command_line/main.cpp
JayKickliter/CML
d21061a3abc013a8386798280b9595e9d4a2978c
[ "MIT" ]
null
null
null
samples/stm32l011xx/command_line/main.cpp
JayKickliter/CML
d21061a3abc013a8386798280b9595e9d4a2978c
[ "MIT" ]
null
null
null
samples/stm32l011xx/command_line/main.cpp
JayKickliter/CML
d21061a3abc013a8386798280b9595e9d4a2978c
[ "MIT" ]
null
null
null
/* Name: main.cpp Copyright(c) 2019 Mateusz Semegen This code is licensed under MIT license (see LICENSE file for details) */ //cml #include <cml/collection/Vector.hpp> #include <cml/common/cstring.hpp> #include <cml/hal/counter.hpp> #include <cml/hal/systick.hpp> #include <cml/hal/peripherals/GPIO.hpp> #include <cml/hal/peripherals/USART.hpp> #include <cml/hal/mcu.hpp> #include <cml/utils/Command_line.hpp> namespace { using namespace cml; using namespace cml::collection; using namespace cml::common; using namespace cml::hal; using namespace cml::hal::peripherals; using namespace cml::utils; void led_cli_callback(const Vector<Command_line::Callback::Parameter>& a_params, void* a_p_user_data) { pin::Out* p_led_pin = reinterpret_cast<pin::Out*>(a_p_user_data); if (2 == a_params.get_length()) { bool is_on = cstring::equals(a_params[1].a_p_value, "on", a_params[1].length); if (true == is_on) { p_led_pin->set_level(pin::Level::high); } else { bool is_off = cstring::equals(a_params[1].a_p_value, "off", a_params[1].length); if (true == is_off) { p_led_pin->set_level(pin::Level::low); } } } } void reset_callback(const Vector<Command_line::Callback::Parameter>& a_params, void* a_p_user_data) { mcu::reset(); } uint32_t write_character(char a_character, void* a_p_user_data) { USART* p_console_usart = reinterpret_cast<USART*>(a_p_user_data); return p_console_usart->transmit_bytes_polling(&a_character, 1).data_length_in_words; } uint32_t write_string(const char* a_p_string, uint32_t a_length, void* a_p_user_data) { USART* p_console_usart = reinterpret_cast<USART*>(a_p_user_data); return p_console_usart->transmit_bytes_polling(a_p_string, a_length).data_length_in_words; } uint32_t read_key(char* a_p_out, uint32_t a_length, void* a_p_user_data) { USART* p_console_usart = reinterpret_cast<USART*>(a_p_user_data); return p_console_usart->receive_bytes_polling(a_p_out, a_length).data_length_in_words; } } // namespace :: int main() { using namespace cml::common; using namespace cml::hal; using namespace cml::utils; mcu::enable_hsi_clock(mcu::Hsi_frequency::_16_MHz); mcu::set_sysclk(mcu::Sysclk_source::hsi, { mcu::Bus_prescalers::AHB::_1, mcu::Bus_prescalers::APB1::_1, mcu::Bus_prescalers::APB2::_1 }); if (mcu::Sysclk_source::hsi == mcu::get_sysclk_source()) { USART::Config usart_config = { 115200u, USART::Oversampling::_16, USART::Stop_bits::_1, USART::Flow_control_flag::none, USART::Sampling_method::three_sample_bit, USART::Mode_flag::rx | USART::Mode_flag::tx }; USART::Frame_format usart_frame_format { USART::Word_length::_8_bit, USART::Parity::none }; USART::Clock usart_clock { USART::Clock::Source::sysclk, mcu::get_sysclk_frequency_hz(), }; pin::af::Config usart_pin_config = { pin::Mode::push_pull, pin::Pull::up, pin::Speed::low, 0x4u }; mcu::disable_msi_clock(); systick::enable((mcu::get_sysclk_frequency_hz() / kHz(1)) - 1, 0x9u); systick::register_tick_callback({ counter::update, nullptr }); GPIO gpio_port_a(GPIO::Id::a); gpio_port_a.enable(); pin::af::enable(&gpio_port_a, 2u, usart_pin_config); pin::af::enable(&gpio_port_a, 15u, usart_pin_config); USART console_usart(USART::Id::_2); bool usart_ready = console_usart.enable(usart_config, usart_frame_format, usart_clock, 0x1u, 10); if (true == usart_ready) { GPIO gpio_port_b(GPIO::Id::b); gpio_port_b.enable(); pin::Out led_pin; pin::out::enable(&gpio_port_b, 3u, { pin::Mode::push_pull, pin::Pull::down, pin::Speed::low }, &led_pin); char preamble[36]; cstring::format(preamble, sizeof(preamble), "\nCML CLI sample. CPU speed: %d MHz\n", mcu::get_sysclk_frequency_hz() / MHz(1)); console_usart.transmit_bytes_polling(preamble, sizeof(preamble)); Command_line command_line({ write_character, &console_usart }, { write_string, &console_usart }, { read_key, &console_usart }, "cmd > ", "Command not found"); command_line.register_callback({ "led", led_cli_callback, &led_pin }); command_line.register_callback({ "reset", reset_callback, nullptr }); command_line.write_prompt(); while (true) { command_line.update(); } } } while (true); }
31.761905
118
0.572714
JayKickliter
d309a3a3096fdebad8cf4baf0f5fd64a39720fe9
673
cpp
C++
Leetcode/remve_duplicates_sorted.cpp
prameetu/CP_codes
41f8cfc188d2e08a8091bc5134247d05ba8a78f5
[ "MIT" ]
null
null
null
Leetcode/remve_duplicates_sorted.cpp
prameetu/CP_codes
41f8cfc188d2e08a8091bc5134247d05ba8a78f5
[ "MIT" ]
null
null
null
Leetcode/remve_duplicates_sorted.cpp
prameetu/CP_codes
41f8cfc188d2e08a8091bc5134247d05ba8a78f5
[ "MIT" ]
null
null
null
//leetcode - 26 #include<bits/stdc++.h> using namespace std; int remove_duplicate_sorteed_array(vector <int> &v) { if(v.size() == 0) return 0; int i(0); int j(1); while(j<v.size()) { if(v[i] == v[j]) { j++; } else { i++; v[i] = v[j]; j++; } } return i+1; } int main() { vector <int> v; int n,x; cin >> n; while(n--) { cin >> x; v.push_back(x); } for(int i=0;i<remove_duplicate_sorteed_array(v);i++) { cout << v[i] << " "; } }
14.020833
57
0.358098
prameetu
d30a03dbe1f2a00e2e21a44e4fae7cec5e64320f
3,974
hh
C++
dependencies/include/fastjet/internal/Triangulation.hh
ZAKI1905/HEP-Phen
bc06fecb2aa6bf108b59f76794e63c29eb37a35a
[ "MIT" ]
1
2019-10-21T08:25:46.000Z
2019-10-21T08:25:46.000Z
dependencies/include/fastjet/internal/Triangulation.hh
ZAKI1905/HEP-Phen
bc06fecb2aa6bf108b59f76794e63c29eb37a35a
[ "MIT" ]
null
null
null
dependencies/include/fastjet/internal/Triangulation.hh
ZAKI1905/HEP-Phen
bc06fecb2aa6bf108b59f76794e63c29eb37a35a
[ "MIT" ]
null
null
null
#ifndef DROP_CGAL // in case we do not have the code for CGAL #ifndef __FASTJET_TRIANGULATION__ #define __FASTJET_TRIANGULATION__ //FJSTARTHEADER // $Id: Triangulation.hh 4354 2018-04-22 07:12:37Z salam $ // // Copyright (c) 2005-2018, Matteo Cacciari, Gavin P. Salam and Gregory Soyez // //---------------------------------------------------------------------- // This file is part of FastJet. // // FastJet is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // The algorithms that underlie FastJet have required considerable // development. They are described in the original FastJet paper, // hep-ph/0512210 and in the manual, arXiv:1111.6097. If you use // FastJet as part of work towards a scientific publication, please // quote the version you use and include a citation to the manual and // optionally also to hep-ph/0512210. // // FastJet is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with FastJet. If not, see <http://www.gnu.org/licenses/>. //---------------------------------------------------------------------- //FJENDHEADER // file: examples/Triangulation_2/Voronoi.C #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/Delaunay_triangulation_2.h> #include <CGAL/Triangulation_hierarchy_2.h> #include <CGAL/Triangulation_vertex_base_with_info_2.h> #include "fastjet/internal/base.hh" FASTJET_BEGIN_NAMESPACE // defined in fastjet/internal/base.hh /// \if internal_doc /// @ingroup internal /// \struct K /// the basic geometrical kernel that lies at the base of all CGAL /// operations /// \endif #ifdef CGAL_SIMPLE_KERNEL struct K : CGAL::Simple_cartesian<double> {}; #else struct K : CGAL::Exact_predicates_inexact_constructions_kernel {}; #endif // CGAL_SIMPLE_KERNEL // our extras to help us navigate, find distance, etc. const int INFINITE_VERTEX=-1; const int NEW_VERTEX=-2; const double HUGE_DOUBLE=1e300; /// \if internal_doc /// @ingroup internal /// \struct InitialisedInt /// A class to provide an "int" with an initial value. /// \endif class InitialisedInt { private: int _val; public: inline InitialisedInt () {_val=NEW_VERTEX;}; inline InitialisedInt& operator= (int value) {_val = value; return *this;}; inline int val() const {return _val;}; }; // We can have triangulations with and without hierarchies -- those with // are able to guarantee N ln N time for the construction of a large // triangulation, whereas those without go as N^{3/2} for points // sufficiently uniformly distributed in a plane. // //#define NOHIERARCHY #ifdef NOHIERARCHY typedef CGAL::Triangulation_vertex_base_with_info_2<InitialisedInt,K> Vb; typedef CGAL::Triangulation_face_base_2<K> Fb; typedef CGAL::Triangulation_data_structure_2<Vb,Fb> Tds; typedef CGAL::Delaunay_triangulation_2<K,Tds> Triangulation; #else typedef CGAL::Triangulation_vertex_base_with_info_2<InitialisedInt,K> Vbb; typedef CGAL::Triangulation_hierarchy_vertex_base_2<Vbb> Vb; typedef CGAL::Triangulation_face_base_2<K> Fb; typedef CGAL::Triangulation_data_structure_2<Vb,Fb> Tds; typedef CGAL::Delaunay_triangulation_2<K,Tds> Dt; typedef CGAL::Triangulation_hierarchy_2<Dt> Triangulation; #endif typedef Triangulation::Vertex_handle Vertex_handle; typedef Triangulation::Point Point; /// CGAL Point structure typedef Triangulation::Vertex_circulator Vertex_circulator; typedef Triangulation::Face_circulator Face_circulator; typedef Triangulation::Face_handle Face_handle; FASTJET_END_NAMESPACE #endif // __FASTJET_TRIANGULATION__ #endif // DROP_CGAL
36.458716
77
0.744338
ZAKI1905
d30e9b47aca32b97d8a7182db8fdd762709681aa
2,451
cpp
C++
BinaryIO/BinaryReader.cpp
ghaffaribehdad/Preprocessor
85165a1259f8dcb1edd92a8113343875dd6085ea
[ "MIT" ]
null
null
null
BinaryIO/BinaryReader.cpp
ghaffaribehdad/Preprocessor
85165a1259f8dcb1edd92a8113343875dd6085ea
[ "MIT" ]
null
null
null
BinaryIO/BinaryReader.cpp
ghaffaribehdad/Preprocessor
85165a1259f8dcb1edd92a8113343875dd6085ea
[ "MIT" ]
null
null
null
#include "BinaryReader.h" #include <fstream> #include <filesystem> // define fs namespace for convenience namespace fs = std::experimental::filesystem; // keep track fo instantiation unsigned int BinaryReader::s_instances = 0; // constructor BinaryReader::BinaryReader(const char* _fileName) { //increment number of instances s_instances += 1; this->m_fileName = _fileName; // extract the current path fs::path path_currentPath = fs::current_path(); this->m_filePath = path_currentPath.u8string(); // add a backslash at the end of path this->m_filePath += "\\"; } // constructor BinaryReader::BinaryReader(const char* _fileName, const char* _filePath) : m_fileName(_fileName), m_filePath(_filePath) {} // getter functions const char* BinaryReader::getfileName() const { return m_fileName.c_str(); } const char* BinaryReader::getfilePath() const { return m_filePath.c_str(); } // setter void BinaryReader::setfileName(const char* _fileName) { m_fileName = std::string(_fileName); } void BinaryReader::setfilePath(const char* _filePath) { m_filePath = std::string(_filePath); } bool BinaryReader::read() { // define the istream std::ifstream myFile; std::string fullPath= m_filePath + m_fileName; myFile = std::ifstream(fullPath, std::ios::binary); // check whether the file is open if (!myFile.is_open()) return false; // get the starting position std::streampos start = myFile.tellg(); // go to the end myFile.seekg(0, std::ios::end); // get the ending position std::streampos end = myFile.tellg(); // return to starting position myFile.seekg(0, std::ios::beg); // size of the buffer const int buffer_size = static_cast<int>(end - start); // resize it to fit the dataset(MUST BE EDITED WHILE IT IS ABOVE THE RAM SIZE) this->m_vec_buffer.resize(buffer_size); //read file and store it into buffer myFile.read(&(m_vec_buffer.at(0)), buffer_size); // close the file myFile.close(); return true; } std::vector<char>* BinaryReader::flush_buffer() { return & m_vec_buffer; } void BinaryReader::clean_buffer() { this->m_vec_buffer.clear(); } BinaryReader::BinaryReader() { this->m_fileName = ""; this->m_filePath = ""; this->m_vec_buffer = {}; } void BinaryReader::setVecBuffer(const std::vector<char> * _vec_buffer) { this->m_vec_buffer = *_vec_buffer; }
20.771186
80
0.681355
ghaffaribehdad
d310a52a4d42d17e75db3bcf05f0fadc483e91be
1,076
cpp
C++
JTS/CF-B/CF714-D2-B/main.cpp
rahulsrma26/ol_codes
dc599f5b70c14229a001c5239c366ba1b990f68b
[ "MIT" ]
2
2019-03-18T16:06:10.000Z
2019-04-07T23:17:06.000Z
JTS/CF-B/CF714-D2-B/main.cpp
rahulsrma26/ol_codes
dc599f5b70c14229a001c5239c366ba1b990f68b
[ "MIT" ]
null
null
null
JTS/CF-B/CF714-D2-B/main.cpp
rahulsrma26/ol_codes
dc599f5b70c14229a001c5239c366ba1b990f68b
[ "MIT" ]
1
2019-03-18T16:06:52.000Z
2019-03-18T16:06:52.000Z
// Date : 2019-03-29 // Author : Rahul Sharma // Problem : http://codeforces.com/contest/714/problem/B #include <algorithm> #include <iostream> #include <vector> int main() { using namespace std; ios_base::sync_with_stdio(false); cin.tie(0); int n; cin >> n; int a = -1, b = -1, c = -1, i = 1; cin >> a; for (int x; i < n; i++) { cin >> x; if(x != a){ b = x; i++; break; } } for (int x; i < n; i++) { cin >> x; if(x != a && x != b){ c = x; i++; break; } } bool possible = true; for (int x; i < n; i++) { cin >> x; if(x != a && x != b && x != c){ possible = false; break; } } if(possible && c != -1){ if(a > b) swap(a, b); if(b > c) swap(b, c); if(a > b) swap(a, b); if(c - b != b - a) possible = false; } cout << (possible ? "YES" : "NO") << '\n'; }
18.877193
56
0.358736
rahulsrma26
d310f83c21ed88818d09c47575a6108e2e6884e7
4,603
hpp
C++
System.Drawing/src/Switch/System/Drawing/Png.hpp
kkptm/CppLikeCSharp
b2d8d9da9973c733205aa945c9ba734de0c734bc
[ "MIT" ]
4
2021-10-14T01:43:00.000Z
2022-03-13T02:16:08.000Z
System.Drawing/src/Switch/System/Drawing/Png.hpp
kkptm/CppLikeCSharp
b2d8d9da9973c733205aa945c9ba734de0c734bc
[ "MIT" ]
null
null
null
System.Drawing/src/Switch/System/Drawing/Png.hpp
kkptm/CppLikeCSharp
b2d8d9da9973c733205aa945c9ba734de0c734bc
[ "MIT" ]
2
2022-03-13T02:16:06.000Z
2022-03-14T14:32:57.000Z
#pragma once #define PNG_SKIP_SETJMP_CHECK #include <png.h> #undef PNG_SKIP_SETJMP_CHECK #include <zlib.h> #include <Switch/System/Object.hpp> #include <Switch/System/IO//BinaryReader.hpp> #include "../../../../include/Switch/System/Drawing/Image.hpp" #include "../../../../include/Switch/System/Drawing/Imaging/FrameDimension.hpp" struct PngMemory { png_structp pp; const unsigned char* current; const unsigned char* last; }; extern "C" { static void PngReadDataFromMem(png_structp png_ptr, png_bytep data, png_size_t length) { struct PngMemory* png_mem_data = (PngMemory*)png_get_io_ptr(png_ptr); if (png_mem_data->current + length > png_mem_data->last) { png_error(png_mem_data->pp, "Invalid attempt to read row data"); return; } memcpy(data, png_mem_data->current, length); png_mem_data->current += length; } } // extern "C" namespace Switch { namespace System { namespace Drawing { class Png : public object { public: template<typename TStream> Png(const TStream& stream) : reader(ref_new<System::IO::BinaryReader>(stream)) {} Png(refptr<System::IO::Stream> stream) : reader(ref_new<System::IO::BinaryReader>(stream)) {} void Read(Image& image) { png_infop info = null; png_structp pp = png_create_read_struct(PNG_LIBPNG_VER_STRING, null, null, null); if (pp) info = png_create_info_struct(pp); if (!pp || !info) { if (pp) png_destroy_read_struct(&pp, null, null); throw OutOfMemoryException(caller_); } if (setjmp(png_jmpbuf(pp))) { png_destroy_read_struct(&pp, &info, null); throw OutOfMemoryException(caller_); } Array<byte> streamData((int32)reader->BaseStream().Length()); reader->Read(streamData, 0, static_cast<int32>(reader->BaseStream().Length())); PngMemory png_mem_data; png_mem_data.current = streamData.Data(); png_mem_data.last = streamData.Data() + reader->BaseStream().Length(); png_mem_data.pp = pp; png_set_read_fn(pp, (png_voidp) &png_mem_data, PngReadDataFromMem); png_read_info(pp, info); if (png_get_color_type(pp, info) == PNG_COLOR_TYPE_PALETTE) png_set_expand(pp); image.size.Width((int)(png_get_image_width(pp, info))); image.size.Height((int)(png_get_image_height(pp, info))); switch (png_get_bit_depth(pp, info)) { case 8: image.pixelFormat = Imaging::PixelFormat::Format8bppIndexed; break; case 16: image.pixelFormat = Imaging::PixelFormat::Format16bppRgb555; break; case 24: image.pixelFormat = Imaging::PixelFormat::Format24bppRgb; break; case 32: image.pixelFormat = Imaging::PixelFormat::Format32bppRgb; break; default: image.pixelFormat = Imaging::PixelFormat::Undefined; break; } if (png_get_bit_depth(pp, info) < 8) { png_set_packing(pp); png_set_expand(pp); } else if (png_get_bit_depth(pp, info) == 16) png_set_strip_16(pp); if (png_get_valid(pp, info, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(pp); Array<byte> rawData(image.size.Width() * image.size.Height() * (image.pixelFormat == Imaging::PixelFormat::Format32bppRgb ? 4 : 3)); Array<png_bytep> rows(image.size.Height()); for (int32 i = 0; i < image.size.Height(); i ++) rows[i] = (png_bytep)(rawData.Data() + i * image.size.Width() * (image.pixelFormat == Imaging::PixelFormat::Format32bppRgb ? 4 : 3)); for (int32 i = png_set_interlace_handling(pp); i > 0; i --) png_read_rows(pp, (png_bytep*)rows.Data(), null, image.size.Height()); #if defined(_WIN32) if (image.pixelFormat == Imaging::PixelFormat::Format32bppRgb) { byte* ptr = (byte*)rawData.Data(); for (int32 i = image.size.Width() * image.size.Height(); i > 0; i --) { if (!ptr[3]) ptr[0] = ptr[1] = ptr[2] = 0; ptr += 4; } } #endif png_read_end(pp, info); png_destroy_read_struct(&pp, &info, null); //image.rawData = Array<byte>(rawData.Data(), image.size.Width() * image.size.Height() * (image.PixelFormat() == System::Drawing::Imaging::PixelFormat::Format32bppRgb ? 4 : 3)); image.rawData = rawData; } private: refptr<System::IO::BinaryReader> reader; }; } } }
37.422764
187
0.611123
kkptm
d31146fb16e388b45f401cec225d5c1702cd50b7
2,865
cpp
C++
SDK/src/lgGuiExplorador.cpp
rgr0912/LibreGame
ffce4dbb3abeea1bbc64bb5bea29f76fc44b1e4f
[ "MIT" ]
null
null
null
SDK/src/lgGuiExplorador.cpp
rgr0912/LibreGame
ffce4dbb3abeea1bbc64bb5bea29f76fc44b1e4f
[ "MIT" ]
null
null
null
SDK/src/lgGuiExplorador.cpp
rgr0912/LibreGame
ffce4dbb3abeea1bbc64bb5bea29f76fc44b1e4f
[ "MIT" ]
null
null
null
#include "lgIMGUI.h" Ogre::String objeto; Ogre::SceneNode* _nodeImgui; static int rb = 1; static int rl = 1; void lgGUI::Explorador(bool* p, Ogre::RenderWindow* win, Ogre::SceneManager* manager){ ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoTitleBar; window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(10,10)); //obteniendo las dimensiones de la venta para asignar tamaño int h = win->getHeight(); int w = win->getWidth(); ImGui::SetNextWindowPos(ImVec2(0,tmenubar+tmenuherrmientas)); ImGui::SetNextWindowSize(ImVec2(200,h)); //explorador de entidades y luces ImGui::Begin("Explorador",p, window_flags); if (ImGui::CollapsingHeader("Entidades")){ ImGuiIO& io = ImGui::GetIO(); int contador_ent = 0; //obteniendo entidades del SceneManager de ogre Ogre::SceneManager::MovableObjectIterator mIterator = manager->getMovableObjectIterator("Entity"); while(mIterator.hasMoreElements()){ e = static_cast<Ogre::Entity*>(mIterator.getNext()); objeto = e->getName(); _nodeImgui = e->getParentSceneNode(); const char* c = objeto.c_str(); ImGui::RadioButton(c, &rb, contador_ent); if(rb == contador_ent){ Propiedades(p,win,e,c); _nodeImgui->showBoundingBox(true); }else{ _nodeImgui->showBoundingBox(false); } ImGui::Separator(); contador_ent = contador_ent + 1; } if(!mIterator.hasMoreElements()){ } } if (ImGui::CollapsingHeader("Luces")){ ImGuiIO& io = ImGui::GetIO(); int contador_l = 0; //obteniendo luces Ogre::SceneManager::MovableObjectIterator mIterator = manager->getMovableObjectIterator("Light"); while(mIterator.hasMoreElements()){ l = static_cast<Ogre::Light*>(mIterator.getNext()); objeto = l->getName(); _nodeImgui = l->getParentSceneNode(); const char* c = objeto.c_str(); ImGui::RadioButton(c, &rb, contador_l); if(rb == contador_l){ PropiedadesLuz(p,win,l,c); SelectorColorLuz(l); _nodeImgui->showBoundingBox(true); }else{ _nodeImgui->showBoundingBox(false); } ImGui::Separator(); contador_l = contador_l + 1; } if(!mIterator.hasMoreElements()){ } } ImGui::End(); ImGui::PopStyleVar(2); }
36.730769
132
0.609773
rgr0912
d312c56b74e161ad7b6c71cf7ae2bf2d04a1e8ec
2,925
cpp
C++
cxx_examples/threshold_detect.cpp
kb3gtn/BladeRF_Setup_Instructions
14f970a5d426a1909ab7d45165c808879bbb1f17
[ "CC0-1.0" ]
1
2021-12-12T15:05:25.000Z
2021-12-12T15:05:25.000Z
cxx_examples/threshold_detect.cpp
kb3gtn/BladeRF_Setup_Instructions
14f970a5d426a1909ab7d45165c808879bbb1f17
[ "CC0-1.0" ]
null
null
null
cxx_examples/threshold_detect.cpp
kb3gtn/BladeRF_Setup_Instructions
14f970a5d426a1909ab7d45165c808879bbb1f17
[ "CC0-1.0" ]
null
null
null
//////////////////////////////////////////// // Threshold Detect // // This is a simple demodulator that just tells // if the received energy is above a threshold // or not. // // You can use a UHF transmitter to transmit // a CW or modulated signal at 446.5 MHz. // // This will indicate if it see the start of the signal // and when the signal goes away.. // // Peter Fetterer (kb3gtn@gmail.com) // //////////////////////////////////////////// #include <vector> #include <string> #include <cstdint> #include <complex> #include <atomic> #include <csignal> #include "bladeRF.hpp" using std::atomic; using std::cout; using std::vector; using std::complex; using cplx_double = complex<double>; using std::string; atomic<bool> g_app_running; void signal_handler( int signum ) { cout << "\nReceived signal: " << signum << " from os. \n"; g_app_running = false; } double compute_avg_magnatude( vector<cplx_double> *samples ); int main(int argc, char **argv) { g_app_running = true; bladeRF::bladeRF myRadio; bladeRF::channel_cfg_t radioConfig; radioConfig.ch_num(0); radioConfig.rx_freq(446500000); radioConfig.rx_samplerate(521000); radioConfig.rx_bandwidth(200000); radioConfig.rx_gain(60); radioConfig.rx_enabled(true); string argstring("*"); if ( myRadio.open( argstring.c_str() ) != bladeRF::result_t::ok ) { cout << "Failed to open radio..\n"; return -1; } if ( myRadio.configure( radioConfig ) != bladeRF::result_t::ok ) { cout << "Failed to configure radio..\n"; return -1; } if ( myRadio.configure_streaming() != bladeRF::result_t::ok ) { cout << "Faile to configure streaming on the radio..\n"; return -1; } // create a buffer to hold samples of the correct size for streaming to use. vector<cplx_double> sample_buffer(myRadio.get_stream_buffer_size() ); bool above_threshold = false; double threshold = 0.05; double measured = 0; int loopcnt=0; // install signal handler signal(SIGINT, signal_handler); cout << "Starting Main Loop.\n"; while( g_app_running == true ) { myRadio.receive( &sample_buffer ); measured = compute_avg_magnatude( &sample_buffer ); if ( measured > threshold ) { if ( above_threshold == false ) { cout << "Signal Detected..\n"; above_threshold = true; } } else { // less than = threshold if ( above_threshold == true ) { cout << "Signal Lost..\n"; } above_threshold = false; } if ( loopcnt == 30 ) { cout << "measured: " << measured << '\n'; loopcnt = 0; } else { ++loopcnt; } } cout << "Main Loop Exit.. clean-up..\n"; myRadio.close(); return 0; } double compute_avg_magnatude( vector<cplx_double> *samples ) { double avg = 0; for (int idx=0; idx < samples->size(); ++idx) { avg += std::abs( (*samples)[idx] ); } avg = avg / samples->size(); return avg; }
22.851563
78
0.623248
kb3gtn
d312ea3a6301bf51be5603d1359d3b40e59b6deb
2,793
hpp
C++
include/Camera.hpp
alecwalsh/glfwogltest2
70224838d4851cb308834662763e51eb310f13b2
[ "BSD-2-Clause" ]
null
null
null
include/Camera.hpp
alecwalsh/glfwogltest2
70224838d4851cb308834662763e51eb310f13b2
[ "BSD-2-Clause" ]
null
null
null
include/Camera.hpp
alecwalsh/glfwogltest2
70224838d4851cb308834662763e51eb310f13b2
[ "BSD-2-Clause" ]
null
null
null
#pragma once #include "GameObject.hpp" #include "TimeManager.hpp" #include <Physics/Collision.hpp> #include <cstdint> #include <glm/glm.hpp> // TODO: Add support for roll class Camera : public GameObject { void UpdateViewMatrix() noexcept; void UpdateVectors(glm::vec3 frontVector, glm::vec3 upVector) noexcept; Physics::SimpleCubeCollider collider = {{}, {1.75, 3, 1.75}, {}}; double xSensitivity = 0.2f; double ySensitivity = 0.2f; double minPitch = -89.0; double maxPitch = 89.0; double pitch; double yaw; public: Camera(glm::vec3 position, glm::vec3 target, float speed = 1.0f, glm::vec3 up = {0.0f, 1.0f, 0.0f} // y-axis defaults to up ); // Runs every frame void Tick() override; void SetPosition(glm::vec3 position) override; void Rotate() noexcept; // Takes the mouse movement during the last frame and translates it into pitch and yaw void CalculatePitchAndYaw(double deltaX, double deltaY) noexcept; glm::mat4 viewMat{1.0f}; enum class Direction : std::uint8_t { Forward, Backward, Right, Left, Up, Down }; struct Vectors { using vec3 = glm::vec3; vec3 front{0.0f}; vec3 back{0.0f}; vec3 right{0.0f}; vec3 left{0.0f}; vec3 up{0.0f}; vec3 down{0.0f}; const vec3& operator[](Direction d) const noexcept; vec3& operator[](Direction d) noexcept; } vectors; float speed = 1.0f; // ParallelToGround means moving forward, back, left, and right results in movement parallel to the ground(pitch is 0) // Up and down movement simply moves up or down // With RelativeToCameraDirection, the camera's pitch applies to movement forward or backward enum class MovementStyle : std::uint8_t { ParallelToGround, RelativeToCameraDirection }; MovementStyle movementStyle = MovementStyle::ParallelToGround; bool CheckCollision(glm::vec3 translation) const; // Create a lambda that translates the camera in a certain direction auto TranslateCamera(Camera::Direction d) { return [this, d] { // TODO: Get key bindings from files // TODO: Figure out how to use control key auto vec = vectors[d]; if (movementStyle == MovementStyle::ParallelToGround) { if (!(d == Camera::Direction::Up || d == Camera::Direction::Down)) { vec.y = 0; vec = glm::normalize(vec); } } auto translation = speed * static_cast<float>(timeManager.deltaTime) * vec; bool willCollide = CheckCollision(translation); if (!willCollide) { ModifyPosition(translation); } }; }; };
28.5
122
0.619764
alecwalsh
d313f98ad8667c00d7d7247bc551e896620dcf27
20,773
cpp
C++
src/pathfinders.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
5
2019-02-01T01:41:19.000Z
2021-06-17T02:16:13.000Z
src/pathfinders.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
2
2020-01-14T16:57:42.000Z
2021-04-01T00:53:18.000Z
src/pathfinders.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
1
2019-03-02T20:03:51.000Z
2019-03-02T20:03:51.000Z
#include <vector> #include <queue> #include <tuple> #include <cstdlib> #include <climits> #include <random> #include "pathfinders.h" using namespace std; int ExploredNodes; vector<int> Landmarks; vector<vector<int>> LD; int BFSFindPath(const int nStartX, const int nStartY, const int nTargetX, const int nTargetY, const unsigned char *pMap, const int nMapWidth, const int nMapHeight, int *pOutBuffer, const int nOutBufferSize) { auto idx = [nMapWidth](int x, int y) { return x + y * nMapWidth; }; const int n = nMapWidth * nMapHeight; const int startPos = idx(nStartX, nStartY), targetPos = idx(nTargetX, nTargetY); ExploredNodes = 0; vector<int> p(n), d(n, INT_MAX); d[startPos] = 0; queue<int> q; q.push(startPos); while (!q.empty()) { int u = q.front(); q.pop(); ExploredNodes++; for (auto e : {+1, -1, +nMapWidth, -nMapWidth}) { int v = u + e; if ((e == 1 && (v % nMapWidth == 0)) || (e == -1 && (u % nMapWidth == 0))) continue; if (0 <= v && v < n && d[v] == INT_MAX && pMap[v]) { p[v] = u; d[v] = d[u] + 1; if (v == targetPos) goto end; q.push(v); } } } end: if (d[targetPos] == INT_MAX) { return -1; } else if (d[targetPos] <= nOutBufferSize) { int curr = targetPos; for (int i = d[targetPos] - 1; i >= 0; i--) { pOutBuffer[i] = curr; curr = p[curr]; } return d[targetPos]; } return d[targetPos]; } int BFSFindPathDiag(const int nStartX, const int nStartY, const int nTargetX, const int nTargetY, const unsigned char *pMap, const int nMapWidth, const int nMapHeight, int *pOutBuffer, const int nOutBufferSize) { auto idx = [nMapWidth](int x, int y) { return x + y * nMapWidth; }; const int n = nMapWidth * nMapHeight; const int startPos = idx(nStartX, nStartY), targetPos = idx(nTargetX, nTargetY); ExploredNodes = 0; vector<int> p(n), d(n, INT_MAX); queue<int> q; d[startPos] = 0; q.push(startPos); while (!q.empty()) { int u = q.front(); q.pop(); ExploredNodes++; for (auto e : {-nMapWidth - 1, -nMapWidth + 1, +nMapWidth - 1, +nMapWidth + 1, +1, -1, +nMapWidth, -nMapWidth}) { int v = u + e; if (((e == 1 || e == -nMapWidth + 1 || e == nMapWidth + 1) && (v % nMapWidth == 0)) || ((e == -1 || e == -nMapWidth - 1 || e == nMapWidth - 1) && (u % nMapWidth == 0))) continue; if (0 <= v && v < n && d[v] == INT_MAX && pMap[v]) { p[v] = u; d[v] = d[u] + 1; if (v == targetPos) goto end; q.push(v); } } } end: if (d[targetPos] == INT_MAX) { return -1; } else if (d[targetPos] <= nOutBufferSize) { int curr = targetPos; for (int i = d[targetPos] - 1; i >= 0; i--) { pOutBuffer[i] = curr; curr = p[curr]; } return d[targetPos]; } return d[targetPos]; // buffer size too small } int AStarFindPath(const int nStartX, const int nStartY, const int nTargetX, const int nTargetY, const unsigned char *pMap, const int nMapWidth, const int nMapHeight, int *pOutBuffer, const int nOutBufferSize) { auto idx = [nMapWidth](int x, int y) { return x + y * nMapWidth; }; auto h = [=](int u) -> int { // lower bound distance to target from u int x = u % nMapWidth, y = u / nMapWidth; return abs(x - nTargetX) + abs(y - nTargetY); }; const int n = nMapWidth * nMapHeight; const int startPos = idx(nStartX, nStartY), targetPos = idx(nTargetX, nTargetY); int discovered = 0; ExploredNodes = 0; vector<int> p(n), d(n, INT_MAX); priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<tuple<int, int, int>>> pq; // A* with tie breaking d[startPos] = 0; pq.push(make_tuple(0 + h(startPos), 0, startPos)); while (!pq.empty()) { int u = get<2>(pq.top()); pq.pop(); ExploredNodes++; for (auto e : {+1, -1, +nMapWidth, -nMapWidth}) { int v = u + e; if ((e == 1 && (v % nMapWidth == 0)) || (e == -1 && (u % nMapWidth == 0))) continue; if (0 <= v && v < n && d[v] > d[u] + 1 && pMap[v]) { p[v] = u; d[v] = d[u] + 1; if (v == targetPos) goto end; pq.push(make_tuple(d[v] + h(v), ++discovered, v)); } } } end: if (d[targetPos] == INT_MAX) { return -1; } else if (d[targetPos] <= nOutBufferSize) { int curr = targetPos; for (int i = d[targetPos] - 1; i >= 0; i--) { pOutBuffer[i] = curr; curr = p[curr]; } return d[targetPos]; } return d[targetPos]; // buffer size too small } int AStarFindPathDiag(const int nStartX, const int nStartY, const int nTargetX, const int nTargetY, const unsigned char *pMap, const int nMapWidth, const int nMapHeight, int *pOutBuffer, const int nOutBufferSize) { auto idx = [nMapWidth](int x, int y) { return x + y * nMapWidth; }; auto h = [=](int u) -> int { // lower bound distance to target from u int x = u % nMapWidth, y = u / nMapWidth; return max(abs(x - nTargetX), abs(y - nTargetY)); }; const int n = nMapWidth * nMapHeight; const int startPos = idx(nStartX, nStartY), targetPos = idx(nTargetX, nTargetY); int discovered = 0; ExploredNodes = 0; vector<int> p(n), d(n, INT_MAX); priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<tuple<int, int, int>>> pq; // A* with tie breaking d[startPos] = 0; pq.push(make_tuple(0 + h(startPos), 0, startPos)); while (!pq.empty()) { int u = get<2>(pq.top()); pq.pop(); ExploredNodes++; for (auto e : {-nMapWidth - 1, -nMapWidth + 1, +nMapWidth - 1, +nMapWidth + 1, +1, -1, +nMapWidth, -nMapWidth}) { int v = u + e; if (((e == 1 || e == -nMapWidth + 1 || e == nMapWidth + 1) && (v % nMapWidth == 0)) || ((e == -1 || e == -nMapWidth - 1 || e == nMapWidth - 1) && (u % nMapWidth == 0))) continue; if (0 <= v && v < n && d[v] > d[u] + 1 && pMap[v]) { p[v] = u; d[v] = d[u] + 1; if (v == targetPos) goto end; pq.push(make_tuple(d[v] + h(v), ++discovered, v)); } } } end: if (d[targetPos] == INT_MAX) { return -1; } else if (d[targetPos] <= nOutBufferSize) { int curr = targetPos; for (int i = d[targetPos] - 1; i >= 0; i--) { pOutBuffer[i] = curr; curr = p[curr]; } return d[targetPos]; } return d[targetPos]; // buffer size too small } void InitializeLandmarks(int k, const unsigned char *pMap, const int nMapWidth, const int nMapHeight) { vector<int> traversable; for (int i = 0; i < nMapWidth; i++) for (int j = 0; j < nMapHeight; j++) if (pMap[nMapWidth * j + i]) traversable.push_back(nMapWidth * j + i); while (Landmarks.size() < k) { if (Landmarks.empty()) { std::random_device rng; std::uniform_int_distribution<int> uniform(0, traversable.size() - 1); Landmarks.push_back(traversable[uniform(rng)]); continue; } const int n = nMapWidth * nMapHeight; vector<int> p(n), d(n, INT_MAX); queue<int> q; for (auto s : Landmarks) { d[s] = 0; q.push(s); } int farthest = -1, maxdist = -1; while (!q.empty()) { int u = q.front(); q.pop(); if (d[u] > maxdist) maxdist = d[u], farthest = u; for (auto e : {+1, -1, +nMapWidth, -nMapWidth}) { int v = u + e; if ((e == 1 && (v % nMapWidth == 0)) || (e == -1 && (u % nMapWidth == 0))) continue; if (0 <= v && v < n && d[v] == INT_MAX && pMap[v]) { p[v] = u; d[v] = d[u] + 1; q.push(v); } } } Landmarks.push_back(farthest); // works well when the graph is not too disconnected } LD.resize(Landmarks.size()); for (int i = 0; i < Landmarks.size(); i++) { const int n = nMapWidth * nMapHeight; vector<int> p(n); LD[i].resize(n, INT_MAX); queue<int> q; int s = Landmarks[i]; LD[i][s] = 0; q.push(s); while (!q.empty()) { int u = q.front(); q.pop(); for (auto e : {+1, -1, +nMapWidth, -nMapWidth}) { int v = u + e; if ((e == 1 && (v % nMapWidth == 0)) || (e == -1 && (u % nMapWidth == 0))) continue; if (0 <= v && v < n && LD[i][v] == INT_MAX && pMap[v]) { p[v] = u; LD[i][v] = LD[i][u] + 1; q.push(v); } } } } } int AStarFindPathLandmarks(const int nStartX, const int nStartY, const int nTargetX, const int nTargetY, const unsigned char *pMap, const int nMapWidth, const int nMapHeight, int *pOutBuffer, const int nOutBufferSize) { auto idx = [nMapWidth](int x, int y) { return x + y * nMapWidth; }; const int n = nMapWidth * nMapHeight; const int startPos = idx(nStartX, nStartY), targetPos = idx(nTargetX, nTargetY); auto h = [=](int u) { // lower bound distance to target from u int m = 0; for (int i = 0; i < Landmarks.size(); i++) // global vector<int> Landmarks m = max(m, LD[i][targetPos] - LD[i][u]); // global vector<vector<int>> LD return m; }; int discovered = 0; ExploredNodes = 0; vector<int> p(n), d(n, INT_MAX); priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<tuple<int, int, int>>> pq; // A* with tie breaking d[startPos] = 0; pq.push(make_tuple(0 + h(startPos), 0, startPos)); while (!pq.empty()) { int u = get<2>(pq.top()); pq.pop(); ExploredNodes++; for (auto e : {+1, -1, +nMapWidth, -nMapWidth}) { int v = u + e; if ((e == 1 && (v % nMapWidth == 0)) || (e == -1 && (u % nMapWidth == 0))) continue; if (0 <= v && v < n && d[v] > d[u] + 1 && pMap[v]) { p[v] = u; d[v] = d[u] + 1; if (v == targetPos) goto end; pq.push(make_tuple(d[v] + h(v), ++discovered, v)); } } } end: if (d[targetPos] == INT_MAX) { return -1; } else if (d[targetPos] <= nOutBufferSize) { int curr = targetPos; for (int i = d[targetPos] - 1; i >= 0; i--) { pOutBuffer[i] = curr; curr = p[curr]; } return d[targetPos]; } return d[targetPos]; // buffer size too small } void InitializeLandmarksDiag(int k, const unsigned char *pMap, const int nMapWidth, const int nMapHeight) { vector<int> traversable; for (int i = 0; i < nMapWidth; i++) for (int j = 0; j < nMapHeight; j++) if (pMap[nMapWidth * j + i]) traversable.push_back(nMapWidth * j + i); while (Landmarks.size() < k) { if (Landmarks.empty()) { std::random_device rng; std::uniform_int_distribution<int> uniform(0, traversable.size() - 1); Landmarks.push_back(traversable[uniform(rng)]); continue; } const int n = nMapWidth * nMapHeight; vector<int> p(n), d(n, INT_MAX); queue<int> q; for (auto s : Landmarks) { d[s] = 0; q.push(s); } int farthest = -1, maxdist = -1; while (!q.empty()) { int u = q.front(); q.pop(); if (d[u] > maxdist) maxdist = d[u], farthest = u; for (auto e : {-nMapWidth - 1, -nMapWidth + 1, +nMapWidth - 1, +nMapWidth + 1, +1, -1, +nMapWidth, -nMapWidth}) { int v = u + e; if (((e == 1 || e == -nMapWidth + 1 || e == nMapWidth + 1) && (v % nMapWidth == 0)) || ((e == -1 || e == -nMapWidth - 1 || e == nMapWidth - 1) && (u % nMapWidth == 0))) continue; if (0 <= v && v < n && d[v] == INT_MAX && pMap[v]) { p[v] = u; d[v] = d[u] + 1; q.push(v); } } } Landmarks.push_back(farthest); // works well when the graph is not too disconnected } LD.resize(Landmarks.size()); for (int i = 0; i < Landmarks.size(); i++) { const int n = nMapWidth * nMapHeight; vector<int> p(n); LD[i].resize(n, INT_MAX); queue<int> q; int s = Landmarks[i]; LD[i][s] = 0; q.push(s); while (!q.empty()) { int u = q.front(); q.pop(); for (auto e : {-nMapWidth - 1, -nMapWidth + 1, +nMapWidth - 1, +nMapWidth + 1, +1, -1, +nMapWidth, -nMapWidth}) { int v = u + e; if (((e == 1 || e == -nMapWidth + 1 || e == nMapWidth + 1) && (v % nMapWidth == 0)) || ((e == -1 || e == -nMapWidth - 1 || e == nMapWidth - 1) && (u % nMapWidth == 0))) continue; if (0 <= v && v < n && LD[i][v] == INT_MAX && pMap[v]) { p[v] = u; LD[i][v] = LD[i][u] + 1; q.push(v); } } } } } int AStarFindPathLandmarksDiag(const int nStartX, const int nStartY, const int nTargetX, const int nTargetY, const unsigned char *pMap, const int nMapWidth, const int nMapHeight, int *pOutBuffer, const int nOutBufferSize) { auto idx = [nMapWidth](int x, int y) { return x + y * nMapWidth; }; const int n = nMapWidth * nMapHeight; const int startPos = idx(nStartX, nStartY), targetPos = idx(nTargetX, nTargetY); auto h = [=](int u) { // lower bound distance to target from u int m = 0; for (int i = 0; i < Landmarks.size(); i++) // global vector<int> Landmarks m = max(m, LD[i][targetPos] - LD[i][u]); // global vector<vector<int>> LD return m; }; int discovered = 0; ExploredNodes = 0; vector<int> p(n), d(n, INT_MAX); priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<tuple<int, int, int>>> pq; // A* with tie breaking d[startPos] = 0; pq.push(make_tuple(0 + h(startPos), 0, startPos)); while (!pq.empty()) { int u = get<2>(pq.top()); pq.pop(); ExploredNodes++; for (auto e : {-nMapWidth - 1, -nMapWidth + 1, +nMapWidth - 1, +nMapWidth + 1, +1, -1, +nMapWidth, -nMapWidth}) { int v = u + e; if (((e == 1 || e == -nMapWidth + 1 || e == nMapWidth + 1) && (v % nMapWidth == 0)) || ((e == -1 || e == -nMapWidth - 1 || e == nMapWidth - 1) && (u % nMapWidth == 0))) continue; if (0 <= v && v < n && d[v] > d[u] + 1 && pMap[v]) { p[v] = u; d[v] = d[u] + 1; if (v == targetPos) goto end; pq.push(make_tuple(d[v] + h(v), ++discovered, v)); } } } end: if (d[targetPos] == INT_MAX) { return -1; } else if (d[targetPos] <= nOutBufferSize) { int curr = targetPos; for (int i = d[targetPos] - 1; i >= 0; i--) { pOutBuffer[i] = curr; curr = p[curr]; } return d[targetPos]; } return d[targetPos]; // buffer size too small } int AStarFindPathNoTie(const int nStartX, const int nStartY, const int nTargetX, const int nTargetY, const unsigned char *pMap, const int nMapWidth, const int nMapHeight, int *pOutBuffer, const int nOutBufferSize) { auto idx = [nMapWidth](int x, int y) { return x + y * nMapWidth; }; auto h = [=](int u) { // lower bound distance to target from u int x = u % nMapWidth, y = u / nMapWidth; return abs(x - nTargetX) + abs(y - nTargetY); }; const int n = nMapWidth * nMapHeight; const int startPos = idx(nStartX, nStartY), targetPos = idx(nTargetX, nTargetY); ExploredNodes = 0; vector<int> p(n), d(n, INT_MAX); priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq; d[startPos] = 0; pq.push(make_pair(0 + h(startPos), startPos)); while (!pq.empty()) { int u = pq.top().second; pq.pop(); ExploredNodes++; for (auto e : {+1, -1, +nMapWidth, -nMapWidth}) { int v = u + e; if ((e == 1 && (v % nMapWidth == 0)) || (e == -1 && (u % nMapWidth == 0))) continue; if (0 <= v && v < n && d[v] > d[u] + 1 && pMap[v]) { p[v] = u; d[v] = d[u] + 1; if (v == targetPos) goto end; pq.push(make_pair(d[v] + h(v), v)); } } } end: if (d[targetPos] == INT_MAX) { return -1; } else if (d[targetPos] <= nOutBufferSize) { int curr = targetPos; for (int i = d[targetPos] - 1; i >= 0; i--) { pOutBuffer[i] = curr; curr = p[curr]; } return d[targetPos]; } return d[targetPos]; // buffer size too small } int AStarFindPathNoTieDiag(const int nStartX, const int nStartY, const int nTargetX, const int nTargetY, const unsigned char *pMap, const int nMapWidth, const int nMapHeight, int *pOutBuffer, const int nOutBufferSize) { auto idx = [nMapWidth](int x, int y) { return x + y * nMapWidth; }; auto h = [=](int u) { // lower bound distance to target from u int x = u % nMapWidth, y = u / nMapWidth; return max(abs(x - nTargetX), abs(y - nTargetY)); }; const int n = nMapWidth * nMapHeight; const int startPos = idx(nStartX, nStartY), targetPos = idx(nTargetX, nTargetY); ExploredNodes = 0; vector<int> p(n), d(n, INT_MAX); priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq; d[startPos] = 0; pq.push(make_pair(0 + h(startPos), startPos)); while (!pq.empty()) { int u = pq.top().second; pq.pop(); ExploredNodes++; for (auto e : {-nMapWidth - 1, -nMapWidth + 1, +nMapWidth - 1, +nMapWidth + 1, +1, -1, +nMapWidth, -nMapWidth}) { int v = u + e; if (((e == 1 || e == -nMapWidth + 1 || e == nMapWidth + 1) && (v % nMapWidth == 0)) || ((e == -1 || e == -nMapWidth - 1 || e == nMapWidth - 1) && (u % nMapWidth == 0))) continue; if (0 <= v && v < n && d[v] > d[u] + 1 && pMap[v]) { p[v] = u; d[v] = d[u] + 1; if (v == targetPos) goto end; pq.push(make_pair(d[v] + h(v), v)); } } } end: if (d[targetPos] == INT_MAX) { return -1; } else if (d[targetPos] <= nOutBufferSize) { int curr = targetPos; for (int i = d[targetPos] - 1; i >= 0; i--) { pOutBuffer[i] = curr; curr = p[curr]; } return d[targetPos]; } return d[targetPos]; // buffer size too small }
33.504839
107
0.460165
rweyrauch
d3145bbc042c71a96f7ad0f02504129db950bdf6
3,108
cpp
C++
rvalue/perfect forwarding/src/Main.cpp
matt360/ModernCpp
42ab42447d22c9e92f3da12dcb8ac16794668879
[ "MIT" ]
null
null
null
rvalue/perfect forwarding/src/Main.cpp
matt360/ModernCpp
42ab42447d22c9e92f3da12dcb8ac16794668879
[ "MIT" ]
16
2018-03-01T11:18:55.000Z
2018-07-01T17:17:32.000Z
rvalue/perfect forwarding/src/Main.cpp
matzar/ModernCpp
42ab42447d22c9e92f3da12dcb8ac16794668879
[ "MIT" ]
null
null
null
// rvalue and perfect forwarding https://www.justsoftwaresolutions.co.uk/cplusplus/rvalue_references_and_perfect_forwarding.html #include <iostream> #include <vector> class X { std::vector<double> data; public: X() : data(100000) { std::cout << "constructed X!" << std::endl; } // lots of data X(X const& other) : // copy constructor data(other.data) { std::cout << "copy constructor called!" << std::endl; } // duplicate all that data X(X&& other) : // move constructor data(std::move(other.data)) { std::cout << "move constructor called!" << std::endl; } // move the data: no copies X& operator=(X const& other) // copy-assignment { std::cout << "copy-assignement called!" << std::endl; data = other.data; // copy all the data return *this; } X& operator=(X&& other) // move-assignment { std::cout << "move-assignment called!" << std::endl; data = std::move(other.data); // move the data: no copies return *this; } }; // perfect forwarding // a function template can pass its arguments through to another function whilst retaining the lvalue/rvalue nature of the function arguments // by using std::forward. This is called "perfect forwarding", avoids excessive copying, and avoids the template author having to write // multiple overloads for lvalue and rvalue references. void g(X& t) { std::cout << "lvalue" << std::endl; }; void g(X&& t) { std::cout << "rvalue" << std::endl; }; template<typename T> void f(T&& t) { std::cout << "template function calling: g(t) and t is "; g(t); std::cout << "template function calling: g(std::forward<T>(t)) and t is "; g(std::forward<T>(t)); } // overload void h(X& t) { std::cout << "overloaded function calling: g(t) and t is "; g(t); } void h(X&& t) { std::cout << "overloaded function calling: g(std::forward<X>(t)) and t is "; g(std::forward<X>(t)); } int main() { // copy constructor and move constructor std::cout << "X x1; "; X x1; std::cout << "X x2(x1); "; X x2(x1); // copy std::cout << "X x3(std::move(x1)); "; X x3(std::move(x1)); // no copy, move: x1 no longer has any data std::cout << "X make_x; "; X make_x; // build an X with data std::cout << "x1 = make_x; "; x1 = make_x; // return value is an rvalue, so move rather than copy // perfect forwarding std::cout << "X x; "; X x; std::cout << std::endl; std::cout << "f(x) " << std::endl; f(x); // we pass a named x object to f, so T is deducted to be an lvalue reference: x&, when T is an lvalue reference, std::forward<T> is an no-operation: it just returns its argument. We therefore call the overload of g that takes an lvalue reference [void g(X& t)] std::cout << std::endl; std::cout << "f(X()) " << std::endl; f(X()); // in this case, std::forward<T>(t) is equivalent to static_cast<T&&>(t): it ensures that the argument is forwarded as an rvalue reference. This means that the overload of g that takes an rvalue refrence is selected [void g(X&& t)] std::cout << std::endl; std::cout << "h(x) " << std::endl; h(x); std::cout << std::endl; std::cout << "h(X()) " << std::endl; h(X()); std::cin.get(); }
29.6
267
0.63964
matt360
d3146253c3afc611d1abb7293222712fee2869d6
2,626
cpp
C++
sources/dansandu/glyph/internal/multimap.test.cpp
dansandu/glyph
d7d51bc57000d85eb4fd576e11502eeadbb0a6cf
[ "MIT" ]
null
null
null
sources/dansandu/glyph/internal/multimap.test.cpp
dansandu/glyph
d7d51bc57000d85eb4fd576e11502eeadbb0a6cf
[ "MIT" ]
null
null
null
sources/dansandu/glyph/internal/multimap.test.cpp
dansandu/glyph
d7d51bc57000d85eb4fd576e11502eeadbb0a6cf
[ "MIT" ]
null
null
null
#include "dansandu/glyph/internal/multimap.hpp" #include "catchorg/catch/catch.hpp" #include <set> using dansandu::glyph::internal::multimap::Multimap; using dansandu::glyph::symbol::Symbol; TEST_CASE("Multimap") { SECTION("set values") { auto table = Multimap{}; table[Symbol{0}] = {Symbol{1}, Symbol{2}}; REQUIRE(table[Symbol{0}] == std::vector<Symbol>{Symbol{1}, Symbol{2}}); table[Symbol{10}] = {Symbol{13}, Symbol{15}}; REQUIRE(table[Symbol{0}] == std::vector<Symbol>{Symbol{1}, Symbol{2}}); REQUIRE(table[Symbol{10}] == std::vector<Symbol>{Symbol{13}, Symbol{15}}); table[Symbol{20}] = {Symbol{26}, Symbol{29}, Symbol{21}}; REQUIRE(table[Symbol{0}] == std::vector<Symbol>{Symbol{1}, Symbol{2}}); REQUIRE(table[Symbol{10}] == std::vector<Symbol>{Symbol{13}, Symbol{15}}); REQUIRE(table[Symbol{20}] == std::vector<Symbol>{Symbol{26}, Symbol{29}, Symbol{21}}); SECTION("merge with new symbol") { table.merge({Symbol{0}, Symbol{40}}); REQUIRE(table[Symbol{0}] == std::vector<Symbol>{Symbol{1}, Symbol{2}}); REQUIRE(table[Symbol{40}] == table[Symbol{0}]); REQUIRE(table[Symbol{10}] == std::vector<Symbol>{Symbol{13}, Symbol{15}}); REQUIRE(table[Symbol{20}] == std::vector<Symbol>{Symbol{26}, Symbol{29}, Symbol{21}}); } SECTION("merge with existing symbols") { table.merge({Symbol{0}, Symbol{20}}); REQUIRE(table[Symbol{0}] == std::vector<Symbol>{Symbol{1}, Symbol{2}, Symbol{26}, Symbol{29}, Symbol{21}}); REQUIRE(table[Symbol{0}] == table[Symbol{20}]); REQUIRE(table[Symbol{10}] == std::vector<Symbol>{Symbol{13}, Symbol{15}}); } SECTION("iteration") { auto actualPartitions = std::vector<std::vector<Symbol>>{}; auto actualValues = std::vector<std::vector<Symbol>>{}; table.forEach( [&](const auto& p, const auto& v) { actualPartitions.push_back(p); actualValues.push_back(v); }); const auto expectedPartitions = std::vector<std::vector<Symbol>>{{Symbol{0}}, {Symbol{10}}, {Symbol{20}}}; const auto expectedValues = std::vector<std::vector<Symbol>>{ {Symbol{1}, Symbol{2}}, {Symbol{13}, Symbol{15}}, {Symbol{26}, Symbol{29}, Symbol{21}}}; REQUIRE(actualPartitions == expectedPartitions); REQUIRE(actualValues == expectedValues); } } }
32.825
119
0.562072
dansandu
d319d61cf22889d604b25ed8057f3f1ff23bf12c
4,435
cpp
C++
firmware/library/L1_Drivers/test/gpio_test.cpp
Adam-D-Sanchez/SJSU-Dev2
ecb5bb01912f6f85a76b6715d0e72f2d3062ceed
[ "Apache-2.0" ]
null
null
null
firmware/library/L1_Drivers/test/gpio_test.cpp
Adam-D-Sanchez/SJSU-Dev2
ecb5bb01912f6f85a76b6715d0e72f2d3062ceed
[ "Apache-2.0" ]
null
null
null
firmware/library/L1_Drivers/test/gpio_test.cpp
Adam-D-Sanchez/SJSU-Dev2
ecb5bb01912f6f85a76b6715d0e72f2d3062ceed
[ "Apache-2.0" ]
null
null
null
#include "L0_LowLevel/LPC40xx.h" #include "L1_Drivers/gpio.hpp" #include "L4_Testing/testing_frameworks.hpp" EMIT_ALL_METHODS(Gpio); TEST_CASE("Testing Gpio", "[gpio]") { // Declared constants that are to be used within the different sections // of this unit test constexpr uint8_t kPin0 = 0; constexpr uint8_t kPin7 = 7; // Simulated local version of LPC_IOCON. // This is necessary since a Gpio is also a Pin. LPC_IOCON_TypeDef local_iocon; memset(&local_iocon, 0, sizeof(local_iocon)); // Substitute the memory mapped LPC_IOCON with the local_iocon test struture // Redirects manipulation to the 'local_iocon' Pin::pin_map = reinterpret_cast<Pin::PinMap_t *>(&local_iocon); // Initialized local LPC_GPIO_TypeDef objects with 0 to observe how the Gpio // class manipulates the data in the registers LPC_GPIO_TypeDef local_gpio_port[2]; memset(&local_gpio_port, 0, sizeof(local_gpio_port)); // Only GPIO port 1 & 2 will be used in this unit test Gpio::gpio_port[0] = &local_gpio_port[0]; Gpio::gpio_port[1] = &local_gpio_port[1]; // Pins that are to be used in the unit test Gpio p0_00(0, 0); Gpio p1_07(1, 7); SECTION("Set as Output and Input") { // Source: "UM10562 LPC408x/407x User manual" table 96 page 148 constexpr uint8_t kInputSet = 0b0; constexpr uint8_t kOutputSet = 0b1; p0_00.SetAsInput(); p1_07.SetAsOutput(); // Check bit 0 of local_gpio_port[0].DIR (port 0 pin 0) // to see if it is cleared CHECK(((local_gpio_port[0].DIR >> kPin0) & 1) == kInputSet); // Check bit 7 of local_gpio_port[1].DIR (port 1 pin 7) // to see if it is set CHECK(((local_gpio_port[1].DIR >> kPin7) & 1) == kOutputSet); p0_00.SetDirection(GpioInterface::kOutput); p1_07.SetDirection(GpioInterface::kInput); // Check bit 0 of local_gpio_port[0].DIR (port 0 pin 0) // to see if it is set CHECK(((local_gpio_port[0].DIR >> kPin0) & 1) == kOutputSet); // Check bit 7 of local_gpio_port[1].DIR (port 1 pin 7) // to see if it is cleared CHECK(((local_gpio_port[1].DIR >> kPin7) & 1) == kInputSet); } SECTION("Set High") { // Source: "UM10562 LPC408x/407x User manual" table 99 page 149 constexpr uint8_t kHighSet = 0b1; p0_00.SetHigh(); p1_07.Set(GpioInterface::kHigh); // Check bit 0 of local_gpio_port[0].SET (port 0 pin 0) // to see if it is set CHECK(((local_gpio_port[0].SET >> kPin0) & 1) == kHighSet); // Check bit 7 of local_gpio_port[1].SET (port 1 pin 7) // to see if it is set CHECK(((local_gpio_port[1].SET >> kPin7) & 1) == kHighSet); } SECTION("Set Low") { // Source: "UM10562 LPC408x/407x User manual" table 100 page 150 constexpr uint8_t kLowSet = 0b1; p0_00.SetLow(); p1_07.Set(GpioInterface::kLow); // Check bit 0 of local_gpio_port[0].CLR (port 0 pin 0) // to see if it is set CHECK(((local_gpio_port[0].CLR >> kPin0) & 1) == kLowSet); // Check bit 7 of local_gpio_port[1].CLR (port 1 pin 7) // to see if it is set CHECK(((local_gpio_port[1].CLR >> kPin7) & 1) == kLowSet); } SECTION("Read Pin") { // Clearing bit 0 of local_gpio_port[0].PIN (port 0 pin 0) in order to // read the pin value through the Read method local_gpio_port[0].PIN &= ~(1 << kPin0); // Setting bit 7 of local_gpio_port[1].PIN (port 1 pin 7) in order to // read the pin value through the Read method local_gpio_port[1].PIN |= (1 << kPin7); CHECK(p0_00.Read() == false); CHECK(p1_07.Read() == true); CHECK(p0_00.Read() == Gpio::State::kLow); CHECK(p1_07.Read() == Gpio::State::kHigh); } SECTION("Toggle") { // Clearing bit 0 of local_gpio_port[0].PIN (port 0 pin 0) in order to // read the pin value through the Read method local_gpio_port[0].PIN &= ~(1 << kPin0); // Setting bit 7 of local_gpio_port[1].PIN (port 1 pin 7) in order to // read the pin value through the Read method local_gpio_port[1].PIN |= (1 << kPin7); // Should change to 1 p0_00.Toggle(); // Should change to 0 p1_07.Toggle(); CHECK(p0_00.Read() == true); CHECK(p1_07.Read() == false); } Gpio::gpio_port[0] = LPC_GPIO0; Gpio::gpio_port[1] = LPC_GPIO1; Gpio::gpio_port[2] = LPC_GPIO2; Gpio::gpio_port[3] = LPC_GPIO3; Gpio::gpio_port[4] = LPC_GPIO4; Gpio::gpio_port[5] = LPC_GPIO5; Pin::pin_map = reinterpret_cast<Pin::PinMap_t *>(LPC_IOCON); }
36.056911
78
0.657046
Adam-D-Sanchez
d31a1bc4f5d321f72ef3f4296b5c9fe2a76dbefc
1,339
cpp
C++
src/gen/PhysXClothState.cpp
BlazesRus/niflib
7e8efb6b2c73a3410135dbd6d73694e29f1e9ce8
[ "BSD-3-Clause" ]
1
2021-12-24T00:42:42.000Z
2021-12-24T00:42:42.000Z
src/gen/PhysXClothState.cpp
BlazesRus/niflib
7e8efb6b2c73a3410135dbd6d73694e29f1e9ce8
[ "BSD-3-Clause" ]
null
null
null
src/gen/PhysXClothState.cpp
BlazesRus/niflib
7e8efb6b2c73a3410135dbd6d73694e29f1e9ce8
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2005-2020, NIF File Format Library and Tools All rights reserved. Please see niflib.h for license. */ //-----------------------------------NOTICE----------------------------------// // Some of this file is automatically filled in by a Python script. Only // // add custom code in the designated areas or it will be overwritten during // // the next update. // //-----------------------------------NOTICE----------------------------------// #include "../../include/gen/PhysXClothState.h" #include "../../include/gen/Matrix34.h" using namespace Niflib; //Constructor PhysXClothState::PhysXClothState() : numVertexPositions((unsigned short)0), numTearIndices((unsigned short)0) {}; //Copy Constructor PhysXClothState::PhysXClothState( const PhysXClothState & src ) { *this = src; }; //Copy Operator PhysXClothState & PhysXClothState::operator=( const PhysXClothState & src ) { this->pose = src.pose; this->numVertexPositions = src.numVertexPositions; this->vertexPositions = src.vertexPositions; this->numTearIndices = src.numTearIndices; this->tearIndices = src.tearIndices; this->tearSplitPlanes = src.tearSplitPlanes; return *this; }; //Destructor PhysXClothState::~PhysXClothState() {}; //--BEGIN MISC CUSTOM CODE--// //--END CUSTOM CODE--//
34.333333
113
0.624347
BlazesRus
d31eac89ad7b1543f83c0bded1103289ffb8d0ff
18,370
cpp
C++
src/lib/rendering/descriptors/DescriptorPool.cpp
Lut99/Rasterizer
453864506db749a93fb82fb17cc5ee88cc4ada01
[ "MIT" ]
1
2021-08-15T19:20:14.000Z
2021-08-15T19:20:14.000Z
src/lib/rendering/descriptors/DescriptorPool.cpp
Lut99/Rasterizer
453864506db749a93fb82fb17cc5ee88cc4ada01
[ "MIT" ]
17
2021-06-05T12:37:04.000Z
2021-10-01T10:20:09.000Z
src/lib/rendering/descriptors/DescriptorPool.cpp
Lut99/Rasterizer
453864506db749a93fb82fb17cc5ee88cc4ada01
[ "MIT" ]
null
null
null
/* DESCRIPTOR POOL.cpp * by Lut99 * * Created: * 26/04/2021, 14:38:48 * Last edited: * 25/05/2021, 18:14:13 * Auto updated? * Yes * * Description: * Contains the DescriptorPool class, which serves as a memory pool for * descriptors, which in turn describe how a certain buffer or other * piece of memory should be accessed on the GPU. **/ #include "tools/Logger.hpp" #include "../auxillary/ErrorCodes.hpp" #include "DescriptorPool.hpp" using namespace std; using namespace Makma3D; using namespace Makma3D::Rendering; /***** POPULATE FUNCTIONS *****/ /* Populates a given VkDescriptorPoolSize struct. */ static void populate_descriptor_pool_size(VkDescriptorPoolSize& descriptor_pool_size, const std::tuple<VkDescriptorType, uint32_t>& descriptor_type) { // Initialize to default descriptor_pool_size = {}; descriptor_pool_size.type = std::get<0>(descriptor_type); descriptor_pool_size.descriptorCount = std::get<1>(descriptor_type); } /* Populates a given VkDescriptorPoolCreateInfo struct. */ static void populate_descriptor_pool_info(VkDescriptorPoolCreateInfo& descriptor_pool_info, const Tools::Array<VkDescriptorPoolSize>& descriptor_pool_sizes, uint32_t n_sets, VkDescriptorPoolCreateFlags descriptor_pool_flags) { // Initialize to default descriptor_pool_info = {}; descriptor_pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; // Set the pool size to use descriptor_pool_info.poolSizeCount = static_cast<uint32_t>(descriptor_pool_sizes.size()); descriptor_pool_info.pPoolSizes = descriptor_pool_sizes.rdata(); // Set the maximum number of sets allowed descriptor_pool_info.maxSets = n_sets; // Set the flags to use descriptor_pool_info.flags = descriptor_pool_flags | VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; } /* Populates a given VkDescriptorSetAllocateInfo struct. */ static void populate_descriptor_set_info(VkDescriptorSetAllocateInfo& descriptor_set_info, VkDescriptorPool vk_descriptor_pool, const Tools::Array<VkDescriptorSetLayout>& vk_descriptor_set_layouts, uint32_t n_sets) { // Set to default descriptor_set_info = {}; descriptor_set_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; // Set the pool that we use to allocate them descriptor_set_info.descriptorPool = vk_descriptor_pool; // Set the number of sets to allocate descriptor_set_info.descriptorSetCount = n_sets; // Set the layout for this descriptor descriptor_set_info.pSetLayouts = vk_descriptor_set_layouts.rdata(); } /***** DESCRIPTORPOOL CLASS *****/ /* Constructor for the DescriptorPool class, which takes the GPU to create the pool on, the number of descriptors we want to allocate in the pool, the maximum number of descriptor sets that can be allocated and optionally custom create flags. */ DescriptorPool::DescriptorPool(const Rendering::GPU& gpu, const std::pair<VkDescriptorType, uint32_t>& descriptor_type, uint32_t max_sets, VkDescriptorPoolCreateFlags flags): gpu(gpu), vk_descriptor_types(Tools::Array<std::pair<VkDescriptorType, uint32_t>>({ descriptor_type })), vk_max_sets(max_sets), vk_create_flags(flags) { logger.logc(Verbosity::important, DescriptorPool::channel, "Initializing with a single type..."); // First, we define how large the pool will be logger.logc(Verbosity::details, DescriptorPool::channel, "Preparing structs..."); VkDescriptorPoolSize descriptor_pool_size; populate_descriptor_pool_size(descriptor_pool_size, this->vk_descriptor_types[0]); // Prepare the create info VkDescriptorPoolCreateInfo descriptor_pool_info; populate_descriptor_pool_info(descriptor_pool_info, Tools::Array<VkDescriptorPoolSize>({ descriptor_pool_size }), this->vk_max_sets, this->vk_create_flags); // Actually allocate the pool logger.logc(Verbosity::details, DescriptorPool::channel, "Allocating pool.."); VkResult vk_result; if ((vk_result = vkCreateDescriptorPool(this->gpu, &descriptor_pool_info, nullptr, &this->vk_descriptor_pool)) != VK_SUCCESS) { logger.fatalc(DescriptorPool::channel, "Could not allocate descriptor pool: ", vk_error_map[vk_result]); } // Before we leave, we can optimise by setting the map to the maximum memory size this->descriptor_sets.reserve(this->vk_max_sets); // D0ne logger.logc(Verbosity::important, DescriptorPool::channel, "Init success."); } /* Constructor for the DescriptorPool class, which takes the GPU to create the pool on, a list of descriptor types and their counts, the maximum number of descriptor sets that can be allocated and optionally custom create flags. */ DescriptorPool::DescriptorPool(const Rendering::GPU& gpu, const Tools::Array<std::pair<VkDescriptorType, uint32_t>>& descriptor_types, uint32_t max_sets, VkDescriptorPoolCreateFlags flags) : gpu(gpu), vk_descriptor_types(descriptor_types), vk_max_sets(max_sets), vk_create_flags(flags) { logger.logc(Verbosity::important, DescriptorPool::channel, "Initializing with multiple types..."); // First, we define how large the pool will be logger.logc(Verbosity::details, DescriptorPool::channel, "Preparing structs..."); Tools::Array<VkDescriptorPoolSize> descriptor_pool_sizes; descriptor_pool_sizes.resize(this->vk_descriptor_types.size()); for (uint32_t i = 0; i < this->vk_descriptor_types.size(); i++) { populate_descriptor_pool_size(descriptor_pool_sizes[i], this->vk_descriptor_types[i]); } // Prepare the create info VkDescriptorPoolCreateInfo descriptor_pool_info; populate_descriptor_pool_info(descriptor_pool_info, descriptor_pool_sizes, this->vk_max_sets, this->vk_create_flags); // Actually allocate the pool logger.logc(Verbosity::details, DescriptorPool::channel, "Allocating pool.."); VkResult vk_result; if ((vk_result = vkCreateDescriptorPool(this->gpu, &descriptor_pool_info, nullptr, &this->vk_descriptor_pool)) != VK_SUCCESS) { logger.fatalc(DescriptorPool::channel, "Could not allocate descriptor pool: ", vk_error_map[vk_result]); } // Before we leave, we can optimise by setting the map to the maximum memory size this->descriptor_sets.reserve(this->vk_max_sets); // D0ne logger.logc(Verbosity::important, DescriptorPool::channel, "Init success."); } /* Copy constructor for the DescriptorPool. */ DescriptorPool::DescriptorPool(const DescriptorPool& other) : gpu(other.gpu), vk_descriptor_types(other.vk_descriptor_types), vk_max_sets(other.vk_max_sets), vk_create_flags(other.vk_create_flags) { logger.logc(Verbosity::debug, DescriptorPool::channel, "Copying..."); // First, we define how large the pool will be Tools::Array<VkDescriptorPoolSize> descriptor_pool_sizes; descriptor_pool_sizes.resize(this->vk_descriptor_types.size()); for (uint32_t i = 0; i < this->vk_descriptor_types.size(); i++) { populate_descriptor_pool_size(descriptor_pool_sizes[i], this->vk_descriptor_types[0]); } // Prepare the create info VkDescriptorPoolCreateInfo descriptor_pool_info; populate_descriptor_pool_info(descriptor_pool_info, descriptor_pool_sizes, this->vk_max_sets, this->vk_create_flags); // Actually allocate the pool VkResult vk_result; if ((vk_result = vkCreateDescriptorPool(this->gpu, &descriptor_pool_info, nullptr, &this->vk_descriptor_pool)) != VK_SUCCESS) { logger.fatalc(DescriptorPool::channel, "Could not allocate descriptor pool: ", vk_error_map[vk_result]); } // Do not copy individual descriptors // Before we leave, we can optimise by setting the map to the maximum memory size this->descriptor_sets.reserve(this->vk_max_sets); // D0ne logger.logc(Verbosity::debug, DescriptorPool::channel, "Copy success."); } /* Move constructor for the DescriptorPool. */ DescriptorPool::DescriptorPool(DescriptorPool&& other): gpu(other.gpu), vk_descriptor_pool(other.vk_descriptor_pool), vk_descriptor_types(other.vk_descriptor_types), vk_max_sets(other.vk_max_sets), vk_create_flags(other.vk_create_flags), descriptor_sets(other.descriptor_sets) { // Set the other's pool & sets to nullptr to avoid deallocation other.vk_descriptor_pool = nullptr; other.descriptor_sets.clear(); } /* Destructor for the DescriptorPool. */ DescriptorPool::~DescriptorPool() { logger.logc(Verbosity::important, DescriptorPool::channel, "Cleaning..."); VkResult vk_result; if (this->descriptor_sets.size() > 0) { logger.logc(Verbosity::details, DescriptorPool::channel, "Deallocating descriptor sets..."); for (uint32_t i = 0; i < this->descriptor_sets.size(); i++) { if ((vk_result = vkFreeDescriptorSets(this->gpu, this->vk_descriptor_pool, 1, &this->descriptor_sets[i]->vulkan())) != VK_SUCCESS) { logger.errorc(DescriptorPool::channel, "Could not deallocate descriptor sets: ", vk_error_map[vk_result]); } } } if (this->vk_descriptor_pool != nullptr) { logger.logc(Verbosity::details, DescriptorPool::channel, "Deallocating pool..."); vkDestroyDescriptorPool(this->gpu, this->vk_descriptor_pool, nullptr); } logger.logc(Verbosity::important, DescriptorPool::channel, "Cleaned."); } /* Allocates a single descriptor set with the given layout. Will fail with errors if there's no more space. */ DescriptorSet* DescriptorPool::allocate(const Rendering::DescriptorSetLayout& descriptor_set_layout) { // Check if we have enough space left if (static_cast<uint32_t>(this->descriptor_sets.size()) >= this->vk_max_sets) { logger.fatalc(DescriptorPool::channel, "Cannot allocate new DescriptorSet: already allocated maximum of ", this->vk_max_sets, " sets."); } // Put the layout in a struct s.t. we can pass it and keep it in memory until after the call Tools::Array<VkDescriptorSetLayout> vk_descriptor_set_layouts({ descriptor_set_layout.vulkan() }); // Next, populate the create info VkDescriptorSetAllocateInfo descriptor_set_info; populate_descriptor_set_info(descriptor_set_info, this->vk_descriptor_pool, vk_descriptor_set_layouts, 1); // We can now call the allocate function VkResult vk_result; VkDescriptorSet set; if ((vk_result = vkAllocateDescriptorSets(this->gpu, &descriptor_set_info, &set)) != VK_SUCCESS) { logger.fatalc(DescriptorPool::channel, "Failed to allocate new DescriptorSet: ", vk_error_map[vk_result]); } // Create the object and insert it DescriptorSet* descriptor_set = new DescriptorSet(this->gpu, set); this->descriptor_sets.push_back(descriptor_set); // With that done, return the handle return descriptor_set; } /* Allocates multiple descriptor sets with the given layout, returning them as an Array. Will fail with errors if there's no more space. */ Tools::Array<DescriptorSet*> DescriptorPool::nallocate(uint32_t n_sets, const Tools::Array<Rendering::DescriptorSetLayout>& descriptor_set_layouts) { #ifndef NDEBUG // If n_sets if null, nothing to do if (n_sets == 0) { logger.warningc(DescriptorPool::channel, "Request to allocate 0 sets received; nothing to do."); return {}; } // If we aren't passed enough layouts, then tell us if (n_sets != descriptor_set_layouts.size()) { logger.fatalc(DescriptorPool::channel, "Not enough descriptor set layouts passed: got ", descriptor_set_layouts.size(), ", expected ", n_sets); } #endif // Check if we have enough space left if (static_cast<uint32_t>(this->descriptor_sets.size()) + n_sets > this->vk_max_sets) { logger.fatalc(DescriptorPool::channel, "Cannot allocate ", n_sets, " new DescriptorSets: only space for ", this->vk_max_sets - static_cast<uint32_t>(this->descriptor_sets.size()), " sets"); } // Get the VkDescriptorSetLayout objects behind the layouts Tools::Array<VkDescriptorSetLayout> vk_descriptor_set_layouts(descriptor_set_layouts.size()); for (uint32_t i = 0; i < descriptor_set_layouts.size(); i++) { vk_descriptor_set_layouts.push_back(descriptor_set_layouts[i]); } // Create a temporary list of result sets to which we can allocate Tools::Array<VkDescriptorSet> sets(n_sets); // Next, populate the create info VkDescriptorSetAllocateInfo descriptor_set_info; populate_descriptor_set_info(descriptor_set_info, this->vk_descriptor_pool, vk_descriptor_set_layouts, n_sets); // We can now call the allocate function VkResult vk_result; if ((vk_result = vkAllocateDescriptorSets(this->gpu, &descriptor_set_info, sets.wdata(n_sets))) != VK_SUCCESS) { logger.fatalc(DescriptorPool::channel, "Failed to allocate ", n_sets, " new DescriptorSets: ", vk_error_map[vk_result]); } // Create the resulting DescriptorSet object for each pair, then return Tools::Array<DescriptorSet*> result(n_sets); for (uint32_t i = 0; i < n_sets; i++) { result.push_back(new DescriptorSet(this->gpu, sets[i])); this->descriptor_sets.push_back(result.last()); } // We're done, so return the set of handles return result; } /* Allocates multiple descriptor sets with the given layout (repeating it), returning them as an Array. Will fail with errors if there's no more space. */ Tools::Array<DescriptorSet*> DescriptorPool::nallocate(uint32_t n_sets, const Rendering::DescriptorSetLayout& descriptor_set_layout) { #ifndef NDEBUG // If n_sets if null, nothing to do if (n_sets == 0) { logger.warningc(DescriptorPool::channel, "Request to allocate 0 sets received; nothing to do."); return {}; } #endif // Check if we have enough space left if (static_cast<uint32_t>(this->descriptor_sets.size()) + n_sets > this->vk_max_sets) { logger.fatalc(DescriptorPool::channel, "Cannot allocate ", n_sets, " new DescriptorSets: only space for ", this->vk_max_sets - static_cast<uint32_t>(this->descriptor_sets.size()), " sets"); } // Get the VkDescriptorSetLayout object behind the layout as an array Tools::Array<VkDescriptorSetLayout> vk_descriptor_set_layout(descriptor_set_layout.vulkan(), n_sets); // Create a temporary list of result sets to which we can allocate Tools::Array<VkDescriptorSet> sets(n_sets); // Next, populate the create info VkDescriptorSetAllocateInfo descriptor_set_info; populate_descriptor_set_info(descriptor_set_info, this->vk_descriptor_pool, vk_descriptor_set_layout, n_sets); // We can now call the allocate function VkResult vk_result; if ((vk_result = vkAllocateDescriptorSets(this->gpu, &descriptor_set_info, sets.wdata(n_sets))) != VK_SUCCESS) { logger.fatalc(DescriptorPool::channel, "Failed to allocate ", n_sets, " new DescriptorSets: ", vk_error_map[vk_result]); } // Create the resulting DescriptorSet object for each pair, then return Tools::Array<DescriptorSet*> result(n_sets); for (uint32_t i = 0; i < n_sets; i++) { result.push_back(new DescriptorSet(this->gpu, sets[i])); this->descriptor_sets.push_back(result.last()); } // We're done, so return the set of handles return result; } /* Deallocates the descriptor set with the given handle. */ void DescriptorPool::free(const DescriptorSet* set) { // Try to remove the pointer from the list bool found = false; for (uint32_t i = 0; i < this->descriptor_sets.size(); i++) { if (this->descriptor_sets[i] == set) { this->descriptor_sets.erase(i); found = true; break; } } if (!found) { logger.fatalc(DescriptorPool::channel, "Tried to free DescriptorSet that was not allocated with this pool."); } // Destroy the VkCommandBuffer vkFreeDescriptorSets(this->gpu, this->vk_descriptor_pool, 1, &set->vulkan()); // Destroy the pointer itself delete set; } /* Deallocates an array of given descriptors sets. */ void DescriptorPool::nfree(const Tools::Array<DescriptorSet*>& sets) { // First, we check if all handles exist Tools::Array<VkDescriptorSet> to_remove(sets.size()); for (uint32_t i = 0; i < sets.size(); i++) { bool found = false; for (uint32_t i = 0; i < this->descriptor_sets.size(); i++) { if (this->descriptor_sets[i] == sets[i]) { this->descriptor_sets.erase(i); found = true; break; } } if (!found) { logger.fatalc(DescriptorPool::channel, "Tried to free DescriptorSet that was not allocated with this pool."); } // Mark the Vk object for removal to_remove.push_back(sets[i]->vulkan()); // Delete the pointer delete sets[i]; } // All that's left is to actually remove the handles; do that VkResult vk_result; if ((vk_result = vkFreeDescriptorSets(this->gpu, this->vk_descriptor_pool, to_remove.size(), to_remove.rdata())) != VK_SUCCESS) { logger.fatalc(DescriptorPool::channel, "Could not deallocate descriptor sets: ", vk_error_map[vk_result]); } } /* Resets the pool in its entirety, quickly deallocating everything. */ void DescriptorPool::reset() { // Call the reset quickly (note the 0, the flags, is reserved for future use and thus fixed for us) vkResetDescriptorPool(this->gpu, this->vk_descriptor_pool, 0); // Delete all internal pointers for (uint32_t i = 0; i < this->descriptor_sets.size(); i++) { delete this->descriptor_sets[i]; } this->descriptor_sets.clear(); } /* Swap operator for the DescriptorPool class. */ void Rendering::swap(DescriptorPool& dp1, DescriptorPool& dp2) { #ifndef NDEBUG // If the GPU is not the same, then initialize to all nullptrs and everything if (dp1.gpu != dp2.gpu) { logger.fatalc(DescriptorPool::channel, "Cannot swap descriptor pools with different GPUs"); } #endif // Swap all fields using std::swap; swap(dp1.vk_descriptor_pool, dp2.vk_descriptor_pool); swap(dp1.vk_descriptor_types, dp2.vk_descriptor_types); swap(dp1.vk_max_sets, dp2.vk_max_sets); swap(dp1.vk_create_flags, dp2.vk_create_flags); swap(dp1.descriptor_sets, dp2.descriptor_sets); }
42.62181
245
0.721121
Lut99
d31f64e26267dc1b13491335ff3dd9b5b5f51e28
3,313
cpp
C++
hi_snex/snex_parser/snex_jit_SymbolParser.cpp
Matt-Dub/HISE
ae2dd1653e1c8d749a9088edcd573de6252b0b96
[ "Intel" ]
null
null
null
hi_snex/snex_parser/snex_jit_SymbolParser.cpp
Matt-Dub/HISE
ae2dd1653e1c8d749a9088edcd573de6252b0b96
[ "Intel" ]
null
null
null
hi_snex/snex_parser/snex_jit_SymbolParser.cpp
Matt-Dub/HISE
ae2dd1653e1c8d749a9088edcd573de6252b0b96
[ "Intel" ]
null
null
null
/* =========================================================================== * * This file is part of HISE. * Copyright 2016 Christoph Hart * * HISE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option any later version. * * HISE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HISE. If not, see <http://www.gnu.org/licenses/>. * * Commercial licences for using HISE in an closed source project are * available on request. Please visit the project's website to get more * information about commercial licencing: * * http://www.hartinstruments.net/hise/ * * HISE is based on the JUCE library, * which also must be licenced for commercial applications: * * http://www.juce.com * * =========================================================================== */ namespace snex { namespace jit { using namespace juce; using namespace asmjit; void NamespaceResolver::CanExist::resolve(NamespaceHandler& n, NamespacedIdentifier& c, const ParserHelpers::CodeLocation& l) { auto r = n.resolve(c, true); if (!r.wasOk()) l.throwError(r.getErrorMessage()); } SymbolParser::SymbolParser(ParserHelpers::TokenIterator& other_, NamespaceHandler& handler_) : ParserHelpers::TokenIterator(other_), handler(handler_), other(other_) { } snex::jit::Symbol SymbolParser::parseExistingSymbol(bool needsStaticTyping) { parseNamespacedIdentifier<NamespaceResolver::MustExist>(); auto type = handler.getVariableType(currentNamespacedIdentifier); location.test(handler.checkVisiblity(currentNamespacedIdentifier)); auto s = Symbol(currentNamespacedIdentifier, type); if (needsStaticTyping && s.typeInfo.isDynamic()) location.throwError("Can't resolve symbol type"); return s; } snex::jit::Symbol SymbolParser::parseNewDynamicSymbolSymbol(NamespaceHandler::SymbolType t) { jassert(other.currentTypeInfo.isDynamic()); parseNamespacedIdentifier<NamespaceResolver::MustBeNew>(); auto s = Symbol(currentNamespacedIdentifier, other.currentTypeInfo); return s; } snex::jit::Symbol SymbolParser::parseNewSymbol(NamespaceHandler::SymbolType t) { auto type = other.currentTypeInfo; parseNamespacedIdentifier<NamespaceResolver::MustBeNew>(); auto s = Symbol(currentNamespacedIdentifier, type); BlockParser::CommentAttacher ca(*this); if (t != NamespaceHandler::Unknown) handler.addSymbol(s.id, type, t, ca.getInfo()); #if 0 if (s.typeInfo.isDynamic() && t != NamespaceHandler::UsingAlias) location.throwError("Can't resolve symbol type"); #endif return s; } void NamespaceResolver::MustExist::resolve(NamespaceHandler& n, NamespacedIdentifier& c, const ParserHelpers::CodeLocation& l) { auto r = n.resolve(c); if (!r.wasOk()) { DBG(n.dump()); l.throwError(r.getErrorMessage()); } } void NamespaceResolver::MustBeNew::resolve(NamespaceHandler& n, NamespacedIdentifier& c, const ParserHelpers::CodeLocation& l) { } } }
27.380165
126
0.715967
Matt-Dub
d3210fd0c26b61c2ef387e112f839acbc13abf16
4,988
cc
C++
src/ImgProc.cc
abhishekdewan101/RealTimeFaceTracking
393dfd9418bf53e006d6c1fe533ecaca82c80e08
[ "MIT" ]
2
2019-02-20T00:37:57.000Z
2019-02-20T00:38:32.000Z
node_modules/opencv/src/ImgProc.cc
nolim1t/opencv-aws-lambda
744d2cc1e9ac257e24c8a1a33e8a0d53dd8aff56
[ "MIT" ]
null
null
null
node_modules/opencv/src/ImgProc.cc
nolim1t/opencv-aws-lambda
744d2cc1e9ac257e24c8a1a33e8a0d53dd8aff56
[ "MIT" ]
4
2015-03-29T19:50:06.000Z
2021-03-31T18:55:35.000Z
#include "ImgProc.h" #include "Matrix.h" void ImgProc::Init(Handle<Object> target) { Persistent<Object> inner; Local<Object> obj = NanNew<Object>(); NanAssignPersistent(inner, obj); NODE_SET_METHOD(obj, "undistort", Undistort); NODE_SET_METHOD(obj, "initUndistortRectifyMap", InitUndistortRectifyMap); NODE_SET_METHOD(obj, "remap", Remap); target->Set(NanNew("imgproc"), obj); } // cv::undistort NAN_METHOD(ImgProc::Undistort) { NanEscapableScope(); try { // Get the arguments // Arg 0 is the image Matrix* m0 = ObjectWrap::Unwrap<Matrix>(args[0]->ToObject()); cv::Mat inputImage = m0->mat; // Arg 1 is the camera matrix Matrix* m1 = ObjectWrap::Unwrap<Matrix>(args[1]->ToObject()); cv::Mat K = m1->mat; // Arg 2 is the distortion coefficents Matrix* m2 = ObjectWrap::Unwrap<Matrix>(args[2]->ToObject()); cv::Mat dist = m2->mat; // Make an mat to hold the result image cv::Mat outputImage; // Undistort cv::undistort(inputImage, outputImage, K, dist); // Wrap the output image Local<Object> outMatrixWrap = NanNew(Matrix::constructor)->GetFunction()->NewInstance(); Matrix *outMatrix = ObjectWrap::Unwrap<Matrix>(outMatrixWrap); outMatrix->mat = outputImage; // Return the output image NanReturnValue(outMatrixWrap); } catch (cv::Exception &e) { const char *err_msg = e.what(); NanThrowError(err_msg); NanReturnUndefined(); } } // cv::initUndistortRectifyMap NAN_METHOD(ImgProc::InitUndistortRectifyMap) { NanEscapableScope(); try { // Arg 0 is the camera matrix Matrix* m0 = ObjectWrap::Unwrap<Matrix>(args[0]->ToObject()); cv::Mat K = m0->mat; // Arg 1 is the distortion coefficents Matrix* m1 = ObjectWrap::Unwrap<Matrix>(args[1]->ToObject()); cv::Mat dist = m1->mat; // Arg 2 is the recification transformation Matrix* m2 = ObjectWrap::Unwrap<Matrix>(args[2]->ToObject()); cv::Mat R = m2->mat; // Arg 3 is the new camera matrix Matrix* m3 = ObjectWrap::Unwrap<Matrix>(args[3]->ToObject()); cv::Mat newK = m3->mat; // Arg 4 is the image size cv::Size imageSize; if (args[4]->IsArray()) { Local<Object> v8sz = args[4]->ToObject(); imageSize = cv::Size(v8sz->Get(1)->IntegerValue(), v8sz->Get(0)->IntegerValue()); } else { JSTHROW_TYPE("Must pass image size"); } // Arg 5 is the first map type, skip for now int m1type = args[5]->IntegerValue(); // Make matrices to hold the output maps cv::Mat map1, map2; // Compute the rectification map cv::initUndistortRectifyMap(K, dist, R, newK, imageSize, m1type, map1, map2); // Wrap the output maps Local<Object> map1Wrap = NanNew(Matrix::constructor)->GetFunction()->NewInstance(); Matrix *map1Matrix = ObjectWrap::Unwrap<Matrix>(map1Wrap); map1Matrix->mat = map1; Local<Object> map2Wrap = NanNew(Matrix::constructor)->GetFunction()->NewInstance(); Matrix *map2Matrix = ObjectWrap::Unwrap<Matrix>(map2Wrap); map2Matrix->mat = map2; // Make a return object with the two maps Local<Object> ret = NanNew<Object>(); ret->Set(NanNew<String>("map1"), map1Wrap); ret->Set(NanNew<String>("map2"), map2Wrap); // Return the maps NanReturnValue(ret); } catch (cv::Exception &e) { const char *err_msg = e.what(); NanThrowError(err_msg); NanReturnUndefined(); } } // cv::remap NAN_METHOD(ImgProc::Remap) { NanEscapableScope(); try { // Get the arguments // Arg 0 is the image Matrix* m0 = ObjectWrap::Unwrap<Matrix>(args[0]->ToObject()); cv::Mat inputImage = m0->mat; // Arg 1 is the first map Matrix* m1 = ObjectWrap::Unwrap<Matrix>(args[1]->ToObject()); cv::Mat map1 = m1->mat; // Arg 2 is the second map Matrix* m2 = ObjectWrap::Unwrap<Matrix>(args[2]->ToObject()); cv::Mat map2 = m2->mat; // Arg 3 is the interpolation mode int interpolation = args[3]->IntegerValue(); // Args 4, 5 border settings, skipping for now // Output image cv::Mat outputImage; // Remap cv::remap(inputImage, outputImage, map1, map2, interpolation); // Wrap the output image Local<Object> outMatrixWrap = NanNew(Matrix::constructor)->GetFunction()->NewInstance(); Matrix *outMatrix = ObjectWrap::Unwrap<Matrix>(outMatrixWrap); outMatrix->mat = outputImage; // Return the image NanReturnValue(outMatrixWrap); } catch (cv::Exception &e) { const char *err_msg = e.what(); NanThrowError(err_msg); NanReturnUndefined(); } }
29.341176
96
0.596231
abhishekdewan101
d323d663b46feee228700e1768c809c4d1307c19
1,100
cpp
C++
source/rho/crypt/tSHA224.cpp
Rhobota/librho
d540cba6227e15ac6ef3dcb6549ed9557f6fee04
[ "BSD-3-Clause" ]
1
2016-09-22T03:27:33.000Z
2016-09-22T03:27:33.000Z
source/rho/crypt/tSHA224.cpp
Rhobota/librho
d540cba6227e15ac6ef3dcb6549ed9557f6fee04
[ "BSD-3-Clause" ]
null
null
null
source/rho/crypt/tSHA224.cpp
Rhobota/librho
d540cba6227e15ac6ef3dcb6549ed9557f6fee04
[ "BSD-3-Clause" ]
null
null
null
#include <rho/crypt/tSHA224.h> #include <rho/crypt/hash_utils.h> #include "sha.h" namespace rho { namespace crypt { tSHA224::tSHA224() : m_context(NULL) { m_context = new SHA256_CTX; SHA224_Init((SHA256_CTX*)m_context); } tSHA224::~tSHA224() { delete ((SHA256_CTX*)m_context); m_context = NULL; } i32 tSHA224::write(const u8* buffer, i32 length) { return this->writeAll(buffer, length); } i32 tSHA224::writeAll(const u8* buffer, i32 length) { if (length <= 0) throw eInvalidArgument("Stream read/write length must be >0"); SHA224_Update(((SHA256_CTX*)m_context), buffer, (u32)length); return length; } std::vector<u8> tSHA224::getHash() const { u8 dg[SHA256_DIGEST_LENGTH]; SHA256_CTX context = *((SHA256_CTX*)m_context); SHA224_Final(dg, &context); std::vector<u8> v(SHA224_DIGEST_LENGTH, 0); for (size_t i = 0; i < v.size(); i++) v[i] = dg[i]; return v; } std::string tSHA224::getHashString() const { std::vector<u8> hash = getHash(); return hashToString(hash); } } // namespace crypt } // namespace rho
18.333333
70
0.653636
Rhobota
d32630e21e4b2010a28a11dce1b2982c461e29fc
243
cpp
C++
src/modules/lib/OrderPositionController.cpp
Thorsten-Geppert/Warehouse
b064e5b422d0b484ca702cc4433cbda90f40e009
[ "BSD-3-Clause" ]
null
null
null
src/modules/lib/OrderPositionController.cpp
Thorsten-Geppert/Warehouse
b064e5b422d0b484ca702cc4433cbda90f40e009
[ "BSD-3-Clause" ]
null
null
null
src/modules/lib/OrderPositionController.cpp
Thorsten-Geppert/Warehouse
b064e5b422d0b484ca702cc4433cbda90f40e009
[ "BSD-3-Clause" ]
null
null
null
#include "OrderPositionController.h" OrderPositionController::OrderPositionController( RuntimeInformationType *rit ) : Controller( rit, _N("orders_positions"), // Table _N("orderPositionId"), // Primary key _N("rank") // Sorting ) { }
20.25
49
0.73251
Thorsten-Geppert
d326cb45b82d86ba7639da9e3043fc07cf6adf18
8,013
cc
C++
src/agent/worker.cc
henrybell/cloud-debug-java
387a904d58260637c2433c2191395fd3d93cd765
[ "Apache-2.0" ]
null
null
null
src/agent/worker.cc
henrybell/cloud-debug-java
387a904d58260637c2433c2191395fd3d93cd765
[ "Apache-2.0" ]
null
null
null
src/agent/worker.cc
henrybell/cloud-debug-java
387a904d58260637c2433c2191395fd3d93cd765
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "worker.h" #include "callbacks_monitor.h" #include "agent_thread.h" #include "bridge.h" DEFINE_FLAG( int32, hub_retry_delay_ms, 10000, // 10 seconds "amount of time in milliseconds to sleep before retrying failed " "requests to Cloud Debugger backend"); DEFINE_FLAG( int32, debuggee_disabled_delay_ms, 600000, // 10 minutes "amount of time in milliseconds to sleep before checking whether " "the debugger was enabled back"); namespace devtools { namespace cdbg { int g_is_enabled_attempts = 0; Worker::Worker( Provider* provider, std::function<std::unique_ptr<AutoResetEvent>()> event_factory, std::function<std::unique_ptr<AgentThread>()> agent_thread_factory, ClassPathLookup* class_path_lookup, std::unique_ptr<Bridge> bridge, FormatQueue* format_queue) : provider_(provider), main_thread_event_(event_factory()), transmission_thread_event_(event_factory()), main_thread_(agent_thread_factory()), transmission_thread_(agent_thread_factory()), class_path_lookup_(class_path_lookup), bridge_(std::move(bridge)), canary_control_(CallbacksMonitor::GetInstance(), bridge_.get()), format_queue_(format_queue) { // Subscribe to receive synchronous notifications every time a breakpoint // update is enqueued. In return we get a cookie that must be returned // back to unsubscribe (on shutdown). on_breakpoint_update_enqueued_cookie_ = format_queue_->SubscribeOnItemEnqueuedEvents([this]() { transmission_thread_event_->Signal(); }); } Worker::~Worker() { } void Worker::Start() { // Initialize the thread event. The debugger thread would be a better place // to have this initialization to reduce the impact on application startup // time. The problem is that if "Shutdown" is called before the event has // been created, it will not be able to signal the debugger thread to stop. if (!main_thread_event_->Initialize()) { LOG(ERROR) << "Debugger thread event could not be initialized. " "Debugger will not be available."; return; } if (!main_thread_->Start( "CloudDebugger_main_worker_thread", std::bind(&Worker::MainThreadProc, this))) { LOG(ERROR) << "Java debugger worker thread could not be started. " "Debugger will not be available."; return; } } void Worker::Shutdown() { format_queue_->UnsubscribeOnItemEnqueuedEvents( std::move(on_breakpoint_update_enqueued_cookie_)); is_unloading_ = true; // Cancel all pending requests to the backend. bridge_->Shutdown(); // Signal for the debugger thread to exit. Then wait until the thread // terminates. main_thread_event_->Signal(); if (main_thread_->IsStarted()) { main_thread_->Join(); } // Now wait until subscriber thread terminates. We only stop the subscriber // thread after the main worker thread exits to make sure that the subscriber // thread does not get created again while we are waiting for the main worker // thread to terminate. provider_->EnableDebugger(false); LOG(INFO) << "Debugger threads terminated"; } void Worker::MainThreadProc() { // // One time initialization of Worker. This initialization logically belongs // to "Start", but it was moved here to reduce the impact of debugger on // application startup time. // // Deferred initialization of the agent. if (!provider_->OnWorkerReady()) { LOG(ERROR) << "Agent initialization failed: " "debugger thread can't continue."; return; // Signal to stop the main debugger thread. } if (!transmission_thread_event_->Initialize()) { LOG(ERROR) << "Transmission event could not be initialized: " "debugger thread can't continue."; return; } // Initialize Hub client. if (!bridge_->Bind(class_path_lookup_)) { LOG(ERROR) << "HubClient not available: debugger thread can't continue."; return; // Signal to stop the main debugger thread. } bool is_enabled = false; while (!is_unloading_ && !bridge_->IsEnabled(&is_enabled)) { // Wait for classes to load. ++g_is_enabled_attempts; provider_->OnIdle(); main_thread_event_->Wait(100); // Wait for 100ms to lower CPU usage } if (!is_enabled) { LOG(WARNING) << "The debugger is disabled on this process."; return; } while (!is_unloading_) { // Register debuggee if not registered or if previous call to list active // breakpoints failed. if (!is_registered_) { RegisterDebuggee(); } else { // Issue a hanging get request to list active breakpoints. ListActiveBreakpoints(); } canary_control_.ApproveHealtyBreakpoints(); provider_->OnIdle(); } // This thread owns the transmission thread. Stop it now. if (transmission_thread_->IsStarted()) { transmission_thread_event_->Signal(); transmission_thread_->Join(); } } void Worker::TransmissionThreadProc() { while (!is_unloading_) { // Wait until one of the following: // 1. New breakpoint update has been enqueued. // 2. Shutdown. // 3. Previously failed transmissions and we are past the retry interval. transmission_thread_event_->Wait( bridge_->HasPendingMessages() ? base::GetFlag(FLAGS_hub_retry_delay_ms) : 100000000); // arbitrary long delay. // Enqueue new breakpoint updates for transmission. while (!is_unloading_) { std::unique_ptr<BreakpointModel> breakpoint = format_queue_->FormatAndPop(); if (breakpoint == nullptr) { break; } bridge_->EnqueueBreakpointUpdate(std::move(breakpoint)); } // Post breakpoint hit results (both the new ones and retry previously // failed messages). bridge_->TransmitBreakpointUpdates(); } } void Worker::RegisterDebuggee() { bool new_is_enabled = false; is_registered_ = bridge_->RegisterDebuggee(&new_is_enabled); if (is_registered_) { provider_->EnableDebugger(new_is_enabled); if (!new_is_enabled) { is_registered_ = false; main_thread_event_->Wait(base::GetFlag(FLAGS_debuggee_disabled_delay_ms)); } } else { // Delay before attempting to retry. main_thread_event_->Wait(base::GetFlag(FLAGS_hub_retry_delay_ms)); } } void Worker::ListActiveBreakpoints() { // Query list of active breakpoints. std::vector<std::unique_ptr<BreakpointModel>> breakpoints; auto rc = bridge_->ListActiveBreakpoints(&breakpoints); switch (rc) { case Bridge::HangingGetResult::SUCCESS: // Start the transmission thread first time a breakpoint is set. We then // never stop the transmission thread until shutdown (for simplicity). if (!breakpoints.empty() && !transmission_thread_->IsStarted()) { if (!transmission_thread_->Start( "CloudDebugger_transmission_thread", std::bind(&Worker::TransmissionThreadProc, this))) { LOG(ERROR) << "Transmission thread could not be started."; } } // Update the list of active breakpoints. provider_->OnBreakpointsUpdated(std::move(breakpoints)); return; case Bridge::HangingGetResult::FAIL: is_registered_ = false; return; case Bridge::HangingGetResult::TIMEOUT: return; } } } // namespace cdbg } // namespace devtools
30.12406
80
0.690877
henrybell
d326f30e97bbe3c6b214736073ea6175cdb5fc6c
1,113
cpp
C++
src/python_bindings.cpp
risteon/voxel-traversal
331f390025d23fdc2d6f6e33292625bf42b3264c
[ "MIT" ]
3
2022-03-02T17:17:52.000Z
2022-03-25T09:03:43.000Z
src/python_bindings.cpp
risteon/voxel-traversal
331f390025d23fdc2d6f6e33292625bf42b3264c
[ "MIT" ]
null
null
null
src/python_bindings.cpp
risteon/voxel-traversal
331f390025d23fdc2d6f6e33292625bf42b3264c
[ "MIT" ]
null
null
null
#include "python_bindings.h" #include <pybind11/stl.h> #include "voxel_traversal.h" namespace py = pybind11; using namespace voxel_traversal; namespace pytraversal { py::array_t<int64_t, py::array::c_style> traverse( const grid_type& grid, const grid_type::Vector3d& ray_origin, const grid_type::Vector3d& ray_end) { TraversedVoxels<double> traversed_voxels{}; const auto ray = Ray<double>::fromOriginEnd(ray_origin, ray_end); const bool hit = traverseVoxelGrid(ray, grid, traversed_voxels); if (hit) { return py::cast(traversed_voxels); } else { // make sure to return empty array with correct shape [0, 3] const py::array::ShapeContainer shape({0, 3}); return py::array_t<int64_t, py::array::c_style>(shape); } } } // namespace pytraversal PYBIND11_MODULE(pytraversal, m) { using namespace pytraversal; m.doc() = "pytraversal bindings"; py::class_<grid_type>(m, "Grid3D") .def(py::init<>()) .def(py::init<const grid_type::Vector3d&, const grid_type::Vector3d&, const grid_type::Index3d&>()) .def("traverse", traverse); }
27.825
75
0.68823
risteon
d328a78b8f0fc5a25dcc8d29380d800d359f106a
20,428
cpp
C++
tests/unit_tests/neutral/windows_runtime/x64_fastcall_thunk.cpp
dbremner/cxxreflect
bbf1649b00755f8463e4a73b28dec4cd5b609493
[ "BSL-1.0" ]
5
2019-03-21T14:52:16.000Z
2021-02-20T13:14:25.000Z
tests/unit_tests/neutral/windows_runtime/x64_fastcall_thunk.cpp
dbremner/cxxreflect
bbf1649b00755f8463e4a73b28dec4cd5b609493
[ "BSL-1.0" ]
null
null
null
tests/unit_tests/neutral/windows_runtime/x64_fastcall_thunk.cpp
dbremner/cxxreflect
bbf1649b00755f8463e4a73b28dec4cd5b609493
[ "BSL-1.0" ]
2
2017-02-17T23:24:23.000Z
2021-07-06T18:10:35.000Z
// Copyright James P. McNellis 2011 - 2013. // // Distributed under the Boost Software License, Version 1.0. // // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // These tests do basic verification of the x64 assembly thunk that we use for dynamic invocation on // x64 for fastcall functions (i.e., all functions, because fastcall is all there is). #include "tests/unit_tests/neutral/precompiled_headers.hpp" #if CXXREFLECT_ARCHITECTURE == CXXREFLECT_ARCHITECTURE_X64 namespace cxr { using namespace cxxreflect; using namespace cxxreflect::windows_runtime; using namespace cxxreflect::windows_runtime::detail; typedef std::int8_t i1; typedef std::uint8_t u1; typedef std::int16_t i2; typedef std::uint16_t u2; typedef std::int32_t i4; typedef std::uint32_t u4; typedef std::int64_t i8; typedef std::uint64_t u8; typedef float r4; typedef double r8; } namespace cxxreflect_test { namespace { // Because we are testing our ability to call arbitrary functions, we cannot pass a pointer to // the current context into each function. To work around this, we use a global context pointer // that gets set at the beginning of each test and unset at the end of the test. // // If we ever run the test suite in parallel, we'll need to synchronize access to the global // context or add some sort of tag that identifies tests as needing to be run in sequence. context const* global_context; class guarded_context_initializer { public: guarded_context_initializer(context const* const c) { global_context = c; } ~guarded_context_initializer() { global_context = nullptr; } }; } } namespace cxxreflect_test { static auto f0() -> void { } CXXREFLECTTEST_DEFINE_TEST(windows_runtime_x64_fastcall_thunk_no_arguments) { guarded_context_initializer const context_guard(&c); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(f0, nullptr, nullptr, 0); } } namespace cxxreflect_test { static auto fi1(cxr::i4 a) -> void { global_context->verify_equals(a, 1); } static auto fi2(cxr::i8 a, cxr::i8 b) -> void { global_context->verify_equals(a, 1); global_context->verify_equals(b, -2); } static auto fi3(cxr::i4 a, cxr::i4 b, cxr::i4 c) -> void { global_context->verify_equals(a, 1); global_context->verify_equals(b, -2); global_context->verify_equals(c, 3); } static auto fi4(cxr::i8 a, cxr::i8 b, cxr::i8 c, cxr::i8 d) -> void { global_context->verify_equals(a, 1); global_context->verify_equals(b, -2); global_context->verify_equals(c, 3); global_context->verify_equals(d, -4); } static auto fi5(cxr::i4 a, cxr::i4 b, cxr::i4 c, cxr::i4 d, cxr::i4 e) -> void { global_context->verify_equals(a, 1); global_context->verify_equals(b, -2); global_context->verify_equals(c, 3); global_context->verify_equals(d, -4); global_context->verify_equals(e, 5); } static auto fi6(cxr::i8 a, cxr::i8 b, cxr::i8 c, cxr::i8 d, cxr::i8 e, cxr::i8 f) -> void { global_context->verify_equals(a, 1); global_context->verify_equals(b, -2); global_context->verify_equals(c, 3); global_context->verify_equals(d, -4); global_context->verify_equals(e, 5); global_context->verify_equals(f, -6); } static auto fi7(cxr::i4 a, cxr::i4 b, cxr::i4 c, cxr::i4 d, cxr::i4 e, cxr::i4 f, cxr::i4 g) -> void { global_context->verify_equals(a, 1); global_context->verify_equals(b, -2); global_context->verify_equals(c, 3); global_context->verify_equals(d, -4); global_context->verify_equals(e, 5); global_context->verify_equals(f, -6); global_context->verify_equals(g, 7); } static auto fi8(cxr::i8 a, cxr::i8 b, cxr::i8 c, cxr::i8 d, cxr::i8 e, cxr::i8 f, cxr::i8 g, cxr::i8 h) -> void { global_context->verify_equals(a, 1); global_context->verify_equals(b, -2); global_context->verify_equals(c, 3); global_context->verify_equals(d, -4); global_context->verify_equals(e, 5); global_context->verify_equals(f, -6); global_context->verify_equals(g, 7); global_context->verify_equals(h, -8); } CXXREFLECTTEST_DEFINE_TEST(windows_runtime_x64_fastcall_thunk_signed_integer_arguments) { guarded_context_initializer const context_guard(&c); cxr::x64_argument_frame frame; frame.push( 1LL); frame.push(-2LL); frame.push( 3LL); frame.push(-4LL); frame.push( 5LL); frame.push(-6LL); frame.push( 7LL); frame.push(-8LL); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fi1, frame.arguments(), frame.types(), 1); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fi2, frame.arguments(), frame.types(), 2); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fi3, frame.arguments(), frame.types(), 3); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fi4, frame.arguments(), frame.types(), 4); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fi5, frame.arguments(), frame.types(), 5); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fi6, frame.arguments(), frame.types(), 6); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fi7, frame.arguments(), frame.types(), 7); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fi8, frame.arguments(), frame.types(), 8); } } namespace cxxreflect_test { static auto fd1(cxr::r8 a) -> void { global_context->verify_equals(a, 1.0); } static auto fd2(cxr::r8 a, cxr::r8 b) -> void { global_context->verify_equals(a, 1.0); global_context->verify_equals(b, -2.0); } static auto fd3(cxr::r8 a, cxr::r8 b, cxr::r8 c) -> void { global_context->verify_equals(a, 1.0); global_context->verify_equals(b, -2.0); global_context->verify_equals(c, 3.0); } static auto fd4(cxr::r8 a, cxr::r8 b, cxr::r8 c, cxr::r8 d) -> void { global_context->verify_equals(a, 1.0); global_context->verify_equals(b, -2.0); global_context->verify_equals(c, 3.0); global_context->verify_equals(d, -4.0); } static auto fd5(cxr::r8 a, cxr::r8 b, cxr::r8 c, cxr::r8 d, cxr::r8 e) -> void { global_context->verify_equals(a, 1.0); global_context->verify_equals(b, -2.0); global_context->verify_equals(c, 3.0); global_context->verify_equals(d, -4.0); global_context->verify_equals(e, 5.0); } static auto fd6(cxr::r8 a, cxr::r8 b, cxr::r8 c, cxr::r8 d, cxr::r8 e, cxr::r8 f) -> void { global_context->verify_equals(a, 1.0); global_context->verify_equals(b, -2.0); global_context->verify_equals(c, 3.0); global_context->verify_equals(d, -4.0); global_context->verify_equals(e, 5.0); global_context->verify_equals(f, -6.0); } static auto fd7(cxr::r8 a, cxr::r8 b, cxr::r8 c, cxr::r8 d, cxr::r8 e, cxr::r8 f, cxr::r8 g) -> void { global_context->verify_equals(a, 1.0); global_context->verify_equals(b, -2.0); global_context->verify_equals(c, 3.0); global_context->verify_equals(d, -4.0); global_context->verify_equals(e, 5.0); global_context->verify_equals(f, -6.0); global_context->verify_equals(g, 7.0); } static auto fd8(cxr::r8 a, cxr::r8 b, cxr::r8 c, cxr::r8 d, cxr::r8 e, cxr::r8 f, cxr::r8 g, cxr::r8 h) -> void { global_context->verify_equals(a, 1.0); global_context->verify_equals(b, -2.0); global_context->verify_equals(c, 3.0); global_context->verify_equals(d, -4.0); global_context->verify_equals(e, 5.0); global_context->verify_equals(f, -6.0); global_context->verify_equals(g, 7.0); global_context->verify_equals(h, -8.0); } CXXREFLECTTEST_DEFINE_TEST(windows_runtime_x64_fastcall_thunk_double_precision_real_arguments) { guarded_context_initializer const context_guard(&c); cxr::x64_argument_frame frame; frame.push( 1.0); frame.push(-2.0); frame.push( 3.0); frame.push(-4.0); frame.push( 5.0); frame.push(-6.0); frame.push( 7.0); frame.push(-8.0); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fd1, frame.arguments(), frame.types(), 1); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fd2, frame.arguments(), frame.types(), 2); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fd3, frame.arguments(), frame.types(), 3); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fd4, frame.arguments(), frame.types(), 4); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fd5, frame.arguments(), frame.types(), 5); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fd6, frame.arguments(), frame.types(), 6); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fd7, frame.arguments(), frame.types(), 7); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fd8, frame.arguments(), frame.types(), 8); } } namespace cxxreflect_test { static auto fs1(cxr::r4 a) -> void { global_context->verify_equals(a, 1.0f); } static auto fs2(cxr::r4 a, cxr::r4 b) -> void { global_context->verify_equals(a, 1.0f); global_context->verify_equals(b, -2.0f); } static auto fs3(cxr::r4 a, cxr::r4 b, cxr::r4 c) -> void { global_context->verify_equals(a, 1.0f); global_context->verify_equals(b, -2.0f); global_context->verify_equals(c, 3.0f); } static auto fs4(cxr::r4 a, cxr::r4 b, cxr::r4 c, cxr::r4 d) -> void { global_context->verify_equals(a, 1.0f); global_context->verify_equals(b, -2.0f); global_context->verify_equals(c, 3.0f); global_context->verify_equals(d, -4.0f); } static auto fs5(cxr::r4 a, cxr::r4 b, cxr::r4 c, cxr::r4 d, cxr::r4 e) -> void { global_context->verify_equals(a, 1.0f); global_context->verify_equals(b, -2.0f); global_context->verify_equals(c, 3.0f); global_context->verify_equals(d, -4.0f); global_context->verify_equals(e, 5.0f); } static auto fs6(cxr::r4 a, cxr::r4 b, cxr::r4 c, cxr::r4 d, cxr::r4 e, cxr::r4 f) -> void { global_context->verify_equals(a, 1.0f); global_context->verify_equals(b, -2.0f); global_context->verify_equals(c, 3.0f); global_context->verify_equals(d, -4.0f); global_context->verify_equals(e, 5.0f); global_context->verify_equals(f, -6.0f); } static auto fs7(cxr::r4 a, cxr::r4 b, cxr::r4 c, cxr::r4 d, cxr::r4 e, cxr::r4 f, cxr::r4 g) -> void { global_context->verify_equals(a, 1.0f); global_context->verify_equals(b, -2.0f); global_context->verify_equals(c, 3.0f); global_context->verify_equals(d, -4.0f); global_context->verify_equals(e, 5.0f); global_context->verify_equals(f, -6.0f); global_context->verify_equals(g, 7.0f); } static auto fs8(cxr::r4 a, cxr::r4 b, cxr::r4 c, cxr::r4 d, cxr::r4 e, cxr::r4 f, cxr::r4 g, cxr::r4 h) -> void { global_context->verify_equals(a, 1.0f); global_context->verify_equals(b, -2.0f); global_context->verify_equals(c, 3.0f); global_context->verify_equals(d, -4.0f); global_context->verify_equals(e, 5.0f); global_context->verify_equals(f, -6.0f); global_context->verify_equals(g, 7.0f); global_context->verify_equals(h, -8.0f); } CXXREFLECTTEST_DEFINE_TEST(windows_runtime_x64_fastcall_thunk_single_precision_real_arguments) { guarded_context_initializer const context_guard(&c); cxr::x64_argument_frame frame; frame.push( 1.0f); frame.push(-2.0f); frame.push( 3.0f); frame.push(-4.0f); frame.push( 5.0f); frame.push(-6.0f); frame.push( 7.0f); frame.push(-8.0f); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fs1, frame.arguments(), frame.types(), 1); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fs2, frame.arguments(), frame.types(), 2); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fs3, frame.arguments(), frame.types(), 3); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fs4, frame.arguments(), frame.types(), 4); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fs5, frame.arguments(), frame.types(), 5); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fs6, frame.arguments(), frame.types(), 6); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fs7, frame.arguments(), frame.types(), 7); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fs8, frame.arguments(), frame.types(), 8); } } namespace cxxreflect_test { template <typename A, typename B, typename C, typename D, typename E, typename F> static auto fm_verify_123456(A a, B b, C c, D d, E e, F f) -> void { global_context->verify_equals(a, 1); global_context->verify_equals(b, 2); global_context->verify_equals(c, 3); global_context->verify_equals(d, 4); global_context->verify_equals(e, 5); global_context->verify_equals(f, 6); } static auto fma(cxr::i1 a, cxr::i2 b, cxr::i1 c, cxr::i2 d, cxr::i1 e, cxr::i2 f) -> void { fm_verify_123456(a, b, c, d, e, f); } static auto fmb(cxr::i2 a, cxr::i4 b, cxr::i2 c, cxr::i4 d, cxr::i2 e, cxr::i4 f) -> void { fm_verify_123456(a, b, c, d, e, f); } static auto fmc(cxr::i4 a, cxr::i8 b, cxr::i4 c, cxr::i8 d, cxr::i4 e, cxr::i8 f) -> void { fm_verify_123456(a, b, c, d, e, f); } static auto fmd(cxr::i1 a, cxr::i2 b, cxr::i4 c, cxr::i8 d, cxr::i1 e, cxr::i2 f) -> void { fm_verify_123456(a, b, c, d, e, f); } static auto fme(cxr::i1 a, cxr::i8 b, cxr::i1 c, cxr::i8 d, cxr::i1 e, cxr::i8 f) -> void { fm_verify_123456(a, b, c, d, e, f); } static auto fmf(cxr::i8 a, cxr::i4 b, cxr::i2 c, cxr::i2 d, cxr::i4 e, cxr::i8 f) -> void { fm_verify_123456(a, b, c, d, e, f); } CXXREFLECTTEST_DEFINE_TEST(windows_runtime_x64_fastcall_thunk_mixed_integer_arguments) { guarded_context_initializer const context_guard(&c); cxr::x64_argument_frame frame; frame.push(1LL); frame.push(2LL); frame.push(3LL); frame.push(4LL); frame.push(5LL); frame.push(6LL); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fma, frame.arguments(), frame.types(), 6); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fmb, frame.arguments(), frame.types(), 6); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fmc, frame.arguments(), frame.types(), 6); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fmd, frame.arguments(), frame.types(), 6); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fme, frame.arguments(), frame.types(), 6); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fmf, frame.arguments(), frame.types(), 6); } } namespace cxxreflect_test { template <typename A, typename B, typename C, typename D, typename E, typename F> static auto fn_init_frame(A a, B b, C c, D d, E e, F f) -> cxr::x64_argument_frame { cxr::x64_argument_frame frame; frame.push(a); frame.push(b); frame.push(c); frame.push(d); frame.push(e); frame.push(f); return frame; } template <typename A, typename B, typename C, typename D, typename E, typename F> static auto fn_verify_123456(A a, B b, C c, D d, E e, F f) -> void { global_context->verify_equals(a, 1); global_context->verify_equals(b, 2); global_context->verify_equals(c, 3); global_context->verify_equals(d, 4); global_context->verify_equals(e, 5); global_context->verify_equals(f, 6); } static auto fna(cxr::r8 a, cxr::i8 b, cxr::r8 c, cxr::i8 d, cxr::r8 e, cxr::i8 f) -> void { fn_verify_123456(a, b, c, d, e, f); } static auto fnb(cxr::i8 a, cxr::r8 b, cxr::r8 c, cxr::i8 d, cxr::i8 e, cxr::r8 f) -> void { fn_verify_123456(a, b, c, d, e, f); } static auto fnc(cxr::i8 a, cxr::r4 b, cxr::r4 c, cxr::i8 d, cxr::i8 e, cxr::r4 f) -> void { fn_verify_123456(a, b, c, d, e, f); } static auto fnd(cxr::i4 a, cxr::r4 b, cxr::r8 c, cxr::i8 d, cxr::r4 e, cxr::r8 f) -> void { fn_verify_123456(a, b, c, d, e, f); } CXXREFLECTTEST_DEFINE_TEST(windows_runtime_x64_fastcall_thunk_mixed_integer_and_real_arguments) { guarded_context_initializer const context_guard(&c); cxr::x64_argument_frame const frame_a(fn_init_frame(1.0, 2LL, 3.0, 4LL, 5.0, 6LL)); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fna, frame_a.arguments(), frame_a.types(), 6); cxr::x64_argument_frame const frame_b(fn_init_frame(1LL, 2.0, 3.0, 4LL, 5LL, 6.0)); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fnb, frame_b.arguments(), frame_b.types(), 6); cxr::x64_argument_frame const frame_c(fn_init_frame(1LL, 2.0f, 3.0f, 4LL, 5LL, 6.0f)); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fnc, frame_c.arguments(), frame_c.types(), 6); cxr::x64_argument_frame const frame_d(fn_init_frame(1LL, 2.0f, 3.0, 4LL, 5.0f, 6.0)); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(fnd, frame_d.arguments(), frame_d.types(), 6); } } namespace cxxreflect_test { struct windows_runtime_x64_fastcall_thunk_basic_struct { cxr::u8 x; cxr::u8 y; cxr::u8 z; }; static auto f_basic_struct(windows_runtime_x64_fastcall_thunk_basic_struct s) -> void { global_context->verify_equals(s.x, 1); global_context->verify_equals(s.y, 2); global_context->verify_equals(s.z, 3); } CXXREFLECTTEST_DEFINE_TEST(windows_runtime_x64_fastcall_thunk_struct_arguments) { guarded_context_initializer const context_guard(&c); windows_runtime_x64_fastcall_thunk_basic_struct x = { 1, 2, 3 }; cxr::x64_argument_frame frame; frame.push(&x); cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(f_basic_struct, frame.arguments(), frame.types(), 1); } } namespace cxxreflect_test { class windows_runtime_x64_fastcall_thunk_f_exception { }; static auto f_throws(int, int, int, int, int, int) -> void { throw windows_runtime_x64_fastcall_thunk_f_exception(); } CXXREFLECTTEST_DEFINE_TEST(windows_runtime_x64_fastcall_thunk_exceptional_return) { guarded_context_initializer const context_guard(&c); cxr::x64_argument_frame frame; frame.push(1LL); frame.push(2LL); frame.push(3LL); frame.push(4LL); frame.push(5LL); frame.push(6LL); try { cxr::cxxreflect_windows_runtime_x64_fastcall_thunk(f_throws, frame.arguments(), frame.types(), 6); c.fail(); } catch (windows_runtime_x64_fastcall_thunk_f_exception const&) { } } } #endif // CXXREFLECT_ARCHITECTURE == CXXREFLECT_ARCHITECTURE_X64
36.741007
116
0.614059
dbremner
d32d1de1a820b1b8bfc0d9799320170b7033bf32
3,351
cpp
C++
packages/monte_carlo/core/src/MonteCarlo_AdjointPhotonProbeState.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/monte_carlo/core/src/MonteCarlo_AdjointPhotonProbeState.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/monte_carlo/core/src/MonteCarlo_AdjointPhotonProbeState.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
//---------------------------------------------------------------------------// //! //! \file MonteCarlo_AdjointPhotonProbeState.cpp //! \author Alex Robinson //! \brief Adjoint photon probe state class declaration //! //---------------------------------------------------------------------------// // FRENSIE Includes #include "MonteCarlo_AdjointPhotonProbeState.hpp" #include "Utility_ArchiveHelpers.hpp" #include "Utility_ContractException.hpp" namespace MonteCarlo{ // Constructor AdjointPhotonProbeState::AdjointPhotonProbeState() : AdjointPhotonState(), d_active( false ) { /* ... */ } // Constructor AdjointPhotonProbeState::AdjointPhotonProbeState( const ParticleState::historyNumberType history_number ) : AdjointPhotonState( history_number, ADJOINT_PHOTON_PROBE ), d_active( false ) { /* ... */ } // Copy constructor (with possible creation of new generation) AdjointPhotonProbeState::AdjointPhotonProbeState( const ParticleState& existing_base_state, const bool increment_generation_number, const bool reset_collision_number ) : AdjointPhotonState( existing_base_state, ADJOINT_PHOTON_PROBE, increment_generation_number, reset_collision_number ), d_active( false ) { /* ... */ } // Copy constructor (with possible creation of new generation) AdjointPhotonProbeState::AdjointPhotonProbeState( const AdjointPhotonProbeState& existing_base_state, const bool increment_generation_number, const bool reset_collision_number ) : AdjointPhotonState( existing_base_state, ADJOINT_PHOTON_PROBE, increment_generation_number, reset_collision_number ), d_active( false ) { /* ... */ } // Set the energy of the particle (MeV) /*! \details An active probe particle gets killed when its energy changes. A * probe particle should only be activated after its initial energy has been * set. */ void AdjointPhotonProbeState::setEnergy( const energyType energy ) { ParticleState::setEnergy( energy ); if( d_active ) this->setAsGone(); } // Check if this is a probe bool AdjointPhotonProbeState::isProbe() const { return true; } // Activate the probe /*! \details Once a probe has been activated the next call to set energy * will cause is to be killed. */ void AdjointPhotonProbeState::activate() { d_active = true; } // Returns if the probe is active bool AdjointPhotonProbeState::isActive() const { return d_active; } // Clone the particle state (do not use to generate new particles!) AdjointPhotonProbeState* AdjointPhotonProbeState::clone() const { return new AdjointPhotonProbeState( *this, false, false ); } // Print the adjoint photon state void AdjointPhotonProbeState::print( std::ostream& os ) const { os << "Particle Type: "; if( d_active ) os << "Active "; else os << "Inactive "; os << "Adjoint Photon Probe" << std::endl; this->printImplementation<AdjointPhotonProbeState>( os ); } } // end MonteCarlo namespace UTILITY_CLASS_EXPORT_IMPLEMENT_SERIALIZE( MonteCarlo::AdjointPhotonProbeState); BOOST_CLASS_EXPORT_IMPLEMENT( MonteCarlo::AdjointPhotonProbeState ); //---------------------------------------------------------------------------// // end MonteCarlo_AdjointPhotonProbeState.cpp //---------------------------------------------------------------------------//
28.887931
79
0.670248
lkersting
d32dfef64b2ca3e8da4825a88a07ae9a60a709fb
5,485
cpp
C++
src/currency/Currency.cpp
MiKlTA/Lust_The_Game
aabe4a951ffd7305526466d378ba8b6769c555e8
[ "MIT" ]
null
null
null
src/currency/Currency.cpp
MiKlTA/Lust_The_Game
aabe4a951ffd7305526466d378ba8b6769c555e8
[ "MIT" ]
null
null
null
src/currency/Currency.cpp
MiKlTA/Lust_The_Game
aabe4a951ffd7305526466d378ba8b6769c555e8
[ "MIT" ]
null
null
null
#include "Currency.h" namespace lust { Currency::Currency(const Fraction *owner, AmountType amount) : m_fraction(owner), m_amount(amount) { } Currency::AmountType Currency::getAmount() const { return m_amount; } const Fraction * Currency::getFraction() const { return m_fraction; } const Currency Currency::operator+(Currency::AmountType cr) const { if (m_amount + cr > 0) { return Currency(m_fraction, m_amount + cr); } return Currency(m_fraction, 0); } const Currency Currency::operator-(Currency::AmountType cr) const { if (m_amount - cr > 0) { return Currency(m_fraction, m_amount - cr); } return Currency(m_fraction, 0); } const Currency Currency::operator*(Currency::AmountType cr) const { if (m_amount * cr > 0) { return Currency(m_fraction, m_amount * cr); } return Currency(m_fraction, 0); } const Currency Currency::operator%(Currency::AmountType cr) const { if (m_amount % cr > 0) { return Currency(m_fraction, m_amount % cr); } return Currency(m_fraction, 0); } const Currency Currency::operator/(Currency::AmountType cr) const { if (m_amount / cr > 0) { return Currency(m_fraction, m_amount / cr); } return Currency(m_fraction, 0); } const Currency Currency::operator+(const Currency &cr) const { return (*this) + cr.m_amount; } const Currency Currency::operator-(const Currency &cr) const { return (*this) - cr.m_amount; } const Currency Currency::operator*(const Currency &cr) const { return (*this) * cr.m_amount; } const Currency Currency::operator%(const Currency &cr) const { return (*this) % cr.m_amount; } const Currency Currency::operator/(const Currency &cr) const { return (*this) / cr.m_amount; } Currency & Currency::operator=(const Currency &cr) { m_amount = cr.m_amount; return (*this); } Currency & Currency::operator=(AmountType num) { m_amount = num; return (*this); } Currency & Currency::operator+=(AmountType cr) { (*this) = (*this) + cr; return (*this); } Currency & Currency::operator-=(AmountType cr) { (*this) = (*this) - cr; return (*this); } Currency & Currency::operator*=(AmountType cr) { (*this) = (*this) * cr; return (*this); } Currency & Currency::operator%=(AmountType cr) { (*this) = (*this) % cr; return (*this); } Currency & Currency::operator/=(AmountType cr) { (*this) = (*this) / cr; return (*this); } Currency & Currency::operator+=(const Currency &cr) { (*this) = (*this) + cr.m_amount; return (*this); } Currency & Currency::operator-=(const Currency &cr) { (*this) = (*this) - cr.m_amount; return (*this); } Currency & Currency::operator*=(const Currency &cr) { (*this) = (*this) * cr.m_amount; return (*this); } Currency & Currency::operator%=(const Currency &cr) { (*this) = (*this) % cr.m_amount; return (*this); } Currency & Currency::operator/=(const Currency &cr) { (*this) = (*this) / cr.m_amount; return (*this); } // private bool Currency::isEqualFractions(const Currency &cr) const { return m_fraction == cr.m_fraction; } // global functions const Currency operator+(Currency::AmountType lhs, const Currency &rhs) { return Currency(rhs + lhs); } const Currency operator-(Currency::AmountType lhs, const Currency &rhs) { return Currency(rhs * -1 + lhs); } const Currency operator*(Currency::AmountType lhs, const Currency &rhs) { return Currency(rhs * lhs); } const Currency operator%(Currency::AmountType lhs, const Currency &rhs) { return Currency(Currency(rhs.m_fraction, lhs) % rhs.m_amount); } const Currency operator/(Currency::AmountType lhs, const Currency &rhs) { return Currency(Currency(rhs.m_fraction, lhs) / rhs.m_amount); } bool operator==(const Currency &lhs, Currency::AmountType rhs) { return lhs.m_amount == rhs; } bool operator!=(const Currency &lhs, Currency::AmountType rhs) { return lhs.m_amount != rhs; } bool operator>(const Currency &lhs, Currency::AmountType rhs) { return lhs.m_amount > rhs; } bool operator<(const Currency &lhs, Currency::AmountType rhs) { return lhs.m_amount < rhs; } bool operator>=(const Currency &lhs, Currency::AmountType rhs) { return lhs.m_amount >= rhs; } bool operator<=(const Currency &lhs, Currency::AmountType rhs) { return lhs.m_amount <= rhs; } bool operator==(const Currency &lhs, const Currency &rhs) { if (lhs.isEqualFractions(rhs)) { return lhs.m_amount == rhs.m_amount; } return false; } bool operator!=(const Currency &lhs, const Currency &rhs) { if (lhs.isEqualFractions(rhs)) { return lhs.m_amount != rhs.m_amount; } return true; } bool operator>(const Currency &lhs, const Currency &rhs) { if (lhs.isEqualFractions(rhs)) { return lhs.m_amount > rhs.m_amount; } return false; } bool operator<(const Currency &lhs, const Currency &rhs) { if (lhs.isEqualFractions(rhs)) { return lhs.m_amount == rhs.m_amount; } return false; } bool operator>=(const Currency &lhs, const Currency &rhs) { if (lhs.isEqualFractions(rhs)) { return lhs.m_amount == rhs.m_amount; } return false; } bool operator<=(const Currency &lhs, const Currency &rhs) { if (lhs.isEqualFractions(rhs)) { return lhs.m_amount == rhs.m_amount; } return false; } }
17.693548
71
0.643938
MiKlTA
d32e26774b56bb2ae1536cf128a94005d600741e
2,576
cpp
C++
example/http.cpp
weiboad/adbase
d37ed32b55da24f7799be286c860e280ee0c786a
[ "Apache-2.0" ]
62
2017-02-15T11:36:46.000Z
2022-03-14T09:11:10.000Z
example/http.cpp
AraHaan/adbase
d37ed32b55da24f7799be286c860e280ee0c786a
[ "Apache-2.0" ]
5
2017-02-21T05:32:14.000Z
2017-05-21T13:15:07.000Z
example/http.cpp
AraHaan/adbase
d37ed32b55da24f7799be286c860e280ee0c786a
[ "Apache-2.0" ]
22
2017-02-16T02:11:25.000Z
2020-02-12T18:12:44.000Z
#include <adbase/Http.hpp> #include <adbase/Logging.hpp> #include <signal.h> adbase::http::Server* ghttp = nullptr; adbase::AsyncLogging* _asnclog = nullptr; // {{{ void asyncLogger() void asyncLogger(const char* msg, int len) { if (_asnclog != nullptr) { _asnclog->append(msg, static_cast<int>(len)); } } // }}} // {{{ void request() void request(adbase::http::Request* request, adbase::http::Response* response, void* data) { (void)request; if (data != nullptr) { std::string* context = reinterpret_cast<std::string*>(data); LOG_INFO << "Context:" << *context; } else { (void)data; } response->sendReply("OK", 200, "OK"); } // }}} // {{{ void echo() void echo(adbase::http::Request* request, adbase::http::Response* response, void* data) { (void)data; std::string post = request->getPostData(); LOG_INFO << request->getServerAddress(); response->sendReply("OK", 200, post); } // }}} // {{{ static void killSignal() static void killSignal(const int sig) { (void)sig; if (ghttp != nullptr) { ghttp->stop(); delete ghttp; ghttp = nullptr; } exit(0); } // }}} // {{{ static void reloadConf() static void reloadConf(const int sig) { (void)sig; } // }}} // {{{ static void registerSignal() static void registerSignal() { /* 忽略Broken Pipe信号 */ signal(SIGPIPE, SIG_IGN); /* 处理kill信号 */ signal(SIGINT, killSignal); signal(SIGKILL, killSignal); signal(SIGQUIT, killSignal); signal(SIGTERM, killSignal); signal(SIGHUP, killSignal); signal(SIGSEGV, killSignal); signal(SIGUSR1, reloadConf); } // }}} int main(void) { registerSignal(); adbase::TimeZone tz(8*3600, "CST"); adbase::Logger::setTimeZone(tz); adbase::http::Config config("0.0.0.0", 40010, 3); config.setTimeZone(tz); config.setServerName("test"); config.setLogDir("logs"); //adbase::Logger::setOutput(std::bind(asyncLogger, // std::placeholders::_1, std::placeholders::_2)); // 启动异步日志落地 std::string basename = "./logs/http"; _asnclog = new adbase::AsyncLogging(basename, 52428800); _asnclog->start(); adbase::http::Server* http = new adbase::http::Server(config); ghttp = http; std::string test = "test string"; http->registerLocation("/debug", std::bind(request, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), &test); http->registerLocation("/echo", std::bind(echo, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), nullptr); http->start(24); // do something while (true) { std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } LOG_INFO << "exit."; return 0; }
23.207207
92
0.661102
weiboad
d331beacb373ece45e66f8f29dc97385a437962a
2,026
cpp
C++
CodeForces/CF1009F.cpp
hardik0899/Competitive_Programming
199039ad7a26a5f48152fe231a9ca5ac8685a707
[ "MIT" ]
1
2020-10-16T18:14:30.000Z
2020-10-16T18:14:30.000Z
CodeForces/CF1009F.cpp
hardik0899/Competitive_Programming
199039ad7a26a5f48152fe231a9ca5ac8685a707
[ "MIT" ]
null
null
null
CodeForces/CF1009F.cpp
hardik0899/Competitive_Programming
199039ad7a26a5f48152fe231a9ca5ac8685a707
[ "MIT" ]
1
2021-01-06T04:45:38.000Z
2021-01-06T04:45:38.000Z
#define __USE_MINGW_ANSI_STDIO 0 #include <iostream> #include <iomanip> #include <stdio.h> #include <stdlib.h> #include <vector> #include <algorithm> #include <queue> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <stack> #include <deque> #include <string.h> #include <bitset> #include <math.h> #include <assert.h> using namespace std; #define PI atan2(0, -1) #define epsilon 0.000000001 #define INF 5000000000000000000 #define MOD 1000000007 #define mp make_pair #define pb push_back #define f first #define s second #define lb lower_bound #define ub upper_bound struct Node{ vector<int>* arr; int maxi; Node(){ arr = new vector<int>(); maxi = 0; } int sz(){ return arr->size(); } void add(int i, int val){ (*arr)[i] += val; if(mp((*arr)[i], i) > mp((*arr)[maxi], maxi)) maxi = i; } }; Node pull(Node x){ Node a; if(x.sz() == 0){ a.arr = new vector<int>(1, 1); return a; } a.arr = x.arr; a.maxi = x.maxi; a.arr->pb(0); a.add(a.sz()-1, 1); return a; } Node mergey(Node a, Node b){ if(a.sz() < b.sz()) swap(a, b); Node c; c.arr = a.arr; c.maxi = a.maxi; for(int i = 0; i < b.sz(); i++) c.add(a.sz()-1-i, (*b.arr)[b.sz()-1-i]); return c; } int N, ret [1000010]; vector<int> adjacency [1000010]; Node nodes [1000010]; void dfs(int curr, int prevy){ for(int nexty : adjacency[curr]){ if(nexty == prevy) continue; dfs(nexty, curr); nodes[curr] = mergey(nodes[curr], nodes[nexty]); } nodes[curr] = pull(nodes[curr]); ret[curr] = nodes[curr].sz()-1-nodes[curr].maxi; } int main(){ //freopen("sort.in", "r", stdin); freopen("sort.out", "w", stdout); ios_base::sync_with_stdio(0); cin.tie(0); cout << fixed << setprecision(18); cin >> N; for(int i = 1; i < N; i++){ int x, y; cin >> x >> y; adjacency[x].pb(y); adjacency[y].pb(x); } dfs(1, 0); for(int i = 1; i <= N; i++) cout << ret[i] << '\n'; return 0; }
23.022727
80
0.579467
hardik0899