blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b0bb02ad5e4b2173c56ad547e92746668c5550f3 | 42a92e83d3ac1f6c1366b2feeccf334950f9be76 | /src/myhal_simulator/src/puppeteer.cpp | 19fb0ef78bfc32f1aa53fe66bdf63b1c23d43500 | [] | no_license | kavyadevd/JackalTourGuide | 788c953d20030f9ca5ce12c9e5cdd751c20f0f11 | 4d979fcc750903674fa69c416595b50127495118 | refs/heads/master | 2022-11-28T03:33:44.052635 | 2020-08-11T21:42:38 | 2020-08-11T21:42:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,647 | cpp | #include "puppeteer.hh"
#include "utilities.hh"
#include "parse_tour.hh"
#include <ros/forwards.h>
GZ_REGISTER_WORLD_PLUGIN(Puppeteer);
//PUPPETEER CLASS
void Puppeteer::Load(gazebo::physics::WorldPtr _world, sdf::ElementPtr _sdf){
//note: world name is default
this->world = _world;
this->sdf = _sdf;
this->update_connection = gazebo::event::Events::ConnectWorldUpdateBegin(std::bind(&Puppeteer::OnUpdate, this, std::placeholders::_1));
this->user_name = "default";
if (const char * user = std::getenv("USER")){
this->user_name = user;
}
this->ReadSDF();
int argc = 0;
char **argv = NULL;
ros::init(argc, argv, "Puppeteer");
this->ReadParams();
this->path_pub = this->nh.advertise<geometry_msgs::PoseStamped>("optimal_path",1000);
auto building = this->world->ModelByName(this->building_name);
this->building_box = building->BoundingBox();
this->building_box.Min().X()-=1;
this->building_box.Min().Y()-=1;
this->building_box.Max().X()+=1;
this->building_box.Max().Y()+=1;
this->static_quadtree = boost::make_shared<QuadTree>(this->building_box);
this->vehicle_quadtree = boost::make_shared<QuadTree>(this->building_box);
this->costmap = boost::make_shared<Costmap>(this->building_box, 0.2);
for (unsigned int i = 0; i < world->ModelCount(); ++i) {
auto model = world->ModelByIndex(i);
auto act = boost::dynamic_pointer_cast<gazebo::physics::Actor>(model);
if (act){
auto new_vehicle = this->CreateVehicle(act);
this->vehicles.push_back(new_vehicle);
auto min = ignition::math::Vector3d(new_vehicle->GetPose().Pos().X() - 0.4, new_vehicle->GetPose().Pos().Y() - 0.4, 0);
auto max = ignition::math::Vector3d(new_vehicle->GetPose().Pos().X() + 0.4, new_vehicle->GetPose().Pos().Y() + 0.4, 0);
auto box = ignition::math::Box(min,max);
auto new_node = QTData(box, new_vehicle, vehicle_type);
this->vehicle_quadtree->Insert(new_node);
continue;
}
if (model->GetName().substr(0,3) == "CAM"){
this->cams.push_back(this->CreateCamera(model));
continue;
}
if (model->GetName() != "ground_plane"){
auto links = model->GetLinks();
for (gazebo::physics::LinkPtr link: links){
std::vector<gazebo::physics::CollisionPtr> collision_boxes = link->GetCollisions();
for (gazebo::physics::CollisionPtr collision_box: collision_boxes){
this->collision_entities.push_back(collision_box);
auto box = collision_box->BoundingBox();
box.Max().Z() = 0;
box.Min().Z() = 0;
auto new_node = QTData(box, collision_box, entity_type);
this->static_quadtree->Insert(new_node);
if (collision_box->BoundingBox().Min().Z() < 1.5 && collision_box->BoundingBox().Max().Z() > 10e-2){
box.Min().X()-=0.2;
box.Min().Y()-=0.2;
box.Max().X()+=0.2;
box.Max().Y()+=0.2;
this->costmap->AddObject(box);
}
}
}
}
}
if (this->tour_name != ""){
TourParser parser = TourParser(this->tour_name);
auto route = parser.GetRoute();
route.insert(route.begin(), ignition::math::Pose3d(ignition::math::Vector3d(0,0,0), ignition::math::Quaterniond(0,0,0,1)));
for (int i =0; i< route.size()-1; i++){
auto start = route[i];
auto end = route[i+1];
std::vector<ignition::math::Vector3d> path;
this->costmap->ThetaStar(start.Pos(), end.Pos(), path);
this->paths.push_back(path);
}
}
if (this->viz_gaz){
this->global_path_viz = boost::make_shared<PathViz>("global_path_viz", 300, ignition::math::Vector4d(0,1,0,1), this->world);
this->local_path_viz = boost::make_shared<PathViz>("local_path_viz", 75, ignition::math::Vector4d(0,0,1,1), this->world);
}
std::cout << "LOADED ALL VEHICLES\n";
if (this->tour_name != ""){
std::cout << "COMMAND: " << this->launch_command << std::endl;
std::system(this->launch_command.c_str());
}
if (this->viz_gaz){
this->global_plan_sub = this->nh.subscribe("/move_base/NavfnROS/plan", 1, &Puppeteer::GlobalPlanCallback, this);
this->local_plan_sub = this->nh.subscribe("/move_base/TrajectoryPlannerROS/local_plan", 1, &Puppeteer::LocalPlanCallback, this);
this->nav_goal_sub = this->nh.subscribe("/move_base/goal", 1, &Puppeteer::NavGoalCallback, this);
this->tf_sub = this->nh.subscribe("/tf", 1, &Puppeteer::TFCallback, this);
}
}
void Puppeteer::OnUpdate(const gazebo::common::UpdateInfo &_info){
double dt = (_info.simTime - this->last_update).Double();
if (dt < 1/this->update_freq){
return;
}
this->last_update = _info.simTime;
//std::cout << "A" << std::endl;
if ((this->tour_name != "") && (this->robot_name != "") && this->robot == nullptr){
for (unsigned int i = 0; i < world->ModelCount(); ++i) {
auto model = world->ModelByIndex(i);
if (model->GetName() == this->robot_name){
this->robot = model;
for (auto vehicle: this->follower_queue){
vehicle->LoadLeader(this->robot);
}
this->robot_links = this->robot->GetLinks();
std::cout << "ADDED ROBOT: " << this->robot->GetName() << std::endl;
}
}
double i = 0;
for (auto path: this->paths){
for (auto pose: path){
geometry_msgs::PoseStamped msg;
msg.pose.position.x = pose.X();
msg.pose.position.y = pose.Y();
msg.pose.position.z = pose.Z();
msg.header.stamp = ros::Time(i);
path_pub.publish(msg);
}
i++;
}
return;
}
//std::cout << "B" << std::endl;
if (this->robot != nullptr){
this->robot_traj.push_back(this->robot->WorldPose().Pos());
this->robot_traj.back().Z() = 0;
for (auto cam: this->cams){
cam->OnUpdate(dt, this->robot_traj);
}
}
//std::cout << "C" << std::endl;
this->vehicle_quadtree = boost::make_shared<QuadTree>(this->building_box);
for (auto vehicle: this->vehicles){
auto min = ignition::math::Vector3d(vehicle->GetPose().Pos().X() - 0.4, vehicle->GetPose().Pos().Y() - 0.4, 0);
auto max = ignition::math::Vector3d(vehicle->GetPose().Pos().X() + 0.4, vehicle->GetPose().Pos().Y() + 0.4, 0);
auto box = ignition::math::Box(min,max);
auto new_node = QTData(box, vehicle, vehicle_type);
this->vehicle_quadtree->Insert(new_node);
}
for (auto vehicle: this->vehicles){
std::vector<boost::shared_ptr<Vehicle>> near_vehicles;
std::vector<gazebo::physics::EntityPtr> near_objects;
auto vehicle_pos = vehicle->GetPose();
auto min = ignition::math::Vector3d(vehicle_pos.Pos().X() - 2, vehicle_pos.Pos().Y() - 2, 0);
auto max = ignition::math::Vector3d(vehicle_pos.Pos().X() + 2, vehicle_pos.Pos().Y() + 2, 0);
auto query_range = ignition::math::Box(min,max);
std::vector<QTData> query_objects = this->static_quadtree->QueryRange(query_range);
for (auto n: query_objects){
if (n.type == entity_type){
near_objects.push_back(boost::static_pointer_cast<gazebo::physics::Entity>(n.data));
}
}
if (this->robot != nullptr && (vehicle_pos.Pos() - this->robot->WorldPose().Pos()).Length()<2){
near_objects.push_back(this->robot);
}
std::vector<QTData> query_vehicles = this->vehicle_quadtree->QueryRange(query_range);
for (auto n: query_vehicles){
if (n.type == vehicle_type){
near_vehicles.push_back(boost::static_pointer_cast<Vehicle>(n.data));
}
}
vehicle->OnUpdate(_info, dt, near_vehicles, near_objects);
}
if (this->old_global_ind != this->new_global_ind){
this->global_path_viz->OnUpdate(this->global_plan);
}
if (this->old_local_ind != this->new_local_ind){
this->local_path_viz->OnUpdate(this->local_plan);
}
if (this->old_nav_ind != this->new_nav_ind){
std::string name = "nav_goal";
if (this->old_nav_ind == 0){
this->AddGoalMarker(name, this->nav_goal, ignition::math::Vector4d(1,0,0,1));
} else{
auto goal = this->world->EntityByName(name);
auto p = this->nav_goal->goal.target_pose.pose.position;
auto pos = ignition::math::Vector3d(p.x, p.y, p.z);
goal->SetWorldPose(ignition::math::Pose3d(pos, ignition::math::Quaterniond(0,0,0,1)));
}
this->old_nav_ind = this->new_nav_ind;
}
if (this->viz_gaz){
geometry_msgs::Pose est_pose;
tf2::doTransform<geometry_msgs::Pose>(this->odom_to_base, est_pose, this->map_to_odom);
this->ManagePoseEstimate(est_pose);
ros::spinOnce();
}
}
void Puppeteer::ReadSDF(){
if (this->sdf->HasElement("building_name")){
this->building_name =this->sdf->GetElement("building_name")->Get<std::string>();
}
if (this->sdf->HasElement("robot_name")){
this->robot_name = this->sdf->GetElement("robot_name")->Get<std::string>();
} else{
this->robot_name = "";
}
}
boost::shared_ptr<Vehicle> Puppeteer::CreateVehicle(gazebo::physics::ActorPtr actor){
boost::shared_ptr<Vehicle> res;
auto sdf = actor->GetSDF();
std::map<std::string, std::string> actor_info;
auto attribute = sdf->GetElement("plugin");
while (attribute){
actor_info[attribute->GetAttribute("name")->GetAsString()] = attribute->GetAttribute("filename")->GetAsString();
attribute = attribute->GetNextElement("plugin");
}
double max_speed = 1;
if (actor_info.find("max_speed") != actor_info.end()){
try{
max_speed = std::stod(actor_info["max_speed"]);
} catch (std::exception& e){
std::cout << "Error converting max_speed argument to double" << std::endl;
}
}
if (actor_info.find("vehicle_type")!=actor_info.end()){
if (actor_info["vehicle_type"] == "wanderer"){
res = boost::make_shared<Wanderer>(actor, this->vehicle_params["mass"], this->vehicle_params["max_force"], max_speed, actor->WorldPose(), ignition::math::Vector3d(0,0,0), this->collision_entities);
} else if (actor_info["vehicle_type"] == "random_walker"){
res = boost::make_shared<RandomWalker>(actor, this->vehicle_params["mass"], this->vehicle_params["max_force"], max_speed, actor->WorldPose(), ignition::math::Vector3d(0,0,0), this->collision_entities);
} else if (actor_info["vehicle_type"] == "boid"){
auto random_vel = ignition::math::Vector3d(ignition::math::Rand::DblUniform(-1,1),ignition::math::Rand::DblUniform(-1,1),0);
random_vel.Normalize();
random_vel*=2;
res = boost::make_shared<Boid>(actor, this->vehicle_params["mass"], this->vehicle_params["max_force"], max_speed, actor->WorldPose(), random_vel, this->collision_entities, this->boid_params["alignement"], this->boid_params["cohesion"], this->boid_params["separation"], this->boid_params["FOV_angle"], this->boid_params["FOV_radius"]); // read in as params
} else if (actor_info["vehicle_type"] == "stander"){
double standing_duration = 5;
double walking_duration = 5;
if (actor_info.find("standing_duration") != actor_info.end()){
try{
standing_duration = std::stod(actor_info["standing_duration"]);
} catch (std::exception& e){
std::cout << "Error converting standing duration argument to double" << std::endl;
}
}
if (actor_info.find("walking_duration") != actor_info.end()){
try{
walking_duration = std::stod(actor_info["walking_duration"]);
} catch (std::exception& e){
std::cout << "Error converting walking duration argument to double" << std::endl;
}
}
res = boost::make_shared<Stander>(actor, 1, 10, max_speed, actor->WorldPose(), ignition::math::Vector3d(0,0,0), this->collision_entities, standing_duration, walking_duration, this->vehicle_params["start_mode"]); // read in as params
} else if (actor_info["vehicle_type"] == "sitter"){
std::string chair = "";
if (actor_info.find("chair") != actor_info.end()){
chair = actor_info["chair"];
}
res = boost::make_shared<Sitter>(actor, chair, this->collision_entities, actor->WorldPose().Pos().Z());
} else if (actor_info["vehicle_type"] == "follower"){
std::string leader_name = "";
if (actor_info.find("leader") != actor_info.end()){
leader_name = actor_info["leader"];
res = boost::make_shared<Follower>(actor, 1, 10, max_speed, actor->WorldPose(), ignition::math::Vector3d(0,0,0), this->collision_entities, leader_name, (bool) this->vehicle_params["blocking"]); // read in as params
this->follower_queue.push_back(boost::dynamic_pointer_cast<Follower>(res));
} else{
std::cout << "leader name not found\n";
}
} else if (actor_info["vehicle_type"] == "path_follower"){
res = boost::make_shared<PathFollower>(actor, this->vehicle_params["mass"], this->vehicle_params["max_force"], max_speed, actor->WorldPose(), ignition::math::Vector3d(0,0,0), this->collision_entities, this->costmap);
} else {
std::cout << "INVALID VEHICLE TYPE\n";
}
}
return res;
}
void Puppeteer::ReadParams(){
if (!nh.getParam("common_vehicle_params", this->vehicle_params)){
ROS_ERROR("ERROR READING COMMON VEHICLE PARAMS");
vehicle_params["mass"] = 1;
vehicle_params["max_force"] = 10;
vehicle_params["slowing_distance"] = 2;
vehicle_params["arrival_distance"] = 0.5;
vehicle_params["obstacle_margin"] = 0.6;
vehicle_params["blocking"] = 0;
vehicle_params["start_mode"] = 2;
}
if (!nh.getParam("common_boid_params", this->boid_params)){
ROS_ERROR("ERROR READING COMMON BOID PARAMS");
boid_params["alignement"] = 0.1;
boid_params["cohesion"] = 0.01;
boid_params["separation"] = 2;
boid_params["FOV_angle"] = 4;
boid_params["FOV_radius"] = 3;
}
if (!nh.getParam("gt_class", this->gt_class)){
std::cout << "ERROR READING gt_class\n";
this->gt_class = false;
}
if (!nh.getParam("filter_status", this->filter_status)){
std::cout << "ERROR READING filter_status\n";
this->filter_status = false;
}
if (!nh.getParam("gmapping_status", this->gmapping_status)){
std::cout << "ERROR READING gmapping_status\n";
this->gmapping_status = false;
}
if (!nh.getParam("viz_gaz", this->viz_gaz)){
std::cout << "ERROR READING viz_gaz\n";
this->viz_gaz = false;
}
//roslaunch jackal_velodyne p2.launch filter:=$FILTER mapping:=$MAPPING gt_classify:=$GTCLASS
if (this->filter_status){
this->launch_command += " filter:=true ";
} else {
this->launch_command += " filter:=false ";
}
if (this->gt_class){
this->launch_command += " gt_classify:=true ";
} else{
this->launch_command += " gt_classify:=false ";
}
if (this->gmapping_status){
this->launch_command += " mapping:=true &";
} else{
this->launch_command += " mapping:=false &";
}
std::cout << "COMMAND: " << this->launch_command << std::endl;
if (!nh.getParam("tour_name", this->tour_name)){
std::cout << "ERROR READING TOUR NAME\n";
this->tour_name = "";
return;
}
}
SmartCamPtr Puppeteer::CreateCamera(gazebo::physics::ModelPtr model){
auto tokens = utilities::split(model->GetName(), '_');
SmartCamPtr new_cam;
if (tokens[1] == "0"){
// sentry
new_cam = boost::make_shared<Sentry>(model,model->WorldPose().Pos());
} else if (tokens[1] == "1"){
// hoverer
double T = std::stod(tokens[2]);
new_cam = boost::make_shared<Hoverer>(model, model->WorldPose().Pos(), T);
} else if (tokens[1] == "2"){
// path follower
double dist = std::stod(tokens[3]);
new_cam = boost::make_shared<Stalker>(model, model->WorldPose().Pos(), dist);
}
return new_cam;
}
void Puppeteer::TFCallback(const tf2_msgs::TFMessage::ConstPtr& msg){
for (auto transform: msg->transforms){
if (transform.header.frame_id == "odom" && transform.child_frame_id == "base_link"){
//std::cout << "GOT ODOM" << std::endl;
auto translation = transform.transform.translation;
auto rotation = transform.transform.rotation;
this->odom_to_base.position.x = translation.x;
this->odom_to_base.position.y = translation.y;
this->odom_to_base.position.z = translation.z;
this->odom_to_base.orientation.x = rotation.x;
this->odom_to_base.orientation.y = rotation.y;
this->odom_to_base.orientation.z = rotation.z;
this->odom_to_base.orientation.w = rotation.w;
//this->odom_to_base = transform;
}
else if (transform.header.frame_id == "map" && transform.child_frame_id == "odom"){
//std::cout << "GOT MAP" << std::endl;
this->map_to_odom = transform;
}
}
}
void Puppeteer::GlobalPlanCallback(const nav_msgs::Path::ConstPtr& path){
if (path->poses.size() > 0){
std::cout << utilities::color_text("Global plan recieved by simulator", BLUE) << std::endl;
this->global_plan = path;
this->new_global_ind++;
}
}
void Puppeteer::LocalPlanCallback(const nav_msgs::Path::ConstPtr& path){
if (path->poses.size() > 0){
std::cout << utilities::color_text("Local plan recieved by simulator", YELLOW) << std::endl;
this->local_plan = path;
this->new_local_ind++;
}
}
void Puppeteer::NavGoalCallback(const move_base_msgs::MoveBaseActionGoal::ConstPtr& goal){
this->nav_goal = goal;
this->new_nav_ind++;
}
void Puppeteer::AddPathMarkers(std::string name, const nav_msgs::Path::ConstPtr& plan, ignition::math::Vector4d color){
boost::shared_ptr<sdf::SDF> sdf = boost::make_shared<sdf::SDF>();
sdf->SetFromString(
"<sdf version ='1.6'>\
<model name ='path'>\
</model>\
</sdf>");
auto model = sdf->Root()->GetElement("model");
model->GetElement("static")->Set(true);
model->GetAttribute("name")->SetFromString(name);
int i = 0;
for (auto pose: plan->poses){
auto p = pose.pose.position;
auto pos = ignition::math::Vector3d(p.x, p.y, p.z);
auto link = model->AddElement("link");
link->GetElement("pose")->Set(pos);
link->GetAttribute("name")->SetFromString("l_" + name + std::to_string(i));
auto cylinder = link->GetElement("visual")->GetElement("geometry")->GetElement("cylinder");
cylinder->GetElement("radius")->Set(0.03);
cylinder->GetElement("length")->Set(0.001);
auto mat = link->GetElement("visual")->GetElement("material");
mat->GetElement("ambient")->Set(color);
mat->GetElement("diffuse")->Set(color);
mat->GetElement("specular")->Set(color);
mat->GetElement("emissive")->Set(color);
i++;
}
this->world->InsertModelSDF(*sdf);
}
void Puppeteer::AddGoalMarker(std::string name, const move_base_msgs::MoveBaseActionGoal::ConstPtr& goal, ignition::math::Vector4d color){
auto p = goal->goal.target_pose.pose.position;
auto pos = ignition::math::Vector3d(p.x, p.y, p.z);
boost::shared_ptr<sdf::SDF> sdf = boost::make_shared<sdf::SDF>();
sdf->SetFromString(
"<sdf version ='1.6'>\
<model name ='path'>\
</model>\
</sdf>");
auto model = sdf->Root()->GetElement("model");
model->GetElement("static")->Set(true);
model->GetAttribute("name")->SetFromString(name);
model->GetElement("pose")->Set(pos);
auto link1 = model->AddElement("link");
link1->GetAttribute("name")->SetFromString("l_1" + name);
auto box1 = link1->GetElement("visual")->GetElement("geometry")->GetElement("box");
box1->GetElement("size")->Set(ignition::math::Vector3d(0.5, 0.05, 0.001));
auto mat1 = link1->GetElement("visual")->GetElement("material");
mat1->GetElement("ambient")->Set(color);
mat1->GetElement("diffuse")->Set(color);
mat1->GetElement("specular")->Set(color);
mat1->GetElement("emissive")->Set(color);
auto link2 = model->AddElement("link");
link2->GetAttribute("name")->SetFromString("l_2" + name);
auto box2 = link2->GetElement("visual")->GetElement("geometry")->GetElement("box");
box2->GetElement("size")->Set(ignition::math::Vector3d(0.05, 0.5, 0.001));
auto mat2 = link2->GetElement("visual")->GetElement("material");
mat2->GetElement("ambient")->Set(color);
mat2->GetElement("diffuse")->Set(color);
mat2->GetElement("specular")->Set(color);
mat2->GetElement("emissive")->Set(color);
this->world->InsertModelSDF(*sdf);
}
void Puppeteer::ManagePoseEstimate(geometry_msgs::Pose est_pose){
auto pos = est_pose.position;
auto ori = est_pose.orientation;
if (std::isnan(pos.x)){
return;
}
auto pose = ignition::math::Pose3d(pos.x, pos.y, 0, ori.w, ori.x, ori.y, ori.z);
if (!this->added_est){
boost::shared_ptr<sdf::SDF> sdf = boost::make_shared<sdf::SDF>();
sdf->SetFromString(
"<sdf version ='1.6'>\
<model name ='path'>\
</model>\
</sdf>");
auto model = sdf->Root()->GetElement("model");
model->GetElement("static")->Set(true);
model->GetAttribute("name")->SetFromString("pose_estimate");
model->GetElement("pose")->Set(pose);
auto color = ignition::math::Vector4d(0,1,1,1);
auto link1 = model->AddElement("link");
link1->GetAttribute("name")->SetFromString("pose_link");
link1->GetElement("pose")->Set(ignition::math::Vector3d(-0.05, 0, 0.001));
auto box1 = link1->GetElement("visual")->GetElement("geometry")->GetElement("box");
box1->GetElement("size")->Set(ignition::math::Vector3d(0.42, 0.43, 0.002));
auto mat1 = link1->GetElement("visual")->GetElement("material");
mat1->GetElement("ambient")->Set(color);
mat1->GetElement("diffuse")->Set(color);
mat1->GetElement("specular")->Set(color);
mat1->GetElement("emissive")->Set(color);
color = ignition::math::Vector4d(1,0,1,1);
auto link2 = model->AddElement("link");
link2->GetAttribute("name")->SetFromString("front_link");
link2->GetElement("pose")->Set(ignition::math::Vector3d(0.21, 0, 0.001));
auto box2 = link2->GetElement("visual")->GetElement("geometry")->GetElement("box");
box2->GetElement("size")->Set(ignition::math::Vector3d(0.1, 0.43, 0.002));
auto mat2 = link2->GetElement("visual")->GetElement("material");
mat2->GetElement("ambient")->Set(color);
mat2->GetElement("diffuse")->Set(color);
mat2->GetElement("specular")->Set(color);
mat2->GetElement("emissive")->Set(color);
this->world->InsertModelSDF(*sdf);
std::cout << utilities::color_text("Added pose estimate", TEAL) << std::endl;
this->added_est = true;
} else {
if (!this->pose_est){
this->pose_est = this->world->ModelByName("pose_estimate");
} else{
this->pose_est->SetWorldPose(pose);
}
}
}
| [
"ben.agro@mail.utoronto.ca"
] | ben.agro@mail.utoronto.ca |
43866f8743b800251c5aa88adcaee413a706219c | f4b1d7e0670113473ddb4e54c55c4d0309132ea6 | /wireSram.cpp | 2b2d09b002d7b1336d108f384d4072af5748bbfc | [] | no_license | lightmanca/WireSram | 38c0dc86da865d989c1186019331e5434df5b9af | 1b804133a5bffc0d60f8ed7e39399106e28942d4 | refs/heads/master | 2021-01-25T10:39:12.374724 | 2013-05-30T05:00:15 | 2013-05-30T05:00:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,383 | cpp | /*
WireSram.cpp - Library for I2c Sram, PCF8570P/FS,112
Warning: Manufacturer says this chip will discontinuted.
Created by Sam Weiss, May 15, 2013.
Released into the public domain.
*/
#include <Wire.h>
#include "Arduino.h"
#include "WireSram.h"
//sleepPin can be set to -1 if you do not want sleep function.
WireSram::WireSram(int i2cAddress, int sleepPin, bool initializeWire) {
_i2cAddress = i2cAddress;
_sleepPin = sleepPin;
_isSleeping = false;
if(_sleepPin > 0) {
pinMode(_sleepPin, OUTPUT);
digitalWrite(_sleepPin, LOW);
}
if(initializeWire)
Wire.begin();
}
void WireSram::sleep() {
if(_sleepPin < 0)
return;
digitalWrite(_sleepPin, HIGH);
_isSleeping=true;
}
void WireSram::wake() {
if(_sleepPin < 0)
return;
digitalWrite(_sleepPin, LOW);
delayMicroseconds(55);
_isSleeping=false;
}
bool WireSram::isSleeping() {
return _isSleeping;
}
//Write 1 byte to i2c SRAM
void WireSram::writeByte(word address, byte data)
{
Wire.beginTransmission(_i2cAddress);
Wire.write((byte)lowByte(address));
Wire.write((byte)highByte(address));
Wire.write(data);
Wire.endTransmission();
}
//Write data buffer to i2c SRAM
void WireSram::writeBytes(word address, byte* data, int len)
{
Wire.beginTransmission(_i2cAddress);
Wire.write((byte)lowByte(address));
Wire.write((byte)highByte(address));
Wire.write(data, len);
Wire.endTransmission();
}
//Read byte from i2c SRAM
byte WireSram::readByte(word address)
{
Wire.beginTransmission(_i2cAddress);
Wire.write((byte)lowByte(address));
Wire.write((byte)highByte(address));
Wire.endTransmission();
Wire.requestFrom(_i2cAddress,1); //only one byte
if(Wire.available())
{ return Wire.read(); }
return B00000000; //FIXME - Report an error here
}
//Read from i2c SRAM into data buffer
void WireSram::readBytes(word address, byte* buffer, int len)
{
Wire.beginTransmission(_i2cAddress);
Wire.write((byte)lowByte(address));
Wire.write((byte)highByte(address));
Wire.endTransmission();
Wire.requestFrom(_i2cAddress, len); //only one byte
int i = 0;
while(Wire.available() && i < len) {
*(buffer + i) = Wire.read();
i++;
}
}
void WireSram::Erase(int startAddress, int numBytes) {
for(int i = startAddress; i <= numBytes; i++)
writeByte(i, (byte)'\0');
}
| [
"samweiss@lightman.org"
] | samweiss@lightman.org |
f274fc55b278184f139863fbe0ece8b48cc8d76a | 489b70681cabfb033200c89af83504c789aa80b4 | /Caribbean Online Judge COJ/1591 - King's Poker.cpp | 6bee637331eabf2675dd57d863c5ba5598f8f649 | [] | no_license | shailendra-singh-dev/ProgrammingChallenges | 5feff1a82a57d3450ac5344e2166850df1378b42 | ea117cb1f17526a060449a1f53c777fa80e0a294 | refs/heads/master | 2023-02-13T21:56:49.645750 | 2021-01-05T05:44:59 | 2021-01-05T05:44:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,137 | cpp | #include <cstdio>
#include <algorithm>
using namespace std;
int out[3];
int main()
{
while(scanf("%d %d %d", &out[0], &out[1], &out[2]) != EOF && (out[0] && out[1] && out[2]))
{
if(out[0] == out[1] && out[0] == out[2] && out[0] == 13)
{
printf("*\n");
continue;
}
if(out[0] == out[1] && out[0] == out[2] && out[0] < 13)
{
out[0]++, out[1]++, out[2]++;
sort(out, out + 3);
printf("%d %d %d\n", out[0], out[1], out[2]);
continue;
}
if(out[0] == out[1] && out[0] != out[2])
{
if(out[2] < 13)
{
if(out[2] + 1 != out[0] && out[2] + 1 <= 13) out[2]++;
else
{
if(out[2] + 2 <= 13) out[2] += 2;
else
{
if(out[0] < 13) out[0]++, out[1]++, out[2] = 1;
else out[0] = out[1] = out[2] = 1;
}
}
}
else
{
if(out[0] < 13) out[0]++, out[1]++, out[2] = 1;
else printf("1 1 1\n");
}
sort(out, out + 3);
printf("%d %d %d\n", out[0], out[1], out[2]);
}
else if(out[0] == out[2] && out[0] != out[1])
{
if(out[1] < 13)
{
if(out[1] + 1 != out[0] && out[1] + 1 <= 13) out[1]++;
else
{
if(out[1] + 2 <= 13) out[1] += 2;
else
{
if(out[0] < 13) out[0]++, out[1] = 1, out[2]++;
else out[0] = out[1] = out[2] = 1;
}
}
}
else
{
if(out[0] < 13) out[0]++, out[1] = 1, out[2]++;
else printf("1 1 1\n");
}
sort(out, out + 3);
printf("%d %d %d\n", out[0], out[1], out[2]);
}
else if(out[1] == out[2] && out[1] != out[0])
{
if(out[0] < 13)
{
if(out[0] + 1 != out[1] && out[0] + 1 <= 13) out[0]++;
else
{
if(out[0] + 2 <= 13) out[0] += 2;
else
{
if(out[1] < 13) out[0] = 1, out[1]++, out[2]++;
else out[0] = out[1] = out[2] = 1;
}
}
}
else
{
if(out[1] < 13) out[0] = 1, out[1]++, out[2]++;
else printf("1 1 1\n");
}
sort(out, out + 3);
printf("%d %d %d\n", out[0], out[1], out[2]);
}
else if(out[0] != out[1] && out[1] != out[2] && out[0] != out[2]) printf("1 1 2\n");
}
return 0;
} | [
"anhell.death999@gmail.com"
] | anhell.death999@gmail.com |
a29c8bbd6aa76dd6530738ee78a3349a733958a3 | f21a6374161189430e50d5d3b197ee24ecd43e32 | /String.h | a1123da76350e724151988a802c66040493a635b | [] | no_license | samueltenka/C- | ab64d2ab22acfc4f4a3e2ec721e514a6502341de | 5c5053bdbfcdac98844fc815aeeeee6d23ae3375 | refs/heads/master | 2021-01-22T14:02:58.797813 | 2014-08-11T21:12:15 | 2014-08-11T21:12:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 81 | h | #ifndef STRING
#define STRING
class String {
char* data;
int length;
};
#endif
| [
"iguavadon@gmail.com"
] | iguavadon@gmail.com |
43717d86e412b074e272141f03ddb3fceac7e79d | af00c6baa2db6e91596c38d79153d37b404a06b3 | /src/rpcdump.cpp | a161fc879f3bd20d1e61de63846366308e0018dc | [
"MIT"
] | permissive | HWW-Lab/HWW | 0443f0940987d3825897c59dfd2e33ec7891e569 | 59ed6e34bc43506c4bdf60cfc2a8f9b29e4ee0dc | refs/heads/main | 2023-03-04T01:47:31.997494 | 2021-02-19T18:37:43 | 2021-02-19T18:37:43 | 340,448,083 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,713 | cpp | // Copyright (c) 2009-2012 Bitcoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <iostream>
#include <fstream>
#include "init.h" // for pwalletMain
#include "bitcoinrpc.h"
#include "ui_interface.h"
#include "base58.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/variant/get.hpp>
#include <boost/algorithm/string.hpp>
#define printf OutputDebugStringF
using namespace json_spirit;
using namespace std;
void EnsureWalletIsUnlocked();
namespace bt = boost::posix_time;
// Extended DecodeDumpTime implementation, see this page for details:
// http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost
const std::locale formats[] = {
std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")),
std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")),
std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")),
std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")),
std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d"))
};
const size_t formats_n = sizeof(formats)/sizeof(formats[0]);
std::time_t pt_to_time_t(const bt::ptime& pt)
{
bt::ptime timet_start(boost::gregorian::date(1970,1,1));
bt::time_duration diff = pt - timet_start;
return diff.ticks()/bt::time_duration::rep_type::ticks_per_second;
}
int64_t DecodeDumpTime(const std::string& s)
{
bt::ptime pt;
for(size_t i=0; i<formats_n; ++i)
{
std::istringstream is(s);
is.imbue(formats[i]);
is >> pt;
if(pt != bt::ptime()) break;
}
return pt_to_time_t(pt);
}
std::string static EncodeDumpTime(int64_t nTime) {
return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
}
std::string static EncodeDumpString(const std::string &str) {
std::stringstream ret;
BOOST_FOREACH(unsigned char c, str) {
if (c <= 32 || c >= 128 || c == '%') {
ret << '%' << HexStr(&c, &c + 1);
} else {
ret << c;
}
}
return ret.str();
}
std::string DecodeDumpString(const std::string &str) {
std::stringstream ret;
for (unsigned int pos = 0; pos < str.length(); pos++) {
unsigned char c = str[pos];
if (c == '%' && pos+2 < str.length()) {
c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
pos += 2;
}
ret << c;
}
return ret.str();
}
class CTxDump
{
public:
CBlockIndex *pindex;
int64_t nValue;
bool fSpent;
CWalletTx* ptx;
int nOut;
CTxDump(CWalletTx* ptx = NULL, int nOut = -1)
{
pindex = NULL;
nValue = 0;
fSpent = false;
this->ptx = ptx;
this->nOut = nOut;
}
};
Value importprivkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"importprivkey <HWWprivkey> [label]\n"
"Adds a private key (as returned by dumpprivkey) to your wallet.");
string strSecret = params[0].get_str();
string strLabel = "";
if (params.size() > 1)
strLabel = params[1].get_str();
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(strSecret);
if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
if (fWalletUnlockStakingOnly)
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only.");
CKey key = vchSecret.GetKey();
CPubKey pubkey = key.GetPubKey();
CKeyID vchAddress = pubkey.GetID();
{
LOCK2(cs_main, pwalletMain->cs_wallet);
pwalletMain->MarkDirty();
pwalletMain->SetAddressBookName(vchAddress, strLabel);
// Don't throw error in case a key is already there
if (pwalletMain->HaveKey(vchAddress))
return Value::null;
pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1;
if (!pwalletMain->AddKey(key))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
// whenever a key is imported, we need to scan the whole chain
pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value'
pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true);
pwalletMain->ReacceptWalletTransactions();
}
return Value::null;
}
Value importaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 3)
throw runtime_error(
"importaddress <address> [label] [rescan=true]\n"
"Adds an address or script (in hex) that can be watched as if it were in your wallet but cannot be used to spend.");
CScript script;
CBitcoinAddress address(params[0].get_str());
if (address.IsValid()) {
script.SetDestination(address.Get());
} else if (IsHex(params[0].get_str())) {
std::vector<unsigned char> data(ParseHex(params[0].get_str()));
script = CScript(data.begin(), data.end());
} else {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid HWW address or script");
}
string strLabel = "";
if (params.size() > 1)
strLabel = params[1].get_str();
// Whether to perform rescan after import
bool fRescan = true;
if (params.size() > 2)
fRescan = params[2].get_bool();
{
//LOCK2(cs_main, pwalletMain->cs_wallet);
if (::IsMine(*pwalletMain, script) == ISMINE_SPENDABLE)
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
// Don't throw error in case an address is already there
if (pwalletMain->HaveWatchOnly(script))
return Value::null;
pwalletMain->MarkDirty();
if (address.IsValid())
//pwalletMain->SetAddressBookName(dest, strLabel);
pwalletMain->SetAddressBookName(address.Get(), strLabel);
if (!pwalletMain->AddWatchOnly(script))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
if (fRescan)
{
pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true);
pwalletMain->ReacceptWalletTransactions();
}
}
return Value::null;
}
Value importwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"importwallet <filename>\n"
"Imports keys from a wallet dump file (see dumpwallet).");
EnsureWalletIsUnlocked();
ifstream file;
file.open(params[0].get_str().c_str());
if (!file.is_open())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
int64_t nTimeBegin = pindexBest->nTime;
bool fGood = true;
while (file.good()) {
std::string line;
std::getline(file, line);
if (line.empty() || line[0] == '#')
continue;
std::vector<std::string> vstr;
boost::split(vstr, line, boost::is_any_of(" "));
if (vstr.size() < 2)
continue;
CBitcoinSecret vchSecret;
if (!vchSecret.SetString(vstr[0]))
continue;
CKey key = vchSecret.GetKey();
CPubKey pubkey = key.GetPubKey();
CKeyID keyid = pubkey.GetID();
if (pwalletMain->HaveKey(keyid)) {
printf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString().c_str());
continue;
}
int64_t nTime = DecodeDumpTime(vstr[1]);
std::string strLabel;
bool fLabel = true;
for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) {
if (boost::algorithm::starts_with(vstr[nStr], "#"))
break;
if (vstr[nStr] == "change=1")
fLabel = false;
if (vstr[nStr] == "reserve=1")
fLabel = false;
if (boost::algorithm::starts_with(vstr[nStr], "label=")) {
strLabel = DecodeDumpString(vstr[nStr].substr(6));
fLabel = true;
}
}
printf("Importing %s...\n", CBitcoinAddress(keyid).ToString().c_str());
if (!pwalletMain->AddKey(key)) {
fGood = false;
continue;
}
pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime;
if (fLabel)
pwalletMain->SetAddressBookName(keyid, strLabel);
nTimeBegin = std::min(nTimeBegin, nTime);
}
file.close();
CBlockIndex *pindex = pindexBest;
while (pindex && pindex->pprev && pindex->nTime > nTimeBegin - 7200)
pindex = pindex->pprev;
if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey)
pwalletMain->nTimeFirstKey = nTimeBegin;
printf("Rescanning last %i blocks\n", pindexBest->nHeight - pindex->nHeight + 1);
pwalletMain->ScanForWalletTransactions(pindex);
pwalletMain->ReacceptWalletTransactions();
pwalletMain->MarkDirty();
if (!fGood)
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet");
return Value::null;
}
Value dumpprivkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"dumpprivkey <HWWaddress>\n"
"Reveals the private key corresponding to <HWWaddress>.");
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
CBitcoinAddress address;
if (!address.SetString(strAddress))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid HWW address");
if (fWalletUnlockStakingOnly)
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only.");
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key");
CKey vchSecret;
if (!pwalletMain->GetKey(keyID, vchSecret))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known");
return CBitcoinSecret(vchSecret).ToString();
}
Value dumpwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"dumpwallet <filename>\n"
"Dumps all wallet keys in a human-readable format.");
EnsureWalletIsUnlocked();
ofstream file;
file.open(params[0].get_str().c_str());
if (!file.is_open())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
std::map<CKeyID, int64_t> mapKeyBirth;
std::set<CKeyID> setKeyPool;
pwalletMain->GetKeyBirthTimes(mapKeyBirth);
pwalletMain->GetAllReserveKeys(setKeyPool);
// sort time/key pairs
std::vector<std::pair<int64_t, CKeyID> > vKeyBirth;
for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) {
vKeyBirth.push_back(std::make_pair(it->second, it->first));
}
mapKeyBirth.clear();
std::sort(vKeyBirth.begin(), vKeyBirth.end());
// produce output
file << strprintf("# Wallet dump created by HWW %s (%s)\n", CLIENT_BUILD.c_str(), CLIENT_DATE.c_str());
file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()).c_str());
file << strprintf("# * Best block at time of backup was %i (%s),\n", nBestHeight, hashBestChain.ToString().c_str());
file << strprintf("# mined on %s\n", EncodeDumpTime(pindexBest->nTime).c_str());
file << "\n";
for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {
const CKeyID &keyid = it->second;
std::string strTime = EncodeDumpTime(it->first);
std::string strAddr = CBitcoinAddress(keyid).ToString();
CKey key;
if (pwalletMain->GetKey(keyid, key)) {
if (pwalletMain->mapAddressBook.count(keyid)) {
file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(key).ToString().c_str(), strTime.c_str(), EncodeDumpString(pwalletMain->mapAddressBook[keyid]).c_str(), strAddr.c_str());
} else if (setKeyPool.count(keyid)) {
file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(key).ToString().c_str(), strTime.c_str(), strAddr.c_str());
} else {
file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(key).ToString().c_str(), strTime.c_str(), strAddr.c_str());
}
}
}
file << "\n";
file << "# End of dump\n";
file.close();
return Value::null;
}
| [
"veluiss82@gmail.com"
] | veluiss82@gmail.com |
3a92194e87e4dcebc9d9577e273c2bd674ad7510 | d520e29e67a8eaa93460ee7ad4b70fbfd1e98ccd | /ELEC291/project1/optical_testCode/optical_testCode.ino | 1236b942a05b206883aaa8d0b96068ebbdd38cba | [] | no_license | diyaren/ELEC291 | ae37dcce6f4e583eecfb1f1ee660b7110c62f690 | 316f23d305ce713357c7bad57b82138c5905b220 | refs/heads/master | 2020-06-24T23:13:15.221754 | 2017-07-12T00:29:46 | 2017-07-12T00:29:46 | 96,947,834 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,094 | ino | /*
read analog data from A0 and send to PC via Serial port
*/
int opticalPin1=1;
int opticalPin2=2;
int opticalPin3=3;
int opticalRead1 = 100;
int opticalRead2 ;
int opticalRead3;
void setup() {
// initialize the serial communication:
Serial.begin(9600);
}
void loop() {
// send the value of analog input 0:
int saveForUse=opticalRead2;
opticalRead1=analogRead(opticalPin1);//left
opticalRead2=analogRead(opticalPin2);//middle
opticalRead2=analogRead(opticalPin3);//right
Serial.println(opticalRead1);
Serial.println(opticalRead2);
while(
if(opticalRead1>opticalRead3)
{
Serial.println("1 is greater");
}else{
Serial.println("2 is greater");
}
if(opticalRead1 <320 && opticalRead2)
{
Serial.println("the car is on track ");
}
else if(opticalRead opticalRead )
{
Serial.println("black line detected");
}
else if(opticalRead > 320)
{
Serial.println("black line detected");
}
// wait a bit for the analog-to-digital converter
// to stabilize after the last reading (min 2 milli sec):
delay(2000); //2000=2 sec
}
| [
"noreply@github.com"
] | diyaren.noreply@github.com |
96625359cebe6a48b79e2587d29633e5c75b24ec | 5fd1e0e2ce1f9bc2c3d5f4a1d368bcde1bc17ae5 | /spoj-WPC4F.cpp | 0bbb7f991c74fea2d60241406bd2f7ed88cf5084 | [] | no_license | srivastavaman641/Competitive-Coding | ec3177cecaf33081fd68f8da4fec4c3cc7669c0d | c3b8f576d41f1aa2f608812c013c4392be3d3392 | refs/heads/master | 2020-03-22T18:11:23.882989 | 2018-07-10T14:18:44 | 2018-07-10T14:18:44 | 140,443,258 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,085 | cpp | #include<bits/stdc++.h>
#define ll long long int
#define s(a) scanf("%d",&a)
#define sl(a) scanf("%lld",&a)
#define ss(a) scanf("%s",a)
#define w(t) while(t--)
#define f(i,n) for(int i=0;i<n;i++)
#define fd(i,n) for(int i=n-1;i>=0;i--)
#define p(a) printf("%d",a)
#define pl(a) printf("%lld",a)
#define ps(a) printf("%s",a)
#define pc(a) printf("%c",a)
#define ent printf("\n")
#define mod 1000000007
#define PI 3.14159265
#define gs getline(cin,s)
#define pb push_back
#define mp make_pair
#define INF 1e18
#define pii pair<int,int>
using namespace std;
int dp[25][5];
int a[25][5];
int n;
int recur(int pos,int prev)
{
if(pos>n)
return 0;
if(dp[pos][prev]!=-1)
return dp[pos][prev];
int ans=INT_MAX;
for(int i=1;i<=3;i++)
{
if(i==prev)continue;
ans=min(ans,a[pos][i]+recur(pos+1,i));
}
return dp[pos][prev]=ans;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
while(t--)
{
cin>>n;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=3;j++)
cin>>a[i][j];
}
memset(dp,-1,sizeof dp);
cout<<recur(1,-1)<<endl;
}
return 0;
}
| [
"srivastav.aman641@gmail.com"
] | srivastav.aman641@gmail.com |
400680ac18905b9c8cf4aebd2db67513fc0020dc | d8d9b66adfad41c0244414f239324c87b51a745b | /Monopoly/Monopoly/GoToSpace.h | f9fa0b68c21eb080a26a2405f87b002c82744cc3 | [] | no_license | rbazeli/Monopoly | 43ab61c5eeec945e8ee055d159b43d06e54b67b3 | c64fb109aa1a194a8c1e6619a7753f1b61143bbe | refs/heads/master | 2023-03-15T14:40:43.562880 | 2015-11-16T22:28:50 | 2015-11-16T22:28:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 548 | h | // GoToSpace.h
#ifndef __Monopoly__GoToSpace__
#define __Monopoly__GoToSpace__
#include <iostream>
#include <string>
#include "Space.h"
class GoToSpace: public Space
{
private:
string name;
int index;
int targetSpaceIndex;
Action *spaceAction;
public:
GoToSpace();
GoToSpace(string, int, int);
~GoToSpace();
// same as virtual function
void set_name(string s);
void set_spaceAction(Action *a);
string get_spaceName();
int get_spaceIndex();
void doAction(Player &p);
};
#endif
| [
"koha@usc.edu"
] | koha@usc.edu |
1ad240c3e556ef3bd45c6746f490953303a3b5fc | c1d5c710593bacdac1fbae8186bf605142c58022 | /416. Partition Equal Subset Sum.cpp | 97f39def9cabc3e0007be75f85fb2aced269259f | [] | no_license | ankitsharma1530/Dynamic-Programming | 7325c6bee3ac71ab0ffc6fa15f9a4c5667df3d39 | 01e41fa5b91273be0f613ce615cbc24a1215c85b | refs/heads/main | 2023-06-15T16:50:09.490563 | 2021-07-20T10:28:44 | 2021-07-20T10:28:44 | 345,287,489 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 915 | cpp | class Solution {
public:
bool canPartition(vector<int>& nums) {
int n = nums.size();
int sum = 0;
for(int i=0;i<n;i++)
{
sum = sum+nums[i];
}
if(n==1)
{
return false;
}
if(sum%2!=0)
{
return false;
}
bool dp[n+1][sum+1];
for(int i=1;i<=sum;i++)
{
dp[0][i] = false;
}
for(int i=0;i<=n;i++)
{
dp[i][0] = true;
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=sum;j++)
{
if(nums[i-1]<=j)
{
dp[i][j] = dp[i-1][j] || dp[i-1][j-nums[i-1]];
}
else
{
dp[i][j] = dp[i-1][j];
}
}
}
return dp[n][sum/2];
}
};
| [
"noreply@github.com"
] | ankitsharma1530.noreply@github.com |
1a211f713930f58f73ca24b8deadaa7c6bfdcd5f | 0a56072ac1fcdce713ec17b84d5f6f8dd7dbd86b | /media/camera/uvcadjust/src/Camera.cpp | 8902d00bcf5e450597989f81b5dc33f1f19649c2 | [] | no_license | aizaivq/CProject1977 | 3bc0101eaa26e7ef60f673bcf87f121a550816d0 | 7a1f50eed0f7fa532b5af5de2daec9a205032580 | refs/heads/master | 2020-06-15T02:25:34.570328 | 2019-07-04T06:41:51 | 2019-07-04T06:41:51 | 195,183,740 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,740 | cpp | #include <Camera.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <malloc.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <asm/types.h>
#include <linux/videodev2.h>
#include <linux/usbdevice_fs.h>
#include <pthread.h>
#include <errno.h>
#define DEBUG_FRAME_SAVE
#define DEBUG_CTL
Camera mCamera;
extern OpenGL mOpenGL;
void *ThreadCall(void *arg)
{
mCamera.StartPreviewInner();
}
int Camera::Init(int id,int width,int height,int format)
{
printf("******\n");
printf("preview format h264: %d\n",V4L2_PIX_FMT_H264);
printf("preview format yuyv: %d\n",V4L2_PIX_FMT_YUYV);
printf("preview format mjpeg: %d\n",V4L2_PIX_FMT_MJPEG);
printf("preview format yuv420: %d\n",V4L2_PIX_FMT_YUV420);
printf("******\n");
//open device
struct stat st;
char dev_name[16];
sprintf(dev_name,"/dev/video%d",id);
if (-1 == stat (dev_name, &st)) {
return -1;
}
if (!S_ISCHR (st.st_mode)) {
return -1;
}
int fd = open (dev_name, O_RDWR | O_NONBLOCK, 0);
mFd = fd;
if (-1 == fd) {
printf("open failed fd=-1\n");
return -1;
}
mHeight = height;
mWidth = width;
mFormat = format;
printf("open successed\n");
return 0;
}
int Camera::StartPreviewInner()
{
//init device
int fd = mFd;
struct v4l2_fmtdesc{
__u32 index; // 需要填充,从0开始,依次上升。
enum v4l2_buf_type type; //Camera,则填写V4L2_BUF_TYPE_VIDEO_CAPTURE
__u32 flags; // 如果压缩的,则Driver 填写:V4L2_FMT_FLAG_COMPRESSED,否则为0
__u8 description[32]; // image format的描述,如:YUV 4:2:2 (YUYV)
__u32 pixelformat; //所支持的格式。 如:V4L2_PIX_FMT_UYVY
__u32 reserved[4];
};
struct v4l2_fmtdesc fmtdesc;
fmtdesc.index = 0;
fmtdesc.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
int ret = ioctl(fd, VIDIOC_ENUM_FMT, &fmtdesc);
int fmtt = fmtdesc.pixelformat;
unsigned char * des = fmtdesc.description;
printf("support format: %d\n",fmtt);
printf("description: %s\n",des);
struct v4l2_capability cap;
struct v4l2_cropcap cropcap;
struct v4l2_crop crop;
struct v4l2_format fmt;
unsigned int min;
if (-1 == ioctl (fd, VIDIOC_QUERYCAP, &cap)) {
if (EINVAL == errno) {
printf("error EINVAL\n");
return -1;
} else {
printf("error undefine\n");
return -1;
}
}
struct v4l2_streamparm* setfps;
setfps=(struct v4l2_streamparm *) calloc(1, sizeof(struct v4l2_streamparm));
memset(setfps, 0, sizeof(struct v4l2_streamparm));
setfps->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
setfps->parm.capture.timeperframe.numerator=1;
setfps->parm.capture.timeperframe.denominator=60;//15
int setret = ioctl(fd, VIDIOC_S_PARM, setfps);
struct v4l2_streamparm *getfps;
getfps=(struct v4l2_streamparm *) calloc(1, sizeof(struct v4l2_streamparm));
memset(getfps, 0, sizeof(struct v4l2_streamparm));
getfps->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
int rel = ioctl(fd, VIDIOC_G_PARM, getfps);
if(rel == 0)
{
printf("frame rate: %u/%u\n",getfps->parm.capture.timeperframe.denominator,getfps->parm.capture.timeperframe.numerator);
}
else
{
printf("Unable to read out current frame rate\n");
return -1;
}
if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
printf("error undefine\n");
return -1;
}
if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
printf("error undefine\n");
return -1;
}
memset (&(cropcap), 0, sizeof (cropcap));
cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (0 == ioctl (fd, VIDIOC_CROPCAP, &cropcap)) {
crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
crop.c = cropcap.defrect;
if (-1 == ioctl (fd, VIDIOC_S_CROP, &crop)) {
switch (errno) {
case EINVAL:
break;
default:
break;
}
}
} else {
}
memset (&(fmt), 0, sizeof (fmt));
printf("preview format: %d\n",mFormat);
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fmt.fmt.pix.width = mWidth;
fmt.fmt.pix.height = mHeight;
fmt.fmt.pix.pixelformat = mFormat;
fmt.fmt.pix.field = V4L2_FIELD_ANY;
struct v4l2_queryctrl qctrl;
// qctrl.id = VIDIOC_G_CTRL;
qctrl.id = V4L2_CID_BRIGHTNESS;
if (ioctl(fd, VIDIOC_QUERYCTRL, &qctrl) >= 0) {
printf("VIDIOC_QUERYCTRL successed\n");
}
else
printf("VIDIOC_QUERYCTRL failed\n");
if (-1 == ioctl (fd, VIDIOC_S_FMT, &fmt))
{
printf("ioctl VIDIOC_S_FMT failed\n");
return -1;
}
min = fmt.fmt.pix.width * 2 ;
if (fmt.fmt.pix.bytesperline < min)
fmt.fmt.pix.bytesperline = min;
min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
if (fmt.fmt.pix.sizeimage < min)
fmt.fmt.pix.sizeimage = min;
printf("fmt.fmt.pix.sizeimage: %d\n",fmt.fmt.pix.sizeimage);
//init map
struct v4l2_requestbuffers req;
memset (&(req), 0, sizeof (req));
req.count = 4;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_MMAP;
if (-1 == ioctl (fd, VIDIOC_REQBUFS, &req)) {
if (EINVAL == errno) {
printf("error undefine\n");
return -1;
} else {
printf("error undefine\n");
return -1;
}
}
if (req.count < 2) {
printf("error undefine\n");
return -1;
}
struct buffer {
void * start;
size_t length;
};
struct buffer * buffers = (buffer *)calloc (req.count, sizeof (*buffers));
if (!buffers) {
return -1;
}
unsigned int n_buffers = 0;
for (n_buffers = 0; n_buffers < req.count; ++n_buffers) {
struct v4l2_buffer buf;
memset (&(buf), 0, sizeof (buf));
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = n_buffers;
if (-1 == ioctl (fd, VIDIOC_QUERYBUF, &buf))
{
printf("ioctl VIDIOC_QUERYBUF failed\n");
return -1;
}
buffers[n_buffers].length = buf.length;
buffers[n_buffers].start =
mmap (NULL ,
buf.length,
PROT_READ | PROT_WRITE,
MAP_SHARED,
fd, buf.m.offset);
if (MAP_FAILED == buffers[n_buffers].start)
{
printf("error undefine\n");
return -1;
}
}
#ifdef DEBUG_CTL
struct v4l2_control getAtExposure;
getAtExposure.id = V4L2_CID_EXPOSURE_AUTO;
int retGetAtExposure = ioctl(fd, VIDIOC_G_CTRL, &getAtExposure);
if (retGetAtExposure < 0)
{
printf("get at exposure failed errno: %d\n",errno);
}
printf("get at exposure :[%d]\n", getAtExposure.value);
struct v4l2_control getExposure;
getExposure.id = V4L2_CID_EXPOSURE_ABSOLUTE;
int retGetExposure = ioctl(fd, VIDIOC_G_CTRL, &getExposure);
if (retGetExposure < 0)
{
printf("get ab exposure failed errno: %d\n",errno);
}
printf("get exposure :[%d]\n", getExposure.value);
struct v4l2_control setExposureType;
setExposureType.id = V4L2_CID_EXPOSURE_AUTO;
setExposureType.value = V4L2_EXPOSURE_MANUAL;
int retSetExposureType = ioctl(fd, VIDIOC_S_CTRL, &setExposureType);
if (retSetExposureType < 0)
{
printf("set exposure type failed errno: %d\n",errno);
}
struct v4l2_control setExposure;
setExposure.id = V4L2_CID_EXPOSURE_ABSOLUTE;
setExposure.value = 1000;
int retSetExposure = ioctl(fd, VIDIOC_S_CTRL, &setExposure);
if (retSetExposure < 0)
{
printf("set exposure failed errno: %d\n",errno);
}
else
{
printf("set exposure successed\n");
}
#endif
//start preview
unsigned int i;
enum v4l2_buf_type type;
for (i = 0; i < n_buffers; ++i) {
struct v4l2_buffer buf;
memset (&(buf), 0, sizeof (buf));
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = i;
if (-1 == ioctl (fd, VIDIOC_QBUF, &buf))
{
printf("ioctl VIDIOC_QBUF failed\n");
return -1;
}
}
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (-1 == ioctl (fd, VIDIOC_STREAMON, &type))
{
printf("ioctl VIDIOC_STREAMON failed\n");
return -1;
}
printf("loop fd: %d\n",fd);
for (;;) {
fd_set fds;
struct timeval tv;
int r;
FD_ZERO (&fds);
FD_SET (fd, &fds);
tv.tv_sec = 2;
tv.tv_usec = 0;
r = select (fd + 1, &fds, NULL, NULL, &tv);
if (-1 == r) {
if (EINTR == errno)
continue;
printf("select failed\n");
return -1;
}
if (0 == r) {
printf("select failed\n");
return -1;
}
{
//printf("frame start\n");
struct v4l2_buffer buf;
unsigned int i;
memset (&(buf), 0, sizeof (buf));
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
if (-1 == ioctl (fd, VIDIOC_DQBUF, &buf)) {
switch (errno) {
case EAGAIN:
printf("ioctl VIDIOC_DQBUF EAGAIN failed\n");
return -1;
case EIO:
default:
{
printf("ioctl VIDIOC_DQBUF failed errno: %d\n", errno);
return -1;
}
}
}
if (-1 == ioctl (fd, VIDIOC_QBUF, &buf))
{
printf("error undefine\n");
return -1;
}
#ifdef DEBUG_FRAME_SAVE
FrameSave("data.yuv");
{
// printf("frame save\n");
write(mFrameFd,buffers[buf.index].start,buf.bytesused);
close(mFrameFd);
mFrameFd = -1;
}
#endif
mOpenGL.mBuff = (unsigned char *)buffers[buf.index].start;
// sleep(1);
//printf("frame end\n");
}
}
close(mFd);
}
int Camera::StartPreview()
{
mOpenGL.CreateYUV420PWindow("main","yuyv.yuv",100,100,1280,720,mCamera.mWidth,mCamera.mHeight,DRAW_YUYV);
pthread_t thread;
int retCreate = pthread_create(&thread, NULL, &ThreadCall, NULL);
printf("pthread_create ret: %d\n",retCreate);
pthread_detach(thread);
pthread_join(thread, NULL);
return retCreate;
}
int Camera::FrameSave(const char *path)
{
mFrameFd = open(path,O_RDWR | O_CREAT,0777);
if(mFrameFd == -1)
{
printf("open failed\n");
return -1;
}
}
| [
"372943264@qq.com"
] | 372943264@qq.com |
dfb70b9314cf5fe7a2fd3714797f9919aa801cf5 | 7e79e0be56f612288e9783582c7b65a1a6a53397 | /problem-solutions/codechef/2017/march/schedule-small.cpp | 0ac6e25f9cf3c105c6eb6c8105256f76e19ff046 | [] | no_license | gcamargo96/Competitive-Programming | a643f492b429989c2d13d7d750c6124e99373771 | 0325097de60e693009094990d408ee8f3e8bb18a | refs/heads/master | 2020-07-14T10:27:26.572439 | 2019-08-24T15:11:20 | 2019-08-24T15:11:20 | 66,391,304 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 974 | cpp | #include <bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define endl "\n"
typedef long long ll;
typedef vector<int> vi;
typedef vector<bool> vb;
typedef pair<int,int> ii;
const int N = 1000002;
int t, n, k;
string s;
int check(){
int i = 0, maior = 0;
while(i < n){
int j;
for(j = i; s[j] == s[j+1]; j++){}
maior = max(maior, j-i+1);
if(i == j) j++;
i = j;
}
return maior;
}
int go(int i, int cnt){
if(i == n){
if(cnt <= k) return check();
else return INF;
}
if(s[i] == '0') s[i] = '1';
else s[i] = '0';
int ret = go(i+1, cnt++);
if(s[i] == '0') s[i] = '1';
else s[i] = '0';
ret = min(ret, go(i+1, cnt));
return ret;
}
int main(void){
ios_base::sync_with_stdio(false);
cin >> t;
while(t--){
cin >> n >> k >> s;
s += '#';
int res = go(0, 0);
cout << res << endl;
}
return 0;
}
| [
"gacamargo1.000@gmail.com"
] | gacamargo1.000@gmail.com |
d9f2e035f796f0e1c1794cf887e706f6d18e10e7 | fa2c1dbe3e20b32f30de0279529031bd278776b6 | /cf/gym/PacificNorth2017-18/r.cpp | 770a8689dde7da5c4a680d0b60f781e8b65a88c8 | [] | no_license | wxnn08/RepLord | f36440b5a3592a56dc6ded2a3eb9dee055d9b83b | 2981c4722cdd199bf75fcce37d729e0770740c54 | refs/heads/master | 2021-06-05T05:31:33.349754 | 2021-01-30T19:54:04 | 2021-01-30T19:54:04 | 124,475,433 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,929 | cpp | /* O nosso maior medo não é sermos inadequados.
O nosso maior medo é sermos infinitamente poderosos.
É a nossa própria luz, não a nossa escuridão, que nos amedronta.
Sermos pequenos não engrandece o mundo.
Não há nada de transcendente em sermos pequenos,
pois assim os outros não se sentirão inseguros ao nosso lado.
Todos estamos destinados a brilhar, como as crianças.
Não apenas alguns de nós, mas todos.
E, enquanto irradiamos a nossa admirável luz interior,
inconscientemente estamos a permitir aos outros fazer o mesmo.
E, quando nos libertarmos dos nossos próprios medos,
a nossa presença automaticamente libertará os medos dos outros. */
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define eb emplace_back
#define mk make_pair
#define fi first
#define se second
#define cc(x) cout << #x << " = " << x << endl
#define ok cout << "ok" << endl
#define endl '\n'
typedef long long ll;
typedef pair<int,int> ii;
const int INF = 0x3f3f3f3f;
const double PI = acos(-1.0);
struct Swalk {
double l, r, v;
bool operator < (const Swalk &a) const {
return l < a.l;
}
};
int n;
double x, v;
vector<Swalk> sws;
// Retorna custo em seg do segmento
double cost(double t) {
return x/(cos(t) * v);
}
// Retorna absoluto da distância entre onde terminou e o ponto 0
double f(double t) {
double y = x * tan(t);
for(auto sw:sws) {
double dx = sw.r - sw.l;
double yf = sw.v * (dx/(cos(t) * v));
y += yf;
}
return abs(y);
}
int main() {
ios_base::sync_with_stdio(false);
cin >>n >>x >>v;
for(int i = 0; i < n; i++) {
double l, r, v;
cin >>l >>r >>v;
sws.pb({l,r,v});
}
sort(sws.begin(), sws.end());
double l = -PI/3;
double r = PI/3;
for(int i = 0; i < 10000; i++) {
double mid = (l+r)/2;
if(f(mid) > 0.0) r = mid;
else l = mid;
}
if(abs(f(l)) > 1e-9) cout <<"Too hard" <<endl;
else cout <<fixed <<setprecision(3) <<cost(l) <<endl;
return 0;
}
| [
"wesleypersilva@gmail.com"
] | wesleypersilva@gmail.com |
8aee324bd9feea96b64c90e70291d9aab4b8cea7 | 46c053bb12e23853950952029ea2464b572f62e6 | /KKLineScanner/ScannerFrame.cpp | c18341e90a4292332718839cdace868122f7878d | [] | no_license | KurtKramer/KSquareLibraries | c2b56bb0b8e8a68f9fd242c4822f9703a72ac32e | c532ab6de38663e6fd55247f6e3171ef8a2751e6 | refs/heads/master | 2022-02-27T15:57:51.532287 | 2021-11-27T15:23:23 | 2021-11-27T15:23:23 | 16,259,859 | 0 | 3 | null | 2022-01-14T06:22:31 | 2014-01-26T19:26:59 | C++ | UTF-8 | C++ | false | false | 1,312 | cpp | #include "FirstIncludes.h"
#include <stdio.h>
#include <iostream>
#include "MemoryDebug.h"
//using namespace std;
#include "KKBaseTypes.h"
using namespace KKB;
#include "ScannerClock.h"
#include "ScannerFrame.h"
using namespace KKLSC;
ScannerFrame::ScannerFrame (ScannerClockPtr _clock,
kkint32 _scanLinesPerFrame,
kkint32 _pixelsPerScanLine
):
clock (_clock),
frameNum (-1),
height (_scanLinesPerFrame),
scanLines (NULL),
scanLineFirst (-1),
scanLineLast (-1),
time (0),
width (_pixelsPerScanLine)
{
clock = _clock;
scanLines = AllocateFrameArray ();
}
ScannerFrame::~ScannerFrame ()
{
if (scanLines)
{
for (kkint32 x = 0; x < height; ++x)
{
delete scanLines[x];
scanLines[x] = NULL;
}
}
delete scanLines;
scanLines = NULL;
}
uchar** ScannerFrame::AllocateFrameArray ()
{
uchar** a = new uchar*[height];
for (kkint32 r = 0; r < height; r++)
a[r] = new uchar[width];
return a;
}
uchar** ScannerFrame::ScanLines ()
{
time = clock->Time ();
return scanLines;
}
void ScannerFrame::ScanLines (uchar** _scanLines)
{
time = clock->Time ();
scanLines = _scanLines;
}
| [
"kurtkramer@gmail.com"
] | kurtkramer@gmail.com |
099a6120b4b872fa2226a1cce40c4daf7b1d0471 | 07a50ef35648b18048129707c34204827e338a78 | /CS132 Program 8 Binary Tree/CS132 Program 8 Binary Tree/Queue.h | 45a2fc22ff47451ba0cdccf063035dd026d50344 | [] | no_license | Jared-Swislow/CS-132 | 69e69c1cd7d054101c01a5e137b83b234827b2c0 | b7250747f3a78030bbeafb67a048a68e7d4ad543 | refs/heads/master | 2022-04-13T05:07:10.775683 | 2020-03-16T05:03:16 | 2020-03-16T05:03:16 | 233,142,088 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,041 | h | // File Name: Queue.h
// Author: Cliff Snyder (csnyder@everett.edu)
// Description: Declarations for the class Queue
#pragma once
#include <iostream>
#define NDEBUG // allow exceptions to fire
#include <cassert>
#include "Node.h"
using namespace std;
template <class P>
class Queue
{
private: // Private attributes
Node<P> *front; // Pointer to the front of the queue
Node<P> *rear; // Pointer to the rear of the queue
unsigned int numNodes; // Number of payloads in the queue
void clearQueue()
{
while (front != nullptr)
{
dequeue();
}
}
void copyNodes(const Node<P> *nodePtr)
{
// Copy each item in the queue.
while (nodePtr != nullptr)
{
enqueue(nodePtr->getPayload());
nodePtr = nodePtr->getNext();
}
}
public:
// Constructors
Queue()
{
front = nullptr;
rear = nullptr;
numNodes = 0;
}
Queue(const Queue& fromQueue)
{
front = nullptr;
rear = nullptr;
numNodes = 0;
this->copyNodes(fromQueue.front); // Deep copy of the Nodes
}
// Enqueue/Dequeue methods
bool enqueue(P newPayload)
{
bool returnVal(true);
try // new throws exceptions
{
// Get a new node, store the new payload, and set its next pointer to null.
Node<P> *newNode = new Node<P>(newPayload, nullptr);
// If this is the first node in the queue, set both front and rear to the new node.
if (numNodes == 0)
{
assert(front == nullptr);
assert(rear == nullptr);
front = newNode;
rear = newNode;
}
else // Just add the new node to the linked list and reset the rear pointer
{
assert(rear != nullptr);
rear->setNext(newNode);
rear = newNode;
}
numNodes++; // increment the number of nodes in the queue
}
catch (...)
{
returnVal = false;
}
return returnVal;
}
P dequeue()
{
// Return the payload of the front node, delete it, and reset the front pointer.
// Throw an exception if the queue is empty
assert(numNodes > 0);
if (numNodes <= 0)
{
throw runtime_error("Illegal dequeue");
}
// Store the payload and next pointer;
P returnVal = front->getPayload();
Node<P> *temp = front->getNext();
// Delete the node; decrement the number of nodes
delete front;
numNodes--;
// Set the front of the queue to the next node
front = temp;
if (numNodes == 0)
{
assert(front == nullptr);
rear = nullptr;
}
// Return the first element in the queue
return(returnVal);
}
// Front accessor
P getFront() const
{
// Return the payload of the front node.
// Throw an exception if the queue is empty
assert(numNodes > 0);
if (numNodes <= 0)
{
throw runtime_error("Illegal readFront");
}
return(front->getPayload());
}
// Num Nodes accessor
unsigned int getNumNodes() const
{
return(numNodes);
}
// isEmpty method
bool isEmpty() const
{
return (numNodes == 0);
}
// Overloaded operators
Queue& operator=(const Queue& fromQueue)
{
// If the passed objects are different, delete the nodes from the to stack and copy the nodes from the from stack
if (this != &fromQueue) // handle queue1 = queue1;
{
this->clearQueue();
this->copyNodes(fromQueue.front);
}
return (*this);
}
bool operator==(const Queue& rhs) const
{
bool retVal = true;
// If the number of nodes is different, the queues are different.
if (rhs.numNodes != this->numNodes)
{
retVal = false;
}
// Else, compare each node and look for differences
else
{
Node<P> *rhsTemp = rhs.front;
Node<P> *lhsTemp = this->front;
while (lhsTemp != nullptr && retVal)
{
if (lhsTemp->getPayload() != rhsTemp->getPayload())
{
retVal = false;
}
lhsTemp = lhsTemp->getNext();
rhsTemp = rhsTemp->getNext();
}
}
return retVal;
}
friend ostream& operator <<(ostream& outputStream, const Queue& queue)
{
Node<P> *nodePtr = queue.front;
while (nodePtr != nullptr)
{
outputStream << *nodePtr;
nodePtr = nodePtr->getNext();
}
return(outputStream);
}
// Destructor
~Queue()
{
clearQueue();
}
};
| [
"jayswis2002@gmail.com"
] | jayswis2002@gmail.com |
f3310f86d34a8858e67228e9a1a65396b8c61c6c | 3bb29f733a297d0265937864725609072bb89368 | /include/scheduler.h | 9f873fea122d381814a1e1417f27aca6cb65b08b | [] | no_license | freddiecoleman/nexusjs | f50144469d76e3f2caba02b6984724f7b0aaea5a | 245c8e4e6d6038b465166914f1ca5e3fbf07a3f0 | refs/heads/master | 2021-08-22T10:14:25.737571 | 2017-11-30T00:21:09 | 2017-11-30T00:21:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,633 | h | /*
* Nexus.js - The next-gen JavaScript platform
* Copyright (C) 2016 Abdullah A. Hassan <abdullah@webtomizer.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef SCHEDULER_H
#define SCHEDULER_H
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/optional.hpp>
#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <boost/asio.hpp>
#undef B0 // JavaSCriptCore will complain if this is defined.
#include <boost/asio/handler_type.hpp>
#include <boost/lockfree/queue.hpp>
#include <boost/atomic.hpp>
#include <boost/assert.hpp>
#include <boost/noncopyable.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <thread>
namespace NX
{
class Nexus;
class AbstractTask;
class Task;
class CoroutineTask;
class Scheduler: public boost::noncopyable
{
public:
typedef boost::asio::deadline_timer timer_type;
typedef timer_type::duration_type duration;
typedef boost::function<void(void)> CompletionHandler;
typedef boost::lockfree::queue<NX::AbstractTask*> TaskQueue;
public:
Scheduler(NX::Nexus *, unsigned int maxThreads);
virtual ~Scheduler();
public:
void start();
void pause() { myPauseTasks.store(true); }
void resume() { myPauseTasks.store(false); }
void stop();
void join();
void joinPool() { dispatcher(); }
NX::AbstractTask * scheduleAbstractTask(NX::AbstractTask * task);
NX::Task * scheduleTask(const CompletionHandler & handler);
NX::Task * scheduleTask(const duration & time, const CompletionHandler & handler);
NX::CoroutineTask * scheduleCoroutine(const CompletionHandler & handler);
NX::CoroutineTask * scheduleCoroutine(const duration & time, const CompletionHandler & handler);
void yield();
NX::Nexus * nexus() { return myNexus; }
unsigned int concurrency() const { return myThreadCount; }
unsigned int queued() const { return myTaskCount; }
unsigned int active() const { return myActiveTaskCount; }
unsigned int remaining() const { return myActiveTaskCount + myTaskCount; }
void hold() { myTaskCount++; }
void release() { myTaskCount--; }
const std::shared_ptr<boost::asio::io_service> service() const { return myService; }
std::shared_ptr<boost::asio::io_service> service() { return myService; }
/**
* Internal use only!
*/
void makeCurrent(NX::AbstractTask * task);
protected:
void addThread();
void balanceThreads();
void dispatcher();
bool processTasks();
private:
NX::Nexus * myNexus;
boost::atomic<unsigned int> myMaxThreads;
boost::atomic_uint myThreadCount;
std::shared_ptr<boost::asio::io_service> myService;
std::shared_ptr<boost::asio::io_service::work> myWork;
boost::thread_group myThreadGroup;
boost::thread_specific_ptr<NX::AbstractTask> myCurrentTask;
TaskQueue myTaskQueue;
boost::atomic_uint myTaskCount, myActiveTaskCount;
boost::atomic_bool myPauseTasks;
boost::recursive_mutex myBalancerMutex;
};
}
#endif // SCHEDULER_H
| [
"voodooattack@hotmail.com"
] | voodooattack@hotmail.com |
bf3969456c7bdcd0f7356085e7386d7dfcf18689 | 2bb45566a81d3c5299b60f0783196b1ecc2b2628 | /src/qt/Openbitstrings.cpp | d1c997da92a84ca547feea22f895cecf41ec83c3 | [
"MIT"
] | permissive | coins-archive/Openbit | 643328d414327414ea3abf43db2abd7cc2b08b4e | 30db307c15b90c1fac5dc05f83f40a8ce464f0aa | refs/heads/master | 2020-04-08T13:23:38.689676 | 2018-11-06T21:17:43 | 2018-11-06T21:17:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,004 | cpp |
#include <QtGlobal>
// Automatically generated by extract_strings.py
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
#else
#define UNUSED
#endif
static const char UNUSED *Openbit_strings[] = {
QT_TRANSLATE_NOOP("Openbit-core", " mints deleted\n"),
QT_TRANSLATE_NOOP("Openbit-core", " mints updated, "),
QT_TRANSLATE_NOOP("Openbit-core", " unconfirmed transactions removed\n"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"(1 = keep tx meta data e.g. account owner and payment request information, 2 "
"= drop tx meta data)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Allow JSON-RPC connections from specified source. Valid for <ip> are a "
"single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or "
"a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"An error occurred while setting up the RPC address %s port %u for listening: "
"%s"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Bind to given address and always listen on it. Use [host]:port notation for "
"IPv6"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Bind to given address and whitelist peers connecting to it. Use [host]:port "
"notation for IPv6"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Bind to given address to listen for JSON-RPC connections. Use [host]:port "
"notation for IPv6. This option can be specified multiple times (default: "
"bind to all interfaces)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Calculated accumulator checkpoint is not what is recorded by block index"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Cannot obtain a lock on data directory %s. Openbit Core is probably already "
"running."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Change automatic finalized budget voting behavior. mode=auto: Vote for only "
"exact finalized budget match to my generated budget. (string, default: auto)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Continuously rate-limit free transactions to <n>*1000 bytes per minute "
"(default:%u)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Create new files with system default permissions, instead of umask 077 (only "
"effective with disabled wallet functionality)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Delete all wallet transactions and only recover those parts of the "
"blockchain through -rescan on startup"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Disable all Openbit specific functionality (Masternodes, Obfuscation, SwiftX, "
"Budgeting) (0-1, default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Distributed under the MIT software license, see the accompanying file "
"COPYING or <http://www.opensource.org/licenses/mit-license.php>."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Enable automatic wallet backups triggered after each zOpenbit minting (0-1, "
"default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Enable spork administration functionality with the appropriate private key."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Enable SwiftX, show confirmations for locked transactions (bool, default: "
"%s)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Enter regression test mode, which uses a special chain in which blocks can "
"be solved instantly."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Error: Listening for incoming connections failed (listen returned error %s)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Error: The transaction was rejected! This might happen if some of the coins "
"in your wallet were already spent, such as if you used a copy of wallet.dat "
"and coins were spent in the copy but not marked as spent here."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Error: This transaction requires a transaction fee of at least %s because of "
"its amount, complexity, or use of recently received funds!"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Error: Unsupported argument -checklevel found. Checklevel must be level 4."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Error: Unsupported argument -socks found. Setting SOCKS version isn't "
"possible anymore, only SOCKS5 proxies are supported."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Execute command when a relevant alert is received or we see a really long "
"fork (%s in cmd is replaced by message)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Execute command when a wallet transaction changes (%s in cmd is replaced by "
"TxID)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Execute command when the best block changes (%s in cmd is replaced by block "
"hash)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Fees (in OPN/Kb) smaller than this are considered zero fee for relaying "
"(default: %s)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Fees (in OPN/Kb) smaller than this are considered zero fee for transaction "
"creation (default: %s)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Flush database activity from memory pool to disk log every <n> megabytes "
"(default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Found unconfirmed denominated outputs, will wait till they confirm to "
"continue."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"If paytxfee is not set, include enough fee so transactions begin "
"confirmation on average within n blocks (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"In this mode -genproclimit controls how many blocks are generated "
"immediately."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Insufficient or insufficient confirmed funds, you might need to wait a few "
"minutes and try again."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay "
"fee of %s to prevent stuck transactions)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Keep the specified amount available for spending at all times (default: 0)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Log transaction priority and fee per kB when mining blocks (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Maintain a full transaction index, used by the getrawtransaction rpc call "
"(default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Maximum size of data in data carrier transactions we relay and mine "
"(default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Maximum total fees to use in a single wallet transaction, setting too low "
"may abort large transactions (default: %s)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Number of seconds to keep misbehaving peers from reconnecting (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Obfuscation uses exact denominated amounts to send funds, you might simply "
"need to anonymize some more coins."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Output debugging information (default: %u, supplying <category> is optional)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Preferred Denomination for automatically minted Zerocoin "
"(1/5/10/50/100/500/1000/5000), 0 for no preference. default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Query for peer addresses via DNS lookup, if low on addresses (default: 1 "
"unless -connect)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Randomize credentials for every proxy connection. This enables Tor stream "
"isolation (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Require high priority for relaying free or low-fee transactions (default:%u)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Send trace/debug info to console instead of debug.log file (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Set the number of script verification threads (%u to %d, 0 = auto, <0 = "
"leave that many cores free, default: %d)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Set the number of threads for coin generation if enabled (-1 = all cores, "
"default: %d)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Show N confirmations for a successfully locked transaction (0-9999, default: "
"%u)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Support filtering of blocks and transaction with bloom filters (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"SwiftX requires inputs with at least 6 confirmations, you might need to "
"wait a few minutes and try again."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"This is a pre-release test build - use at your own risk - do not use for "
"staking or merchant applications!"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"This product includes software developed by the OpenSSL Project for use in "
"the OpenSSL Toolkit <https://www.openssl.org/> and cryptographic software "
"written by Eric Young and UPnP software written by Thomas Bernard."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"To use Openbitd, or the -server option to Openbit-qt, you must set an rpcpassword "
"in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=Openbitrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file "
"permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"Openbit Alert\" admin@foo.com\n"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Unable to bind to %s on this computer. Openbit Core is probably already running."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Unable to locate enough Obfuscation denominated funds for this transaction."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Unable to locate enough Obfuscation non-denominated funds for this "
"transaction that are not equal 10000 OPN."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Unable to locate enough funds for this transaction that are not equal 10000 "
"OPN."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: "
"%s)"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Warning: -maxtxfee is set very high! Fees this large could be paid on a "
"single transaction."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Warning: -paytxfee is set very high! This is the transaction fee you will "
"pay if you send a transaction."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Warning: Please check that your computer's date and time are correct! If "
"your clock is wrong Openbit Core will not work properly."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Warning: The network does not appear to fully agree! Some miners appear to "
"be experiencing issues."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Warning: We do not appear to fully agree with our peers! You may need to "
"upgrade, or other nodes may need to upgrade."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Warning: error reading wallet.dat! All keys read correctly, but transaction "
"data or address book entries might be missing or incorrect."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as "
"wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect "
"you should restore from a backup."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Whitelist peers connecting from the given netmask or IP address. Can be "
"specified multiple times."),
QT_TRANSLATE_NOOP("Openbit-core", ""
"Whitelisted peers cannot be DoS banned and their transactions are always "
"relayed, even if they are already in the mempool, useful e.g. for a gateway"),
QT_TRANSLATE_NOOP("Openbit-core", ""
"You must specify a masternodeprivkey in the configuration. Please see "
"documentation for help."),
QT_TRANSLATE_NOOP("Openbit-core", "(7091 could be used only on mainnet)"),
QT_TRANSLATE_NOOP("Openbit-core", "(default: %s)"),
QT_TRANSLATE_NOOP("Openbit-core", "(default: 1)"),
QT_TRANSLATE_NOOP("Openbit-core", "(must be 7091 for mainnet)"),
QT_TRANSLATE_NOOP("Openbit-core", "<category> can be:"),
QT_TRANSLATE_NOOP("Openbit-core", "Accept command line and JSON-RPC commands"),
QT_TRANSLATE_NOOP("Openbit-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"),
QT_TRANSLATE_NOOP("Openbit-core", "Accept public REST requests (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Acceptable ciphers (default: %s)"),
QT_TRANSLATE_NOOP("Openbit-core", "Add a node to connect to and attempt to keep the connection open"),
QT_TRANSLATE_NOOP("Openbit-core", "Allow DNS lookups for -addnode, -seednode and -connect"),
QT_TRANSLATE_NOOP("Openbit-core", "Already have that input."),
QT_TRANSLATE_NOOP("Openbit-core", "Always query for peer addresses via DNS lookup (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Attempt to force blockchain corruption recovery"),
QT_TRANSLATE_NOOP("Openbit-core", "Attempt to recover private keys from a corrupt wallet.dat"),
QT_TRANSLATE_NOOP("Openbit-core", "Automatically create Tor hidden service (default: %d)"),
QT_TRANSLATE_NOOP("Openbit-core", "Block creation options:"),
QT_TRANSLATE_NOOP("Openbit-core", "Calculating missing accumulators..."),
QT_TRANSLATE_NOOP("Openbit-core", "Can't denominate: no compatible inputs left."),
QT_TRANSLATE_NOOP("Openbit-core", "Can't find random Masternode."),
QT_TRANSLATE_NOOP("Openbit-core", "Can't mix while sync in progress."),
QT_TRANSLATE_NOOP("Openbit-core", "Cannot downgrade wallet"),
QT_TRANSLATE_NOOP("Openbit-core", "Cannot resolve -bind address: '%s'"),
QT_TRANSLATE_NOOP("Openbit-core", "Cannot resolve -externalip address: '%s'"),
QT_TRANSLATE_NOOP("Openbit-core", "Cannot resolve -whitebind address: '%s'"),
QT_TRANSLATE_NOOP("Openbit-core", "Cannot write default address"),
QT_TRANSLATE_NOOP("Openbit-core", "Collateral not valid."),
QT_TRANSLATE_NOOP("Openbit-core", "Connect only to the specified node(s)"),
QT_TRANSLATE_NOOP("Openbit-core", "Connect through SOCKS5 proxy"),
QT_TRANSLATE_NOOP("Openbit-core", "Connect to a node to retrieve peer addresses, and disconnect"),
QT_TRANSLATE_NOOP("Openbit-core", "Connection options:"),
QT_TRANSLATE_NOOP("Openbit-core", "Copyright (C) 2009-%i The Bitcoin Core Developers"),
QT_TRANSLATE_NOOP("Openbit-core", "Copyright (C) 2014-%i The Dash Core Developers"),
QT_TRANSLATE_NOOP("Openbit-core", "Copyright (C) 2015-%i The PIVX Core Developers"),
QT_TRANSLATE_NOOP("Openbit-core", "Copyright (C) 2017-%i The Openbit Core Developers"),
QT_TRANSLATE_NOOP("Openbit-core", "Corrupted block database detected"),
QT_TRANSLATE_NOOP("Openbit-core", "Could not parse -rpcbind value %s as network address"),
QT_TRANSLATE_NOOP("Openbit-core", "Could not parse masternode.conf"),
QT_TRANSLATE_NOOP("Openbit-core", "Debugging/Testing options:"),
QT_TRANSLATE_NOOP("Openbit-core", "Delete blockchain folders and resync from scratch"),
QT_TRANSLATE_NOOP("Openbit-core", "Disable OS notifications for incoming transactions (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Disable safemode, override a real safe mode event (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Discover own IP address (default: 1 when listening and no -externalip)"),
QT_TRANSLATE_NOOP("Openbit-core", "Display the stake modifier calculations in the debug.log file."),
QT_TRANSLATE_NOOP("Openbit-core", "Display verbose coin stake messages in the debug.log file."),
QT_TRANSLATE_NOOP("Openbit-core", "Do not load the wallet and disable wallet RPC calls"),
QT_TRANSLATE_NOOP("Openbit-core", "Do you want to rebuild the block database now?"),
QT_TRANSLATE_NOOP("Openbit-core", "Done loading"),
QT_TRANSLATE_NOOP("Openbit-core", "Enable automatic Zerocoin minting (0-1, default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Enable publish hash block in <address>"),
QT_TRANSLATE_NOOP("Openbit-core", "Enable publish hash transaction (locked via SwiftX) in <address>"),
QT_TRANSLATE_NOOP("Openbit-core", "Enable publish hash transaction in <address>"),
QT_TRANSLATE_NOOP("Openbit-core", "Enable publish raw block in <address>"),
QT_TRANSLATE_NOOP("Openbit-core", "Enable publish raw transaction (locked via SwiftX) in <address>"),
QT_TRANSLATE_NOOP("Openbit-core", "Enable publish raw transaction in <address>"),
QT_TRANSLATE_NOOP("Openbit-core", "Enable staking functionality (0-1, default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Enable the client to act as a masternode (0-1, default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Entries are full."),
QT_TRANSLATE_NOOP("Openbit-core", "Error connecting to Masternode."),
QT_TRANSLATE_NOOP("Openbit-core", "Error initializing block database"),
QT_TRANSLATE_NOOP("Openbit-core", "Error initializing wallet database environment %s!"),
QT_TRANSLATE_NOOP("Openbit-core", "Error loading block database"),
QT_TRANSLATE_NOOP("Openbit-core", "Error loading wallet.dat"),
QT_TRANSLATE_NOOP("Openbit-core", "Error loading wallet.dat: Wallet corrupted"),
QT_TRANSLATE_NOOP("Openbit-core", "Error loading wallet.dat: Wallet requires newer version of Openbit Core"),
QT_TRANSLATE_NOOP("Openbit-core", "Error opening block database"),
QT_TRANSLATE_NOOP("Openbit-core", "Error reading from database, shutting down."),
QT_TRANSLATE_NOOP("Openbit-core", "Error recovering public key."),
QT_TRANSLATE_NOOP("Openbit-core", "Error"),
QT_TRANSLATE_NOOP("Openbit-core", "Error: A fatal internal error occured, see debug.log for details"),
QT_TRANSLATE_NOOP("Openbit-core", "Error: Can't select current denominated inputs"),
QT_TRANSLATE_NOOP("Openbit-core", "Error: Disk space is low!"),
QT_TRANSLATE_NOOP("Openbit-core", "Error: Unsupported argument -tor found, use -onion."),
QT_TRANSLATE_NOOP("Openbit-core", "Error: Wallet locked, unable to create transaction!"),
QT_TRANSLATE_NOOP("Openbit-core", "Error: You already have pending entries in the Obfuscation pool"),
QT_TRANSLATE_NOOP("Openbit-core", "Failed to listen on any port. Use -listen=0 if you want this."),
QT_TRANSLATE_NOOP("Openbit-core", "Failed to read block index"),
QT_TRANSLATE_NOOP("Openbit-core", "Failed to read block"),
QT_TRANSLATE_NOOP("Openbit-core", "Failed to write block index"),
QT_TRANSLATE_NOOP("Openbit-core", "Fee (in OPN/kB) to add to transactions you send (default: %s)"),
QT_TRANSLATE_NOOP("Openbit-core", "Finalizing transaction."),
QT_TRANSLATE_NOOP("Openbit-core", "Force safe mode (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Found enough users, signing ( waiting %s )"),
QT_TRANSLATE_NOOP("Openbit-core", "Found enough users, signing ..."),
QT_TRANSLATE_NOOP("Openbit-core", "Generate coins (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "How many blocks to check at startup (default: %u, 0 = all)"),
QT_TRANSLATE_NOOP("Openbit-core", "If <category> is not supplied, output all debugging information."),
QT_TRANSLATE_NOOP("Openbit-core", "Importing..."),
QT_TRANSLATE_NOOP("Openbit-core", "Imports blocks from external blk000??.dat file"),
QT_TRANSLATE_NOOP("Openbit-core", "Include IP addresses in debug output (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Incompatible mode."),
QT_TRANSLATE_NOOP("Openbit-core", "Incompatible version."),
QT_TRANSLATE_NOOP("Openbit-core", "Incorrect or no genesis block found. Wrong datadir for network?"),
QT_TRANSLATE_NOOP("Openbit-core", "Information"),
QT_TRANSLATE_NOOP("Openbit-core", "Initialization sanity check failed. Openbit Core is shutting down."),
QT_TRANSLATE_NOOP("Openbit-core", "Input is not valid."),
QT_TRANSLATE_NOOP("Openbit-core", "Insufficient funds"),
QT_TRANSLATE_NOOP("Openbit-core", "Insufficient funds."),
QT_TRANSLATE_NOOP("Openbit-core", "Invalid -onion address or hostname: '%s'"),
QT_TRANSLATE_NOOP("Openbit-core", "Invalid -proxy address or hostname: '%s'"),
QT_TRANSLATE_NOOP("Openbit-core", "Invalid amount for -maxtxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("Openbit-core", "Invalid amount for -minrelaytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("Openbit-core", "Invalid amount for -mintxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("Openbit-core", "Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
QT_TRANSLATE_NOOP("Openbit-core", "Invalid amount for -paytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("Openbit-core", "Invalid amount for -reservebalance=<amount>"),
QT_TRANSLATE_NOOP("Openbit-core", "Invalid amount"),
QT_TRANSLATE_NOOP("Openbit-core", "Invalid masternodeprivkey. Please see documenation."),
QT_TRANSLATE_NOOP("Openbit-core", "Invalid netmask specified in -whitelist: '%s'"),
QT_TRANSLATE_NOOP("Openbit-core", "Invalid port detected in masternode.conf"),
QT_TRANSLATE_NOOP("Openbit-core", "Invalid private key."),
QT_TRANSLATE_NOOP("Openbit-core", "Invalid script detected."),
QT_TRANSLATE_NOOP("Openbit-core", "Keep at most <n> unconnectable transactions in memory (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Last Obfuscation was too recent."),
QT_TRANSLATE_NOOP("Openbit-core", "Last successful Obfuscation action was too recent."),
QT_TRANSLATE_NOOP("Openbit-core", "Less than 3 mints added, unable to create spend"),
QT_TRANSLATE_NOOP("Openbit-core", "Limit size of signature cache to <n> entries (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Line: %d"),
QT_TRANSLATE_NOOP("Openbit-core", "Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Listen for connections on <port> (default: %u or testnet: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Loading addresses..."),
QT_TRANSLATE_NOOP("Openbit-core", "Loading block index..."),
QT_TRANSLATE_NOOP("Openbit-core", "Loading budget cache..."),
QT_TRANSLATE_NOOP("Openbit-core", "Loading masternode cache..."),
QT_TRANSLATE_NOOP("Openbit-core", "Loading masternode payment cache..."),
QT_TRANSLATE_NOOP("Openbit-core", "Loading sporks..."),
QT_TRANSLATE_NOOP("Openbit-core", "Loading wallet... (%3.2f %%)"),
QT_TRANSLATE_NOOP("Openbit-core", "Loading wallet..."),
QT_TRANSLATE_NOOP("Openbit-core", "Lock is already in place."),
QT_TRANSLATE_NOOP("Openbit-core", "Lock masternodes from masternode configuration file (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Maintain at most <n> connections to peers (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Masternode options:"),
QT_TRANSLATE_NOOP("Openbit-core", "Masternode queue is full."),
QT_TRANSLATE_NOOP("Openbit-core", "Masternode:"),
QT_TRANSLATE_NOOP("Openbit-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Missing input transaction information."),
QT_TRANSLATE_NOOP("Openbit-core", "Mixing in progress..."),
QT_TRANSLATE_NOOP("Openbit-core", "Need to specify a port with -whitebind: '%s'"),
QT_TRANSLATE_NOOP("Openbit-core", "No Masternodes detected."),
QT_TRANSLATE_NOOP("Openbit-core", "No compatible Masternode found."),
QT_TRANSLATE_NOOP("Openbit-core", "No funds detected in need of denominating."),
QT_TRANSLATE_NOOP("Openbit-core", "No matching denominations found for mixing."),
QT_TRANSLATE_NOOP("Openbit-core", "Node relay options:"),
QT_TRANSLATE_NOOP("Openbit-core", "Non-standard public key detected."),
QT_TRANSLATE_NOOP("Openbit-core", "Not compatible with existing transactions."),
QT_TRANSLATE_NOOP("Openbit-core", "Not enough file descriptors available."),
QT_TRANSLATE_NOOP("Openbit-core", "Not in the Masternode list."),
QT_TRANSLATE_NOOP("Openbit-core", "Number of automatic wallet backups (default: 10)"),
QT_TRANSLATE_NOOP("Openbit-core", "Obfuscation is idle."),
QT_TRANSLATE_NOOP("Openbit-core", "Obfuscation request complete:"),
QT_TRANSLATE_NOOP("Openbit-core", "Obfuscation request incomplete:"),
QT_TRANSLATE_NOOP("Openbit-core", "Only accept block chain matching built-in checkpoints (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Only connect to nodes in network <net> (ipv4, ipv6 or onion)"),
QT_TRANSLATE_NOOP("Openbit-core", "Options:"),
QT_TRANSLATE_NOOP("Openbit-core", "Password for JSON-RPC connections"),
QT_TRANSLATE_NOOP("Openbit-core", "Percentage of automatically minted Zerocoin (10-100, default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Preparing for resync..."),
QT_TRANSLATE_NOOP("Openbit-core", "Prepend debug output with timestamp (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Print version and exit"),
QT_TRANSLATE_NOOP("Openbit-core", "RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)"),
QT_TRANSLATE_NOOP("Openbit-core", "RPC server options:"),
QT_TRANSLATE_NOOP("Openbit-core", "RPC support for HTTP persistent connections (default: %d)"),
QT_TRANSLATE_NOOP("Openbit-core", "Randomly drop 1 of every <n> network messages"),
QT_TRANSLATE_NOOP("Openbit-core", "Randomly fuzz 1 of every <n> network messages"),
QT_TRANSLATE_NOOP("Openbit-core", "Rebuild block chain index from current blk000??.dat files"),
QT_TRANSLATE_NOOP("Openbit-core", "Recalculating coin supply may take 30-60 minutes..."),
QT_TRANSLATE_NOOP("Openbit-core", "Recalculating supply statistics may take 30-60 minutes..."),
QT_TRANSLATE_NOOP("Openbit-core", "Receive and display P2P network alerts (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Relay and mine data carrier transactions (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Relay non-P2SH multisig (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Rescan the block chain for missing wallet transactions"),
QT_TRANSLATE_NOOP("Openbit-core", "Rescanning..."),
QT_TRANSLATE_NOOP("Openbit-core", "ResetMintZerocoin finished: "),
QT_TRANSLATE_NOOP("Openbit-core", "ResetSpentZerocoin finished: "),
QT_TRANSLATE_NOOP("Openbit-core", "Run a thread to flush wallet periodically (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Run in the background as a daemon and accept commands"),
QT_TRANSLATE_NOOP("Openbit-core", "Send transactions as zero-fee transactions if possible (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Server certificate file (default: %s)"),
QT_TRANSLATE_NOOP("Openbit-core", "Server private key (default: %s)"),
QT_TRANSLATE_NOOP("Openbit-core", "Session not complete!"),
QT_TRANSLATE_NOOP("Openbit-core", "Session timed out."),
QT_TRANSLATE_NOOP("Openbit-core", "Set database cache size in megabytes (%d to %d, default: %d)"),
QT_TRANSLATE_NOOP("Openbit-core", "Set external address:port to get to this masternode (example: %s)"),
QT_TRANSLATE_NOOP("Openbit-core", "Set key pool size to <n> (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Set maximum block size in bytes (default: %d)"),
QT_TRANSLATE_NOOP("Openbit-core", "Set minimum block size in bytes (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Set the Maximum reorg depth (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Set the masternode private key"),
QT_TRANSLATE_NOOP("Openbit-core", "Set the number of threads to service RPC calls (default: %d)"),
QT_TRANSLATE_NOOP("Openbit-core", "Sets the DB_PRIVATE flag in the wallet db environment (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Show all debugging options (usage: --help -help-debug)"),
QT_TRANSLATE_NOOP("Openbit-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"),
QT_TRANSLATE_NOOP("Openbit-core", "Signing failed."),
QT_TRANSLATE_NOOP("Openbit-core", "Signing timed out."),
QT_TRANSLATE_NOOP("Openbit-core", "Signing transaction failed"),
QT_TRANSLATE_NOOP("Openbit-core", "Specify configuration file (default: %s)"),
QT_TRANSLATE_NOOP("Openbit-core", "Specify connection timeout in milliseconds (minimum: 1, default: %d)"),
QT_TRANSLATE_NOOP("Openbit-core", "Specify data directory"),
QT_TRANSLATE_NOOP("Openbit-core", "Specify masternode configuration file (default: %s)"),
QT_TRANSLATE_NOOP("Openbit-core", "Specify pid file (default: %s)"),
QT_TRANSLATE_NOOP("Openbit-core", "Specify wallet file (within data directory)"),
QT_TRANSLATE_NOOP("Openbit-core", "Specify your own public address"),
QT_TRANSLATE_NOOP("Openbit-core", "Spend unconfirmed change when sending transactions (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Staking options:"),
QT_TRANSLATE_NOOP("Openbit-core", "Stop running after importing blocks from disk (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Submitted following entries to masternode: %u / %d"),
QT_TRANSLATE_NOOP("Openbit-core", "Submitted to masternode, waiting for more entries ( %u / %d ) %s"),
QT_TRANSLATE_NOOP("Openbit-core", "Submitted to masternode, waiting in queue %s"),
QT_TRANSLATE_NOOP("Openbit-core", "SwiftX options:"),
QT_TRANSLATE_NOOP("Openbit-core", "Synchronization failed"),
QT_TRANSLATE_NOOP("Openbit-core", "Synchronization finished"),
QT_TRANSLATE_NOOP("Openbit-core", "Synchronization pending..."),
QT_TRANSLATE_NOOP("Openbit-core", "Synchronizing budgets..."),
QT_TRANSLATE_NOOP("Openbit-core", "Synchronizing masternode winners..."),
QT_TRANSLATE_NOOP("Openbit-core", "Synchronizing masternodes..."),
QT_TRANSLATE_NOOP("Openbit-core", "Synchronizing sporks..."),
QT_TRANSLATE_NOOP("Openbit-core", "This help message"),
QT_TRANSLATE_NOOP("Openbit-core", "This is experimental software."),
QT_TRANSLATE_NOOP("Openbit-core", "This is intended for regression testing tools and app development."),
QT_TRANSLATE_NOOP("Openbit-core", "This is not a Masternode."),
QT_TRANSLATE_NOOP("Openbit-core", "Threshold for disconnecting misbehaving peers (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Tor control port password (default: empty)"),
QT_TRANSLATE_NOOP("Openbit-core", "Tor control port to use if onion listening enabled (default: %s)"),
QT_TRANSLATE_NOOP("Openbit-core", "Transaction amount too small"),
QT_TRANSLATE_NOOP("Openbit-core", "Transaction amounts must be positive"),
QT_TRANSLATE_NOOP("Openbit-core", "Transaction created successfully."),
QT_TRANSLATE_NOOP("Openbit-core", "Transaction fees are too high."),
QT_TRANSLATE_NOOP("Openbit-core", "Transaction not valid."),
QT_TRANSLATE_NOOP("Openbit-core", "Transaction too large for fee policy"),
QT_TRANSLATE_NOOP("Openbit-core", "Transaction too large"),
QT_TRANSLATE_NOOP("Openbit-core", "Transmitting final transaction."),
QT_TRANSLATE_NOOP("Openbit-core", "Unable to bind to %s on this computer (bind returned error %s)"),
QT_TRANSLATE_NOOP("Openbit-core", "Unable to sign spork message, wrong key?"),
QT_TRANSLATE_NOOP("Openbit-core", "Unknown network specified in -onlynet: '%s'"),
QT_TRANSLATE_NOOP("Openbit-core", "Unknown state: id = %u"),
QT_TRANSLATE_NOOP("Openbit-core", "Upgrade wallet to latest format"),
QT_TRANSLATE_NOOP("Openbit-core", "Use OpenSSL (https) for JSON-RPC connections"),
QT_TRANSLATE_NOOP("Openbit-core", "Use UPnP to map the listening port (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Use UPnP to map the listening port (default: 1 when listening)"),
QT_TRANSLATE_NOOP("Openbit-core", "Use a custom max chain reorganization depth (default: %u)"),
QT_TRANSLATE_NOOP("Openbit-core", "Use the test network"),
QT_TRANSLATE_NOOP("Openbit-core", "Username for JSON-RPC connections"),
QT_TRANSLATE_NOOP("Openbit-core", "Value more than Obfuscation pool maximum allows."),
QT_TRANSLATE_NOOP("Openbit-core", "Verifying blocks..."),
QT_TRANSLATE_NOOP("Openbit-core", "Verifying wallet..."),
QT_TRANSLATE_NOOP("Openbit-core", "Wallet %s resides outside data directory %s"),
QT_TRANSLATE_NOOP("Openbit-core", "Wallet is locked."),
QT_TRANSLATE_NOOP("Openbit-core", "Wallet needed to be rewritten: restart Openbit Core to complete"),
QT_TRANSLATE_NOOP("Openbit-core", "Wallet options:"),
QT_TRANSLATE_NOOP("Openbit-core", "Wallet window title"),
QT_TRANSLATE_NOOP("Openbit-core", "Warning"),
QT_TRANSLATE_NOOP("Openbit-core", "Warning: This version is obsolete, upgrade required!"),
QT_TRANSLATE_NOOP("Openbit-core", "Warning: Unsupported argument -benchmark ignored, use -debug=bench."),
QT_TRANSLATE_NOOP("Openbit-core", "Warning: Unsupported argument -debugnet ignored, use -debug=net."),
QT_TRANSLATE_NOOP("Openbit-core", "Will retry..."),
QT_TRANSLATE_NOOP("Openbit-core", "You need to rebuild the database using -reindex to change -txindex"),
QT_TRANSLATE_NOOP("Openbit-core", "Your entries added successfully."),
QT_TRANSLATE_NOOP("Openbit-core", "Your transaction was accepted into the pool!"),
QT_TRANSLATE_NOOP("Openbit-core", "Zapping all transactions from wallet..."),
QT_TRANSLATE_NOOP("Openbit-core", "ZeroMQ notification options:"),
QT_TRANSLATE_NOOP("Openbit-core", "Zerocoin options:"),
QT_TRANSLATE_NOOP("Openbit-core", "failed to validate zerocoin"),
QT_TRANSLATE_NOOP("Openbit-core", "on startup"),
QT_TRANSLATE_NOOP("Openbit-core", "wallet.dat corrupt, salvage failed"),
};
| [
"info@openbit.online"
] | info@openbit.online |
d0706464dcf874ce5556bcb6a154a1724a730f63 | 39037d6530eaa1963458c4c5bec4f9e41f201b0c | /common/include/ustl/ualgo.h | c56dde712ac49d529aa88a6f43b0aca501bd61ad | [] | no_license | stefan2904/sweb | 4ad768c3bc7d75e5f5ba46af8e852ed7b73bc9fd | 8cda2eb0c7f86ac488d638513aa1f6255b3691a0 | refs/heads/master | 2021-01-18T15:35:36.919534 | 2015-01-31T15:40:35 | 2015-01-31T15:40:35 | 30,116,361 | 0 | 0 | null | 2015-01-31T15:33:21 | 2015-01-31T15:33:21 | null | UTF-8 | C++ | false | false | 25,623 | h | // This file is part of the uSTL library, an STL implementation.
//
// Copyright (c) 2005 by Mike Sharov <msharov@users.sourceforge.net>
// This file is free software, distributed under the MIT License.
#ifndef UALGO_H_711AB4214D417A51166694D47A662D6E
#define UALGO_H_711AB4214D417A51166694D47A662D6E
#include "upair.h"
#include "ualgobase.h"
#include "ufunction.h"
#include "umemory.h"
//#include <stdlib.h> // for rand()
namespace ustl {
/// Swaps corresponding elements of [first, last) and [result,)
/// \ingroup SwapAlgorithms
///
template <typename ForwardIterator1, typename ForwardIterator2>
inline ForwardIterator2 swap_ranges (ForwardIterator1 first, ForwardIterator2 last, ForwardIterator2 result)
{
for (; first != last; ++first, ++result)
iter_swap (first, result);
return (result);
}
/// Returns the first iterator i in the range [first, last) such that
/// *i == value. Returns last if no such iterator exists.
/// \ingroup SearchingAlgorithms
///
template <typename InputIterator, typename EqualityComparable>
inline InputIterator find (InputIterator first, InputIterator last, const EqualityComparable& value)
{
while (first != last && !(*first == value))
++ first;
return (first);
}
/// Returns the first iterator such that *i == *(i + 1)
/// \ingroup SearchingAlgorithms
///
template <typename ForwardIterator>
ForwardIterator adjacent_find (ForwardIterator first, ForwardIterator last)
{
if (first != last)
for (ForwardIterator prev = first; ++first != last; ++ prev)
if (*prev == *first)
return (prev);
return (last);
}
/// Returns the pointer to the first pair of unequal elements.
/// \ingroup SearchingAlgorithms
///
template <typename InputIterator>
pair<InputIterator,InputIterator>
mismatch (InputIterator first1, InputIterator last1, InputIterator first2)
{
while (first1 != last1 && *first1 == *first2)
++ first1, ++ first2;
return (make_pair (first1, first2));
}
/// \brief Returns true if two ranges are equal.
/// This is an extension, present in uSTL and SGI STL.
/// \ingroup SearchingAlgorithms
///
template <typename InputIterator>
inline bool equal (InputIterator first1, InputIterator last1, InputIterator first2)
{
return (mismatch (first1, last1, first2).first == last1);
}
/// Count finds the number of elements in [first, last) that are equal
/// to value. More precisely, the first version of count returns the
/// number of iterators i in [first, last) such that *i == value.
/// \ingroup SearchingAlgorithms
///
template <typename InputIterator, typename EqualityComparable>
inline size_t count (InputIterator first, InputIterator last, const EqualityComparable& value)
{
size_t total = 0;
for (; first != last; ++first)
if (*first == value)
++ total;
return (total);
}
///
/// The first version of transform performs the operation op(*i) for each
/// iterator i in the range [first, last), and assigns the result of that
/// operation to *o, where o is the corresponding output iterator. That is,
/// for each n such that 0 <= n < last - first, it performs the assignment
/// *(result + n) = op(*(first + n)).
/// The return value is result + (last - first).
/// \ingroup MutatingAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename InputIterator, typename OutputIterator, typename UnaryFunction>
inline OutputIterator transform (InputIterator first, InputIterator last, OutputIterator result, UnaryFunction op)
{
for (; first != last; ++result, ++first)
*result = op (*first);
return (result);
}
///
/// The second version of transform is very similar, except that it uses a
/// Binary Function instead of a Unary Function: it performs the operation
/// op(*i1, *i2) for each iterator i1 in the range [first1, last1) and assigns
/// the result to *o, where i2 is the corresponding iterator in the second
/// input range and where o is the corresponding output iterator. That is,
/// for each n such that 0 <= n < last1 - first1, it performs the assignment
/// *(result + n) = op(*(first1 + n), *(first2 + n).
/// The return value is result + (last1 - first1).
/// \ingroup MutatingAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename InputIterator1, typename InputIterator2, typename OutputIterator, typename BinaryFunction>
inline OutputIterator transform (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, OutputIterator result, BinaryFunction op)
{
for (; first1 != last1; ++result, ++first1, ++first2)
*result = op (*first1, *first2);
return (result);
}
/// Replace replaces every element in the range [first, last) equal to
/// old_value with new_value. That is: for every iterator i,
/// if *i == old_value then it performs the assignment *i = new_value.
/// \ingroup MutatingAlgorithms
///
template <typename ForwardIterator, typename T>
inline void replace (ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value)
{
for (; first != last; ++first)
if (*first == old_value)
*first = new_value;
}
/// Replace_copy copies elements from the range [first, last) to the range
/// [result, result + (last-first)), except that any element equal to old_value
/// is not copied; new_value is copied instead. More precisely, for every
/// integer n such that 0 <= n < last-first, replace_copy performs the
/// assignment *(result+n) = new_value if *(first+n) == old_value, and
/// *(result+n) = *(first+n) otherwise.
/// \ingroup MutatingAlgorithms
///
template <typename InputIterator, typename OutputIterator, typename T>
inline OutputIterator replace_copy (InputIterator first, InputIterator last, OutputIterator result, const T& old_value, const T& new_value)
{
for (; first != last; ++result, ++first)
*result = (*first == old_value) ? new_value : *first;
}
/// Generate assigns the result of invoking gen, a function object that
/// takes no arguments, to each element in the range [first, last).
/// \ingroup GeneratorAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename ForwardIterator, typename Generator>
inline void generate (ForwardIterator first, ForwardIterator last, Generator gen)
{
for (; first != last; ++first)
*first = gen();
}
/// Generate_n assigns the result of invoking gen, a function object that
/// takes no arguments, to each element in the range [first, first+n).
/// The return value is first + n.
/// \ingroup GeneratorAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename OutputIterator, typename Generator>
inline OutputIterator generate_n (OutputIterator first, size_t n, Generator gen)
{
for (uoff_t i = 0; i != n; ++i, ++first)
*first = gen();
return (first);
}
/// \brief Reverse reverses a range.
/// That is: for every i such that 0 <= i <= (last - first) / 2),
/// it exchanges *(first + i) and *(last - (i + 1)).
/// \ingroup MutatingAlgorithms
///
template <typename BidirectionalIterator>
inline void reverse (BidirectionalIterator first, BidirectionalIterator last)
{
for (; distance (first, --last) > 0; ++first)
iter_swap (first, last);
}
/// \brief Reverses [first,last) and writes it to \p output.
/// \ingroup MutatingAlgorithms
///
template <typename BidirectionalIterator, typename OutputIterator>
inline OutputIterator reverse_copy (BidirectionalIterator first, BidirectionalIterator last, OutputIterator result)
{
for (; first != last; ++result)
*result = *--last;
return (result);
}
/// \brief Exchanges ranges [first, middle) and [middle, last)
/// \ingroup MutatingAlgorithms
///
template <typename ForwardIterator>
ForwardIterator rotate (ForwardIterator first, ForwardIterator middle, ForwardIterator last)
{
if (first == middle || middle == last)
return (first);
reverse (first, middle);
reverse (middle, last);
for (;first != middle && middle != last; ++first)
iter_swap (first, --last);
reverse (first, (first == middle ? last : middle));
return (first);
}
/// Specialization for pointers, which can be treated identically.
template <typename T>
inline T* rotate (T* first, T* middle, T* last)
{
rotate_fast (first, middle, last);
return (first);
}
/// \brief Exchanges ranges [first, middle) and [middle, last) into \p result.
/// \ingroup MutatingAlgorithms
///
template <typename ForwardIterator, typename OutputIterator>
inline OutputIterator rotate_copy (ForwardIterator first, ForwardIterator middle, ForwardIterator last, OutputIterator result)
{
return (copy (first, middle, copy (middle, last, result)));
}
/// \brief Combines two sorted ranges.
/// \ingroup SortingAlgorithms
///
template <typename InputIterator1, typename InputIterator2, typename OutputIterator>
OutputIterator merge (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2, OutputIterator result)
{
for (; first1 != last1 && first2 != last2; ++result) {
if (*first1 < *first2)
*result = *first1++;
else
*result = *first2++;
}
if (first1 < last1)
return (copy (first1, last1, result));
else
return (copy (first2, last2, result));
}
/// Combines two sorted ranges from the same container.
/// \ingroup SortingAlgorithms
///
template <typename InputIterator>
void inplace_merge (InputIterator first, InputIterator middle, InputIterator last)
{
for (; middle != last; ++first) {
while (*first < *middle)
++ first;
reverse (first, middle);
reverse (first, ++middle);
}
}
/// Remove_copy copies elements that are not equal to value from the range
/// [first, last) to a range beginning at result. The return value is the
/// end of the resulting range. This operation is stable, meaning that the
/// relative order of the elements that are copied is the same as in the
/// range [first, last).
/// \ingroup MutatingAlgorithms
///
template <typename InputIterator, typename OutputIterator, typename T>
OutputIterator remove_copy (InputIterator first, InputIterator last, OutputIterator result, const T& value)
{
for (; first != last; ++first) {
if (!(*first == value)) {
*result = *first;
++ result;
}
}
return (result);
}
/// Remove_copy copies elements pointed to by iterators in [rfirst, rlast)
/// from the range [first, last) to a range beginning at result. The return
/// value is the end of the resulting range. This operation is stable, meaning
/// that the relative order of the elements that are copied is the same as in the
/// range [first, last). Range [rfirst, rlast) is assumed to be sorted.
/// This algorithm is a uSTL extension.
/// \ingroup MutatingAlgorithms
///
template <typename InputIterator, typename OutputIterator, typename RInputIterator>
OutputIterator remove_copy (InputIterator first, InputIterator last, OutputIterator result, RInputIterator rfirst, RInputIterator rlast)
{
for (; first != last; ++first) {
while (rfirst != rlast && *rfirst < first)
++ rfirst;
if (rfirst == rlast || first != *rfirst) {
*result = *first;
++ result;
}
}
return (result);
}
/// Remove removes from the range [first, last) all elements that are equal to
/// value. That is, remove returns an iterator new_last such that the range
/// [first, new_last) contains no elements equal to value. [1] The iterators
/// in the range [new_last, last) are all still dereferenceable, but the
/// elements that they point to are unspecified. Remove is stable, meaning
/// that the relative order of elements that are not equal to value is
/// unchanged.
/// \ingroup MutatingAlgorithms
///
template <typename ForwardIterator, typename T>
inline ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& value)
{
return (remove_copy (first, last, first, value));
}
/// Unique_copy copies elements from the range [first, last) to a range
/// beginning with result, except that in a consecutive group of duplicate
/// elements only the first one is copied. The return value is the end of
/// the range to which the elements are copied. This behavior is similar
/// to the Unix filter uniq.
/// \ingroup MutatingAlgorithms
///
template <typename InputIterator, typename OutputIterator>
OutputIterator unique_copy (InputIterator first, InputIterator last, OutputIterator result)
{
if (first != last) {
*result = *first;
while (++first != last)
if (!(*first == *result))
*++result = *first;
++ result;
}
return (result);
}
/// Every time a consecutive group of duplicate elements appears in the range
/// [first, last), the algorithm unique removes all but the first element.
/// That is, unique returns an iterator new_last such that the range [first,
/// new_last) contains no two consecutive elements that are duplicates.
/// The iterators in the range [new_last, last) are all still dereferenceable,
/// but the elements that they point to are unspecified. Unique is stable,
/// meaning that the relative order of elements that are not removed is
/// unchanged.
/// \ingroup MutatingAlgorithms
///
template <typename ForwardIterator>
inline ForwardIterator unique (ForwardIterator first, ForwardIterator last)
{
return (unique_copy (first, last, first));
}
/// Returns the furthermost iterator i in [first, last) such that,
/// for every iterator j in [first, i), *j < value
/// Assumes the range is sorted.
/// \ingroup SearchingAlgorithms
///
template <typename ForwardIterator, typename LessThanComparable>
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const LessThanComparable& value)
{
ForwardIterator mid;
while (first != last) {
mid = advance (first, distance (first,last) / 2);
if (*mid < value)
first = mid + 1;
else
last = mid;
}
return (first);
}
/// Performs a binary search inside the sorted range.
/// \ingroup SearchingAlgorithms
///
template <typename ForwardIterator, typename LessThanComparable>
inline bool binary_search (ForwardIterator first, ForwardIterator last, const LessThanComparable& value)
{
ForwardIterator found = lower_bound (first, last, value);
return (found != last && !(value < *found));
}
/// Returns the furthermost iterator i in [first,last) such that for
/// every iterator j in [first,i), value < *j is false.
/// \ingroup SearchingAlgorithms
///
template <typename ForwardIterator, typename LessThanComparable>
ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last, const LessThanComparable& value)
{
ForwardIterator mid;
while (first != last) {
mid = advance (first, distance (first,last) / 2);
if (value < *mid)
last = mid;
else
first = mid + 1;
}
return (last);
}
/// Returns pair<lower_bound,upper_bound>
/// \ingroup SearchingAlgorithms
///
template <typename ForwardIterator, typename LessThanComparable>
inline pair<ForwardIterator,ForwardIterator> equal_range (ForwardIterator first, ForwardIterator last, const LessThanComparable& value)
{
pair<ForwardIterator,ForwardIterator> rv;
rv.second = rv.first = lower_bound (first, last, value);
while (rv.second != last && !(value < *(rv.second)))
++ rv.second;
return (rv);
}
/// Randomly permute the elements of the container.
/// \ingroup GeneratorAlgorithms
///
/*
template <typename RandomAccessIterator>
void random_shuffle (RandomAccessIterator first, RandomAccessIterator last)
{
for (; first != last; ++ first)
iter_swap (first, first + (rand() % distance (first, last)));
}
*/
/// \brief Generic compare function adaptor to pass to qsort
/// \ingroup FunctorObjects
template <typename ConstPointer, typename Compare>
int qsort_adapter (const void* p1, const void* p2)
{
ConstPointer i1 = reinterpret_cast<ConstPointer>(p1);
ConstPointer i2 = reinterpret_cast<ConstPointer>(p2);
Compare comp;
return (comp (*i1, *i2) ? -1 : (comp (*i2, *i1) ? 1 : 0));
}
/// Sorts the container
/// \ingroup SortingAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename RandomAccessIterator, typename Compare>
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare)
{
typedef typename iterator_traits<RandomAccessIterator>::value_type value_type;
typedef typename iterator_traits<RandomAccessIterator>::const_pointer const_pointer;
qsort (first, distance (first, last), sizeof(value_type),
&qsort_adapter<const_pointer, Compare>);
}
/// Sorts the container
/// \ingroup SortingAlgorithms
///
template <typename RandomAccessIterator>
inline void sort (RandomAccessIterator first, RandomAccessIterator last)
{
typedef typename iterator_traits<RandomAccessIterator>::value_type value_type;
sort (first, last, less<value_type>());
}
/// Sorts the container preserving order of equal elements.
/// \ingroup SortingAlgorithms
/// \ingroup PredicateAlgorithms
///
template <typename RandomAccessIterator, typename Compare>
void stable_sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp)
{
for (RandomAccessIterator j, i = first; ++i < last;) { // Insertion sort
for (j = i; j-- > first && comp(*i, *j);) ;
if (++j != i) rotate (j, i, i + 1);
}
}
/// Sorts the container
/// \ingroup SortingAlgorithms
///
template <typename RandomAccessIterator>
inline void stable_sort (RandomAccessIterator first, RandomAccessIterator last)
{
typedef typename iterator_traits<RandomAccessIterator>::value_type value_type;
stable_sort (first, last, less<value_type>());
}
/// \brief Searches for the first subsequence [first2,last2) in [first1,last1)
/// \ingroup SearchingAlgorithms
template <typename ForwardIterator1, typename ForwardIterator2>
inline ForwardIterator1 search (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2)
{
typedef typename iterator_traits<ForwardIterator1>::value_type value_type;
return (search (first1, last1, first2, last2, equal_to<value_type>()));
}
/// \brief Searches for the last subsequence [first2,last2) in [first1,last1)
/// \ingroup SearchingAlgorithms
template <typename ForwardIterator1, typename ForwardIterator2>
inline ForwardIterator1 find_end (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2)
{
typedef typename iterator_traits<ForwardIterator1>::value_type value_type;
return (find_end (first1, last1, first2, last2, equal_to<value_type>()));
}
/// \brief Searches for the first occurence of \p count \p values in [first, last)
/// \ingroup SearchingAlgorithms
template <typename Iterator, typename T>
inline Iterator search_n (Iterator first, Iterator last, size_t count, const T& value)
{
typedef typename iterator_traits<Iterator>::value_type value_type;
return (search_n (first, last, count, value, equal_to<value_type>()));
}
/// \brief Searches [first1,last1) for the first occurrence of an element from [first2,last2)
/// \ingroup SearchingAlgorithms
template <typename InputIterator, typename ForwardIterator>
inline InputIterator find_first_of (InputIterator first1, InputIterator last1, ForwardIterator first2, ForwardIterator last2)
{
typedef typename iterator_traits<InputIterator>::value_type value_type;
return (find_first_of (first1, last1, first2, last2, equal_to<value_type>()));
}
/// \brief Returns true if [first2,last2) is a subset of [first1,last1)
/// \ingroup ConditionAlgorithms
/// \ingroup SetAlgorithms
template <typename InputIterator1, typename InputIterator2>
inline bool includes (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2)
{
typedef typename iterator_traits<InputIterator1>::value_type value_type;
return (includes (first1, last1, first2, last2, less<value_type>()));
}
/// \brief Merges [first1,last1) with [first2,last2)
///
/// Result will contain every element that is in either set. If duplicate
/// elements are present, max(n,m) is placed in the result.
///
/// \ingroup SetAlgorithms
template <typename InputIterator1, typename InputIterator2, typename OutputIterator>
inline OutputIterator set_union (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result)
{
typedef typename iterator_traits<InputIterator1>::value_type value_type;
return (set_union (first1, last1, first2, last2, result, less<value_type>()));
}
/// \brief Creates a set containing elements shared by the given ranges.
/// \ingroup SetAlgorithms
template <typename InputIterator1, typename InputIterator2, typename OutputIterator>
inline OutputIterator set_intersection (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result)
{
typedef typename iterator_traits<InputIterator1>::value_type value_type;
return (set_intersection (first1, last1, first2, last2, result, less<value_type>()));
}
/// \brief Removes from [first1,last1) elements present in [first2,last2)
/// \ingroup SetAlgorithms
template <typename InputIterator1, typename InputIterator2, typename OutputIterator>
inline OutputIterator set_difference (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result)
{
typedef typename iterator_traits<InputIterator1>::value_type value_type;
return (set_difference (first1, last1, first2, last2, result, less<value_type>()));
}
/// \brief Performs union of sets A-B and B-A.
/// \ingroup SetAlgorithms
template <typename InputIterator1, typename InputIterator2, typename OutputIterator>
inline OutputIterator set_symmetric_difference (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result)
{
typedef typename iterator_traits<InputIterator1>::value_type value_type;
return (set_symmetric_difference (first1, last1, first2, last2, result, less<value_type>()));
}
/// \brief Returns true if the given range is sorted.
/// \ingroup ConditionAlgorithms
template <typename ForwardIterator>
inline bool is_sorted (ForwardIterator first, ForwardIterator last)
{
typedef typename iterator_traits<ForwardIterator>::value_type value_type;
return (is_sorted (first, last, less<value_type>()));
}
/// \brief Compares two given containers like strcmp compares strings.
/// \ingroup ConditionAlgorithms
template <typename InputIterator1, typename InputIterator2>
inline bool lexicographical_compare (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2)
{
typedef typename iterator_traits<InputIterator1>::value_type value_type;
return (lexicographical_compare (first1, last1, first2, last2, less<value_type>()));
}
/// \brief Creates the next lexicographical permutation of [first,last).
/// Returns false if no further permutations can be created.
/// \ingroup GeneratorAlgorithms
template <typename BidirectionalIterator>
inline bool next_permutation (BidirectionalIterator first, BidirectionalIterator last)
{
typedef typename iterator_traits<BidirectionalIterator>::value_type value_type;
return (next_permutation (first, last, less<value_type>()));
}
/// \brief Creates the previous lexicographical permutation of [first,last).
/// Returns false if no further permutations can be created.
/// \ingroup GeneratorAlgorithms
template <typename BidirectionalIterator>
inline bool prev_permutation (BidirectionalIterator first, BidirectionalIterator last)
{
typedef typename iterator_traits<BidirectionalIterator>::value_type value_type;
return (prev_permutation (first, last, less<value_type>()));
}
/// \brief Returns iterator to the max element in [first,last)
/// \ingroup SearchingAlgorithms
template <typename ForwardIterator>
inline ForwardIterator max_element (ForwardIterator first, ForwardIterator last)
{
typedef typename iterator_traits<ForwardIterator>::value_type value_type;
return (max_element (first, last, less<value_type>()));
}
/// \brief Returns iterator to the min element in [first,last)
/// \ingroup SearchingAlgorithms
template <typename ForwardIterator>
inline ForwardIterator min_element (ForwardIterator first, ForwardIterator last)
{
typedef typename iterator_traits<ForwardIterator>::value_type value_type;
return (min_element (first, last, less<value_type>()));
}
/// \brief Makes [first,middle) a part of the sorted array.
/// Contents of [middle,last) is undefined. This implementation just calls stable_sort.
/// \ingroup SortingAlgorithms
template <typename RandomAccessIterator>
inline void partial_sort (RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last)
{
typedef typename iterator_traits<RandomAccessIterator>::value_type value_type;
partial_sort (first, middle, last, less<value_type>());
}
/// \brief Puts \p nth element into its sorted position.
/// In this implementation, the entire array is sorted. I can't think of any
/// use for it where the time gained would be useful.
/// \ingroup SortingAlgorithms
/// \ingroup SearchingAlgorithms
///
template <typename RandomAccessIterator>
inline void nth_element (RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last)
{
partial_sort (first, nth, last);
}
/// \brief Like partial_sort, but outputs to [result_first,result_last)
/// \ingroup SortingAlgorithms
template <typename InputIterator, typename RandomAccessIterator>
inline RandomAccessIterator partial_sort_copy (InputIterator first, InputIterator last, RandomAccessIterator result_first, RandomAccessIterator result_last)
{
typedef typename iterator_traits<InputIterator>::value_type value_type;
return (partial_sort_copy (first, last, result_first, result_last, less<value_type>()));
}
} // namespace ustl
#endif
| [
"gruss@student.tugraz.at"
] | gruss@student.tugraz.at |
27564d531c6ad41af085a6bd0393c9e44f798403 | 082f8c3ce5e9d162726a066788746245831f5c57 | /ViewSynLibStatic/src/ViewInterpolation.cpp | 177cf0528667bb6369d6689b78f2c27c581aad17 | [] | no_license | Songminkee/VSRS15_float | 2bb7cb61c390e93a7333f2b4d50db0e7308e7a80 | 5e2ff5ad06e893ff032b3118126a5a10c08198e5 | refs/heads/master | 2020-08-06T01:24:35.678456 | 2019-10-04T10:15:38 | 2019-10-04T10:15:38 | 212,783,801 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,265 | cpp |
#ifdef WIN32
#pragma warning(disable : 4996)
#endif
#include "yuv.h"
#include "ParameterViewInterpolation.h"
#include "ViewSynthesis.h"
#include "Visbd.h"
#include "BounaryNoiseRemoval.h"
#include "ViewInterpolation.h"
#ifndef SAFE_RELEASE_IMAGE
#define SAFE_RELEASE_IMAGE(p) { if((p)!=NULL){ cvReleaseImage(&(p)); (p)=NULL; } }
#endif
CViewInterpolation::CViewInterpolation()
{
m_pViewSynthesisGeneral = NULL;
m_pViewSynthesis1D = NULL;
m_pcDepthMapLeft = m_pcDepthMapRight = NULL;
m_pcImageLeft = m_pcImageRight = NULL;
m_pcTempYuvLeft = m_pcTempYuvRight = NULL;
m_pSynColorLeft = NULL;
m_pSynColorRight = NULL;
m_pSynDepthLeft = NULL;
m_pSynDepthRight = NULL;
m_iFrameNumber = 0; //Zhejiang
#ifdef _DEBUG
m_ucSetup = 0;
#endif
}
CViewInterpolation::~CViewInterpolation()
{
if(m_pViewSynthesisGeneral!=NULL) delete m_pViewSynthesisGeneral;
if(m_pViewSynthesis1D!=NULL) delete m_pViewSynthesis1D;
if(m_pcDepthMapLeft!=NULL) delete m_pcDepthMapLeft;
if(m_pcDepthMapRight!=NULL) delete m_pcDepthMapRight;
if(m_pcImageLeft!=m_pcTempYuvLeft && m_pcTempYuvLeft!=NULL) delete m_pcTempYuvLeft;
if(m_pcImageRight!=m_pcTempYuvRight && m_pcTempYuvRight!=NULL) delete m_pcTempYuvRight;
if(m_pcImageLeft!=NULL) delete m_pcImageLeft;
if(m_pcImageRight!=NULL) delete m_pcImageRight;
if(m_pSynColorLeft !=NULL) free( m_pSynColorLeft );
if(m_pSynColorRight!=NULL) free( m_pSynColorRight);
if(m_pSynDepthLeft !=NULL) free( m_pSynDepthLeft );
if(m_pSynDepthRight!=NULL) free( m_pSynDepthRight );
m_pcDepthMapLeft = m_pcDepthMapRight = NULL;
m_pcImageLeft = m_pcImageRight = NULL;
m_pcTempYuvLeft = m_pcTempYuvRight = NULL;
m_pSynColorLeft = NULL;
m_pSynColorRight = NULL;
m_pSynDepthLeft = NULL;
m_pSynDepthRight = NULL;
#ifdef _DEBUG
m_ucSetup = 0;
#endif
}
bool CViewInterpolation::Init(CParameterViewInterpolation &cParameter)
{
int iWidth, iHeight;
m_iSynthesisMode = cParameter.getSynthesisMode(); // 0
//std::cout << "m_iSynthesisMode" << m_iSynthesisMode << std::endl;
m_uiBoundary = cParameter.getBoundaryNoiseRemoval(); // 0
//std::cout << "m_uiBoundary" << m_uiBoundary << std::endl;
m_uiColorSpace = cParameter.getColorSpace(); // 0
//std::cout << "m_uiColorSpace" << m_uiColorSpace << std::endl;
m_uiViewBlending = cParameter.getViewBlending(); // 0
//std::cout << "m_uiViewBlending" << m_uiViewBlending << std::endl;
if (m_iSynthesisMode == 0) // General mode
{
m_pViewSynthesisGeneral = new CViewInterpolationGeneral();
m_pViewSynthesisGeneral->SetWidth(cParameter.getSourceWidth()); // 1024
std::cout << "Width = "<<cParameter.getSourceWidth() << std::endl;
m_pViewSynthesisGeneral->SetHeight(cParameter.getSourceHeight()); // 768
std::cout << "Height = " << cParameter.getSourceHeight() << std::endl;
m_pViewSynthesisGeneral->SetDepthType(cParameter.getDepthType()); // 0
std::cout << "DepthType = " << cParameter.getDepthType() << std::endl;
m_pViewSynthesisGeneral->SetColorSpace(cParameter.getColorSpace()); // 0
std::cout << "ColorSpace = " << cParameter.getColorSpace() << std::endl;
m_pViewSynthesisGeneral->SetSubPelOption(cParameter.getPrecision()); // 2
std::cout << "Precision = " << cParameter.getPrecision() << std::endl;
m_pViewSynthesisGeneral->SetViewBlending(cParameter.getViewBlending()); // 0
std::cout << "ViewBlending = " << cParameter.getViewBlending() << std::endl;
m_pViewSynthesisGeneral->SetBoundaryNoiseRemoval(cParameter.getBoundaryNoiseRemoval()); // 0
std::cout << "BoundaryNoiseRemoval = " << cParameter.getBoundaryNoiseRemoval() << std::endl;
#ifdef POZNAN_DEPTH_BLEND
m_pViewSynthesisGeneral->SetDepthBlendDiff(cParameter.getDepthBlendDiff()); // 5
std::cout << "DepthBlendDiff = " << cParameter.getDepthBlendDiff() << std::endl;
#endif
#ifdef NICT_IVSRS
// NICT start
m_pViewSynthesisGeneral->SetIvsrsInpaint(cParameter.getIvsrsInpaint()); // 1
std::cout << "getIvsrsInpaint = " << cParameter.getIvsrsInpaint() << std::endl;
// NICT end
#endif
if(!m_pViewSynthesisGeneral->InitLR(cParameter.getSourceWidth(), cParameter.getSourceHeight(),
cParameter.getPrecision(), cParameter.getDepthType(),
cParameter.getLeftNearestDepthValue(), cParameter.getLeftFarthestDepthValue(),
cParameter.getRightNearestDepthValue(), cParameter.getRightFarthestDepthValue(),
cParameter.getCameraParameterFile().c_str(),
cParameter.getLeftCameraName().c_str(), cParameter.getRightCameraName().c_str(),
cParameter.getVirtualCameraName().c_str(),
cParameter.getMat_In_Left(), cParameter.getMat_Ex_Left(), cParameter.getMat_Trans_Left(),
cParameter.getMat_In_Right(), cParameter.getMat_Ex_Right(), cParameter.getMat_Trans_Right(),
cParameter.getMat_In_Virtual(), cParameter.getMat_Ex_Virtual(), cParameter.getMat_Trans_Virtual()
)) return false;
}
else // 1D mode
{
m_pViewSynthesis1D = new CViewInterpolation1D();
m_pViewSynthesis1D->SetFocalLength(cParameter.getFocalLength());
m_pViewSynthesis1D->SetLTranslationLeft(cParameter.getLTranslationLeft());
m_pViewSynthesis1D->SetLTranslationRight(cParameter.getLTranslationRight());
m_pViewSynthesis1D->SetduPrincipalLeft(cParameter.getduPrincipalLeft());
m_pViewSynthesis1D->SetduPrincipalRight(cParameter.getduPrincipalRight());
m_pViewSynthesis1D->SetZnearL(cParameter.getLeftNearestDepthValue());
m_pViewSynthesis1D->SetZfarL (cParameter.getLeftFarthestDepthValue());
m_pViewSynthesis1D->SetZnearR(cParameter.getRightNearestDepthValue());
m_pViewSynthesis1D->SetZfarR (cParameter.getRightFarthestDepthValue());
m_pViewSynthesis1D->SetWidth(cParameter.getSourceWidth());
m_pViewSynthesis1D->SetHeight(cParameter.getSourceHeight());
m_pViewSynthesis1D->SetSubPelOption(cParameter.getPrecision()); // Modify ViSBD how to set subpel
m_pViewSynthesis1D->SetSplattingOption(cParameter.getSplattingOption());
m_pViewSynthesis1D->SetBoundaryGrowth(cParameter.getBoudaryGrowth());
//m_pViewSynthesis1D->SetUpsampleRefs(cParameter.getUpsampleRefs()); // Remove it
m_pViewSynthesis1D->SetMergingOption(cParameter.getMergingOption());
m_pViewSynthesis1D->SetDepthThreshold(cParameter.getDepthThreshold());
m_pViewSynthesis1D->SetHoleCountThreshold(cParameter.getHoleCountThreshold());
m_pViewSynthesis1D->SetTemporalImprovementOption(cParameter.getTemporalImprovementOption()); //Zhejiang, May, 4
m_pViewSynthesis1D->SetWarpEnhancementOption(cParameter.getWarpEnhancementOption());
m_pViewSynthesis1D->SetCleanNoiseOption(cParameter.getCleanNoiseOption());
m_pViewSynthesis1D->AllocMem();
}
if (m_uiBoundary && cParameter.getSplattingOption() != 1 && m_iSynthesisMode == 1) {
if (getBoundaryNoiseRemoval()) {
if (m_pViewSynthesis1D->GetSplattingOption() != 1) {
printf("\nWarning: When you use 1D Mode, 'Boundary Noise Removal' mode supports only \n");
printf(" only 'SplattingOption = 1'.\n");
printf(" Hence, 'SplattingOption' is changed to '1'.\n\n");
m_pViewSynthesis1D->SetSplattingOption(1);
}
}
}
m_pBoundaryNoiseRemoval = new CBoundaryNoiseRemoval(); // Boundary Noise Removal
iWidth = int( cParameter.getSourceWidth() );
iHeight = int( cParameter.getSourceHeight() );
std::cout << "iWidth--------" << iWidth << std::endl;
std::cout << "iHeight--------" << iHeight << std::endl;
m_pcDepthMapLeft = new CIYuv<DepthType>(iHeight, iWidth, POZNAN_DEPTHMAP_CHROMA_FORMAT);
m_pcDepthMapRight = new CIYuv<DepthType>(iHeight, iWidth, POZNAN_DEPTHMAP_CHROMA_FORMAT);
if (m_iSynthesisMode == 0) // General mode
{
m_pcImageLeft = new CIYuv<ImageType>(iHeight, iWidth*cParameter.getPrecision(), 444);
m_pcImageRight = new CIYuv<ImageType>(iHeight, iWidth*cParameter.getPrecision(), 444);
}
else
{
m_pcImageLeft = new CIYuv<ImageType>(iHeight, iWidth, 444);
m_pcImageRight = new CIYuv<ImageType>(iHeight, iWidth, 444);
}
if(cParameter.getPrecision() != 1)
{
m_pcTempYuvLeft = new CIYuv<ImageType>(iHeight, iWidth, 444);
m_pcTempYuvRight = new CIYuv<ImageType>(iHeight, iWidth, 444);
}
else
{
m_pcTempYuvLeft = m_pcImageLeft;
m_pcTempYuvRight = m_pcImageRight;
}
if( m_pcDepthMapLeft==NULL || m_pcDepthMapRight==NULL ||
m_pcImageLeft==NULL || m_pcImageRight==NULL ||
m_pcTempYuvLeft==NULL || m_pcTempYuvRight==NULL ) return false;
if (m_iSynthesisMode == 0) // General mode
{
if(!m_pcImageLeft->setUpsampleFilter(cParameter.getFilter(), cParameter.getPrecision())) return false;
if(!m_pcImageRight->setUpsampleFilter(cParameter.getFilter(), cParameter.getPrecision())) return false;
}
else // 1D mode: No upsampling is done before going into Visbd
{
if(!m_pcImageLeft ->setUpsampleFilter(cParameter.getFilter(), 1)) return false;
if(!m_pcImageRight->setUpsampleFilter(cParameter.getFilter(), 1)) return false;
}
// Prepare buffer for boundary noise removal:
m_iWidth = iWidth * cParameter.getPrecision();
m_iHeight = iHeight;
m_pSynColorLeft = (unsigned char*) malloc(sizeof(unsigned char)*(m_iWidth*m_iHeight*3)); // in 444
m_pSynColorRight = (unsigned char*) malloc(sizeof(unsigned char)*(m_iWidth*m_iHeight*3)); // in 444
m_pSynDepthLeft = (unsigned char*) malloc(sizeof(unsigned char)*(m_iWidth*m_iHeight)); // in 400
m_pSynDepthRight = (unsigned char*) malloc(sizeof(unsigned char)*(m_iWidth*m_iHeight)); // in 400
if (m_pSynColorLeft == NULL || m_pSynColorRight == NULL ||
m_pSynDepthLeft == NULL || m_pSynDepthRight == NULL)
return false;
#ifdef _DEBUG
m_ucSetup = 1;
#endif
return true;
}
bool CViewInterpolation::SetReferenceImage(int iLeft, CIYuv<ImageType> *pcYuv)
{
#ifdef _DEBUG
if(m_ucSetup==0) return false;
#endif
if(iLeft)
{
if(m_uiColorSpace)
m_pcTempYuvLeft->setData444_inIBGR(pcYuv); // RGB
else
m_pcTempYuvLeft->setData444_inIYUV(pcYuv); // YUV
//std::cout << "??????????=" << std::endl;
m_pcImageLeft->upsampling(m_pcTempYuvLeft);
}
else
{
if(m_uiColorSpace)
m_pcTempYuvRight->setData444_inIBGR(pcYuv); // RGB
else
m_pcTempYuvRight->setData444_inIYUV(pcYuv); // YUV
m_pcImageRight->upsampling(m_pcTempYuvRight);
}
#ifdef _DEBUG
m_ucSetup=1;
#endif
return true;
}
/*
* \brief
* The main interface function to perform view interpolation
* to be called from the application
*
* \param pSynYuvBuffer
* Store the synthesized picture into the buffer
*
* \return
* true: if succeed;
* false: if fails.
*/
bool CViewInterpolation::DoViewInterpolation( CIYuv<ImageType>* pSynYuvBuffer )
{
/*
ImageType*** RefLeft = m_pcImageLeft->getData();
ImageType*** RefRight = m_pcImageRight->getData();
DepthType** RefDepthLeft = m_pcDepthMapLeft->Y;
DepthType** RefDepthRight = m_pcDepthMapRight->Y;
//*/
bool ret = false;
if (m_iSynthesisMode == 0) // General mode
ret = xViewInterpolationGeneralMode( pSynYuvBuffer );
else if(m_iSynthesisMode == 1) // 1-D mode
ret = xViewInterpolation1DMode( pSynYuvBuffer );
if (ret == false)
return ret;
return ret;
}
bool CViewInterpolation::xViewInterpolationGeneralMode(CIYuv<ImageType>* pSynYuvBuffer)
{
ImageType*** RefLeft = m_pcImageLeft->getData();
ImageType*** RefRight = m_pcImageRight->getData();
DepthType** RefDepthLeft = m_pcDepthMapLeft->Y;
DepthType** RefDepthRight = m_pcDepthMapRight->Y;
if ( 0 != m_pViewSynthesisGeneral->DoOneFrameGeneral(RefLeft, RefRight, RefDepthLeft, RefDepthRight, pSynYuvBuffer) )
return false;
if (getBoundaryNoiseRemoval()) {
CIYuv<ImageType> pRefLeft;
CIYuv<ImageType> pRefRight;
CIYuv<DepthType> pRefDepthLeft;
CIYuv<DepthType> pRefDepthRight;
CIYuv<HoleType> pRefHoleLeft;
CIYuv<HoleType> pRefHoleRight;
int Width = m_iWidth/m_pViewSynthesisGeneral->GetInterpolatedLeft()->GetPrecision();
m_pBoundaryNoiseRemoval->SetViewBlending(m_uiViewBlending);
m_pBoundaryNoiseRemoval->SetColorSpace(m_uiColorSpace);
if(!pRefLeft.resize(m_iHeight, Width, 444)) return false;
if(!pRefRight.resize(m_iHeight, Width, 444)) return false;
if(!pRefDepthLeft.resize(m_iHeight, Width, POZNAN_DEPTHMAP_CHROMA_FORMAT)) return false;
if(!pRefDepthRight.resize(m_iHeight, Width, POZNAN_DEPTHMAP_CHROMA_FORMAT))return false;
if(!pRefHoleLeft.resize(m_iHeight, Width, POZNAN_DEPTHMAP_CHROMA_FORMAT)) return false;
if(!pRefHoleRight.resize(m_iHeight, Width, POZNAN_DEPTHMAP_CHROMA_FORMAT)) return false;
xFileConvertingforGeneralMode(&pRefLeft, &pRefRight, &pRefDepthLeft, &pRefDepthRight, &pRefHoleLeft, &pRefHoleRight);
xBoundaryNoiseRemoval(&pRefLeft, &pRefRight, &pRefDepthLeft, &pRefDepthRight, &pRefHoleLeft, &pRefHoleRight, pSynYuvBuffer, false/*General Mode*/);
}
return true;
}
/*
* To perform 1-D view interpolation
*
* \Output:
* All the color images below are in 444, depth images are 400
* \param pSynYuvBuffer
* To store the synthesis result.
* \member m_pSynColorLeft
* To store the synthesis color component from left ref w/o hole filling
* \member m_pSynColorRight
* To store the synthesis color component from right ref w/o hole filling
* \member m_pSynDepthLeft
* To store the synthesis depth component from left ref w/o hole filling
* \member m_pSynDepthRight
* To store the synthesis depth component from right ref w/o hole filling
*
* Return:
* true: if succeed;
* false: if fails.
*/
bool CViewInterpolation::xViewInterpolation1DMode( CIYuv<ImageType>* pSynYuvBuffer )
{
ImageType* RefLeft = m_pcImageLeft->getBuffer();
ImageType* RefRight = m_pcImageRight->getBuffer();
DepthType* RefDepthLeft = m_pcDepthMapLeft->getBuffer();
DepthType* RefDepthRight = m_pcDepthMapRight->getBuffer();
m_pViewSynthesis1D->SetFrameNumber( getFrameNumber()); //Zhejiang
if ( 0 != m_pViewSynthesis1D->DoOneFrame(RefLeft, RefRight, RefDepthLeft, RefDepthRight, pSynYuvBuffer->getBuffer()) )
return false;
if (getBoundaryNoiseRemoval()) {
CIYuv<ImageType> pRefLeft;
CIYuv<ImageType> pRefRight;
CIYuv<DepthType> pRefDepthLeft;
CIYuv<DepthType> pRefDepthRight;
CIYuv<HoleType> pRefHoleLeft;
CIYuv<HoleType> pRefHoleRight;
int Width = m_pViewSynthesis1D->GetWidth();
int Height = m_pViewSynthesis1D->GetHeight();
int SampleFactor = m_pViewSynthesis1D->GetSubPelOption() * m_pViewSynthesis1D->GetUpsampleRefs();
m_pBoundaryNoiseRemoval->SetViewBlending(m_uiViewBlending);
m_pBoundaryNoiseRemoval->SetColorSpace(m_uiColorSpace);
m_pBoundaryNoiseRemoval->SetPrecision(SampleFactor);
if(!pRefLeft.resize(Height, Width*SampleFactor, 444)) return false;
if(!pRefRight.resize(Height, Width*SampleFactor, 444)) return false;
if(!pRefDepthLeft.resize(Height, Width*SampleFactor, POZNAN_DEPTHMAP_CHROMA_FORMAT)) return false;
if(!pRefDepthRight.resize(Height, Width*SampleFactor, POZNAN_DEPTHMAP_CHROMA_FORMAT)) return false;
if(!pRefHoleLeft.resize(Height, Width*SampleFactor, 400)) return false;
if(!pRefHoleRight.resize(Height, Width*SampleFactor, 400)) return false;
xFileConvertingfor1DMode(&pRefLeft, &pRefRight, &pRefDepthLeft, &pRefDepthRight, &pRefHoleLeft, &pRefHoleRight);
xBoundaryNoiseRemoval(&pRefLeft, &pRefRight, &pRefDepthLeft, &pRefDepthRight, &pRefHoleLeft, &pRefHoleRight, pSynYuvBuffer, true/*1D Mode*/);
}
return true;
}
bool CViewInterpolation::xBoundaryNoiseRemoval(CIYuv<ImageType>* pRefLeft, CIYuv<ImageType>* pRefRight, CIYuv<DepthType>* pRefDepthLeft, CIYuv<DepthType>* pRefDepthRight, CIYuv<HoleType>* pRefHoleLeft, CIYuv<HoleType>* pRefHoleRight, CIYuv<ImageType>* pSynYuvBuffer, bool SynthesisMode)
{
switch(SynthesisMode)
{
case false: // General Mode
m_pBoundaryNoiseRemoval->SetWidth (m_iWidth/m_pViewSynthesisGeneral->GetInterpolatedLeft()->GetPrecision());
m_pBoundaryNoiseRemoval->SetHeight(m_iHeight);
m_pBoundaryNoiseRemoval->SetLeftBaseLineDist(m_pViewSynthesisGeneral->GetInterpolatedLeft()->getBaselineDistance());
m_pBoundaryNoiseRemoval->SetRightBaseLineDist(m_pViewSynthesisGeneral->GetInterpolatedRight()->getBaselineDistance());
m_pBoundaryNoiseRemoval->SetLeftH_V2R (m_pViewSynthesisGeneral->GetInterpolatedLeft() ->GetMatH_V2R());
m_pBoundaryNoiseRemoval->SetRightH_V2R(m_pViewSynthesisGeneral->GetInterpolatedRight()->GetMatH_V2R());
break;
case true: // 1D Mode
m_pBoundaryNoiseRemoval->SetWidth (m_pViewSynthesis1D->GetWidth());
m_pBoundaryNoiseRemoval->SetHeight(m_pViewSynthesis1D->GetHeight());
m_pBoundaryNoiseRemoval->SetduPrincipal(m_pViewSynthesis1D->GetduPrincipal());
m_pBoundaryNoiseRemoval->SetFocalLength(m_pViewSynthesis1D->GetFocalLength());
m_pBoundaryNoiseRemoval->SetLTranslationLeft(m_pViewSynthesis1D->GetLTranslation());
m_pBoundaryNoiseRemoval->SetZfar(m_pViewSynthesis1D->GetZfar());
m_pBoundaryNoiseRemoval->SetZnear(m_pViewSynthesis1D->GetZnear());
break;
}
if ( 0 != m_pBoundaryNoiseRemoval->DoBoundaryNoiseRemoval(pRefLeft, pRefRight, pRefDepthLeft, pRefDepthRight, pRefHoleLeft, pRefHoleRight, pSynYuvBuffer, SynthesisMode))
return false;
/*FILE *fp = fopen("mask.yuv", "wb");
for (j=0;j<m_iHeight*m_iWidth;j++) {
fputc(tar_L[j], fp);
}
fclose(fp);*/
return true;
}
void CViewInterpolation::xFileConvertingforGeneralMode(CIYuv<ImageType>* pRefLeft, CIYuv<ImageType>* pRefRight, CIYuv<DepthType>* pRefDepthLeft, CIYuv<DepthType>* pRefDepthRight, CIYuv<HoleType>* pRefHoleLeft, CIYuv<HoleType>* pRefHoleRight)
{
int Width, Height;
ImageType* tar_L_image, *tar_R_image;
ImageType* org_L_image, *org_R_image;
DepthType* tar_L_depth, *tar_R_depth;
DepthType* org_L_depth, *org_R_depth;
HoleType* tar_L_hole, *tar_R_hole;
HoleType* org_L_hole, *org_R_hole;
Width = m_iWidth/m_pViewSynthesisGeneral->GetInterpolatedLeft()->GetPrecision();
Height= m_iHeight;
// Color Image with hole
org_L_image = (ImageType*)m_pViewSynthesisGeneral->GetSynLeftWithHole()->imageData;
org_R_image = (ImageType*)m_pViewSynthesisGeneral->GetSynRightWithHole()->imageData;
tar_L_image = pRefLeft ->getBuffer();
tar_R_image = pRefRight->getBuffer();
memcpy(tar_L_image, org_L_image, Height*Width*3*sizeof(ImageType));
memcpy(tar_R_image, org_R_image, Height*Width*3*sizeof(ImageType));
org_L_depth = (DepthType*)m_pViewSynthesisGeneral->GetSynDepthLeftWithHole()->imageData;
org_R_depth = (DepthType*)m_pViewSynthesisGeneral->GetSynDepthRightWithHole()->imageData;
tar_L_depth = pRefDepthLeft ->getBuffer();
tar_R_depth = pRefDepthRight->getBuffer();
memcpy(tar_L_depth, org_L_depth, Height*Width*sizeof(DepthType));
memcpy(tar_R_depth, org_R_depth, Height*Width*sizeof(DepthType));
org_L_hole = (HoleType*)m_pViewSynthesisGeneral->GetSynHoleLeft() ->imageData;
org_R_hole = (HoleType*)m_pViewSynthesisGeneral->GetSynHoleRight()->imageData;
tar_L_hole = pRefHoleLeft ->getBuffer();
tar_R_hole = pRefHoleRight->getBuffer();
memcpy(tar_L_hole, org_L_hole, Height*Width*sizeof(HoleType));
memcpy(tar_R_hole, org_R_hole, Height*Width*sizeof(HoleType));
}
void CViewInterpolation::xFileConvertingfor1DMode( CIYuv<ImageType>* pRefLeft, CIYuv<ImageType>* pRefRight, CIYuv<DepthType>* pRefDepthLeft, CIYuv<DepthType>* pRefDepthRight, CIYuv<HoleType>* pRefHoleLeft, CIYuv<HoleType>* pRefHoleRight)
{
int Width, Height, UpSampleFactor;
//CPictureResample resmple;
ImageType* tar_L, *tar_R;
UpSampleFactor = m_pViewSynthesis1D->GetSubPelOption() * m_pViewSynthesis1D->GetUpsampleRefs();
Width = m_pViewSynthesis1D->GetWidth()*UpSampleFactor;
Height= m_pViewSynthesis1D->GetHeight();
//CIYuv pRefSrc, pRefDst;
//pRefSrc.resize(Height, Width, 444);
//pRefDst.resize(Height, Width, 444);
// Left Synthesized Image
tar_L = pRefLeft->getBuffer();
memcpy(&tar_L[Height*Width*0], m_pViewSynthesis1D->GetSynColorLeftY(), Height*Width);
memcpy(&tar_L[Height*Width*1], m_pViewSynthesis1D->GetSynColorLeftU(), Height*Width);
memcpy(&tar_L[Height*Width*2], m_pViewSynthesis1D->GetSynColorLeftV(), Height*Width);
// Right Synthesized Image
tar_R = pRefRight->getBuffer();
memcpy(&tar_R[Height*Width*0], m_pViewSynthesis1D->GetSynColorRightY(), Height*Width);
memcpy(&tar_R[Height*Width*1], m_pViewSynthesis1D->GetSynColorRightU(), Height*Width);
memcpy(&tar_R[Height*Width*2], m_pViewSynthesis1D->GetSynColorRightV(), Height*Width);
// Left Synthesized Depth Image
memcpy(pRefDepthLeft->getBuffer(), m_pViewSynthesis1D->GetSynDepthLeft(), Height*Width);
// Right Synthesized Depth Image
memcpy(pRefDepthRight->getBuffer(), m_pViewSynthesis1D->GetSynDepthRight(), Height*Width);
m_pBoundaryNoiseRemoval->DepthMatchingWithColor(pRefDepthLeft , pRefLeft , pRefHoleLeft );
m_pBoundaryNoiseRemoval->DepthMatchingWithColor(pRefDepthRight, pRefRight, pRefHoleRight);
}
| [
"42332899+Songminkee@users.noreply.github.com"
] | 42332899+Songminkee@users.noreply.github.com |
b90c3efec203e8de32982d01e8f96b93b2a2dff4 | 59655542d31f4e27094554c95f189ac57403007f | /19_Permutering.cpp | 0d487ac1f74af9172f0641523d7ab4db960229c5 | [] | no_license | JorgenEriksen/Algoritmer | 556b4c7084225d8beebe5c0e7ac0409b56ffafdf | 0e750785dec340832338f815fe60d314cb7ab569 | refs/heads/master | 2023-06-04T06:33:21.368951 | 2021-06-27T09:02:37 | 2021-06-27T09:02:37 | 380,682,883 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,182 | cpp |
#include <iostream>
using namespace std;
const int N = 4;
void bytt(int &tall1, int &tall2);
void display(const int arr[], const int n);
void permuter(int arr[], const int i, const int n);
void roterVenstre(int arr[], const int i, const int n);
int main()
{
int array[N];
for (int i = 0; i < N; i++)
array[i] = i + 1;
permuter(array, 0, N);
cout << '\n';
display(array, N);
cout << "\n\n";
return 0;
}
void bytt(int &tall1, int &tall2)
{
int temp = tall1;
tall1 = tall2;
tall2 = temp;
}
void display(const int arr[], const int n)
{
for (int i = 0; i < n; i++)
cout << ' ' << arr[i];
cout << '\n';
}
void permuter(int arr[], const int i, const int n)
{
if (i == n - 1)
display(arr, n);
else
{
permuter(arr, i + 1, n);
for (int t = i + 1; t < n; t++)
{
bytt(arr[i], arr[t]);
permuter(arr, i + 1, n);
}
roterVenstre(arr, i, n);
}
}
void roterVenstre(int arr[], const int i, const int n)
{
int venstreVerdi = arr[i];
for (int k = i + 1; k < n; k++)
arr[k - 1] = arr[k];
arr[n - 1] = venstreVerdi;
}
| [
"jorgen.eriksen93@gmail.com"
] | jorgen.eriksen93@gmail.com |
cd3c48ad85ed3982c849aae668435f408efca05b | 3b1c7561c8d3b9452fc0cdefe299b208e0db1853 | /src/sksl/ir/SkSLBlock.h | 7bf3286a84f76d33aa8b0b1459d0aac9bd8a58da | [
"BSD-3-Clause"
] | permissive | NearTox/Skia | dee04fc980bd40c1861c424b5643e7873f656b01 | 4d0cd2b6deca44eb2255651c4f04396963688761 | refs/heads/master | 2022-12-24T02:01:41.138176 | 2022-08-27T14:32:37 | 2022-08-27T14:32:37 | 153,816,056 | 0 | 0 | BSD-3-Clause | 2022-12-13T23:42:44 | 2018-10-19T17:05:47 | C++ | UTF-8 | C++ | false | false | 3,275 | h | /*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SKSL_BLOCK
#define SKSL_BLOCK
#include "include/private/SkSLDefines.h"
#include "include/private/SkSLStatement.h"
#include "include/private/SkTArray.h"
#include "include/sksl/SkSLPosition.h"
#include <memory>
#include <string>
#include <utility>
namespace SkSL {
class SymbolTable;
/**
* A block of multiple statements functioning as a single statement.
*/
class Block final : public Statement {
public:
inline static constexpr Kind kStatementKind = Kind::kBlock;
// "kBracedScope" represents an actual language-level block. Other kinds of block are used to
// pass around multiple statements as if they were a single unit, with no semantic impact.
enum class Kind {
kUnbracedBlock, // Represents a group of statements without curly braces.
kBracedScope, // Represents a language-level Block, with curly braces.
kCompoundStatement, // A block which conceptually represents a single statement, such as
// `int a, b;`. (SkSL represents this internally as two statements:
// `int a; int b;`) Allowed to optimize away to its interior Statement.
// Treated as a single statement by the debugger.
};
Block(
Position pos, StatementArray statements, Kind kind = Kind::kBracedScope,
const std::shared_ptr<SymbolTable> symbols = nullptr)
: INHERITED(pos, kStatementKind),
fChildren(std::move(statements)),
fBlockKind(kind),
fSymbolTable(std::move(symbols)) {}
// Make is allowed to simplify compound statements. For a single-statement unscoped Block,
// Make can return the Statement as-is. For an empty unscoped Block, Make can return Nop.
static std::unique_ptr<Statement> Make(
Position pos, StatementArray statements, Kind kind = Kind::kBracedScope,
std::shared_ptr<SymbolTable> symbols = nullptr);
// MakeBlock always makes a real Block object. This is important because many callers rely on
// Blocks specifically; e.g. a function body must be a scoped Block, nothing else will do.
static std::unique_ptr<Block> MakeBlock(
Position pos, StatementArray statements, Kind kind = Kind::kBracedScope,
std::shared_ptr<SymbolTable> symbols = nullptr);
const StatementArray& children() const noexcept { return fChildren; }
StatementArray& children() noexcept { return fChildren; }
bool isScope() const noexcept { return fBlockKind == Kind::kBracedScope; }
Kind blockKind() const noexcept { return fBlockKind; }
void setBlockKind(Kind kind) noexcept { fBlockKind = kind; }
std::shared_ptr<SymbolTable> symbolTable() const noexcept { return fSymbolTable; }
bool isEmpty() const override {
for (const std::unique_ptr<Statement>& stmt : this->children()) {
if (!stmt->isEmpty()) {
return false;
}
}
return true;
}
std::unique_ptr<Statement> clone() const override;
std::string description() const override;
private:
StatementArray fChildren;
Kind fBlockKind;
std::shared_ptr<SymbolTable> fSymbolTable;
using INHERITED = Statement;
};
} // namespace SkSL
#endif
| [
"NearTox@outlook.com"
] | NearTox@outlook.com |
4c4aa286c4f89265d34da04c7501e6eca06c8471 | 4097247824061b3c6e33de55da6297b27a4e4175 | /euler12.cxx | f7e3693338f1971f155a01091c39f4127d521bfe | [] | no_license | zrzw/tour-cxx | b085fc7300add8b5a04394f00558ea89aa81b019 | c10c79f7d926885c9946db9eed35775268c1e1a1 | refs/heads/master | 2020-03-18T02:11:16.177545 | 2018-06-10T13:59:40 | 2018-06-10T13:59:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,208 | cxx | /*
* Project Euler #12
* "Highly divisible triangle numbers"
*/
#include <iostream>
#include <iomanip>
#include <math.h>
#include <vector>
/* factorise using trial division */
std::vector<int> factorise(long int n)
{
std::vector<int> results {};
int limit = n;
for(auto i=1; i<limit; ++i){
if(n % i == 0){
results.push_back(i);
results.push_back(n / i);
limit /= i;
}
}
return results;
}
int count_factors(double n)
{
int result = 0;
int limit = n;
for(auto i=1; i<limit; ++i){
if(fmod(n,i) == 0){
if(n / i != i)
result += 2;
else
result += 1;
limit /= i;
}
}
return result;
}
int test()
{
std::vector<int> r = factorise(28);
for(auto& a : r)
std::cout << a << " ";
std::cout << std::endl;
return 0;
}
int main()
{
int size {0};
int n {1};
double t {0}; //the current triangle number
int target = 23;
while(size <= target){
t += n;
++n;
size = count_factors(t);
}
std::cout << t << " has more than " << target << " factors\n";
return 0;
}
| [
"31051194+fen-ton@users.noreply.github.com"
] | 31051194+fen-ton@users.noreply.github.com |
55406ba9291042ad1e1c7f6c40a9d6b439bc43db | 1d4b65e8e7e10b1ad0bc41a9af0e0c8b630aeab2 | /stream/time/NdgStreamTimeConf.hpp | 1778656dc3b9126507fbacc3ebc0f2be037d5e71 | [
"BSD-2-Clause"
] | permissive | dailu/ngx_cpp_dev | d4ea8f70a291b364abc50b3d096f3c7794ea2bab | a47354f77e0e98db9e7371559ed4edb8c0bbdc8b | refs/heads/master | 2020-07-02T16:34:35.181172 | 2019-08-10T07:50:54 | 2019-08-10T07:50:54 | 201,590,496 | 0 | 0 | BSD-2-Clause | 2019-08-10T06:33:37 | 2019-08-10T06:33:37 | null | UTF-8 | C++ | false | false | 752 | hpp | // Copyright (c) 2016-2017
// Author: Chrono Law
#ifndef _NDG_STREAM_TIME_CONF_HPP
#define _NDG_STREAM_TIME_CONF_HPP
#include "NgxStreamAll.hpp"
class NdgStreamTimeConf final
{
public:
typedef NdgStreamTimeConf this_type;
public:
NdgStreamTimeConf() = default;
~NdgStreamTimeConf() = default;
public:
static void* create(ngx_conf_t* cf)
{
return NgxPool(cf).alloc<this_type>();
}
static char* merge(ngx_conf_t *cf, void *parent, void *child)
{
return NGX_CONF_OK;
}
public:
static this_type& cast(void* p)
{
return *reinterpret_cast<this_type*>(p);
}
};
NGX_MOD_INSTANCE(NdgStreamTimeModule, ndg_stream_datetime_module, NdgStreamTimeConf)
#endif //_NDG_STREAM_TIME_CONF_HPP
| [
"chrono_cpp@me.com"
] | chrono_cpp@me.com |
5b866f2a411556597a9b71a959086e01c49e2075 | f5892fc6800b43517a5f6d317140e37ec305ad53 | /include/mimas/MenuBar.h | 657643ea8dc8f539e29d602e7619da41ef82244c | [] | no_license | lubyk/mimas | 32272ed4518f3a689c8ed27d1f186993b11444ca | 202b73a2325cb1424ca76dd1b8bfa438fc10c0c8 | refs/heads/master | 2020-03-29T13:17:02.412415 | 2013-04-11T10:51:44 | 2013-04-11T10:51:44 | 3,227,183 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,953 | h | /*
==============================================================================
This file is part of the LUBYK project (http://lubyk.org)
Copyright (c) 2007-2011 by Gaspard Bucher (http://teti.ch).
------------------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
==============================================================================
*/
#ifndef LUBYK_INCLUDE_MIMAS_MENU_BAR_H_
#define LUBYK_INCLUDE_MIMAS_MENU_BAR_H_
#include "mimas/mimas.h"
#include "mimas/Color.h"
#include "mimas/Menu.h"
#include <QtGui/QMenuBar>
/** This lets us define menus.
*
* @see Menu
* @see QMenuBar
* @dub push: pushobject
* register: MenuBar_core
*/
class MenuBar : public QMenuBar, public dub::Thread {
Q_OBJECT
public:
MenuBar(QWidget *parent = 0)
: QMenuBar(parent) {
}
~MenuBar() {
}
};
#endif // LUBYK_INCLUDE_MIMAS_MENU_BAR_H_
| [
"gaspard@teti.ch"
] | gaspard@teti.ch |
be27dbcd60350412fdf5193219b26d35be2999c8 | 65e4d6838a298b6bef954235294f8f7e90a325eb | /final/src/core/integrator.h | 4c9cf49d5b7af47db8d3db05b2a1ffff634c7cb4 | [] | no_license | steven5401/course_Rendering | dd84d1ed5f8c9b175c5f69ce6dad625be3cf7524 | 67326ab8e6e8f82cebeca7fb82b7a877eadaa683 | refs/heads/master | 2021-01-17T07:52:42.262613 | 2017-03-04T14:31:05 | 2017-03-04T14:31:05 | 83,808,799 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,095 | h |
/*
pbrt source code Copyright(c) 1998-2012 Matt Pharr and Greg Humphreys.
This file is part of pbrt.
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.
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.
*/
#if defined(_MSC_VER)
#pragma once
#endif
#ifndef PBRT_CORE_INTEGRATOR_H
#define PBRT_CORE_INTEGRATOR_H
// core/integrator.h*
#include "pbrt.h"
#include "primitive.h"
#include "spectrum.h"
#include "light.h"
#include "reflection.h"
#include "sampler.h"
#include "material.h"
#include "probes.h"
#include "renderer.h"
#include "camera.h"//euphoria5401//
// Integrator Declarations
class Integrator {
public:
// Integrator Interface
virtual ~Integrator();
virtual void Preprocess(const Scene *scene, const Camera *camera,
const Renderer *renderer) {
}
virtual void RequestSamples(Sampler *sampler, Sample *sample,
const Scene *scene) {
}
//euphoria5401//
virtual void Postprocess(const Scene *scene, Renderer* renderer, const Camera* camera) {}
//euphoria5401//
};
class SurfaceIntegrator : public Integrator {
public:
// SurfaceIntegrator Interface
virtual Spectrum Li(const Scene *scene, const Renderer *renderer,
const RayDifferential &ray, const Intersection &isect,
const Sample *sample, RNG &rng, MemoryArena &arena) const = 0;
};
Spectrum UniformSampleAllLights(const Scene *scene, const Renderer *renderer,
MemoryArena &arena, const Point &p, const Normal &n, const Vector &wo,
float rayEpsilon, float time, BSDF *bsdf, const Sample *sample, RNG &rng,
const LightSampleOffsets *lightSampleOffsets,
const BSDFSampleOffsets *bsdfSampleOffsets);
Spectrum UniformSampleOneLight(const Scene *scene, const Renderer *renderer,
MemoryArena &arena, const Point &p, const Normal &n, const Vector &wo,
float rayEpsilon, float time, BSDF *bsdf,
const Sample *sample, RNG &rng, int lightNumOffset = -1,
const LightSampleOffsets *lightSampleOffset = NULL,
const BSDFSampleOffsets *bsdfSampleOffset = NULL);
Spectrum EstimateDirect(const Scene *scene, const Renderer *renderer,
MemoryArena &arena, const Light *light, const Point &p,
const Normal &n, const Vector &wo, float rayEpsilon, float time, const BSDF *bsdf,
RNG &rng, const LightSample &lightSample, const BSDFSample &bsdfSample,
BxDFType flags);
Spectrum SpecularReflect(const RayDifferential &ray, BSDF *bsdf, RNG &rng,
const Intersection &isect, const Renderer *renderer, const Scene *scene,
const Sample *sample, MemoryArena &arena);
Spectrum SpecularTransmit(const RayDifferential &ray, BSDF *bsdf, RNG &rng,
const Intersection &isect, const Renderer *renderer, const Scene *scene,
const Sample *sample, MemoryArena &arena);
Distribution1D *ComputeLightSamplingCDF(const Scene *scene);
#endif // PBRT_CORE_INTEGRATOR_H
| [
"Euphoria"
] | Euphoria |
ccdc8149b18479684a8d4f6fab4f706144492862 | 8ccf11efe7eab78ae0766799ba103838ed4b008c | /rust_sdk/classes.hpp | aceb8b3033fee0c76766199f753015e879bed65c | [] | no_license | Spookycpp/rust_internal_sdk | 2571033ba56919b66d229448e2bb3569287ea66d | 1ad8942dd60ff7656c36d9e2fa13687843d4866d | refs/heads/master | 2022-04-14T12:56:33.513521 | 2019-12-16T14:48:45 | 2019-12-16T14:48:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,241 | hpp | #pragma once
#include <cstdint>
#include <mutex>
#include "vector.hpp"
std::mutex entity_mutex;
template <typename t>
struct mono_array
{
char pad_0[0x20];
t array[];
};
struct mono_string
{
char pad_0[ 0x10 ];
std::uint32_t size;
wchar_t buffer;
};
struct item_container
{
char pad_0[ 0x30 ];
void* contents;
};
struct player_inventory
{
char pad_0[ 0x20 ];
item_container* container_main;
item_container* container_belt;
item_container* container_wear;
};
struct player_input
{
char pad_0[ 0x3c ];
geo::vec3_t body_angles;
};
struct player_model
{
char pad_0[ 0x1d4 ];
bool is_visible;
char pad_1[ 0xc ];
bool is_local_player;
};
struct unity_transform
{
char pad_0[ 0x10 ];
void* transform;
};
struct model_transforms
{
char pad_0[ 0x190 ];
unity_transform* neck;
unity_transform* head;
};
struct model
{
char pad_0[ 0x28 ];
unity_transform* head_bone_transform;
char pad_1[ 0x10 ];
model_transforms* transforms;
};
struct base_collision
{
char pad_0[ 0x20 ];
model* model;
};
struct base_player
{
char pad_0[ 0xb0 ];
model* model;
char pad_1[ 0x13c ];
float health;
char pad_2[ 0x298 ];
player_inventory* inventory;
char pad_3[ 0x10 ];
player_input* input;
char pad_4[ 0x8 ];
base_collision* collision;
char pad_5[ 0x28 ];
mono_string* display_name;
char pad_6[ 0x30 ];
player_model* player_model;
char pad_7[ 0x41 ];
bool sleeping;
char pad_8[ 0x3e ];
std::uint32_t team;
};
struct base_camera
{
char pad_0[ 0x2e4 ];
geo::mat4x4_t view_matrix;
};
struct unk2
{
char pad_0[ 0x28 ];
base_player* player;
};
struct game_object
{
char pad_0[ 0x18 ];
unk2* unk;
};
struct mono_object
{
char pad_1[ 0x30 ];
game_object* object;
char pad_2[ 0x1c ];
std::uint16_t tag;
char pad_3[ 0xa ];
mono_string* name;
};
struct unk1
{
char pad_0[ 0x8 ];
unk1* next;
mono_object* object;
};
struct buffer_list
{
char pad_0[ 0x10 ];
std::uint32_t size;
void* buffer;
};
struct dictionary
{
char pad_0[ 0x20 ];
buffer_list* keys;
buffer_list* values;
};
struct entity_realm
{
char pad_0[ 0x10 ];
dictionary* list;
};
| [
"noreply@github.com"
] | Spookycpp.noreply@github.com |
c5c7563da2607eea1c650892153ab8e62fdd39cd | f85fdd8b8e779ec564abb52876b82ebea9337bcf | /hw2-3/min_max_sum.cc | 94e290671a7c8dd82322676dcab3ca815f1c0c56 | [
"MIT"
] | permissive | revsic/HYU-ITE1015 | 0a02b5ee014d9cec8b83fed6ef55a5515afea17f | b2d2d210f4b936be0fd94bd258e15b6c16c432fe | refs/heads/master | 2020-04-06T09:11:54.463873 | 2019-03-07T08:36:00 | 2019-03-07T08:36:00 | 157,332,436 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 489 | cc | #include <stdio.h>
#include <iostream>
int main() {
int arr[5] = { 0, };
for (int i = 0; i < 5; ++i) {
scanf("%d", &arr[i]);
}
int min, max, sum;
min = max = sum = arr[0];
for (int i = 1; i < 5; ++i) {
min = min < arr[i] ? min : arr[i];
max = max > arr[i] ? max : arr[i];
sum += arr[i];
}
std::cout
<< "min: " << min << std::endl
<< "max: " << max << std::endl
<< "sum: " << sum << std::endl;
}
| [
"revsic99@gmail.com"
] | revsic99@gmail.com |
09cd0c48163ba43f62c74bc07edca15abd76f7c0 | 5b12760333f6ce9f2c818c9406a788bbdde83cb3 | /shynet/protocol/FilterProces.cpp | 87784ac8fd77b468d745e9f05eef27708f18f919 | [] | no_license | JoyZou/gameframe | a9476948b86b34d4bb5e8eae47552023c07d7566 | a5db12da016b65033cc088ba3c2a464936b2b942 | refs/heads/master | 2023-08-28T22:18:56.117350 | 2021-11-10T09:04:30 | 2021-11-10T09:04:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,677 | cpp | #include "shynet/protocol/filterproces.h"
#include "shynet/net/ipaddress.h"
#include "shynet/utils/logger.h"
namespace shynet {
namespace protocol {
FilterProces::FilterProces(std::shared_ptr<events::EventBuffer> iobuf,
ProtoType pt, Identity ident)
{
iobuf_ = iobuf;
pt_ = pt;
ident_ = ident;
if (pt_ == ProtoType::SHY)
tcpip_.reset(new protocol::Tcpip(this));
else if (pt_ == ProtoType::HTTP)
http_.reset(new protocol::Http(this));
else if (pt_ == ProtoType::WEBSOCKET)
websocket_.reset(new protocol::WebSocket(this));
}
FilterProces::~FilterProces()
{
}
int FilterProces::process()
{
switch (pt_) {
case ProtoType::SHY:
return tcpip_->process();
case ProtoType::HTTP:
return http_->process();
case ProtoType::WEBSOCKET:
return websocket_->process();
default:
LOG_WARN << "未知的协议类型";
return -1;
}
}
FilterProces::Identity FilterProces::ident() const { return ident_; }
int FilterProces::send(const char* data, size_t len) const
{
switch (pt_) {
case ProtoType::SHY: {
return tcpip_->send(data, len, Tcpip::FrameType::Binary);
}
case ProtoType::HTTP: {
if (ident_ == Identity::ACCEPTOR) {
return http_->send_responses(data, len);
} else if (ident_ == Identity::CONNECTOR) {
return http_->send_requset(data, len);
}
}
case ProtoType::WEBSOCKET: {
return websocket_->send(data, len, protocol::WebSocket::FrameType::Binary);
}
default:
LOG_WARN << "未知的协议类型";
return -1;
}
return -1;
}
int FilterProces::send(std::string data) const
{
return send(data.c_str(), data.length());
}
int FilterProces::ping() const
{
switch (pt_) {
case ProtoType::SHY: {
return tcpip_->send(nullptr, 0, Tcpip::FrameType::Ping);
}
case ProtoType::WEBSOCKET: {
return websocket_->send(nullptr, 0, protocol::WebSocket::FrameType::Ping);
}
default:
LOG_WARN << "未知的协议类型";
return -1;
}
return -1;
}
int FilterProces::request_handshake() const
{
if (pt_ == ProtoType::WEBSOCKET) {
return websocket_->request_handshake();
} else {
LOG_WARN << "使用的不是websoket协议";
return -1;
}
}
}
}
| [
"54823051@qq.com"
] | 54823051@qq.com |
77eb3eac618b7ab89e7c2879d66806411ac3a0c1 | 30528f64af4c68ebd96de8f17782e61ab125cf43 | /Furiosity/Core/Transformable3D.h | 0ab8efe8678445ca9ac73a2e8dc8d0d3996ae660 | [
"MIT"
] | permissive | enci/Furiosity | ac99163594bd310aeac02105fa6df5373a4fb213 | 0f823b31ba369a6f20a69ca079627dccd4b4549a | refs/heads/master | 2020-05-18T04:00:19.825590 | 2015-11-24T08:51:40 | 2015-11-24T08:51:40 | 31,144,326 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,282 | h | ////////////////////////////////////////////////////////////////////////////////
// Transformable3D.h
// Furiosity
//
// Created by Bojan Endrovski on 9/16/13.
// Copyright (c) 2013 Game Oven. All rights reserved.
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "Matrix44.h"
#include <vector>
namespace Furiosity
{
/*
class Transformable3D;
///
/// Data - Used by the entities mostly via the
///
struct Transform3D
{
friend Transformable3D;
protected:
Matrix44 local;
Matrix44 world;
Transform3D* parent = nullptr;
std::vector<Transform3D*> childern;
public:
inline void UpdateTransform()
{
if(parent)
world = local * parent->world;
else
world = local;
for(auto c : childern)
c->UpdateTransform();
}
};
*/
/*
///
///
///
class Transformable3D
{
protected:
Matrix44 _trns;
Vector3 _scale;
public:
Transformable3D() : _trns(), _scale(1, 1, 1) {}
inline Matrix44 Transform() const { return _trns * Matrix44::CreateScale(_scale); }
inline Matrix33 Orientation() const { return _trns.GetMatrix33(); }
inline void SetTransform(const Matrix44& mat)
{
// Extract the orientation vectors
Vector3 x(_trns.m00, _trns.m01, _trns.m03);
Vector3 y(_trns.m10, _trns.m11, _trns.m13);
Vector3 z(_trns.m20, _trns.m21, _trns.m23);
// Get their scale
_scale.x = x.Magnitude();
_scale.y = y.Magnitude();
_scale.z = z.Magnitude();
// Normalize the orientation vectors
x *= 1.0f / _scale.x;
y *= 1.0f / _scale.y;
z *= 1.0f / _scale.z;
// Set the orientation and transaltion
_trns.SetOrientation(x, y, z);
_trns.SetTranslation(mat.Translation());
}
inline Vector3 Position() const { return _trns.Translation(); }
inline void SetPosition(Vector3 position) { _trns.SetTranslation(position); }
inline Vector3 Scale() const { return _scale; }
inline void SetScale(Vector3 scale) { _scale = scale; }
inline void SetOrientation(const Vector3& x,
const Vector3& y,
const Vector3& z)
{ _trns.SetOrientation(x, y, z); }
};
*/
/*
class Transformable3D
{
protected:
Transform3D transform;
void SetParent(Transformable3D* parent)
{
transform.parent = parent->transform;
transform.parent->childern.push_back(&transform);
}
public:
///
/// Create a new transformable object.
///
Transformable3D() {}
///
///
///
inline Matrix44 Transform() const { return transform.world; }
///
///
///
inline Matrix33 Orientation() const { return transform.world.GetMatrix33(); }
///
///
///
inline void SetTransformation(const Matrix44& trans)
{
transform.local = trans;
transform.UpdateTransform();
}
///
///
///
inline Vector3 Position() const { return transform.world.Translation(); }
///
///
///
inline void SetPosition(Vector3 position)
{
if(!transform.parent)
{
transform.local.SetTranslation(position);
}
else
{
Vector3 wPos = transform.world.Translation();
Vector3 lPos = transform.local.Translation();
transform.local.SetTranslation(position + (wPos - lPos));
}
transform.UpdateTransform();
}
///
///
///
inline Vector3 LocalPosition() const { return transform.world.Translation(); }
///
///
///
inline void SetLocalPosition(Vector3 position)
{
transform.local.SetTranslation(position);
transform.UpdateTransform();
}
///
/// Gets the local scale. Might be non uniform.
///
inline Vector3 LocalScale() const
{
// Extract the orientation vectors
const Matrix44& trns = transform.local;
Vector3 x(trns.m00, trns.m01, trns.m02);
Vector3 y(trns.m10, trns.m11, trns.m12);
Vector3 z(trns.m20, trns.m21, trns.m22);
// Get their scale
return Vector3(x.Magnitude(), y.Magnitude(), z.Magnitude());
}
///
/// Set the local scale. Might accumulate errors over time.
///
inline void SetLocalScale(Vector3 scale)
{
Vector3 currentScale = LocalScale();
Vector3 relativeScale(scale.x / currentScale.x,
scale.y / currentScale.y,
scale.z / currentScale.z);
transform.local = transform.local * Matrix44::CreateScale(relativeScale);
transform.UpdateTransform();
}
///
/// Set the local orientation.
///
inline void SetLocalOrientation(const Vector3& x,
const Vector3& y,
const Vector3& z)
{
Vector3 scale = LocalScale();
transform.local.SetOrientation(x * scale.x,
y * scale.y,
z * scale.z);
transform.UpdateTransform();
}
};
*/
}
| [
"bojan.endrovski@gmail.com"
] | bojan.endrovski@gmail.com |
172af1976e4c9c55365a7be8e0f1c3f3b52c16a0 | c13c121d96fdd8682982854f43e50be011863aa1 | /Code/Include/core/Transform.h | f37287b4cf4e5cd2c5bdc1138fa281e7f5128c94 | [] | no_license | paksas/Tamy | 14fe8e2ff5633ced9b24c855c6e06776bf221c10 | 6e4bd2f14d54cc718ed12734a3ae0ad52337cf40 | refs/heads/master | 2020-06-03T08:06:09.511028 | 2015-03-21T20:37:03 | 2015-03-21T20:37:03 | 25,319,755 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,236 | h | /// @file core/Transform.h
/// @brief mathematical transform definition
#ifndef _TRANSFORM_H
#define _TRANSFORM_H
#include <iostream>
#include "core/types.h"
#include "core/Vector.h"
#include "core/Quaternion.h"
///////////////////////////////////////////////////////////////////////////////
struct Vector;
struct Quaternion;
struct EulerAngles;
struct Plane;
struct Matrix;
class OutStream;
class InStream;
///////////////////////////////////////////////////////////////////////////////
/**
* Mathematical transform definition. This is an affine transform that
* rotates and translates ( in that exact order ) while preserving the scale
* of the transformed objects.
*/
ALIGN_16 struct Transform
{
DECLARE_ALLOCATOR( Transform, AM_ALIGNED_16 );
Vector m_translation;
Quaternion m_rotation;
static Transform IDENTITY;
/**
* Default constructor.
*/
Transform();
/**
* Constructor that creates a rotation transform.
* We want it to be called explicitly and not as a conversion constructor.
*
* @param translation
* @param rotation
*/
explicit Transform( const Quaternion& rotation );
/**
* Constructor that creates a translation transform.
* We want it to be called explicitly and not as a conversion constructor.
*
* @param translation
* @param rotation
*/
explicit Transform( const Vector& translation );
/**
* Constructor.
*
* @param translation
* @param rotation
*/
Transform( const Vector& translation, const Quaternion& rotation );
/**
* Defines a transform using a quaternion( axis, angle ) and a translation vector.
*
* @param rotationAxis
* @param rotationAngle
* @param translation
*/
void set( const Vector& rotationAxis, const FastFloat& rotationAngle, const Vector& translation );
/**
* Defines a transform using a quaternion( axis, angle ) and a translation vector.
*
* @param rotationAxis
* @param rotationAngle
* @param translation
*/
void set( const Vector& rotationAxis, float rotationAngle, const Vector& translation );
/**
* Defines a transform using a quaternion( axis, angle ) and a translation vector.
*
* @param rotationAxis
* @param rotationAngle
* @param translation
*/
void set( const Quaternion& rotation, const Vector& translation );
// -------------------------------------------------------------------------
// Operators
// -------------------------------------------------------------------------
Transform& operator=( const Transform& rhs );
bool operator==( const Transform& rhs ) const;
bool operator!=( const Transform& rhs ) const;
// -------------------------------------------------------------------------
// Operations
// -------------------------------------------------------------------------
/**
* Creates a rotation matrix with rotation corresponding to the specified Euler angle value
*
* @param angles
*/
Transform& setRotation( const EulerAngles& angles );
/**
* Returns the rotation this matrix describes in the form of Euler angles.
*
* @param outAngles
*/
void getRotation( EulerAngles& outAngles ) const;
/**
* Converts the transform to a regular 4x4 matrix
*
* @param outMatrix
*/
void toMatrix( Matrix& outMatrix ) const;
/**
* Converts a 4x4 matrix to a transform
*
* @param matrix
*/
void set( const Matrix& matrix );
/**
* this = a * b
*
* @param a
* @param b
*/
void setMul( const Transform& a, const Transform& b );
/**
* this = this * a
*
* CAUTION - it allocates temporary data on stack, thus it's slower than setMul.
*
* @param a
*/
void mul( const Transform& a );
/**
* this = a * this
*
* CAUTION - it allocates temporary data on stack, thus it's slower than setMul.
*
* @param a
*/
void preMul( const Transform& a );
/**
* this = a * b^-1
*
* @param a
* @param b
*/
void setMulInverse( const Transform& a, const Transform& b );
/**
* Sets an inverted transform.
*
* @param rhs
*/
void setInverse( const Transform& rhs );
/**
* Inverts the transform.
*/
void invert();
/**
* this = a*t + b*(1-t)
*
* Rotation will be spherically interpolated.
*
* @param a
* @param b
* @param t
*/
void setSlerp( const Transform& a, const Transform& b, const FastFloat& t );
/**
* this = a*t + b*(1-t)
*
* Rotation will be linearly interpolated.
*
* @param a
* @param b
* @param t
*/
void setNlerp( const Transform& a, const Transform& b, const FastFloat& t );
/**
* Transforms the specified vector.
*
* @param inVec vector to be transformed.
* @param outVec transformed vector
*/
void transform( const Vector& inVec, Vector& outVec ) const;
/**
* Transforms the specified normal vector
*
* @param inNorm normal vector to be transformed.
* @param outNorm transformed normal
*/
void transformNorm( const Vector& inNorm, Vector& outNorm ) const;
/**
* Transforms the specified plane.
*
* @param inPlane plane to be transformed.
* @param outPlane transformed plane
*/
void transform( const Plane& inPlane, Plane& outPlane ) const;
/**
* This method writes the contents of the orientation to the specified
* output stream.
*
* @param stream output stream
* @param rhs orientation description of which we want to output
*/
friend std::ostream& operator<<( std::ostream& stream, const Transform& rhs );
// -------------------------------------------------------------------------
// Serialization support
// -------------------------------------------------------------------------
friend OutStream& operator<<( OutStream& serializer, const Transform& rhs );
friend InStream& operator>>( InStream& serializer, Transform& rhs );
};
///////////////////////////////////////////////////////////////////////////////
#endif // _TRANSFORM_H
| [
"ptrochim@gmail.com"
] | ptrochim@gmail.com |
1d76de8f2b69df571cfdc55ef62390625c628fb1 | ddfa627ca795d278b8515aa7ff915f01916e12f4 | /src/bitcoind.cpp | 92ad6640d02c888ab69a7d4abb48e01c29337b4a | [
"MIT"
] | permissive | etherscan-io/Megacoin | 67805904093d7aecdc7ffd99f80ab377f8ad58fa | d18a29cb9acc14b05713e69a34685e2ac97f01a5 | refs/heads/master | 2020-07-15T22:53:50.485909 | 2018-04-16T16:31:56 | 2018-04-16T16:31:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,755 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clientversion.h"
#include "rpcserver.h"
#include "init.h"
#include "main.h"
#include "noui.h"
#include "ui_interface.h"
#include "util.h"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
/* Introduction text for doxygen: */
/*! \mainpage Developer documentation
*
* \section intro_sec Introduction
*
* This is the developer documentation of the reference client for an experimental new digital currency called Bitcoin (http://www.bitcoin.org/),
* which enables instant payments to anyone, anywhere in the world. Bitcoin uses peer-to-peer technology to operate
* with no central authority: managing transactions and issuing money are carried out collectively by the network.
*
* The software is a community-driven open source project, released under the MIT license.
*
* \section Navigation
* Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code.
*/
static bool fDaemon;
void DetectShutdownThread(boost::thread_group* threadGroup)
{
bool fShutdown = ShutdownRequested();
// Tell the main threads to shutdown.
while (!fShutdown)
{
MilliSleep(200);
fShutdown = ShutdownRequested();
}
if (threadGroup)
{
threadGroup->interrupt_all();
threadGroup->join_all();
}
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
boost::thread_group threadGroup;
boost::thread* detectShutdownThread = NULL;
bool fRet = false;
//
// Parameters
//
// If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
ParseParameters(argc, argv);
// Process help and version before taking care about datadir
if (mapArgs.count("-?") || mapArgs.count("-help") || mapArgs.count("-version"))
{
std::string strUsage = _("Megacoin Core Daemon") + " " + _("version") + " " + FormatFullVersion() + "\n";
if (mapArgs.count("-version"))
{
strUsage += LicenseInfo();
}
else
{
strUsage += "\n" + _("Usage:") + "\n" +
" megacoind [options] " + _("Start Liteocin Core Daemon") + "\n";
strUsage += "\n" + HelpMessage(HMM_BITCOIND);
}
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
try
{
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str());
return false;
}
try
{
ReadConfigFile(mapArgs, mapMultiArgs);
} catch(std::exception &e) {
fprintf(stderr,"Error reading configuration file: %s\n", e.what());
return false;
}
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
if (!SelectParamsFromCommandLine()) {
fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n");
return false;
}
// Command-line RPC
bool fCommandLine = false;
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "megacoin:"))
fCommandLine = true;
if (fCommandLine)
{
fprintf(stderr, "Error: There is no RPC client functionality in megacoind anymore. Use the megacoin-cli utility instead.\n");
exit(1);
}
#ifndef WIN32
fDaemon = GetBoolArg("-daemon", false);
if (fDaemon)
{
fprintf(stdout, "Megacoin server starting\n");
// Daemonize
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0) // Parent process, pid is child process id
{
return true;
}
// Child process falls through to rest of initialization
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
SoftSetBoolArg("-server", true);
detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));
fRet = AppInit2(threadGroup);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "AppInit()");
} catch (...) {
PrintExceptionContinue(NULL, "AppInit()");
}
if (!fRet)
{
if (detectShutdownThread)
detectShutdownThread->interrupt();
threadGroup.interrupt_all();
// threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of
// the startup-failure cases to make sure they don't result in a hang due to some
// thread-blocking-waiting-for-another-thread-during-startup case
}
if (detectShutdownThread)
{
detectShutdownThread->join();
delete detectShutdownThread;
detectShutdownThread = NULL;
}
Shutdown();
return fRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
// Connect bitcoind signal handlers
noui_connect();
return (AppInit(argc, argv) ? 0 : 1);
}
| [
"apfelbaum@email.de"
] | apfelbaum@email.de |
b8beb46faf5a368ed14fca303db9a3d65c4e5a6e | 3d8cecd0debdf4fc68a523b17386ebad53a50a0a | /SafeArray/main.cpp | 9b8487da8dcb2257f6334a33427a4be460d14aa2 | [] | no_license | JimyTD/HOMEWORK | 705236b1ce7a456e004b6c62f98b03619e227e66 | 74b40721fb6cb66a0d1d98117e680b03b7658f82 | refs/heads/master | 2021-01-23T08:38:56.267644 | 2015-07-25T03:08:57 | 2015-07-25T03:08:57 | 32,575,704 | 0 | 0 | null | 2015-05-06T08:57:25 | 2015-03-20T09:46:29 | C++ | UTF-8 | C++ | false | false | 149 | cpp | #include <iostream>
#include"CSafeArray.h"
using namespace std;
int main()
{
CSafeArray a(10);
a[5]=1;
cout<<a;
//;
return 0;
}
| [
"604384365@qq.com"
] | 604384365@qq.com |
137e0ec58e7cd79e0e9d463657f81d0fceda87db | 7527538ce31ae3ddda75d24772b29374e4f3ba35 | /asm.tests/AsmCodeTests.cpp | c3a4de5d6c4adac4805692c7006e96fe0d4ed71d | [
"MIT"
] | permissive | janm31415/asmvm | a548ba994d46c24c6dff3f877d3ddbb4d66168b1 | 50a011d04203545d693822490e56f0313424b228 | refs/heads/main | 2023-04-01T02:53:31.945483 | 2021-03-31T10:58:40 | 2021-03-31T10:58:40 | 352,767,468 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 51,321 | cpp | ///////////////////////////////////////////////////////////////////////////////
// Includes
/////////////////////////////////////////////////////////////////////////////////
#include "AsmCodeTests.h"
#include <stdint.h>
#include "asm/asmcode.h"
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/mman.h>
#endif
#include "test_assert.h"
ASM_BEGIN
struct asmcode_fixture
{
asmcode code;
uint8_t buffer[255];
};
namespace
{
std::string _uchar_to_hex(unsigned char i)
{
std::string hex;
int h1 = (i >> 4) & 0x0f;
if (h1 < 10)
hex += '0' + char(h1);
else
hex += 'A' + char(h1) - 10;
int h2 = (i) & 0x0f;
if (h2 < 10)
hex += '0' + char(h2);
else
hex += 'A' + char(h2) - 10;
return hex;
}
void _check_buffer(uint8_t* buffer, uint64_t size, std::vector<uint8_t> expected)
{
bool error = false;
TEST_EQ(expected.size(), size);
if (size != expected.size())
error = true;
if (size == expected.size())
{
for (size_t i = 0; i < size; ++i)
{
TEST_EQ(expected[i], buffer[i]);
if (expected[i] != buffer[i])
error = true;
}
}
if (error)
{
printf("expect : ");
for (size_t i = 0; i < expected.size(); ++i)
{
printf("%s ", _uchar_to_hex(expected[i]).c_str());
}
printf("\nactual : ");
for (size_t i = 0; i < size; ++i)
{
printf("%s ", _uchar_to_hex(buffer[i]).c_str());
}
printf("\n");
}
}
void asmcode_mov_rax_number()
{
asmcode code; uint8_t buffer[255];
double d = 5.0;
code.add(asmcode::MOV, asmcode::RAX, asmcode::NUMBER, *reinterpret_cast<uint64_t*>(&d));
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x40 });
}
void asmcode_mov_rax_number_2()
{
asmcode code; uint8_t buffer[255];
int64_t d = 5;
code.add(asmcode::MOV, asmcode::RAX, asmcode::NUMBER, d);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0xC7, 0xC0, 0x05, 0x00, 0x00, 0x00 });
}
void asmcode_mov_rbx_number()
{
asmcode code; uint8_t buffer[255];
double d = 5.0;
code.add(asmcode::MOV, asmcode::RBX, asmcode::NUMBER, *reinterpret_cast<uint64_t*>(&d));
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0xBB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x40 });
}
void asmcode_mov_r15_number()
{
asmcode code; uint8_t buffer[255];
double d = 5.0;
code.add(asmcode::MOV, asmcode::R15, asmcode::NUMBER, *reinterpret_cast<uint64_t*>(&d));
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x49, 0xBF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x40 });
}
void asmcode_mov_rax_rcx()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::RAX, asmcode::RCX);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0xC8 });
}
void asmcode_mov_rcx_rax()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::RCX, asmcode::RAX);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0xC1 });
}
void asmcode_mov_rax_memrsp_8()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::RAX, asmcode::MEM_RSP, -8);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x8B, 0x44, 0x24, 0xF8 });
}
void asmcode_mov_rax_memrsp_4096()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::RAX, asmcode::MEM_RSP, -4096);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x8B, 0x84, 0x24, 0x00, 0xF0, 0xFF, 0xFF });
}
void asmcode_mov_memrsp_8_rax()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::MEM_RSP, -8, asmcode::RAX);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0x44, 0x24, 0xF8 });
}
void asmcode_mov_memrsp_4096_rax()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::MEM_RSP, -4096, asmcode::RAX);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0x84, 0x24, 0x00, 0xF0, 0xFF, 0xFF });
}
void asmcode_mov_memrsp_8_rcx()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::MEM_RSP, -8, asmcode::RCX);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0x4C, 0x24, 0xF8 });
}
void asmcode_mov_r14_mem_r13()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::R14, asmcode::MEM_R13);
code.add(asmcode::MOV, asmcode::R13, asmcode::MEM_R14);
code.add(asmcode::MOV, asmcode::R13, asmcode::MEM_R13);
code.add(asmcode::MOV, asmcode::R14, asmcode::MEM_R14);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x4D, 0x8B, 0x75, 0x00 }); //<== BUG: TO FIX
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x4D, 0x8B, 0x2E });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x4D, 0x8B, 0x6D, 0x00 });
size = code.get_instructions_list().front()[3].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x4D, 0x8B, 0x36 });
}
void asmcode_movq_xmm0_rax()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOVQ, asmcode::XMM0, asmcode::RAX);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x66, 0x48, 0x0F, 0x6E, 0xC0 });
}
void asmcode_movq_rax_xmm0()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOVQ, asmcode::RAX, asmcode::XMM0);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x66, 0x48, 0x0F, 0x7E, 0xC0 });
}
void asmcode_mov_rsp_rdx()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::RSP, asmcode::RDX);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0xD4 });
}
void asmcode_mov_rbp_r8()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::RBP, asmcode::R8);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x4C, 0x89, 0xC5 });
}
void asmcode_and_rsp_number()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::AND, asmcode::RSP, asmcode::NUMBER, 0xFFFFFFFFFFFFFFF0);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xE4, 0xF0 });
}
void asmcode_and_rsp_number_32()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::AND, asmcode::RSP, asmcode::NUMBER, 0xABCDEF);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x81, 0xE4, 0xEF, 0xCD, 0xAB, 0x00 });
}
void asmcode_and_rbp_number()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::AND, asmcode::RBP, asmcode::NUMBER, 0xFFFFFFFFFFFFFFF0);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xE5, 0xF0 });
}
void asmcode_and_rbp_number_32()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::AND, asmcode::RBP, asmcode::NUMBER, 0xABCDEF);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x81, 0xE5, 0xEF, 0xCD, 0xAB, 0x00 });
}
void asmcode_or_rsp_number()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::OR, asmcode::RSP, asmcode::NUMBER, 0xFFFFFFFFFFFFFFF0);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xCC, 0xF0 });
}
void asmcode_or_rsp_number_32()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::OR, asmcode::RSP, asmcode::NUMBER, 0xABCDEF);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x81, 0xCC, 0xEF, 0xCD, 0xAB, 0x00 });
}
void asmcode_or_rbp_number()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::OR, asmcode::RBP, asmcode::NUMBER, 0xFFFFFFFFFFFFFFF0);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xCD, 0xF0 });
}
void asmcode_or_rbp_number_32()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::OR, asmcode::RBP, asmcode::NUMBER, 0xABCDEF);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x81, 0xCD, 0xEF, 0xCD, 0xAB, 0x00 });
}
void asmcode_add_rbp_number_15()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::ADD, asmcode::RBP, asmcode::NUMBER, 15);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xC5, 0x0F });
}
void asmcode_add_rbp_number_4096()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::ADD, asmcode::RBP, asmcode::NUMBER, 4096);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x81, 0xC5, 0x00, 0x10, 0x00, 0x00 });
}
void asmcode_sub_rbp_number_15()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::SUB, asmcode::RBP, asmcode::NUMBER, 15);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xED, 0x0F });
}
void asmcode_sub_rbp_number_4096()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::SUB, asmcode::RBP, asmcode::NUMBER, 4096);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x81, 0xED, 0x00, 0x10, 0x00, 0x00 });
}
void asmcode_xor_rax_rax()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::XOR, asmcode::RAX, asmcode::RAX);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x31, 0xC0 });
}
void asmcode_xor_r14_r14()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::XOR, asmcode::R14, asmcode::R14);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x4D, 0x31, 0xF6 });
}
void asmcode_pop_rbp()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::POP, asmcode::RBP);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x5D });
}
void asmcode_push_rbp()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::PUSH, asmcode::RBP);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x55 });
}
void asmcode_ret()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::RET);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0xC3 });
}
void asmcode_intro_1()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::RBX, asmcode::R9);
code.add(asmcode::ADD, asmcode::RBX, asmcode::NUMBER, 7);
code.add(asmcode::AND, asmcode::RBX, asmcode::NUMBER, 0xFFFFFFFFFFFFFFF8);
code.add(asmcode::XOR, asmcode::R14, asmcode::R14);
code.add(asmcode::MOV, asmcode::RAX, asmcode::NUMBER, 9843185);
code.add(asmcode::MOV, asmcode::MEM_RBX, asmcode::RAX);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x4C, 0x89, 0xCB });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xC3, 0x07 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xE3, 0xF8 });
size = code.get_instructions_list().front()[3].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x4D, 0x31, 0xF6 });
size = code.get_instructions_list().front()[4].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0xC7, 0xC0, 0xF1, 0x31, 0x96, 0x00 });
size = code.get_instructions_list().front()[5].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0x03 });
}
void asmcode_store_registers()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::MEM_R10, 8, asmcode::RBX);
code.add(asmcode::MOV, asmcode::MEM_R10, 32, asmcode::RDI);
code.add(asmcode::MOV, asmcode::MEM_R10, 40, asmcode::RSI);
code.add(asmcode::MOV, asmcode::MEM_R10, 48, asmcode::RSP);
code.add(asmcode::MOV, asmcode::MEM_R10, 56, asmcode::RBP);
code.add(asmcode::MOV, asmcode::MEM_R10, 96, asmcode::R12);
code.add(asmcode::MOV, asmcode::MEM_R10, 104, asmcode::R13);
code.add(asmcode::MOV, asmcode::MEM_R10, 112, asmcode::R14);
code.add(asmcode::MOV, asmcode::MEM_R10, 120, asmcode::R15);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x49, 0x89, 0x5A, 0x08 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x49, 0x89, 0x7A, 0x20 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x49, 0x89, 0x72, 0x28 });
size = code.get_instructions_list().front()[3].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x49, 0x89, 0x62, 0x30 });
size = code.get_instructions_list().front()[4].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x49, 0x89, 0x6A, 0x38 });
size = code.get_instructions_list().front()[5].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x4D, 0x89, 0x62, 0x60 });
size = code.get_instructions_list().front()[6].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x4D, 0x89, 0x6A, 0x68 });
size = code.get_instructions_list().front()[7].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x4D, 0x89, 0x72, 0x70 });
size = code.get_instructions_list().front()[8].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x4D, 0x89, 0x7A, 0x78 });
}
void asmcode_load_registers()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::RBX, asmcode::MEM_R10, 8);
code.add(asmcode::MOV, asmcode::RDI, asmcode::MEM_R10, 32);
code.add(asmcode::MOV, asmcode::RSI, asmcode::MEM_R10, 40);
code.add(asmcode::MOV, asmcode::RSP, asmcode::MEM_R10, 48);
code.add(asmcode::MOV, asmcode::RBP, asmcode::MEM_R10, 56);
code.add(asmcode::MOV, asmcode::R12, asmcode::MEM_R10, 96);
code.add(asmcode::MOV, asmcode::R13, asmcode::MEM_R10, 104);
code.add(asmcode::MOV, asmcode::R14, asmcode::MEM_R10, 112);
code.add(asmcode::MOV, asmcode::R15, asmcode::MEM_R10, 120);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x49, 0x8B, 0x5A, 0x08 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x49, 0x8B, 0x7A, 0x20 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x49, 0x8B, 0x72, 0x28 });
size = code.get_instructions_list().front()[3].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x49, 0x8B, 0x62, 0x30 });
size = code.get_instructions_list().front()[4].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x49, 0x8B, 0x6A, 0x38 });
size = code.get_instructions_list().front()[5].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x4D, 0x8B, 0x62, 0x60 });
size = code.get_instructions_list().front()[6].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x4D, 0x8B, 0x6A, 0x68 });
size = code.get_instructions_list().front()[7].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x4D, 0x8B, 0x72, 0x70 });
size = code.get_instructions_list().front()[8].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x4D, 0x8B, 0x7A, 0x78 });
}
void asmcode_prepare_external_function_call()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::SUB, asmcode::RSP, asmcode::NUMBER, 48);
code.add(asmcode::PUSH, asmcode::R10);
code.add(asmcode::PUSH, asmcode::RBP);
code.add(asmcode::MOV, asmcode::RBP, asmcode::RSP);
code.add(asmcode::SUB, asmcode::RSP, asmcode::NUMBER, 32 + 8);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xEC, 0x30 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x41, 0x52 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x55 });
size = code.get_instructions_list().front()[3].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0xE5 });
size = code.get_instructions_list().front()[4].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xEC, 0x28 });
}
void finalize_external_function_call()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::ADD, asmcode::RSP, asmcode::NUMBER, 32 + 8);
code.add(asmcode::POP, asmcode::RBP);
code.add(asmcode::POP, asmcode::R10);
code.add(asmcode::ADD, asmcode::RSP, asmcode::NUMBER, 48);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xC4, 0x28 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x5D });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x41, 0x5A });
size = code.get_instructions_list().front()[3].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xC4, 0x30 });
}
void code_get_stack_item()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::RAX, asmcode::MEM_RSP, -1064);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x8B, 0x84, 0x24, 0xD8, 0xFB, 0xFF, 0xFF });
}
void save_rax_on_stack()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::MEM_RSP, -1064, asmcode::RAX);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0x84, 0x24, 0xD8, 0xFB, 0xFF, 0xFF });
}
void convert_short_string_to_string()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::MEM_RBP, asmcode::RAX);
code.add(asmcode::MOV, asmcode::RAX, asmcode::RBP);
code.add(asmcode::ADD, asmcode::RBP, asmcode::NUMBER, 8);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0x45, 0x00 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0xE8 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xC5, 0x08 });
}
void asmcode_call()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::CALL, asmcode::RBX);
code.add(asmcode::CALL, asmcode::MEM_RBX);
code.add(asmcode::CALL, asmcode::NUMBER, 64);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0xFF, 0xD3 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0xFF, 0x13 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0xE8, 0x40, 0x00, 0x00, 0x00 });
}
void asmcode_add_7_and_3()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::RAX, asmcode::NUMBER, 7);
code.add(asmcode::MOV, asmcode::RCX, asmcode::NUMBER, 3);
code.add(asmcode::ADD, asmcode::RAX, asmcode::RCX);
code.add(asmcode::RET);
uint64_t size = 0;
const auto& commands = code.get_instructions_list().front();
for (const auto& c : commands)
size += c.fill_opcode(buffer);
#ifdef _WIN32
unsigned char* my_func = (unsigned char*)malloc(size);
#else
unsigned char* my_func = (unsigned char*)mmap(NULL, size, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
#endif
unsigned char* ptr = my_func;
for (const auto& c : commands)
{
ptr += c.fill_opcode(ptr);
}
unsigned long i;
#ifdef _WIN32
auto success = VirtualProtect((void *)(my_func), size, 0x40/*PAGE_EXECUTE_READWRITE*/, (unsigned long *)&i);
TEST_ASSERT(success);
#endif
typedef uint64_t(*fun_ptr)(void);
uint64_t res = ((fun_ptr)(my_func))();
TEST_EQ(res, uint64_t(10));
#ifdef _WIN32
free(my_func);
#else
munmap((void*)(my_func), size);
#endif
}
void asmcode_add_two_integers()
{
asmcode code; uint8_t buffer[255];
#ifdef _WIN32
code.add(asmcode::MOV, asmcode::RAX, asmcode::RCX); // windows calling convention
code.add(asmcode::ADD, asmcode::RAX, asmcode::RDX);
#else
code.add(asmcode::MOV, asmcode::RAX, asmcode::RSI); // linux calling convention
code.add(asmcode::ADD, asmcode::RAX, asmcode::RDI);
#endif
code.add(asmcode::RET);
uint64_t size = 0;
const auto& commands = code.get_instructions_list().front();
for (const auto& c : commands)
size += c.fill_opcode(buffer);
#ifdef _WIN32
unsigned char* my_func = (unsigned char*)malloc(size);
#else
unsigned char* my_func = (unsigned char*)mmap(NULL, size, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
#endif
unsigned char* ptr = my_func;
for (const auto& c : commands)
{
ptr += c.fill_opcode(ptr);
}
unsigned long i;
#ifdef _WIN32
auto success = VirtualProtect((void *)(my_func), size, 0x40/*PAGE_EXECUTE_READWRITE*/, (unsigned long *)&i);
TEST_ASSERT(success);
#endif
typedef uint64_t(*fun_ptr)(uint64_t a, uint64_t b);
uint64_t res = ((fun_ptr)(my_func))(3, 7);
TEST_EQ(res, uint64_t(10));
res = ((fun_ptr)(my_func))(100, 211);
TEST_EQ(res, uint64_t(311));
#ifdef _WIN32
free(my_func);
#else
munmap((void*)(my_func), size);
#endif
}
void asmcode_cmp()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::CMP, asmcode::RAX, asmcode::NUMBER, 1024);
code.add(asmcode::CMP, asmcode::RBX, asmcode::NUMBER, 1024);
code.add(asmcode::CMP, asmcode::RAX, asmcode::NUMBER, 8);
code.add(asmcode::CMP, asmcode::RBX, asmcode::NUMBER, 8);
code.add(asmcode::CMP, asmcode::RAX, asmcode::RCX);
code.add(asmcode::CMP, asmcode::RBX, asmcode::RCX);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x3D, 0x00, 0x04, 0x00, 0x00 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x81, 0xFB, 0x00, 0x04, 0x00, 0x00 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xF8, 0x08 });
size = code.get_instructions_list().front()[3].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xFB, 0x08 });
size = code.get_instructions_list().front()[4].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x39, 0xC8 });
size = code.get_instructions_list().front()[5].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x39, 0xCB });
}
void asmcode_dec_inc()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::INC, asmcode::RAX);
code.add(asmcode::INC, asmcode::RBX);
code.add(asmcode::DEC, asmcode::RCX);
code.add(asmcode::DEC, asmcode::RDX);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0xFF, 0xC0 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0xFF, 0xC3 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0xFF, 0xC9 });
size = code.get_instructions_list().front()[3].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0xFF, 0xCA });
}
void asmcode_mul()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MUL, asmcode::RCX);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0xF7, 0xE1 });
}
void asmcode_div()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::DIV, asmcode::RCX);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0xF7, 0xF1 });
}
void asmcode_nop()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::NOP);
auto first_instruction = code.get_instructions_list().front().front();
auto size = first_instruction.fill_opcode(buffer);
_check_buffer(buffer, size, { 0x90 });
}
void asmcode_cvt_sd_si()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::CVTSI2SD, asmcode::XMM0, asmcode::RAX);
code.add(asmcode::CVTSI2SD, asmcode::XMM1, asmcode::RAX);
code.add(asmcode::CVTTSD2SI, asmcode::RAX, asmcode::XMM0);
code.add(asmcode::CVTTSD2SI, asmcode::RCX, asmcode::XMM1);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0xF2, 0x48, 0x0F, 0x2A, 0xC0 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0xF2, 0x48, 0x0F, 0x2A, 0xC8 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0xF2, 0x48, 0x0F, 0x2C, 0xC0 });
size = code.get_instructions_list().front()[3].fill_opcode(buffer);
_check_buffer(buffer, size, { 0xF2, 0x48, 0x0F, 0x2C, 0xC9 });
}
void asmcode_cmp_bytes()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::CMP, asmcode::BYTE_MEM_RCX, asmcode::AL);
code.add(asmcode::CMP, asmcode::BYTE_MEM_RAX, asmcode::AL);
code.add(asmcode::CMP, asmcode::BYTE_MEM_RSP, asmcode::AL);
code.add(asmcode::CMP, asmcode::BYTE_MEM_RCX, 8, asmcode::AL);
code.add(asmcode::CMP, asmcode::BYTE_MEM_RAX, 8, asmcode::AL);
code.add(asmcode::CMP, asmcode::BYTE_MEM_RSP, -8, asmcode::AL);
code.add(asmcode::CMP, asmcode::BYTE_MEM_RCX, asmcode::NUMBER, 0);
code.add(asmcode::CMP, asmcode::BYTE_MEM_RAX, asmcode::NUMBER, 0);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x38, 0x01 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x38, 0x00 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x38, 0x04, 0x24 });
size = code.get_instructions_list().front()[3].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x38, 0x41, 0x08 });
size = code.get_instructions_list().front()[4].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x38, 0x40, 0x08 });
size = code.get_instructions_list().front()[5].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x38, 0x44, 0x24, 0xF8 });
size = code.get_instructions_list().front()[6].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x80, 0x39, 0x00 });
size = code.get_instructions_list().front()[7].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x80, 0x38, 0x00 });
}
void asmcode_mov_bytes()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::AL, asmcode::BYTE_MEM_RDX);
code.add(asmcode::MOV, asmcode::BYTE_MEM_RDX, asmcode::AL);
code.add(asmcode::MOV, asmcode::DL, asmcode::BYTE_MEM_RBP);
code.add(asmcode::MOV, asmcode::BYTE_MEM_RBP, asmcode::DL);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x8A, 0x02 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x88, 0x02 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x8A, 0x55, 0x00 });
size = code.get_instructions_list().front()[3].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x88, 0x55, 0x00 });
}
void asmcode_sse_basic_ops()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::ADDSD, asmcode::XMM0, asmcode::XMM1);
code.add(asmcode::SUBSD, asmcode::XMM0, asmcode::XMM1);
code.add(asmcode::DIVSD, asmcode::XMM0, asmcode::XMM1);
code.add(asmcode::MULSD, asmcode::XMM0, asmcode::XMM1);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0xF2, 0x0F, 0x58, 0xC1 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0xF2, 0x0F, 0x5C, 0xC1 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0xF2, 0x0F, 0x5E, 0xC1 });
size = code.get_instructions_list().front()[3].fill_opcode(buffer);
_check_buffer(buffer, size, { 0xF2, 0x0F, 0x59, 0xC1 });
}
void asmcode_sse_cmp_ops()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::CMPEQPD, asmcode::XMM0, asmcode::XMM1);
code.add(asmcode::CMPLTPD, asmcode::XMM0, asmcode::XMM1);
code.add(asmcode::CMPLEPD, asmcode::XMM0, asmcode::XMM1);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x66, 0x0F, 0xC2, 0xC1, 0x00 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x66, 0x0F, 0xC2, 0xC1, 0x01 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x66, 0x0F, 0xC2, 0xC1, 0x02 });
}
void asmcode_sse_other_ops()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOVMSKPD, asmcode::RAX, asmcode::XMM0);
code.add(asmcode::SQRTPD, asmcode::XMM1, asmcode::XMM0);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x66, 0x0F, 0x50, 0xC0 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x66, 0x0F, 0x51, 0xC8 });
}
void asmcode_fpu()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::FLD, asmcode::MEM_RSP, -8);
code.add(asmcode::FLD, asmcode::MEM_RAX, 0);
code.add(asmcode::FADD);
code.add(asmcode::FADD, asmcode::ST0, asmcode::ST5);
code.add(asmcode::FADD, asmcode::ST5, asmcode::ST0);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0xDD, 0x44, 0x24, 0xF8 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0xDD, 0x00 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0xDE, 0xC1 });
size = code.get_instructions_list().front()[3].fill_opcode(buffer);
_check_buffer(buffer, size, { 0xD8, 0xC5 });
size = code.get_instructions_list().front()[4].fill_opcode(buffer);
_check_buffer(buffer, size, { 0xDC, 0xC5 });
}
void asmcode_string_literals()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::RAX, asmcode::NUMBER, 0x6F77206F6C6C6548);
code.add(asmcode::MOV, asmcode::MEM_RBP, asmcode::RAX);
code.add(asmcode::ADD, asmcode::RBP, asmcode::NUMBER, 0x0000000000000008);
code.add(asmcode::MOV, asmcode::RAX, asmcode::NUMBER, 0x0000000021646C72);
code.add(asmcode::MOV, asmcode::MEM_RBP, asmcode::RAX);
code.add(asmcode::ADD, asmcode::RBP, asmcode::NUMBER, 0x0000000000000008);
code.add(asmcode::MOV, asmcode::RAX, asmcode::RBP);
code.add(asmcode::SUB, asmcode::RAX, asmcode::NUMBER, 0x0000000000000010);
code.add(asmcode::MOV, asmcode::MEM_RBX, 8, asmcode::RAX);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0xB8, 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x77, 0x6F });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0x45, 0x00 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xC5, 0x08 });
size = code.get_instructions_list().front()[3].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0xC7, 0xC0, 0x72, 0x6C, 0x64, 0x21 });
size = code.get_instructions_list().front()[4].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0x45, 0x00 });
size = code.get_instructions_list().front()[5].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xC5, 0x08 });
size = code.get_instructions_list().front()[6].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0xE8 });
size = code.get_instructions_list().front()[7].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xE8, 0x10 });
size = code.get_instructions_list().front()[8].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0x43, 0x08 });
}
void asmcode_print_statement()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::RAX, asmcode::MEM_RBX, 8);
code.add(asmcode::MOV, asmcode::RCX, asmcode::RAX);
code.add(asmcode::SUB, asmcode::RSP, asmcode::NUMBER, 0);
code.add(asmcode::PUSH, asmcode::R10);
code.add(asmcode::PUSH, asmcode::RBP);
code.add(asmcode::MOV, asmcode::RBP, asmcode::RSP);
code.add(asmcode::SUB, asmcode::RSP, asmcode::NUMBER, 0x0000000000000028);
code.add(asmcode::ADD, asmcode::R14, asmcode::RAX);
code.add(asmcode::XOR, asmcode::R14, asmcode::R14);
code.add(asmcode::ADD, asmcode::RSP, asmcode::NUMBER, 0);
code.add(asmcode::POP, asmcode::RBP);
code.add(asmcode::POP, asmcode::R10);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x8B, 0x43, 0x08 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0xC1 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xEC, 0x00 });
size = code.get_instructions_list().front()[3].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x41, 0x52 });
size = code.get_instructions_list().front()[4].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x55 });
size = code.get_instructions_list().front()[5].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0xE5 });
size = code.get_instructions_list().front()[6].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xEC, 0x28 });
size = code.get_instructions_list().front()[7].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x49, 0x01, 0xC6 });
size = code.get_instructions_list().front()[8].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x4D, 0x31, 0xF6 });
size = code.get_instructions_list().front()[9].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xC4, 0x00 });
size = code.get_instructions_list().front()[10].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x5D });
size = code.get_instructions_list().front()[11].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x41, 0x5A });
}
void asmcode_string_literals_tst()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::RAX, asmcode::NUMBER, 0x0000000000747374);
code.add(asmcode::MOV, asmcode::MEM_RBP, 0, asmcode::RAX);
code.add(asmcode::ADD, asmcode::RBP, asmcode::NUMBER, 0x0000000000000008);
code.add(asmcode::MOV, asmcode::RAX, asmcode::RBP);
code.add(asmcode::SUB, asmcode::RAX, asmcode::NUMBER, 0x0000000000000008);
code.add(asmcode::MOV, asmcode::MEM_RBX, 8, asmcode::RAX);
code.add(asmcode::RET);
code.add(asmcode::MOV, asmcode::R10, asmcode::RCX);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0xC7, 0xC0, 0x74, 0x73, 0x74, 0x00 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0x45, 0x00 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xC5, 0x08 });
size = code.get_instructions_list().front()[3].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0xE8 });
size = code.get_instructions_list().front()[4].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xE8, 0x08 });
size = code.get_instructions_list().front()[5].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0x43, 0x08 });
size = code.get_instructions_list().front()[6].fill_opcode(buffer);
_check_buffer(buffer, size, { 0xC3 });
size = code.get_instructions_list().front()[7].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x49, 0x89, 0xCA });
}
void asmcode_eq()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::MEM_RSP, -8, asmcode::RAX);
code.add(asmcode::MOV, asmcode::RAX, asmcode::MEM_RSP, -8);
code.add(asmcode::MOVQ, asmcode::XMM0, asmcode::RAX);
code.add(asmcode::MOVQ, asmcode::XMM1, asmcode::RAX);
code.add(asmcode::CMPEQPD, asmcode::XMM0, asmcode::XMM1);
code.add(asmcode::MOVMSKPD, asmcode::RAX, asmcode::XMM0);
code.add(asmcode::CMP, asmcode::RAX, asmcode::NUMBER, 0x0000000000000003);
code.add(asmcode::MOVMSKPD, asmcode::RAX, asmcode::XMM1);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0x44, 0x24, 0xF8 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x8B, 0x44, 0x24, 0xF8 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x66, 0x48, 0x0F, 0x6E, 0xC0 });
size = code.get_instructions_list().front()[3].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x66, 0x48, 0x0F, 0x6E, 0xC8 });
size = code.get_instructions_list().front()[4].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x66, 0x0F, 0xC2, 0xC1, 0x00 });
size = code.get_instructions_list().front()[5].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x66, 0x0F, 0x50, 0xC0 });
size = code.get_instructions_list().front()[6].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x83, 0xF8, 0x03 });
size = code.get_instructions_list().front()[7].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x66, 0x0F, 0x50, 0xC1 });
}
void asmcode_int()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOVQ, asmcode::XMM0, asmcode::RAX);
code.add(asmcode::CVTTSD2SI, asmcode::RAX, asmcode::XMM0);
code.add(asmcode::CVTSI2SD, asmcode::XMM0, asmcode::RAX);
code.add(asmcode::MOVQ, asmcode::RAX, asmcode::XMM0);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x66, 0x48, 0x0F, 0x6E, 0xC0 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0xF2, 0x48, 0x0F, 0x2C, 0xC0 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0xF2, 0x48, 0x0F, 0x2A, 0xC0 });
size = code.get_instructions_list().front()[3].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x66, 0x48, 0x0F, 0x7E, 0xC0 });
}
void asmcode_checks()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::RAX, asmcode::MEM_RBX, 8);
code.add(asmcode::MOV, asmcode::MEM_R12, asmcode::RAX);
code.add(asmcode::NEG, asmcode::RAX);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x8B, 0x43, 0x08 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x49, 0x89, 0x04, 0x24 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0xF7, 0xD8 });
}
void asmcode_byte_boundary()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOV, asmcode::MEM_RBX, 128, asmcode::RAX);
code.add(asmcode::MOV, asmcode::MEM_RBX, -128, asmcode::RAX);
code.add(asmcode::MOV, asmcode::MEM_RSP, -128, asmcode::RAX);
code.add(asmcode::MOV, asmcode::MEM_RSP, 128, asmcode::RAX);
code.add(asmcode::MOV, asmcode::RAX, asmcode::NUMBER, 0x00000000ffffffff);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0x83, 0x80, 0x00, 0x00, 0x00 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0x43, 0x80 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0x44, 0x24, 0x80 });
size = code.get_instructions_list().front()[3].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x89, 0x84, 0x24, 0x80, 0x00, 0x00, 0x00 });
size = code.get_instructions_list().front()[4].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0xB8, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00 });
}
void asmcode_and_8bit()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::AND, asmcode::AL, asmcode::NUMBER, 3);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x24, 0x03 });
}
void asmcode_cmp_8bit()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::CMP, asmcode::AL, asmcode::NUMBER, 3);
code.add(asmcode::CMP, asmcode::CL, asmcode::NUMBER, 3);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x3c, 0x03 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x80, 0xF9, 0x03 });
}
void asmcode_shl_shr_sal_sar()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::SHL, asmcode::RAX, asmcode::NUMBER, 3);
code.add(asmcode::SAL, asmcode::RAX, asmcode::NUMBER, 3);
code.add(asmcode::SHR, asmcode::RAX, asmcode::NUMBER, 3);
code.add(asmcode::SAR, asmcode::RAX, asmcode::NUMBER, 3);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0xC1, 0xE0, 0x03 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0xC1, 0xE0, 0x03 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0xC1, 0xE8, 0x03 });
size = code.get_instructions_list().front()[3].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0xC1, 0xF8, 0x03 });
}
void asmcode_sete()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::SETE, asmcode::AL);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x0F, 0x94, 0xC0 });
}
void asmcode_movsd()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOVSD, asmcode::XMM0, asmcode::XMM1);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0xF2, 0x0F, 0x11, 0xC8 });
}
void asmcode_movzx()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::MOVZX, asmcode::RAX, asmcode::AL);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x0F, 0xB6, 0xC0 });
}
void asmcode_idiv()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::IDIV, asmcode::R11);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x49, 0xF7, 0xFB });
}
void asmcode_cqo()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::CQO);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x99 });
}
void asmcode_jmp()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::JMP, asmcode::R11);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x41, 0xFF, 0xE3 });
}
void asmcode_or_r15mem()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::OR, asmcode::BYTE_MEM_R15, asmcode::AL);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x41, 0x08, 0x07 });
}
void test_test()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::TEST, asmcode::RAX, asmcode::NUMBER, 1);
code.add(asmcode::TEST, asmcode::RCX, asmcode::NUMBER, 1);
code.add(asmcode::TEST, asmcode::RCX, asmcode::RDX);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0xA9, 0x01, 0x00, 0x00, 0x00 });
size = code.get_instructions_list().front()[1].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0xF7, 0xC1, 0x01, 0x00, 0x00, 0x00 });
size = code.get_instructions_list().front()[2].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x48, 0x85, 0xD1 });
}
void test_ucomisd()
{
asmcode code; uint8_t buffer[255];
code.add(asmcode::UCOMISD, asmcode::XMM0, asmcode::XMM1);
uint64_t size;
size = code.get_instructions_list().front()[0].fill_opcode(buffer);
_check_buffer(buffer, size, { 0x66, 0x0F, 0x2E, 0xC1 });
}
}
ASM_END
void run_all_asm_code_tests()
{
using namespace ASM;
asmcode_mov_rax_number();
asmcode_mov_rax_number_2();
asmcode_mov_rbx_number();
asmcode_mov_r15_number();
asmcode_mov_rax_rcx();
asmcode_mov_rcx_rax();
asmcode_mov_rax_memrsp_8();
asmcode_mov_rax_memrsp_4096();
asmcode_mov_memrsp_8_rax();
asmcode_mov_memrsp_4096_rax();
asmcode_mov_memrsp_8_rcx();
asmcode_mov_r14_mem_r13();
asmcode_movq_xmm0_rax();
asmcode_movq_rax_xmm0();
asmcode_mov_rsp_rdx();
asmcode_mov_rbp_r8();
asmcode_and_rsp_number();
asmcode_and_rsp_number_32();
asmcode_and_rbp_number();
asmcode_and_rbp_number_32();
asmcode_or_rsp_number();
asmcode_or_rsp_number_32();
asmcode_or_rbp_number();
asmcode_or_rbp_number_32();
asmcode_add_rbp_number_15();
asmcode_add_rbp_number_4096();
asmcode_sub_rbp_number_15();
asmcode_sub_rbp_number_4096();
asmcode_xor_rax_rax();
asmcode_xor_r14_r14();
asmcode_pop_rbp();
asmcode_push_rbp();
asmcode_ret();
asmcode_intro_1();
asmcode_store_registers();
asmcode_load_registers();
asmcode_prepare_external_function_call();
finalize_external_function_call();
code_get_stack_item();
save_rax_on_stack();
convert_short_string_to_string();
asmcode_call();
asmcode_add_7_and_3();
asmcode_add_two_integers();
asmcode_cmp();
asmcode_dec_inc();
asmcode_mul();
asmcode_div();
asmcode_nop();
asmcode_cvt_sd_si();
asmcode_cmp_bytes();
asmcode_mov_bytes();
asmcode_sse_basic_ops();
asmcode_sse_cmp_ops();
asmcode_sse_other_ops();
asmcode_fpu();
asmcode_string_literals();
asmcode_print_statement();
asmcode_string_literals_tst();
asmcode_eq();
asmcode_int();
asmcode_checks();
asmcode_byte_boundary();
asmcode_and_8bit();
asmcode_cmp_8bit();
asmcode_shl_shr_sal_sar();
asmcode_sete();
asmcode_movsd();
asmcode_movzx();
asmcode_idiv();
asmcode_cqo();
asmcode_jmp();
asmcode_or_r15mem();
test_test();
test_ucomisd();
} | [
"janm31415@gmail.com"
] | janm31415@gmail.com |
7ad37b784da8094953fa43f7560151a15e34b257 | 6ffbb7f19f7230e91bb91b22e375bebd1d1469a5 | /src/external-reference-table.cc | b277d195bc5b20a3aba1b5342486eb8785c13927 | [
"BSD-3-Clause",
"SunPro",
"bzip2-1.0.6"
] | permissive | mohan-chinnappan-n/v8 | bdd7eb0ca73a866a4b8710bd2cdfa04c9a4c5618 | ab5d90dab8db449aa28ac4a6f6e51933effd3369 | refs/heads/master | 2023-01-23T01:05:13.714019 | 2018-12-11T19:11:23 | 2018-12-11T20:12:19 | 161,392,086 | 0 | 0 | NOASSERTION | 2023-01-08T02:38:36 | 2018-12-11T20:50:10 | C++ | UTF-8 | C++ | false | false | 8,540 | cc | // Copyright 2016 the V8 project 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 "src/external-reference-table.h"
#include "src/accessors.h"
#include "src/counters.h"
#include "src/external-reference.h"
#include "src/ic/stub-cache.h"
#if defined(DEBUG) && defined(V8_OS_LINUX) && !defined(V8_OS_ANDROID)
#define SYMBOLIZE_FUNCTION
#include <execinfo.h>
#include <vector>
#endif // DEBUG && V8_OS_LINUX && !V8_OS_ANDROID
namespace v8 {
namespace internal {
#define ADD_EXT_REF_NAME(name, desc) desc,
#define ADD_BUILTIN_NAME(Name, ...) "Builtin_" #Name,
#define ADD_RUNTIME_FUNCTION(name, ...) "Runtime::" #name,
#define ADD_ISOLATE_ADDR(Name, name) "Isolate::" #name "_address",
#define ADD_ACCESSOR_INFO_NAME(_, __, AccessorName, ...) \
"Accessors::" #AccessorName "Getter",
#define ADD_ACCESSOR_SETTER_NAME(name) "Accessors::" #name,
// static
const char* const
ExternalReferenceTable::ref_name_[ExternalReferenceTable::kSize] = {
// Special references:
"nullptr",
// External references:
EXTERNAL_REFERENCE_LIST(ADD_EXT_REF_NAME)
EXTERNAL_REFERENCE_LIST_WITH_ISOLATE(ADD_EXT_REF_NAME)
// Builtins:
BUILTIN_LIST_C(ADD_BUILTIN_NAME)
// Runtime functions:
FOR_EACH_INTRINSIC(ADD_RUNTIME_FUNCTION)
// Isolate addresses:
FOR_EACH_ISOLATE_ADDRESS_NAME(ADD_ISOLATE_ADDR)
// Accessors:
ACCESSOR_INFO_LIST_GENERATOR(ADD_ACCESSOR_INFO_NAME, /* not used */)
ACCESSOR_SETTER_LIST(ADD_ACCESSOR_SETTER_NAME)
// Stub cache:
"Load StubCache::primary_->key",
"Load StubCache::primary_->value",
"Load StubCache::primary_->map",
"Load StubCache::secondary_->key",
"Load StubCache::secondary_->value",
"Load StubCache::secondary_->map",
"Store StubCache::primary_->key",
"Store StubCache::primary_->value",
"Store StubCache::primary_->map",
"Store StubCache::secondary_->key",
"Store StubCache::secondary_->value",
"Store StubCache::secondary_->map",
};
#undef ADD_EXT_REF_NAME
#undef ADD_BUILTIN_NAME
#undef ADD_RUNTIME_FUNCTION
#undef ADD_ISOLATE_ADDR
#undef ADD_ACCESSOR_INFO_NAME
#undef ADD_ACCESSOR_SETTER_NAME
// Forward declarations for C++ builtins.
#define FORWARD_DECLARE(Name) \
Object* Builtin_##Name(int argc, Address* args, Isolate* isolate);
BUILTIN_LIST_C(FORWARD_DECLARE)
#undef FORWARD_DECLARE
void ExternalReferenceTable::Init(Isolate* isolate) {
int index = 0;
// kNullAddress is preserved through serialization/deserialization.
Add(kNullAddress, &index);
AddReferences(isolate, &index);
AddBuiltins(&index);
AddRuntimeFunctions(&index);
AddIsolateAddresses(isolate, &index);
AddAccessors(&index);
AddStubCache(isolate, &index);
is_initialized_ = static_cast<uint32_t>(true);
USE(unused_padding_);
CHECK_EQ(kSize, index);
}
const char* ExternalReferenceTable::ResolveSymbol(void* address) {
#ifdef SYMBOLIZE_FUNCTION
char** names = backtrace_symbols(&address, 1);
const char* name = names[0];
// The array of names is malloc'ed. However, each name string is static
// and do not need to be freed.
free(names);
return name;
#else
return "<unresolved>";
#endif // SYMBOLIZE_FUNCTION
}
void ExternalReferenceTable::Add(Address address, int* index) {
ref_addr_[(*index)++] = address;
}
void ExternalReferenceTable::AddReferences(Isolate* isolate, int* index) {
CHECK_EQ(kSpecialReferenceCount, *index);
#define ADD_EXTERNAL_REFERENCE(name, desc) \
Add(ExternalReference::name().address(), index);
EXTERNAL_REFERENCE_LIST(ADD_EXTERNAL_REFERENCE)
#undef ADD_EXTERNAL_REFERENCE
#define ADD_EXTERNAL_REFERENCE(name, desc) \
Add(ExternalReference::name(isolate).address(), index);
EXTERNAL_REFERENCE_LIST_WITH_ISOLATE(ADD_EXTERNAL_REFERENCE)
#undef ADD_EXTERNAL_REFERENCE
CHECK_EQ(kSpecialReferenceCount + kExternalReferenceCount, *index);
}
void ExternalReferenceTable::AddBuiltins(int* index) {
CHECK_EQ(kSpecialReferenceCount + kExternalReferenceCount, *index);
static const Address c_builtins[] = {
#define DEF_ENTRY(Name, ...) FUNCTION_ADDR(&Builtin_##Name),
BUILTIN_LIST_C(DEF_ENTRY)
#undef DEF_ENTRY
};
for (Address addr : c_builtins) {
Add(ExternalReference::Create(addr).address(), index);
}
CHECK_EQ(kSpecialReferenceCount + kExternalReferenceCount +
kBuiltinsReferenceCount,
*index);
}
void ExternalReferenceTable::AddRuntimeFunctions(int* index) {
CHECK_EQ(kSpecialReferenceCount + kExternalReferenceCount +
kBuiltinsReferenceCount,
*index);
static constexpr Runtime::FunctionId runtime_functions[] = {
#define RUNTIME_ENTRY(name, ...) Runtime::k##name,
FOR_EACH_INTRINSIC(RUNTIME_ENTRY)
#undef RUNTIME_ENTRY
};
for (Runtime::FunctionId fId : runtime_functions) {
Add(ExternalReference::Create(fId).address(), index);
}
CHECK_EQ(kSpecialReferenceCount + kExternalReferenceCount +
kBuiltinsReferenceCount + kRuntimeReferenceCount,
*index);
}
void ExternalReferenceTable::AddIsolateAddresses(Isolate* isolate, int* index) {
CHECK_EQ(kSpecialReferenceCount + kExternalReferenceCount +
kBuiltinsReferenceCount + kRuntimeReferenceCount,
*index);
for (int i = 0; i < IsolateAddressId::kIsolateAddressCount; ++i) {
Add(isolate->get_address_from_id(static_cast<IsolateAddressId>(i)), index);
}
CHECK_EQ(kSpecialReferenceCount + kExternalReferenceCount +
kBuiltinsReferenceCount + kRuntimeReferenceCount +
kIsolateAddressReferenceCount,
*index);
}
void ExternalReferenceTable::AddAccessors(int* index) {
CHECK_EQ(kSpecialReferenceCount + kExternalReferenceCount +
kBuiltinsReferenceCount + kRuntimeReferenceCount +
kIsolateAddressReferenceCount,
*index);
static const Address accessors[] = {
// Getters:
#define ACCESSOR_INFO_DECLARATION(_, __, AccessorName, ...) \
FUNCTION_ADDR(&Accessors::AccessorName##Getter),
ACCESSOR_INFO_LIST_GENERATOR(ACCESSOR_INFO_DECLARATION, /* not used */)
#undef ACCESSOR_INFO_DECLARATION
// Setters:
#define ACCESSOR_SETTER_DECLARATION(name) FUNCTION_ADDR(&Accessors::name),
ACCESSOR_SETTER_LIST(ACCESSOR_SETTER_DECLARATION)
#undef ACCESSOR_SETTER_DECLARATION
};
for (Address addr : accessors) {
Add(addr, index);
}
CHECK_EQ(kSpecialReferenceCount + kExternalReferenceCount +
kBuiltinsReferenceCount + kRuntimeReferenceCount +
kIsolateAddressReferenceCount + kAccessorReferenceCount,
*index);
}
void ExternalReferenceTable::AddStubCache(Isolate* isolate, int* index) {
CHECK_EQ(kSpecialReferenceCount + kExternalReferenceCount +
kBuiltinsReferenceCount + kRuntimeReferenceCount +
kIsolateAddressReferenceCount + kAccessorReferenceCount,
*index);
StubCache* load_stub_cache = isolate->load_stub_cache();
// Stub cache tables
Add(load_stub_cache->key_reference(StubCache::kPrimary).address(), index);
Add(load_stub_cache->value_reference(StubCache::kPrimary).address(), index);
Add(load_stub_cache->map_reference(StubCache::kPrimary).address(), index);
Add(load_stub_cache->key_reference(StubCache::kSecondary).address(), index);
Add(load_stub_cache->value_reference(StubCache::kSecondary).address(), index);
Add(load_stub_cache->map_reference(StubCache::kSecondary).address(), index);
StubCache* store_stub_cache = isolate->store_stub_cache();
// Stub cache tables
Add(store_stub_cache->key_reference(StubCache::kPrimary).address(), index);
Add(store_stub_cache->value_reference(StubCache::kPrimary).address(), index);
Add(store_stub_cache->map_reference(StubCache::kPrimary).address(), index);
Add(store_stub_cache->key_reference(StubCache::kSecondary).address(), index);
Add(store_stub_cache->value_reference(StubCache::kSecondary).address(),
index);
Add(store_stub_cache->map_reference(StubCache::kSecondary).address(), index);
CHECK_EQ(kSpecialReferenceCount + kExternalReferenceCount +
kBuiltinsReferenceCount + kRuntimeReferenceCount +
kIsolateAddressReferenceCount + kAccessorReferenceCount +
kStubCacheReferenceCount,
*index);
CHECK_EQ(kSize, *index);
}
} // namespace internal
} // namespace v8
#undef SYMBOLIZE_FUNCTION
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
f101d1e8f39c3eea35c603e93765f86d70fcbd78 | 549554339d71ba619b8306cb539a2b648a622f9f | /joint_qualification_controllers/include/joint_qualification_controllers/checkout_controller.h | 7b8340079cd91910a6034b3dadd149ff68014955 | [] | no_license | PR2/pr2_self_test | d653524fef93e3a7701c26179aed53e88aed1515 | 886d78c20cba72b266652e4df30a1f9eb7ddc9ca | refs/heads/kinetic-devel | 2021-09-03T09:26:50.282057 | 2021-08-25T01:40:41 | 2021-08-25T01:40:41 | 11,626,702 | 2 | 5 | null | 2021-08-25T01:40:42 | 2013-07-24T05:07:43 | C++ | UTF-8 | C++ | false | false | 4,346 | h | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
// Author: Kevin Watts
#ifndef _JOINT_QUALIFICATION_CONTROLLERS_CHECKOUT_CONTROLLER_H_
#define _JOINT_QUALIFICATION_CONTROLLERS_CHECKOUT_CONTROLLER_H_
/***************************************************/
/*! \class controller::CheckoutController
\brief Checkout Controller
This tests that all joints of a robot are calibrated
and all actuators are enabled. It outputs a RobotData srv request
to the /robot_checkout topic with relevant joint and actuator information.
*/
/***************************************************/
#include "ros/ros.h"
#include <string>
#include <math.h>
#include <boost/scoped_ptr.hpp>
#include "joint_qualification_controllers/RobotData.h"
#include "realtime_tools/realtime_publisher.h"
#include "pr2_controller_interface/controller.h"
namespace joint_qualification_controllers
{
/***************************************************/
/*! \class joint_qualification_controllers::CheckoutController
\brief Checkout Controller checks state of PR2 mechanism
Verifies that all robot joints are calibrated. Publishes state of actuators and joints.
*/
/***************************************************/
class CheckoutController : public pr2_controller_interface::Controller
{
public:
enum { STARTING, LISTENING, ANALYZING, DONE};
CheckoutController();
~CheckoutController() { }
/*!
* \brief Functional way to initialize.
* \param *robot The robot that is being controlled.
* \param &n NodeHandle of mechanism control
*/
bool init( pr2_mechanism_model::RobotState *robot, ros::NodeHandle &n);
/*!
* \brief Called when controller is started or restarted
*/
void starting();
/*!
* \brief Checks joint, actuator status for calibrated and enabled.
*/
void update();
/*!
* \brief Sends data, returns true if sent
*/
bool sendData();
/*!
* \brief Perform the test analysis
*/
void analysis(double time, bool timeout = false);
private:
pr2_mechanism_model::RobotState *robot_;
ros::Time initial_time_; /**< Start time of the test. */
double timeout_;
joint_qualification_controllers::RobotData robot_data_;
int state_;
int joint_count_;
int actuator_count_;
bool done() { return state_ == DONE; }
bool data_sent_;
double last_publish_time_;
// RT service call
boost::scoped_ptr<realtime_tools::RealtimePublisher<
joint_qualification_controllers::RobotData> > robot_data_pub_;
};
}
#endif // _JOINT_QUALIFICATION_CONTROLLERS_CHECKOUT_CONTROLLER_H_
| [
"watts@7275ad9f-c29b-430a-bdc5-66f4b3af1622"
] | watts@7275ad9f-c29b-430a-bdc5-66f4b3af1622 |
51af8194f02ac063defddde5b025c1af98602e01 | 0061bfb09a0f2e41adfe6903b287f181610deb22 | /tests/cpp-tests/Classes/PerformanceTest/PerformanceSpriteTest.h | 8ec6eb62dff5e2868673bb39f91350111c54b4d9 | [] | no_license | joyjjjjz/cocos2d-x | 2c151e4991083a3fb93eaf29ca13cb4982d03200 | f6f316afcd1c18f5a99f797c0a390cd449c8eaca | refs/heads/v3 | 2021-01-02T22:52:57.527595 | 2018-01-08T13:47:34 | 2018-01-08T13:47:34 | 99,409,531 | 4 | 0 | null | 2017-08-05T08:22:35 | 2017-08-05T08:22:35 | null | UTF-8 | C++ | false | false | 4,685 | h | /****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __PERFORMANCE_SPRITE_TEST_H__
#define __PERFORMANCE_SPRITE_TEST_H__
#include <vector>
#include "PerformanceTest.h"
class SubTest
{
public:
~SubTest();
void removeByTag(int tag);
cocos2d::Sprite* createSpriteWithTag(int tag);
void initWithSubTest(int nSubTest, cocos2d::Node* parent);
protected:
int _subtestNumber;
cocos2d::Node* _parentNode;
};
class SpriteMenuLayer : public PerformBasicLayer
{
public:
SpriteMenuLayer(bool bControlMenuVisible, int nMaxCases = 0, int nCurCase = 0)
: PerformBasicLayer(bControlMenuVisible, nMaxCases, nCurCase)
{
}
virtual void restartCallback(cocos2d::Ref* sender) override;
virtual void nextCallback(cocos2d::Ref* sender) override;
virtual void backCallback(cocos2d::Ref* sender) override;
virtual void showCurrentTest();
};
class SpriteMainScene : public cocos2d::Scene
{
public:
virtual ~SpriteMainScene();
virtual std::string title() const;
virtual std::string subtitle() const;
void initWithSubTest(int nSubTest, int nNodes);
void updateNodes();
void testNCallback(cocos2d::Ref* sender);
void onIncrease(cocos2d::Ref* sender);
void onDecrease(cocos2d::Ref* sender);
virtual void doTest(cocos2d::Sprite* sprite) = 0;
int getSubTestNum() { return _subtestNumber; }
int getNodesNum() { return _quantityNodes; }
virtual void onEnter() override;
virtual void onExit() override;
void updateAutoTest(float dt);
void onAutoTest(cocos2d::Ref* sender);
// auto tests
static bool _s_autoTest;
static int _s_nSpriteCurCase;
static int _s_spritesQuatityIndex;
static int _s_spritesQuanityArray[];
static std::vector<float> _s_saved_fps;
protected:
void dumpProfilerFPS();
void saveFPS();
void beginAutoTest();
void endAutoTest();
void nextAutoTest();
void finishAutoTest();
void autoShowSpriteTests(int curCase, int subTest,int nodes);
int _lastRenderedCount;
int _quantityNodes;
SubTest* _subTest;
int _subtestNumber;
};
class SpritePerformTestA : public SpriteMainScene
{
public:
virtual void doTest(cocos2d::Sprite* sprite) override;
virtual std::string title() const override;
};
class SpritePerformTestB : public SpriteMainScene
{
public:
virtual void doTest(cocos2d::Sprite* sprite) override;
virtual std::string title() const override;
};
class SpritePerformTestC : public SpriteMainScene
{
public:
virtual void doTest(cocos2d::Sprite* sprite) override;
virtual std::string title() const override;
};
class SpritePerformTestD : public SpriteMainScene
{
public:
virtual void doTest(cocos2d::Sprite* sprite) override;
virtual std::string title() const override;
};
class SpritePerformTestE : public SpriteMainScene
{
public:
virtual void doTest(cocos2d::Sprite* sprite) override;
virtual std::string title() const override;
};
class SpritePerformTestF : public SpriteMainScene
{
public:
virtual void doTest(cocos2d::Sprite* sprite) override;
virtual std::string title() const override;
};
class SpritePerformTestG : public SpriteMainScene
{
public:
virtual void doTest(cocos2d::Sprite* sprite) override;
virtual std::string title() const override;
};
void runSpriteTest();
#endif
| [
"joyjjjz@126.com"
] | joyjjjz@126.com |
a485478eccbe889a136539d865202c5a52fee250 | 0a3585fe75690663f29b4daac50a86a7abb396e8 | /Ch9/shortestPash.cpp | fcba400ba9410b9299da2ca133520ba63d98abbb | [] | no_license | DavidLee999/Data_Structures_and_Algorithm_Analysis_Cpp | 0d976cae6928e077acb18cda2f59690f7ef79df5 | fda8fce28ed271f55ba12d00fdfad34e1109c7a1 | refs/heads/master | 2021-01-22T03:40:05.415337 | 2018-10-28T15:12:42 | 2018-10-28T15:12:42 | 92,391,493 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,091 | cpp | #include <iostream>
// #include <list>
#include <vector>
#include <unordered_map>
#include <queue>
#include <algorithm>
#include <memory>
using namespace std;
#include "Vertex.h"
#include "Vertex.cpp"
void shortestPath(const vector<shared_ptr<Vertex> >& points, const shared_ptr<Vertex>& item, unordered_map<int, int>& dist, unordered_map<int, int>& path)
{
const int MAX = 100;
std::queue<shared_ptr<Vertex> > q;
for (auto it = points.begin(); it != points.end(); ++it)
{
dist.insert(make_pair((*it)->name, MAX));
path.insert(make_pair((*it)->name, 0));
}
dist.find(item->name)->second = 0;
// auto ptr = find(points.begin(), points.end(), item);
// q.push(*ptr);
//
q.push(item);
while (!q.empty()) {
shared_ptr<Vertex>& v = q.front();
q.pop();
int currDist = dist.find(v->name)->second;
for (auto it = v->adj.begin(); it != v->adj.end(); ++it)
{
if (dist.find((*it)->name)->second == MAX)
{
dist.find((*it)->name)->second = currDist + 1;
path.find((*it)->name)->second = v->name;
q.push(*it);
}
}
}
}
int main()
{
vector<shared_ptr<Vertex> > points;
int from, to;
while (cin >> from >> to) {
shared_ptr<Vertex> p1 { new Vertex { from } };
shared_ptr<Vertex> p2 { new Vertex { to } };
readEdges(points, p1, p2);
// auto it1 = find(points.begin(), points.end(), p1);
// auto it2 = find(points.begin(), points.end(), p2);
// if (it1 == points.end() && it2 == points.end())
// {
// ++(p2->indegree);
// p1->add(p2);
// points.push_back(p1);
// points.push_back(p2);
// }
// else if (it1 != points.end() && it2 == points.end())
// {
// ++(p2->indegree);
// (*it1)->add(p2);
// points.push_back(p2);
// }
// else if (it1 == points.end() && it2 != points.end())
// {
// ++((*it2)->indegree);
// p1->add(*it2);
// points.push_back(p1);
// }
// else if (it1 != points.end() && it2 != points.end())
// {
// if ((*it1)->isLinked(*it2) == false)
// {
// ++((*it2)->indegree);
// (*it1)->add(*it2);
// }
// }
}
cin.clear();
int start;
cout << "input start point: ";
cin >> start;
auto it = find(points.begin(), points.end(), Vertex { start });
// shared_ptr<Vertex> item (new Vertex { start });
unordered_map<int, int> dist;
unordered_map<int, int> path;
shortestPath(points, *it, dist, path);
cout << "Distances: " << '\n';
for (auto it = dist.begin(); it != dist.end(); ++it)
cout << it->first << " " << it->second << '\n';
cout << "Path: " << '\n';
for (auto it = path.begin(); it != path.end(); ++it)
cout << it->first << " " << it->second <<'\n';
return 0;
}
| [
"MoonLee003@outlook.com"
] | MoonLee003@outlook.com |
5f3f297973c612c0d780a74d18db2ec44fb1349f | 411d3fd50c0d46abbd0dd521c24eb04fd388cae2 | /main.cpp | 0e4393ba73394e6c422ad70fda04598b4b378027 | [] | no_license | SSE4/ghactions_test | 9b0d8ef30bb5f003951ced54751ccc5f7ebb6946 | 7b5220da96d58566dbc83e152c96c6e7f52c5e3b | refs/heads/main | 2023-02-05T03:57:53.858703 | 2020-12-25T15:05:28 | 2020-12-25T15:05:28 | 324,378,518 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 46 | cpp | #include <iostream>
int main() { return 0; }
| [
"noreply@github.com"
] | SSE4.noreply@github.com |
2ff397cf2cd57c514eb5eab25eb51a3bb9555829 | e386dbf7da7796f5d04fdf33873365cd50ec6e31 | /study/20170831_StarCraftMinigame/Dx3D/SphereCollider.cpp | 8a6b3eddbe3db835f609c61bcef08e93ca0145e5 | [] | no_license | jaejunlee0538/NoThinking | 0e52658d9c089faf3c15da94110cf63d6f5eb430 | 456c42b5a44cd63a5aef1e5220adc376b49bfa2c | refs/heads/master | 2021-01-21T12:52:39.357221 | 2017-12-02T01:58:14 | 2017-12-02T01:58:14 | 102,102,482 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,682 | cpp | #include "stdafx.h"
#include "SphereCollider.h"
LPD3DXMESH SphereCollider::m_pSphere = NULL;
SphereCollider::SphereCollider(float radius, D3DXVECTOR3 offsetFromParent)
:m_radius(radius), m_offsetFromParent(offsetFromParent)
{
if (m_pSphere==NULL) {
D3DXCreateSphere(g_pD3DDevice, radius, 10, 10, &m_pSphere, NULL);
}
}
SphereCollider::~SphereCollider()
{
SAFE_RELEASE(m_pSphere);
}
bool SphereCollider::CheckRayCollision(D3DXVECTOR3 rayPos, D3DXVECTOR3 rayDir, float * distance) const
{
//광선의 위치를 구의 로컬 좌표계로 변경한다.
D3DXVECTOR3 sphereWorldPos = m_offsetFromParent;
if (m_parentObject) {
sphereWorldPos += m_parentObject->getWorldPosition();
}
rayPos = rayPos - sphereWorldPos;
//a*t*t + b*t + c = 0;
float a, b, c;
a = D3DXVec3Dot(&rayDir, &rayDir);
b = 2 * D3DXVec3Dot(&rayPos, &rayDir);
c = D3DXVec3Dot(&rayPos, &rayPos) - m_radius*m_radius;
//근의 공식
float test = b*b - 4*a*c;//판별식
if (test < 0.0f)//판별식이 0보다 작으면 방정식의 해가 존재하지 않는다!
return false;
float t = (-b - test) / (2 * a);
if (t < 0.0f) //t가 0보다 작다는 것은 충돌하는 구가 광선의 뒤쪽에 있다는 뜻!
return false;
if (distance) //거리가 필요하면 충돌점까지의 거리를 계산해서 반환해준다.
*distance = D3DXVec3Length(&(rayDir*t));
return true;
}
void SphereCollider::Render() const
{
g_pD3DDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME);
g_pD3DDevice->SetRenderState(D3DRS_LIGHTING, false);
m_pSphere->DrawSubset(0);
g_pD3DDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
g_pD3DDevice->SetRenderState(D3DRS_LIGHTING, true);
}
| [
"jaejun0201@gmail.com"
] | jaejun0201@gmail.com |
02126184d20800b53f02e3c4b078b32f1ad00f6a | 8ad605137c8f492d3d870781ab58be824c5a25d9 | /pshapes.h | 7a881548e84e8b742f995ab3e08b60cb37406e8c | [] | no_license | anwlf/world3d_qt4_linux | 0bd064ed0007653129809439bf13c4b9826f374b | d5b8a5b9f595af417cc715167ff1d6b1fe6af9ce | refs/heads/master | 2020-06-03T06:12:51.710725 | 2019-06-12T20:30:36 | 2019-06-12T20:30:36 | 191,475,070 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,026 | h | /****************************************************************************/
/* Math3D Library. Performs 3D Vector and matrix calculations. */
/* Simle 3D graphics objects. */
/* Copyright (C), 1991-2012, Andrei Volkov */
/* */
/* This program is free software: you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation, either version 3 of the License, or */
/* (at your option) any later version. */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/****************************************************************************/
/* Points shapes header */
/* A. Volkov, 2016 */
/****************************************************************************/
#ifndef PSHAPES_H
#define PSHAPES_H
#include "math3d/obshapes.h"
//01.23.2016
class points_shape: public shape
{
protected:
REAL_TYPE size_coef;
public:
//points_shape() {size_coef=1.0;}
points_shape(REAL_TYPE k) {size_coef=k;}
};
class sphere_points_shape: public points_shape
{
protected:
public:
sphere_points_shape(REAL_TYPE k=1.0) : points_shape(k) {}
virtual image* create_image(int f_c, REAL_TYPE size, basis v_b,
vector l_v, video_params* v_p) {
location p = v_b(location(0,0,0));
REAL_TYPE d=p[2];
if (d<=0) return NULL;
int r = (int)((v_p->scale*size*size_coef/2)/d);
/*
if (d>0)
{
//v_proections[i][0]=v_p->max_x/2+v_p->scale*(vrtx[0]/d);
//v_proections[i][1]=v_p->max_y/2-v_p->scale*v_p->aspect_ratio*(vrtx[1]/d);
REAL_TYPE x0 = v_p->max_x/2 + v_p->scale*((p[0]-r)/d);
REAL_TYPE x1 = v_p->max_x/2 + v_p->scale*((p[0]+r)/d);
REAL_TYPE y0 = v_p->max_y/2-v_p->scale*v_p->aspect_ratio*((p[1]-r)/d);
REAL_TYPE y1 = v_p->max_y/2-v_p->scale*v_p->aspect_ratio*((p[1]+r)/d);
}*/
//
int cnt = (int)pow(r*2,2);
image* im = new image();
points_image *pim = new points_image(f_c, cnt, NULL, d);
vector l=l_v;
l.normalization();
int z=0;
for (int i=-r; i<=r; i++) {
for (int j=-r; j<=r; j++) {
REAL_TYPE y = i;
REAL_TYPE x = j;
if ((pow(x,2)+pow(y,2))<pow(r,2)) {
p = v_b(location(x,y,sqrt(pow(r,2) - (pow(x,2)+pow(y,2)))));
if (p[2]>0) {
int _x = v_p->max_x/2+p[0];
int _y = v_p->max_y/2-v_p->aspect_ratio*p[1];
(*pim)[z++]=v_point(f_c,_x,_y,(ort(p)*(-l)));
}
}
}
}
(*im)+=pim;
return im;
}
};
class ellipsoid_points_shape: public points_shape
{
protected:
REAL_TYPE x_coef,y_coef,z_coef;
public:
ellipsoid_points_shape(REAL_TYPE k=1.0,REAL_TYPE x_c=1.0,REAL_TYPE y_c=1.0,REAL_TYPE z_c=1.0) : points_shape(k) {x_coef=x_c;y_coef=y_c;z_coef=z_c;}
virtual image* create_image(int f_c, REAL_TYPE size, basis v_b,
vector l_v, video_params* v_p) {
location p = v_b(location(0,0,0));
REAL_TYPE d=p[2];
if (d<=0) return NULL;
int r = (int)((v_p->scale*size*size_coef/2)/d);
//
int cnt = (int)pow(r*2,2);
image* im = new image();
points_image *pim = new points_image(f_c, cnt, NULL, d);
vector l=l_v;
l.normalization();
int z=0;
for (int i=-r; i<=r; i++) {
for (int j=-r; j<=r; j++) {
REAL_TYPE y = i;
REAL_TYPE x = j;
if ((x_coef*pow(x,2)+y_coef*pow(y,2))<z_coef*pow(r,2)) {
p = v_b(location(x,y,sqrt((pow(r,2) - (x_coef*pow(x,2)+y_coef*pow(y,2)))/z_coef)));
if (p[2]>0) {
int _x = v_p->max_x/2+p[0];
int _y = v_p->max_y/2-v_p->aspect_ratio*p[1];
(*pim)[z++]=v_point(f_c,_x,_y,(ort(p)*(-l)));
}
}
}
}
(*im)+=pim;
return im;
}
};
#endif // PSHAPES_H
| [
"avolkovs@verizon.com"
] | avolkovs@verizon.com |
02e2afba0ddf38eb4bc21829e66c98a7037f214e | 56433f582bdf2a2924e7a267196aa7319b487ee7 | /FengYun/frameworks/runtime-src/Classes/misc/HeartBeatProcess.cpp | f9e8a5c4c98387c41a5c5eb06065cc65aadd1df9 | [] | no_license | evil-squad/FengYunMobile_Client | c0fff092527b932107f774dc50c85f5b5f05df87 | 0364b7268fcb30d9d78b154bd01ee0219e340a44 | refs/heads/master | 2021-03-22T03:42:00.743759 | 2017-03-31T02:26:43 | 2017-03-31T02:26:43 | 79,458,672 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,006 | cpp | /**
* @file HeartBeatProcess.cpp
* @project FengYun
* @author Bluce Nong <nongjinxia@mokylin.com>
* @Created by BluceNong on 2017/2/16.
* @ Copyright © 2017年 MokyLin Bluce Nong <nongjinxia@mokylin.com>. All rights reserved.
*/
#include "HeartBeatProcess.h"
#include "cocos2d.h"
#include "GameModule.h"
#include "NetManager.h"
#include "GameApp.h"
BEGIN_NS_FY
HeartBeatProcess::HeartBeatProcess()
: delayTime(0.0)
, running(false)
, currDelayTime(0)
, sendTime(0)
, isStartClock(false)
, overTime(0)
{
cocos2d::Director::getInstance()->getScheduler()->schedule(std::bind(&HeartBeatProcess::update, this, std::placeholders::_1), this, 0, false, "heart_beat_process");
}
HeartBeatProcess::~HeartBeatProcess()
{
cocos2d::Director::getInstance()->getScheduler()->unschedule("heart_beat_process", this);
}
void HeartBeatProcess::recvHeartPacket()
{
currDelayTime = 0;
GameApp::runInMainThread([this](){
});
}
void HeartBeatProcess::resetTime()
{
currDelayTime = 0;
sendTime = 0;
isStartClock = false;
}
void HeartBeatProcess::setDelayTime(float time)
{
delayTime = time;
}
void HeartBeatProcess::setOverTime(float time)
{
overTime = time;
}
void HeartBeatProcess::start()
{
running = true;
}
void HeartBeatProcess::stop()
{
running = false;
isStartClock = false;
sendTime = 0;
currDelayTime = 0;
}
void HeartBeatProcess::sendHeartBeatPkt()
{
isStartClock = true;
sendTime = 0;
return;
fy::GamePacketSendHelper h(2ul << 32 | 15, 0);
}
void HeartBeatProcess::update(float time)
{
if (!running) return ;
if (isStartClock)
{
sendTime += time;
if (sendTime > overTime)
{
running = false;
GameApp::getInstance()->sendEvent("game_connection_losted");
}
}
else
{
currDelayTime += time;
if (currDelayTime > delayTime)
{
sendHeartBeatPkt();
}
}
}
END_NS_FY
| [
"351536411@163.com"
] | 351536411@163.com |
14ba920927a216a579dc38d08d0829392b92173e | 29abd0070a63d8cd0fdf3fca533572344c9611ee | /Source/SettingsEditors/EQCurveEditor.h | c252f41896777d42cd08ddf71d439fe65bfca75d | [] | no_license | PaulPopat/SimpleGenetics | d8c660b081ad1d72ec094bbe1c26591aa5d65c35 | f29ba1b5ff0a1ad0883ef09b732ece92f2f2585d | refs/heads/Master | 2021-01-10T16:03:47.411786 | 2018-05-27T11:21:46 | 2018-05-27T11:21:46 | 52,290,313 | 0 | 1 | null | 2016-02-26T12:08:04 | 2016-02-22T17:11:31 | C++ | UTF-8 | C++ | false | false | 773 | h | /*
==============================================================================
EQCurveEditor.h
Created: 18 Feb 2016 3:52:50pm
Author: Paul Popat
==============================================================================
*/
#ifndef EQCURVEEDITOR_H_INCLUDED
#define EQCURVEEDITOR_H_INCLUDED
#include "../JuceLibraryCode/JuceHeader.h"
#include "../Settings/CustomLookAndFeel.h"
#include "GraphEditor.h"
#include "../Utilities/ListenerComponents.h"
#include "../Settings/Settings.h"
class EQCurveEditor : public GraphEditor
{
public:
EQCurveEditor(String Title, String Name);
private:
void floorData() override;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(EQCurveEditor)
};
#endif // EQCURVEEDITOR_H_INCLUDED
| [
"p.t.popat@googlemail.com"
] | p.t.popat@googlemail.com |
2c3b99cc0819c2e40946d5d9e884845997b39c86 | 55b6ea69cef65682158432ab2372fd55004d1165 | /abc/misc/silkroad.cpp | d82e477c4924c0a1d74ad6fb114090d7c9146788 | [] | no_license | cohhei/code | f7a9e46c23732f455c5db04103e242f6a6c35a82 | ac7f35bbcae29a676baa73fb0156f96f73e11a3e | refs/heads/master | 2022-11-10T23:48:15.511545 | 2020-06-29T00:07:11 | 2020-06-29T00:07:11 | 255,014,172 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 586 | cpp | #include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;
const int MAX_N = 1000;
const int MAX_M = 1000;
int dp[MAX_M + 1][MAX_N + 1];
int main() {
int n, m;
cin >> n >> m;
vector<int> d(n);
rep(i, n) cin >> d[i];
vector<int> c(m);
rep(i, m) cin >> c[i];
// dp[city][day] = cost
for (int i = 1; i <= n; i++) rep(j, m + 1) dp[i][j] = 1001001001;
rep(i, n) rep(j, m) {
dp[i + 1][j + 1] = min(dp[i + 1][j], dp[i][j] + d[i] * c[j]);
}
cout << dp[n][m] << endl;
return 0;
}
| [
"kohei.kimura@nulab.com"
] | kohei.kimura@nulab.com |
8e50b102dd0221eb9d602bc62fe2ce5e061b7eeb | 995bf7af4f3e502a0e286610cbbc97cdf237aea0 | /SOA/Communication.cpp | 1e0c1ac42f39d44fe078b43b95b4f472a46147ed | [] | no_license | indrimuska/Service-Oriented-Architecture | cfe8cd054d1b1248afe223128b040629cb265a0e | 0bfd145a0233a590e9401849f62f9b4ab2709bc0 | refs/heads/master | 2020-05-17T18:10:26.189900 | 2012-05-02T19:48:16 | 2012-05-02T19:48:16 | 3,846,514 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,513 | cpp | /**
* @file SOA/Communication.cpp
* @brief Definizione dei metodi dichiarati in SOA/Communication.hpp
*
* @date 01/04/2012
* @author Indri Muska <indrimuska@gmail.com>
* @author Paolo Antonio Rossi <paoloantoniorossi@gmail.com>
*
* @copyright Copyright (c) 2012 Indri Muska, Paolo Antonio Rossi. All rights reserved.
*/
#include "Communication.hpp"
Socket::Socket() {
sk = -1;
}
Socket::Socket(int sk) {
this->sk = sk;
}
bool Socket::sendInt(int number) {
int i = (int) send(sk, &number, sizeof(int), 0);
if (i == -1 || i < (int) sizeof(int)) {
cerr << "Errore nell'invio di un intero\n";
return false;
}
return true;
}
bool Socket::sendString(string s_string) {
if (!sendInt((int) s_string.size())) return false;
int i = (int) send(sk, s_string.c_str(), s_string.size(), MSG_WAITALL);
if (i == -1 || i < (int) s_string.size()) {
cerr << "Errore nel'invio di una stringa\n";
return false;
}
return true;
}
bool Socket::sendFile(string filename) {
struct stat info;
if (stat(filename.c_str(), &info) == -1) {
cerr << "Impossibile determinare la dimensione del file specificato\n"
"Controllare che il file esista e che si abbiano i permessi necessari\n";
return false;
}
int dimension = static_cast<int>(info.st_size);
FILE * file;
if (!(file = fopen(filename.c_str(), "r"))) {
cerr << "Impossibile aprire il file specificato\n"
"Controllare di avere i permessi necessari\n";
return false;
}
char * content = new char[dimension];
if ((int) fread(content, 1, dimension, file) < dimension) {
cerr << "Impossibile leggere il contenuto del file\n"
"Controllare di avere i permessi necessari\n";
return false;
}
fclose(file);
if (!sendString(filename)) return false;
if (!sendInt(dimension)) return false;
int i = (int) send(sk, content, dimension, MSG_WAITALL);
if (i == -1 || i < dimension) {
cerr << "Errore nell'invio del file\n";
return false;
}
delete content;
return true;
}
bool Socket::sendBinary(void * binary, size_t length) {
int i = (int) send(sk, binary, length, MSG_WAITALL);
if (i == -1 || i < (int) length) {
cerr << "Errore nel'invio di un insieme di bit\n";
return false;
}
return true;
}
bool Socket::sendParameter(parameter &p) {
parameter_direction direction = p.getDirection();
if (!sendBinary((void *) &direction, sizeof(parameter_direction))) return false;
parameter_type type = p.getType();
if (!sendBinary((void *) &type, sizeof(parameter_type))) return false;
if (!sendInt((int) p.getValueDimension())) return false;
if (p.getValueDimension()) {
void * buffer = malloc(p.getValueDimension());
p.getValue(buffer);
if (!sendBinary(buffer, p.getValueDimension())) return false;
free(buffer);
}
return true;
}
bool Socket::receiveInt(int &number) {
int i = (int) recv(sk, &number, sizeof(int), MSG_WAITALL);
if (i == -1 || i < (int) sizeof(int)) {
cerr << "Errore nella ricezione di un intero\n";
return false;
}
return true;
}
bool Socket::receiveString(string &s_string) {
int length;
if (!receiveInt(length)) return false;
char * c_string = new char[length + 1];
memset(c_string, '\0', length + 1);
int i = (int) recv(sk, c_string, length, MSG_WAITALL);
if (i == -1 || i < length) {
cerr << "Errore nella ricezione di una stringa\n";
return false;
}
s_string = string(c_string);
delete c_string;
return true;
}
bool Socket::receiveFile(string where, string &filename) {
int dimension;
if (!receiveString(filename)) return false;
if (!receiveInt(dimension)) return false;
char * binary = new char[dimension + 1];
memset(binary, '\0', dimension + 1);
int i = (int) recv(sk, binary, dimension, MSG_WAITALL);
if (i == -1 || i < dimension) {
cerr << "Il file non è stato ricevuto correttamente\n";
return false;
}
binary[dimension] = '\0';
FILE * file;
if (!(file = fopen((where + '/' + filename).c_str(), "w"))) {
cerr << "Impossibile creare il file richiesto\n"
"Controllare di avere i permessi necessari\n";
return false;
}
i = (int) fwrite(binary, 1, dimension, file);
fclose(file);
delete binary;
if (i < dimension) {
cerr << "Impossibile salvare il contenuto del file richiesto\n"
"Controllare di avere i permessi necessari\n";
return false;
}
return true;
}
bool Socket::receiveBinary(void * binary, size_t length) {
bzero(binary, length);
int i = (int) recv(sk, binary, length, MSG_WAITALL);
if (i == -1 || i < (int) length) {
cerr << "Errore nella ricezione di un insieme di bit\n";
return false;
}
return true;
}
bool Socket::receiveParameter(parameter &p) {
parameter_direction direction;
if (!receiveBinary((void *) &direction, sizeof(parameter_direction))) return false;
parameter_type type;
if (!receiveBinary((void *) &type, sizeof(parameter_type))) return false;
int length;
if (!receiveInt(length)) return false;
p = parameter(direction, type);
if (length > 0) {
void * buffer = malloc(length);
if (!receiveBinary(buffer, length)) return false;
p.setValue(buffer, length);
free(buffer);
}
return true;
}
bool Socket::operator==(const Socket &operand) {
return sk == operand.sk;
}
bool Socket::closeSocket() {
if (close(sk) == -1) {
cerr << "Impossibile chiudere la connessione\n";
return false;
}
return true;
}
bool Communicator::startListener(string port, int backlog_queue) {
listenSocket = socket(PF_INET, SOCK_STREAM, 0);
if (listenSocket == -1) {
cerr << "Impossibile connettersi al server richiesto\n"
"Controllare che sia in linea e disponibile\n";
return false;
}
struct sockaddr_in server;
memset(&server, '\0', sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = htons(atoi(port.c_str()));
if (bind(listenSocket, (sockaddr *) &server, sizeof(server)) == -1) {
cerr << "Impossibile associare l'indirizzo al socket\n"
"Riprovare più tardi\n";
return false;
}
if (listen(listenSocket, backlog_queue) == -1) {
cerr << "Impossibile mettersi in ascolto sul socket creato\n"
"Riprovare più tardi\n";
return false;
}
return true;
}
bool Communicator::waitForConnection(Socket &clientSocket) {
struct sockaddr_in client;
socklen_t client_size = sizeof(client);
int client_socket = accept(listenSocket, (sockaddr *) &client, &client_size);
if (client_socket == -1) {
cerr << "Impossibile accettare la connessione\n";
return false;
}
clientSocket = Socket(client_socket);
sockets.push_back(clientSocket);
return true;
}
bool Communicator::waitForConnection(Socket &clientSocket, string &clientAddress) {
struct sockaddr_in client;
socklen_t client_size = sizeof(client);
int client_socket = accept(listenSocket, (sockaddr *) &client, &client_size);
if (client_socket == -1) {
cerr << "Impossibile accettare la connessione\n";
return false;
}
clientSocket = Socket(client_socket);
char client_address[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &client.sin_addr, client_address, INET_ADDRSTRLEN);
clientAddress = client_address;
sockets.push_back(clientSocket);
return true;
}
bool Communicator::stopListener() {
if (close(listenSocket) == -1) {
cerr << "Impossibile chiudere la connessione\n"
"Riprovare più tardi\n";
return false;
}
return true;
}
bool Communicator::connectTo(string address, string port, Socket &S_socket) {
int sk = socket(PF_INET, SOCK_STREAM, 0);
if (sk == -1) {
cerr << "Impossibile connettersi al server richiesto\n"
"Controllare che sia in linea e disponibile\n";
return false;
}
struct sockaddr_in server;
memset(&server, '\0', sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(atoi(port.c_str()));
if (!inet_pton(AF_INET, (char *) address.c_str(), &server.sin_addr.s_addr)) {
cerr << "Indirizzo non valido, il formato deve essere del tipo 127.0.0.1\n";
return false;
}
if (connect(sk, (sockaddr *) &server, sizeof(struct sockaddr)) == -1) {
cerr << "Impossibile connettersi al server richiesto\n"
"Controllare che sia in linea e disponibile\n";
return false;
}
S_socket = Socket(sk);
sockets.push_back(S_socket);
return true;
}
bool Communicator::closeAllCommunications() {
for (int i = 0; i < (int) sockets.size(); i++)
if (!sockets[i].closeSocket()) return false;
sockets.clear();
return true;
}
string Communicator::getIP() {
char hostname[MAXHOSTNAMELEN];
if (gethostname(hostname, MAXHOSTNAMELEN)) {
struct in_addr address;
struct hostent * ip = gethostbyname(hostname);
memcpy(&address, ip->h_addr_list[0], sizeof(in_addr));
return inet_ntoa(address);
}
return "127.0.0.1";
} | [
"indrimuska@gmail.com"
] | indrimuska@gmail.com |
0a8ba79345e2c95ec92015c22975e2ddae75d2e2 | f6f0f87647e23507dca538760ab70e26415b8313 | /6.1.0/msvc2019_64/include/QtNetwork/qnetworkcookie.h | 4ff78433323a1c6586de223e06ebb42435d2ab13 | [] | no_license | stenzek/duckstation-ext-qt-minimal | a942c62adc5654c03d90731a8266dc711546b268 | e5c412efffa3926f7a4d5bf0ae0333e1d6784f30 | refs/heads/master | 2023-08-17T16:50:21.478373 | 2023-08-15T14:53:43 | 2023-08-15T14:53:43 | 233,179,313 | 3 | 1 | null | 2021-11-16T15:34:28 | 2020-01-11T05:05:34 | C++ | UTF-8 | C++ | false | false | 4,346 | h | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtNetwork module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QNETWORKCOOKIE_H
#define QNETWORKCOOKIE_H
#include <QtNetwork/qtnetworkglobal.h>
#include <QtCore/QSharedDataPointer>
#include <QtCore/QList>
#include <QtCore/QMetaType>
#include <QtCore/QObject>
QT_BEGIN_NAMESPACE
class QByteArray;
class QDateTime;
class QString;
class QUrl;
class QNetworkCookiePrivate;
class Q_NETWORK_EXPORT QNetworkCookie
{
Q_GADGET
public:
enum RawForm {
NameAndValueOnly,
Full
};
enum class SameSite {
Default,
None,
Lax,
Strict
};
Q_ENUM(SameSite)
explicit QNetworkCookie(const QByteArray &name = QByteArray(), const QByteArray &value = QByteArray());
QNetworkCookie(const QNetworkCookie &other);
~QNetworkCookie();
QNetworkCookie &operator=(QNetworkCookie &&other) noexcept { swap(other); return *this; }
QNetworkCookie &operator=(const QNetworkCookie &other);
void swap(QNetworkCookie &other) noexcept { qSwap(d, other.d); }
bool operator==(const QNetworkCookie &other) const;
inline bool operator!=(const QNetworkCookie &other) const
{ return !(*this == other); }
bool isSecure() const;
void setSecure(bool enable);
bool isHttpOnly() const;
void setHttpOnly(bool enable);
SameSite sameSitePolicy() const;
void setSameSitePolicy(SameSite sameSite);
bool isSessionCookie() const;
QDateTime expirationDate() const;
void setExpirationDate(const QDateTime &date);
QString domain() const;
void setDomain(const QString &domain);
QString path() const;
void setPath(const QString &path);
QByteArray name() const;
void setName(const QByteArray &cookieName);
QByteArray value() const;
void setValue(const QByteArray &value);
QByteArray toRawForm(RawForm form = Full) const;
bool hasSameIdentifier(const QNetworkCookie &other) const;
void normalize(const QUrl &url);
static QList<QNetworkCookie> parseCookies(const QByteArray &cookieString);
private:
QSharedDataPointer<QNetworkCookiePrivate> d;
friend class QNetworkCookiePrivate;
};
Q_DECLARE_SHARED(QNetworkCookie)
#ifndef QT_NO_DEBUG_STREAM
class QDebug;
Q_NETWORK_EXPORT QDebug operator<<(QDebug, const QNetworkCookie &);
#endif
QT_END_NAMESPACE
Q_DECLARE_METATYPE(QNetworkCookie)
#endif
| [
"stenzek@gmail.com"
] | stenzek@gmail.com |
6f9635cfad21293586d13f75de62a934f9c9944c | 51ea7ec0e9d8993010a2e565377b03c5deb2b298 | /solved/arihon/2/2.1.3_maze.cpp | 4064fadc04e357ae13451108d4643107a4b9bc7d | [] | no_license | PreSoichiSumi/CompetitiveProgrammingLibrary | 1dd1d2e1ede119f0b58a6067ef395bb3665ffead | 7d3b6d61303fb03dcea1b90c0a75d3057fbd3b2c | refs/heads/master | 2021-06-27T00:50:08.684118 | 2017-09-16T20:17:32 | 2017-09-16T20:17:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,391 | cpp | #include <iostream>
#include <stdio.h>
#include <queue>
#include <climits>
using namespace std;
typedef pair<int,int> P;
const int INF=INT_MAX/2;
//const int INF=1000;
const int MAXRC=50;
char maze[MAXRC + 1][MAXRC + 1];
int dist[MAXRC + 1][MAXRC + 1];
int r,c,sx,sy,gx,gy;
int dx[4]={-1,0,1,0};
int dy[4]={0,-1,0,1};
int bfs(){
std::queue<P> qu;
qu.push(P(sx,sy));
dist[sx][sy]=0;
while (!qu.empty()){
P now=qu.front();qu.pop();
if(now.first==gx && now.second==gy)
break;
for (int i = 0; i < 4; i++) {
int x=now.first+dx[i];
int y=now.second+dy[i];
if(0<=x && x<r && 0<=y && y<c && maze[x][y]=='.' && dist[x][y]==INF){
dist[x][y]=dist[now.first][now.second]+1;
qu.push(P(x,y));
}
}
}
return dist[gx][gy];
}
void printMat(int* arr){
for (int i = 0; i < r; i++) {
for (int j = 0; j <c ; j++) {
cout<<arr[i*(MAXRC+1)+j]<<" \t ";
}
cout<<endl;
}
}
int main(int argc, char ** argv) {
cin>> r>>c;
cin>>sx>>sy;
cin>>gx>>gy;
sx--;sy--;gx--;gy--;
for (int i = 0; i < r ; i++) {
scanf("%s", maze[i]);
}
fill(dist[0], dist[MAXRC+1], INF);
// printMat(dist[0]);
// cout<<endl<<bfs()<<endl<<endl;
// printMat(dist[0]);
cout<<bfs()<<endl;
return 0;
} | [
"s-sumi@ist.osaka-u.ac.jp"
] | s-sumi@ist.osaka-u.ac.jp |
a5737d5995264f1afb914d3a132914daeda1b93d | 87b7a592f6daee1efbf2c0653678d787e0b2bd95 | /src/BenchmarkApplication/Scenarios/Containers/Ringbuffer_Benchmarks.cpp | 5695471e1fd711547eeb5d0bc58b44fd97981562 | [] | no_license | ParzivalSec/Spark | 1c4f04cd00ff31a2b767347b74875b207e52b649 | 2255eeb53db50e3c16b63cda577bf24c6c8cc069 | refs/heads/master | 2021-03-24T10:18:42.208167 | 2018-05-12T15:29:09 | 2018-05-12T15:29:09 | 122,495,290 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 932 | cpp | #include "Ringbuffer_Benchmarks.h"
#include "../CommonStruct.h"
#include "RingBuffer/RingBuffer.h"
static const size_t RINGBUFFER_COUNT = 1000;
static const size_t WRAPPING_OFFSET = 500;
void ringbuffer_1000_write()
{
sp::container::RingBuffer<AllocationData, RINGBUFFER_COUNT> ringbuffer;
for (size_t idx = 0; idx < RINGBUFFER_COUNT; ++idx)
{
ringbuffer.Write(AllocationData());
}
}
void ringbuffer_1000_read()
{
sp::container::RingBuffer<AllocationData, RINGBUFFER_COUNT> ringbuffer;
for (size_t idx = 0; idx < RINGBUFFER_COUNT; ++idx)
{
ringbuffer.Write(AllocationData());
}
for (size_t idx = 0; idx < RINGBUFFER_COUNT; ++idx)
{
AllocationData* data = ringbuffer.Read();
}
}
void ringbuffer_500_write_wrapping()
{
sp::container::RingBuffer<AllocationData, RINGBUFFER_COUNT> ringbuffer;
for (size_t idx = 0; idx < RINGBUFFER_COUNT + WRAPPING_OFFSET; ++idx)
{
ringbuffer.Write(AllocationData());
}
}
| [
"lukas.vogl12@gmail.com"
] | lukas.vogl12@gmail.com |
bd2226e8011c821456dd40aeab81a9b79c2c829b | fbfdc0fa28d3d8a9cb4ae2615b721cf5e89bd081 | /examples/i2c_scanner/I2C_scanner.ino | 07977242b3c147ee98376ec8bb0f25808f239526 | [
"MIT"
] | permissive | VCSFA-MARS/TSLPB | 1285ad6c607217699d0aad5c55e5b7a0e9b92524 | e6d53a25968b29f8592ef450cf3dacb68c3c3da4 | refs/heads/master | 2020-05-19T04:25:59.267752 | 2019-05-15T12:51:50 | 2019-05-15T12:51:50 | 184,825,782 | 0 | 0 | MIT | 2019-05-15T12:51:52 | 2019-05-03T22:06:38 | C++ | UTF-8 | C++ | false | false | 1,066 | ino | #include "TSLPB.h"
TSLPB pb;
ThinsatPacket_t missionData;
void setup() {
// put your setup code here, to run once:
pb.begin();
}
void loop() {
byte error, address;
int nDevices;
Serial.println("Scanning...");
nDevices = 0;
for(address = 1; address < 127; address++ )
{
// The i2c_scanner uses the return value of
// the Write.endTransmisstion to see if
// a device did acknowledge to the address.
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0)
{
Serial.print("I2C device found at address 0x");
if (address<16)
Serial.print("0");
Serial.print(address,HEX);
Serial.println(" !");
nDevices++;
}
else if (error==4)
{
Serial.print("Unknown error at address 0x");
if (address<16)
Serial.print("0");
Serial.println(address,HEX);
}
}
if (nDevices == 0)
Serial.println("No I2C devices found\n");
else
Serial.println("done\n");
delay(50000); // wait 5 seconds for next scan
} | [
"nick.counts@gmail.com"
] | nick.counts@gmail.com |
a8c4129600ea6f8389d061805aabfac7a90160c4 | e966d5df4db23e394a5e24cfd387a912e9004be9 | /Graph Algorithms/Bridges_In_Graph.cpp | bb12a7ae9c44ab79291627f48c6b5567e34235a3 | [] | no_license | Tatvam/Data-Structure-And-Algorithms | f90f6a436841620e1209d8b89bd618eec97caede | abe1e2b6ca2a6796bfb25c9af19a13850351c6ff | refs/heads/master | 2020-03-12T17:40:29.702916 | 2018-11-06T06:37:37 | 2018-11-06T06:37:37 | 130,742,021 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,892 | cpp | /**************************************************
* NAME: TATVAM DADHEECH(td_1417) *
* INSTITUITION: IIT BHUBANESWAR *
**************************************************/
#include <bits/stdc++.h>
using namespace std;
typedef vector<long long> vl;
typedef vector<string> vs;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
#define vzero fill(v.begin(), v.end(), 0);
#define re(i, n) for(int i = 0; i < n; i++)
#define test int t; cin >> t; while(t--)
#define rep(i,a,b) for(int i = (a); i <= (b); i++)
#define ren(i,a,b) for(int i = (a); i >= (b); i--)
#define turbo ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define MOD 1000000007
#define PI 3.1415926535897932384626433832795
#define MAX 100001
#define INF (1<<20)
#define si(x) scanf("%d",&x)
#define sl(x) scanf("%lld",&x)
#define ss(s) scanf("%s",s)
#define pi(x) printf("%d\n",x)
#define pl(x) printf("%lld\n",x)
#define ps(s) printf("%s\n",s)
vector<int> adj[100000];
vector<bool> visited(100000,false);
vector<int> disc(100000);
vector<int> low(100000);
vector<int> parent(100000,-1);
vector<bool> arti(100000,false);
int tim = 0;
void dfs(int u)
{
disc[u]=low[u]=tim++;
visited[u]=true;
for(int i=0;i<adj[u].size();i++)
{
int v = adj[u][i];
if(visited[v]==false){
parent[v]=u;
dfs(adj[u][i]);
low[u]=min(low[u],low[v]);
if(low[v]>disc[u]){
cout<<u<<" "<<v<<endl;
}
}
else if(parent[u]!=v){
low[u]=min(low[u],disc[v]);
}
}
}
int main(){
int nodes,edges;
cin>>nodes>>edges;
re(i,edges){
int x,y;
cin>>x>>y;
adj[x].push_back(y);
adj[y].push_back(x);
}
re(i,nodes){
if(visited[i]==false){
dfs(i);
}
}
} | [
"td14@iitbbs.ac.in"
] | td14@iitbbs.ac.in |
53d29daa99d73e988355a4d507b3266bee46b618 | a4ba3644a14ae8ba0f81a70e69b0a9a3e8e4e231 | /C+ Driving License.cpp | 0b4df542b1a6ac516acac0d4e7ef1bc0cfe2ed7b | [] | no_license | molinexx/Portfolio | c09e8ac6b3a3dd576a96270daabc376c8a28da91 | ee1f41d9d93801c967bfeca36e97be0f07875b66 | refs/heads/master | 2021-07-31T19:27:58.146620 | 2021-07-19T16:24:30 | 2021-07-19T16:24:30 | 215,858,375 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 542 | cpp | #include <iostream>
using namespace std;
void student(char[],int);
int main() {
const char STUDENT_ANSWERS=20;
char questions[STUDENT_ANSWERS];
char correctAnswers[] = { 'A','D','B','B','C','B','A','B','C','D','A','C','D','B','D','C','C','A','D','B' };
student(questions, STUDENT_ANSWERS);
while ()
system("pause");
return 0;
}
void student(char questions[],int size) {
cout << " enter answers to all questions; ";
for (int i = 0; i < size;i++) {
cout << i + 1 << ". ";
cin >> questions[i];
}
}
| [
"noreply@github.com"
] | molinexx.noreply@github.com |
9d1dc29253f574761edc479fd1eb45abd93a5683 | 120cf10a541b4462cacbfb81b1263b3675f99e97 | /tests/AdapterTest/tst_adapter.cpp | bcbc12ac18755d3d4d297bcd125ea2dc0a55850d | [
"MIT"
] | permissive | xishuai416/qt-json-1 | 65b7173b4d4f351dd6f56a1e6116c08016ea6ba7 | aab888bc3d0878d7c13411e4445616e69ca81842 | refs/heads/master | 2023-03-16T00:42:13.275190 | 2020-05-20T15:36:32 | 2020-05-20T15:36:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,083 | cpp | #include <QtTest>
#include <serializableadapter.h>
#include <testserializable.h>
using namespace QtJson;
class AdapterTest : public QObject
{
Q_OBJECT
private slots:
void testWrapNormalType();
void testWrapSerializableType();
};
void AdapterTest::testWrapNormalType()
{
QCOMPARE(SerializableAdapter<int>::toJson(42), QJsonValue{42});
QCOMPARE(SerializableAdapter<int>::toCbor(42), QCborValue{42});
QCOMPARE(SerializableAdapter<int>::fromJson(QJsonValue{42}), 42);
QCOMPARE(SerializableAdapter<int>::fromCbor(QCborValue{42}), 42);
}
void AdapterTest::testWrapSerializableType()
{
QCOMPARE(SerializableAdapter<TestSerializable>::toJson({4.2}), QJsonValue{4.2});
QCOMPARE(SerializableAdapter<TestSerializable>::toCbor({4.2}), QCborValue{4.2});
QCOMPARE(SerializableAdapter<TestSerializable>::fromJson(QJsonValue{4.2}), TestSerializable{4.2});
QCOMPARE(SerializableAdapter<TestSerializable>::fromCbor(QCborValue{4.2}), TestSerializable{4.2});
}
QTEST_APPLESS_MAIN(AdapterTest)
#include "tst_adapter.moc"
| [
"Skycoder42@users.noreply.github.com"
] | Skycoder42@users.noreply.github.com |
9524720b07f4b88a0058fa02f1e73f56388fb6a3 | 43b11b5555ff17973aa222432fc5a3593b6ef3d8 | /Boiler/Boiler.ino | 0531636eeb00da469c7deafed191f826d2cae840 | [] | no_license | ChiHyeonKim/Arduino | ca111d86f294eb5435bd2ace0c5417d6576b7f32 | fec68ec7cd7deed796a50053a8911bb5b58a5cc7 | refs/heads/master | 2021-01-20T13:28:27.462160 | 2017-02-21T15:49:03 | 2017-02-21T15:49:03 | 82,693,264 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,669 | ino | #include <SoftwareSerial.h>
#include "DHT11.h"
DHT11 dht11(4);
SoftwareSerial btSerial(2, 3);
int power = 0, heat = 0, buzer = 0; //POWER 0 : OFF, 1 : ON. HEAT 0: NANBANG, 1 : HOT WATER
void setup() {
// put your setup code here, to run once:
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
Serial.begin(9600);
btSerial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
if(btSerial.available() ){
char ch = btSerial.read();
//CLICK POWER ON
if( ch == '1'){
//IF POWER OFF
if(power == 0){
power = 1; //POWER
heat = 0;
digitalWrite(5, HIGH);
digitalWrite(6, HIGH);
digitalWrite(7, LOW);
}
//IF POWER ON
else{
power = 0;
digitalWrite(5, LOW);
digitalWrite(6, LOW);
digitalWrite(7, LOW);
}
}
//CLICK NANBANG
else if( ch == '2'){
if (power == 1 && heat == 1 ){
heat = 0;
digitalWrite(6, HIGH);
digitalWrite(7, LOW);
}
}
else if( ch == '3'){
if (power == 1 && heat == 0 ){
heat = 1;
digitalWrite(6, LOW);
digitalWrite(7, HIGH);
}
}
else if( ch == '4'){
if ( buzer == 0 ){
buzer = 1;
digitalWrite(8, HIGH);
}
else{
buzer = 0;
digitalWrite(8, LOW);
}
}
else if( ch == '4'){
}
}
float temp, humidity;
int err = dht11.read(humidity, temp);
if(err == 0){
btSerial.print(temp);
btSerial.print(":");
btSerial.print(humidity);
btSerial.print(":");
}
}
| [
"chihyunll@naver.com"
] | chihyunll@naver.com |
76f6a2219f354cef4f92c0b4489e6657b225765e | 9dc59ad7b3cd31ad4e248e728d45ff89a0bb446a | /Examples_3/Unit_Tests/src/20_JointAttachment/20_JointAttachment.cpp | ed80e48060db5063d09e82ca56e11c28ac0dc631 | [
"Apache-2.0"
] | permissive | Affrounia/The-Forge | 35917928754993b360c16e09d1cead0b9efca6d6 | 2ecdccaf57f86548e3b1e27a35e489fdda53147f | refs/heads/master | 2020-06-18T09:39:11.646296 | 2019-06-29T03:00:41 | 2019-06-29T03:00:41 | 196,255,893 | 1 | 0 | Apache-2.0 | 2019-07-10T18:26:19 | 2019-07-10T18:26:19 | null | UTF-8 | C++ | false | false | 38,283 | cpp | /*
* Copyright (c) 2018-2019 Confetti Interactive Inc.
*
* This file is part of The-Forge
* (see https://github.com/ConfettiFX/The-Forge).
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*/
/********************************************************************************************************
*
* The Forge - ANIMATION - JOINT ATTACHMENT UNIT TEST
*
* The purpose of this demo is to show how to attach an object to a rig which
* is playing an animation using the animation middleware
*
*********************************************************************************************************/
// Interfaces
#include "../../../../Common_3/OS/Interfaces/ICameraController.h"
#include "../../../../Common_3/OS/Interfaces/IApp.h"
#include "../../../../Common_3/OS/Interfaces/ILogManager.h"
#include "../../../../Common_3/OS/Interfaces/IFileSystem.h"
#include "../../../../Common_3/OS/Interfaces/ITimeManager.h"
#include "../../../../Common_3/OS/Interfaces/IProfiler.h"
// Rendering
#include "../../../../Common_3/Renderer/IRenderer.h"
#include "../../../../Common_3/Renderer/ResourceLoader.h"
// Middleware packages
#include "../../../../Middleware_3/Animation/SkeletonBatcher.h"
#include "../../../../Middleware_3/Animation/AnimatedObject.h"
#include "../../../../Middleware_3/Animation/Animation.h"
#include "../../../../Middleware_3/Animation/Clip.h"
#include "../../../../Middleware_3/Animation/ClipController.h"
#include "../../../../Middleware_3/Animation/Rig.h"
#include "../../../../Middleware_3/UI/AppUI.h"
#include "../../../../Common_3/OS/Input/InputSystem.h"
#include "../../../../Common_3/OS/Input/InputMappings.h"
// tiny stl
#include "../../../../Common_3/ThirdParty/OpenSource/EASTL/vector.h"
#include "../../../../Common_3/ThirdParty/OpenSource/EASTL/string.h"
// Math
#include "../../../../Common_3/OS/Math/MathTypes.h"
// Memory
#include "../../../../Common_3/OS/Interfaces/IMemoryManager.h"
const char* pszBases[FSR_Count] = {
"../../../src/20_JointAttachment/", // FSR_BinShaders
"../../../src/20_JointAttachment/", // FSR_SrcShaders
"../../../UnitTestResources/", // FSR_Textures
"../../../UnitTestResources/", // FSR_Meshes
"../../../UnitTestResources/", // FSR_Builtin_Fonts
"../../../src/20_JointAttachment/", // FSR_GpuConfig
"../../../UnitTestResources/", // FSR_Animation
"", // FSR_Audio
"", // FSR_OtherFiles
"../../../../../Middleware_3/Text/", // FSR_MIDDLEWARE_TEXT
"../../../../../Middleware_3/UI/", // FSR_MIDDLEWARE_UI
};
//--------------------------------------------------------------------------------------------
// RENDERING PIPELINE DATA
//--------------------------------------------------------------------------------------------
#define MAX_INSTANCES 815 // For allocating space in uniform block. Must match with shader.
const uint32_t gImageCount = 3;
bool bToggleMicroProfiler = false;
bool bPrevToggleMicroProfiler = false;
uint32_t gFrameIndex = 0;
Renderer* pRenderer = NULL;
Queue* pGraphicsQueue = NULL;
CmdPool* pCmdPool = NULL;
Cmd** ppCmds = NULL;
SwapChain* pSwapChain = NULL;
RenderTarget* pDepthBuffer = NULL;
Fence* pRenderCompleteFences[gImageCount] = { NULL };
Semaphore* pImageAcquiredSemaphore = NULL;
Semaphore* pRenderCompleteSemaphores[gImageCount] = { NULL };
#ifdef TARGET_IOS
VirtualJoystickUI gVirtualJoystick;
#endif
DepthState* pDepth = NULL;
RasterizerState* pPlaneRast = NULL;
RasterizerState* pSkeletonRast = NULL;
Shader* pSkeletonShader = NULL;
Buffer* pJointVertexBuffer = NULL;
Buffer* pBoneVertexBuffer = NULL;
Buffer* pCuboidVertexBuffer = NULL;
Pipeline* pSkeletonPipeline = NULL;
int gNumberOfJointPoints;
int gNumberOfBonePoints;
int gNumberOfCuboidPoints;
Shader* pPlaneDrawShader = NULL;
Buffer* pPlaneVertexBuffer = NULL;
Pipeline* pPlaneDrawPipeline = NULL;
RootSignature* pRootSignature = NULL;
DescriptorBinder* pDescriptorBinderPlane = NULL;
struct UniformBlockPlane
{
mat4 mProjectView;
mat4 mToWorldMat;
};
UniformBlockPlane gUniformDataPlane;
Buffer* pPlaneUniformBuffer[gImageCount] = { NULL };
struct UniformBlock
{
mat4 mProjectView;
mat4 mToWorldMat[MAX_INSTANCES];
vec4 mColor[MAX_INSTANCES];
vec3 mLightPosition;
vec3 mLightColor;
};
UniformBlock gUniformDataCuboid;
Buffer* pCuboidUniformBuffer[gImageCount] = { NULL };
//--------------------------------------------------------------------------------------------
// CAMERA CONTROLLER & SYSTEMS (File/Log/UI)
//--------------------------------------------------------------------------------------------
ICameraController* pCameraController = NULL;
UIApp gAppUI;
GuiComponent* pStandaloneControlsGUIWindow = NULL;
TextDrawDesc gFrameTimeDraw = TextDrawDesc(0, 0xff00ffff, 18);
GpuProfiler* pGpuProfiler = NULL;
//--------------------------------------------------------------------------------------------
// ANIMATION DATA
//--------------------------------------------------------------------------------------------
// AnimatedObjects
AnimatedObject gStickFigureAnimObject;
// Animations
Animation gWalkAnimation;
// ClipControllers
ClipController gWalkClipController;
// Clips
Clip gWalkClip;
// Rigs
Rig gStickFigureRig;
// SkeletonBatcher
SkeletonBatcher gSkeletonBatcher;
// Filenames
const char* gStickFigureName = "stickFigure/skeleton.ozz";
const char* gWalkClipName = "stickFigure/animations/walk.ozz";
const char* pPlaneImageFileName = "Skybox_right1";
const int gSphereResolution = 30; // Increase for higher resolution joint spheres
const float gBoneWidthRatio = 0.2f; // Determines how far along the bone to put the max width [0,1]
const float gJointRadius = gBoneWidthRatio * 0.5f; // set to replicate Ozz skeleton
// Timer to get animationsystem update time
static HiresTimer gAnimationUpdateTimer;
// Attached Cuboid Object
mat4 gCuboidTransformMat = mat4::identity(); //Will get updated as the animated object updates
const mat4 gCuboidScaleMat = mat4::scale(vec3(0.05f, 0.05f, 0.4f));
const vec4 gCuboidColor = vec4(1.f, 0.f, 0.f, 1.f);
//--------------------------------------------------------------------------------------------
// UI DATA
//--------------------------------------------------------------------------------------------
const unsigned int kLeftHandMiddleJointIndex = 18; // index of the left hand's middle joint in this specific skeleton
struct UIData
{
struct BlendParamsData
{
bool* mAutoSetBlendParams;
float* mWalkClipWeight;
float* mThreshold;
};
BlendParamsData mBlendParams;
struct AttachedObjectData
{
unsigned int mJointIndex = kLeftHandMiddleJointIndex;
float mXOffset = -0.001f; // Values that will place it naturally in the hand
float mYOffset = 0.041f;
float mZOffset = -0.141f;
};
AttachedObjectData mAttachedObject;
struct ClipData
{
bool* mPlay;
bool* mLoop;
float mAnimationTime; // will get set by clip controller
float* mPlaybackSpeed;
};
ClipData mWalkClip;
struct GeneralSettingsData
{
bool mShowBindPose = false;
bool mDrawAttachedObject = true;
bool mDrawPlane = true;
};
GeneralSettingsData mGeneralSettings;
};
UIData gUIData;
// Hard set the controller's time ratio via callback when it is set in the UI
void WalkClipTimeChangeCallback() { gWalkClipController.SetTimeRatioHard(gUIData.mWalkClip.mAnimationTime); }
//--------------------------------------------------------------------------------------------
// APP CODE
//--------------------------------------------------------------------------------------------
class JointAttachment: public IApp
{
public:
bool Init()
{
// WINDOW AND RENDERER SETUP
//
RendererDesc settings = { 0 };
initRenderer(GetName(), &settings, &pRenderer);
if (!pRenderer) //check for init success
return false;
// CREATE COMMAND LIST AND GRAPHICS/COMPUTE QUEUES
//
QueueDesc queueDesc = {};
queueDesc.mType = CMD_POOL_DIRECT;
addQueue(pRenderer, &queueDesc, &pGraphicsQueue);
addCmdPool(pRenderer, pGraphicsQueue, false, &pCmdPool);
addCmd_n(pCmdPool, false, gImageCount, &ppCmds);
for (uint32_t i = 0; i < gImageCount; ++i)
{
addFence(pRenderer, &pRenderCompleteFences[i]);
addSemaphore(pRenderer, &pRenderCompleteSemaphores[i]);
}
addSemaphore(pRenderer, &pImageAcquiredSemaphore);
// INITIALIZE RESOURCE/DEBUG SYSTEMS
//
initResourceLoaderInterface(pRenderer);
#ifdef TARGET_IOS
if (!gVirtualJoystick.Init(pRenderer, "circlepad", FSR_Absolute))
return false;
#endif
initProfiler(pRenderer, gImageCount);
profileRegisterInput();
addGpuProfiler(pRenderer, pGraphicsQueue, &pGpuProfiler, "GpuProfiler");
// INITIALIZE PIPILINE STATES
//
ShaderLoadDesc planeShader = {};
planeShader.mStages[0] = { "plane.vert", NULL, 0, FSR_SrcShaders };
planeShader.mStages[1] = { "plane.frag", NULL, 0, FSR_SrcShaders };
ShaderLoadDesc basicShader = {};
basicShader.mStages[0] = { "basic.vert", NULL, 0, FSR_SrcShaders };
basicShader.mStages[1] = { "basic.frag", NULL, 0, FSR_SrcShaders };
addShader(pRenderer, &planeShader, &pPlaneDrawShader);
addShader(pRenderer, &basicShader, &pSkeletonShader);
Shader* shaders[] = { pSkeletonShader, pPlaneDrawShader };
RootSignatureDesc rootDesc = {};
rootDesc.mShaderCount = 2;
rootDesc.ppShaders = shaders;
addRootSignature(pRenderer, &rootDesc, &pRootSignature);
DescriptorBinderDesc descriptorBinderDescPlane = { pRootSignature, 0, 2 };
addDescriptorBinder(pRenderer, 0, 1, &descriptorBinderDescPlane, &pDescriptorBinderPlane);
RasterizerStateDesc rasterizerStateDesc = {};
rasterizerStateDesc.mCullMode = CULL_MODE_NONE;
addRasterizerState(pRenderer, &rasterizerStateDesc, &pPlaneRast);
RasterizerStateDesc skeletonRasterizerStateDesc = {};
skeletonRasterizerStateDesc.mCullMode = CULL_MODE_FRONT;
addRasterizerState(pRenderer, &skeletonRasterizerStateDesc, &pSkeletonRast);
DepthStateDesc depthStateDesc = {};
depthStateDesc.mDepthTest = true;
depthStateDesc.mDepthWrite = true;
depthStateDesc.mDepthFunc = CMP_LEQUAL;
addDepthState(pRenderer, &depthStateDesc, &pDepth);
// GENERATE VERTEX BUFFERS
//
// Generate joint vertex buffer
float* pJointPoints;
generateSpherePoints(&pJointPoints, &gNumberOfJointPoints, gSphereResolution, gJointRadius);
uint64_t jointDataSize = gNumberOfJointPoints * sizeof(float);
BufferLoadDesc jointVbDesc = {};
jointVbDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_VERTEX_BUFFER;
jointVbDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_GPU_ONLY;
jointVbDesc.mDesc.mSize = jointDataSize;
jointVbDesc.mDesc.mVertexStride = sizeof(float) * 6;
jointVbDesc.pData = pJointPoints;
jointVbDesc.ppBuffer = &pJointVertexBuffer;
addResource(&jointVbDesc);
// Need to free memory;
conf_free(pJointPoints);
// Generate bone vertex buffer
float* pBonePoints;
generateBonePoints(&pBonePoints, &gNumberOfBonePoints, gBoneWidthRatio);
uint64_t boneDataSize = gNumberOfBonePoints * sizeof(float);
BufferLoadDesc boneVbDesc = {};
boneVbDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_VERTEX_BUFFER;
boneVbDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_GPU_ONLY;
boneVbDesc.mDesc.mSize = boneDataSize;
boneVbDesc.mDesc.mVertexStride = sizeof(float) * 6;
boneVbDesc.pData = pBonePoints;
boneVbDesc.ppBuffer = &pBoneVertexBuffer;
addResource(&boneVbDesc);
// Need to free memory;
conf_free(pBonePoints);
// Generate attached object vertex buffer
float* pCuboidPoints;
generateCuboidPoints(&pCuboidPoints, &gNumberOfCuboidPoints);
uint64_t cuboidDataSize = gNumberOfCuboidPoints * sizeof(float);
BufferLoadDesc cuboidVbDesc = {};
cuboidVbDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_VERTEX_BUFFER;
cuboidVbDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_GPU_ONLY;
cuboidVbDesc.mDesc.mSize = cuboidDataSize;
cuboidVbDesc.mDesc.mVertexStride = sizeof(float) * 6;
cuboidVbDesc.pData = pCuboidPoints;
cuboidVbDesc.ppBuffer = &pCuboidVertexBuffer;
addResource(&cuboidVbDesc);
// Need to free memory;
conf_free(pCuboidPoints);
//Generate plane vertex buffer
float planePoints[] = { -10.0f, 0.0f, -10.0f, 1.0f, 0.0f, 0.0f, -10.0f, 0.0f, 10.0f, 1.0f, 1.0f, 0.0f,
10.0f, 0.0f, 10.0f, 1.0f, 1.0f, 1.0f, 10.0f, 0.0f, 10.0f, 1.0f, 1.0f, 1.0f,
10.0f, 0.0f, -10.0f, 1.0f, 0.0f, 1.0f, -10.0f, 0.0f, -10.0f, 1.0f, 0.0f, 0.0f };
uint64_t planeDataSize = 6 * 6 * sizeof(float);
BufferLoadDesc planeVbDesc = {};
planeVbDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_VERTEX_BUFFER;
planeVbDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_GPU_ONLY;
planeVbDesc.mDesc.mSize = planeDataSize;
planeVbDesc.mDesc.mVertexStride = sizeof(float) * 6;
planeVbDesc.pData = planePoints;
planeVbDesc.ppBuffer = &pPlaneVertexBuffer;
addResource(&planeVbDesc);
BufferLoadDesc ubDescPlane = {};
ubDescPlane.mDesc.mDescriptors = DESCRIPTOR_TYPE_UNIFORM_BUFFER;
ubDescPlane.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU;
ubDescPlane.mDesc.mSize = sizeof(UniformBlockPlane);
ubDescPlane.mDesc.mFlags = BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT;
ubDescPlane.pData = NULL;
for (uint32_t i = 0; i < gImageCount; ++i)
{
ubDescPlane.ppBuffer = &pPlaneUniformBuffer[i];
addResource(&ubDescPlane);
}
BufferLoadDesc ubDescCuboid = {};
ubDescCuboid.mDesc.mDescriptors = DESCRIPTOR_TYPE_UNIFORM_BUFFER;
ubDescCuboid.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU;
ubDescCuboid.mDesc.mSize = sizeof(UniformBlock);
ubDescCuboid.mDesc.mFlags = BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT;
ubDescCuboid.pData = NULL;
for (uint32_t i = 0; i < gImageCount; ++i)
{
ubDescCuboid.ppBuffer = &pCuboidUniformBuffer[i];
addResource(&ubDescCuboid);
}
/************************************************************************/
// SETUP ANIMATION STRUCTURES
/************************************************************************/
// SKELETON RENDERER
//
// Set up details for rendering the skeleton
SkeletonRenderDesc skeletonRenderDesc = {};
skeletonRenderDesc.mRenderer = pRenderer;
skeletonRenderDesc.mSkeletonPipeline = pSkeletonPipeline;
skeletonRenderDesc.mRootSignature = pRootSignature;
skeletonRenderDesc.mJointVertexBuffer = pJointVertexBuffer;
skeletonRenderDesc.mNumJointPoints = gNumberOfJointPoints;
skeletonRenderDesc.mDrawBones = true;
skeletonRenderDesc.mBoneVertexBuffer = pBoneVertexBuffer;
skeletonRenderDesc.mNumBonePoints = gNumberOfBonePoints;
gSkeletonBatcher.Initialize(skeletonRenderDesc);
// RIGS
//
eastl::string fullPath = FileSystem::FixPath(gStickFigureName, FSR_Animation);
// Initialize the rig with the path to its ozz file and its rendering details
gStickFigureRig.Initialize(fullPath.c_str());
// Add the rig to the list of skeletons to render
gSkeletonBatcher.AddRig(&gStickFigureRig);
// CLIPS
//
fullPath = FileSystem::FixPath(gWalkClipName, FSR_Animation);
gWalkClip.Initialize(fullPath.c_str(), &gStickFigureRig);
// CLIP CONTROLLERS
//
// Initialize with the length of the animation they are controlling and an
// optional external time to set based on their updating
gWalkClipController.Initialize(gWalkClip.GetDuration(), &gUIData.mWalkClip.mAnimationTime);
// ANIMATIONS
//
AnimationDesc animationDesc{};
animationDesc.mRig = &gStickFigureRig;
animationDesc.mNumLayers = 1;
animationDesc.mLayerProperties[0].mClip = &gWalkClip;
animationDesc.mLayerProperties[0].mClipController = &gWalkClipController;
gWalkAnimation.Initialize(animationDesc);
// ANIMATED OBJECTS
//
gStickFigureAnimObject.Initialize(&gStickFigureRig, &gWalkAnimation);
/************************************************************************/
finishResourceLoading();
// SETUP THE MAIN CAMERA
//
CameraMotionParameters cmp{ 50.0f, 75.0f, 150.0f };
vec3 camPos{ -1.3f, 1.8f, 3.8f };
vec3 lookAt{ 1.2f, 0.0f, 0.4f };
pCameraController = createFpsCameraController(camPos, lookAt);
pCameraController->setMotionParameters(cmp);
#if defined(TARGET_IOS) || defined(__ANDROID__)
gVirtualJoystick.InitLRSticks();
pCameraController->setVirtualJoystick(&gVirtualJoystick);
#endif
requestMouseCapture(true);
InputSystem::RegisterInputEvent(cameraInputEvent);
// INITIALIZE THE USER INTERFACE
//
if (!gAppUI.Init(pRenderer))
return false;
gAppUI.LoadFont("TitilliumText/TitilliumText-Bold.otf", FSR_Builtin_Fonts);
// Add the GUI Panels/Windows
const TextDrawDesc UIPanelWindowTitleTextDesc = { 0, 0xffff00ff, 16 };
vec2 UIPosition = { mSettings.mWidth * 0.01f, mSettings.mHeight * 0.05f };
vec2 UIPanelSize = { 650, 1000 };
GuiDesc guiDesc(UIPosition, UIPanelSize, UIPanelWindowTitleTextDesc);
pStandaloneControlsGUIWindow = gAppUI.AddGuiComponent("Walk Animation", &guiDesc);
pStandaloneControlsGUIWindow->AddWidget(CheckboxWidget("Toggle Micro Profiler", &bToggleMicroProfiler));
// SET gUIData MEMBERS THAT NEED POINTERS TO ANIMATION DATA
//
// Blend Params
gUIData.mBlendParams.mAutoSetBlendParams = gWalkAnimation.GetAutoSetBlendParamsPtr();
gUIData.mBlendParams.mWalkClipWeight = gWalkClipController.GetWeightPtr();
gUIData.mBlendParams.mThreshold = gWalkAnimation.GetThresholdPtr();
// Walk Clip
gUIData.mWalkClip.mPlay = gWalkClipController.GetPlayPtr();
gUIData.mWalkClip.mLoop = gWalkClipController.GetLoopPtr();
gUIData.mWalkClip.mPlaybackSpeed = gWalkClipController.GetPlaybackSpeedPtr();
// SET UP GUI BASED ON gUIData STRUCT
//
{
// BLEND PARAMETERS
//
CollapsingHeaderWidget CollapsingBlendParamsWidgets("Blend Parameters");
// AutoSetBlendParams - Checkbox
CollapsingBlendParamsWidgets.AddSubWidget(SeparatorWidget());
CollapsingBlendParamsWidgets.AddSubWidget(CheckboxWidget("Auto Set Blend Params", gUIData.mBlendParams.mAutoSetBlendParams));
// Walk Clip Weight - Slider
float fValMin = 0.0f;
float fValMax = 1.0f;
float sliderStepSize = 0.01f;
CollapsingBlendParamsWidgets.AddSubWidget(SeparatorWidget());
CollapsingBlendParamsWidgets.AddSubWidget(
SliderFloatWidget("Clip Weight [Walk]", gUIData.mBlendParams.mWalkClipWeight, fValMin, fValMax, sliderStepSize));
// Threshold - Slider
fValMin = 0.01f;
fValMax = 1.0f;
sliderStepSize = 0.01f;
CollapsingBlendParamsWidgets.AddSubWidget(SeparatorWidget());
CollapsingBlendParamsWidgets.AddSubWidget(
SliderFloatWidget("Threshold", gUIData.mBlendParams.mThreshold, fValMin, fValMax, sliderStepSize));
CollapsingBlendParamsWidgets.AddSubWidget(SeparatorWidget());
// ATTACHED OBJECT
//
CollapsingHeaderWidget CollapsingAttachedObjectWidgets("Attached Object");
// Joint Index - Slider
unsigned uintValMin = 0;
unsigned uintValMax = gStickFigureRig.GetNumJoints() - 1;
unsigned sliderStepSizeUint = 1;
CollapsingAttachedObjectWidgets.AddSubWidget(SeparatorWidget());
CollapsingAttachedObjectWidgets.AddSubWidget(
SliderUintWidget("Joint Index", &gUIData.mAttachedObject.mJointIndex, uintValMin, uintValMax, sliderStepSizeUint));
// XOffset - Slider
fValMin = -1.0f;
fValMax = 1.0f;
sliderStepSize = 0.001f;
CollapsingAttachedObjectWidgets.AddSubWidget(SeparatorWidget());
CollapsingAttachedObjectWidgets.AddSubWidget(
SliderFloatWidget("X Offset", &gUIData.mAttachedObject.mXOffset, fValMin, fValMax, sliderStepSize));
// YOffset - Slider
fValMin = -1.0f;
fValMax = 1.0f;
sliderStepSize = 0.001f;
CollapsingAttachedObjectWidgets.AddSubWidget(SeparatorWidget());
CollapsingAttachedObjectWidgets.AddSubWidget(
SliderFloatWidget("Y Offset", &gUIData.mAttachedObject.mYOffset, fValMin, fValMax, sliderStepSize));
// ZOffset - Slider
fValMin = -1.0f;
fValMax = 1.0f;
sliderStepSize = 0.001f;
CollapsingAttachedObjectWidgets.AddSubWidget(SeparatorWidget());
CollapsingAttachedObjectWidgets.AddSubWidget(
SliderFloatWidget("Z Offset", &gUIData.mAttachedObject.mZOffset, fValMin, fValMax, sliderStepSize));
CollapsingAttachedObjectWidgets.AddSubWidget(SeparatorWidget());
// WALK CLIP
//
CollapsingHeaderWidget CollapsingWalkClipWidgets("Walk Clip");
// Play/Pause - Checkbox
CollapsingWalkClipWidgets.AddSubWidget(SeparatorWidget());
CollapsingWalkClipWidgets.AddSubWidget(CheckboxWidget("Play", gUIData.mWalkClip.mPlay));
// Loop - Checkbox
CollapsingWalkClipWidgets.AddSubWidget(SeparatorWidget());
CollapsingWalkClipWidgets.AddSubWidget(CheckboxWidget("Loop", gUIData.mWalkClip.mLoop));
// Animation Time - Slider
fValMin = 0.0f;
fValMax = gWalkClipController.GetDuration();
sliderStepSize = 0.01f;
SliderFloatWidget SliderAnimationTime("Animation Time", &gUIData.mWalkClip.mAnimationTime, fValMin, fValMax, sliderStepSize);
SliderAnimationTime.pOnActive = WalkClipTimeChangeCallback;
CollapsingWalkClipWidgets.AddSubWidget(SeparatorWidget());
CollapsingWalkClipWidgets.AddSubWidget(SliderAnimationTime);
// Playback Speed - Slider
fValMin = -5.0f;
fValMax = 5.0f;
sliderStepSize = 0.1f;
CollapsingWalkClipWidgets.AddSubWidget(SeparatorWidget());
CollapsingWalkClipWidgets.AddSubWidget(
SliderFloatWidget("Playback Speed", gUIData.mWalkClip.mPlaybackSpeed, fValMin, fValMax, sliderStepSize));
CollapsingWalkClipWidgets.AddSubWidget(SeparatorWidget());
// GENERAL SETTINGS
//
CollapsingHeaderWidget CollapsingGeneralSettingsWidgets("General Settings");
// ShowBindPose - Checkbox
CollapsingGeneralSettingsWidgets.AddSubWidget(SeparatorWidget());
CollapsingGeneralSettingsWidgets.AddSubWidget(CheckboxWidget("Show Bind Pose", &gUIData.mGeneralSettings.mShowBindPose));
// DrawAttachedObject - Checkbox
CollapsingGeneralSettingsWidgets.AddSubWidget(SeparatorWidget());
CollapsingGeneralSettingsWidgets.AddSubWidget(
CheckboxWidget("Draw Attached Object", &gUIData.mGeneralSettings.mDrawAttachedObject));
// DrawPlane - Checkbox
CollapsingGeneralSettingsWidgets.AddSubWidget(SeparatorWidget());
CollapsingGeneralSettingsWidgets.AddSubWidget(CheckboxWidget("Draw Plane", &gUIData.mGeneralSettings.mDrawPlane));
CollapsingGeneralSettingsWidgets.AddSubWidget(SeparatorWidget());
// Add all widgets to the window
pStandaloneControlsGUIWindow->AddWidget(CollapsingBlendParamsWidgets);
pStandaloneControlsGUIWindow->AddWidget(CollapsingAttachedObjectWidgets);
pStandaloneControlsGUIWindow->AddWidget(CollapsingWalkClipWidgets);
pStandaloneControlsGUIWindow->AddWidget(CollapsingGeneralSettingsWidgets);
}
return true;
}
void Exit()
{
// wait for rendering to finish before freeing resources
waitQueueIdle(pGraphicsQueue);
exitProfiler(pRenderer);
// Animation data
gSkeletonBatcher.Destroy();
gStickFigureRig.Destroy();
gWalkClip.Destroy();
gWalkAnimation.Destroy();
gStickFigureAnimObject.Destroy();
destroyCameraController(pCameraController);
#ifdef TARGET_IOS
gVirtualJoystick.Exit();
#endif
removeGpuProfiler(pRenderer, pGpuProfiler);
gAppUI.Exit();
for (uint32_t i = 0; i < gImageCount; ++i)
{
removeResource(pPlaneUniformBuffer[i]);
removeResource(pCuboidUniformBuffer[i]);
}
removeResource(pCuboidVertexBuffer);
removeResource(pJointVertexBuffer);
removeResource(pBoneVertexBuffer);
removeResource(pPlaneVertexBuffer);
removeShader(pRenderer, pSkeletonShader);
removeShader(pRenderer, pPlaneDrawShader);
removeRootSignature(pRenderer, pRootSignature);
removeDescriptorBinder(pRenderer, pDescriptorBinderPlane);
removeDepthState(pDepth);
removeRasterizerState(pSkeletonRast);
removeRasterizerState(pPlaneRast);
for (uint32_t i = 0; i < gImageCount; ++i)
{
removeFence(pRenderer, pRenderCompleteFences[i]);
removeSemaphore(pRenderer, pRenderCompleteSemaphores[i]);
}
removeSemaphore(pRenderer, pImageAcquiredSemaphore);
removeCmd_n(pCmdPool, gImageCount, ppCmds);
removeCmdPool(pRenderer, pCmdPool);
removeResourceLoaderInterface(pRenderer);
removeQueue(pGraphicsQueue);
removeRenderer(pRenderer);
}
bool Load()
{
// INITIALIZE SWAP-CHAIN AND DEPTH BUFFER
//
if (!addSwapChain())
return false;
if (!addDepthBuffer())
return false;
// LOAD USER INTERFACE
//
if (!gAppUI.Load(pSwapChain->ppSwapchainRenderTargets))
return false;
#ifdef TARGET_IOS
if (!gVirtualJoystick.Load(pSwapChain->ppSwapchainRenderTargets[0], pDepthBuffer->mDesc.mFormat))
return false;
#endif
//layout and pipeline for skeleton draw
VertexLayout vertexLayout = {};
vertexLayout.mAttribCount = 2;
vertexLayout.mAttribs[0].mSemantic = SEMANTIC_POSITION;
vertexLayout.mAttribs[0].mFormat = ImageFormat::RGB32F;
vertexLayout.mAttribs[0].mBinding = 0;
vertexLayout.mAttribs[0].mLocation = 0;
vertexLayout.mAttribs[0].mOffset = 0;
vertexLayout.mAttribs[1].mSemantic = SEMANTIC_NORMAL;
vertexLayout.mAttribs[1].mFormat = ImageFormat::RGB32F;
vertexLayout.mAttribs[1].mBinding = 0;
vertexLayout.mAttribs[1].mLocation = 1;
vertexLayout.mAttribs[1].mOffset = 3 * sizeof(float);
PipelineDesc desc = {};
desc.mType = PIPELINE_TYPE_GRAPHICS;
GraphicsPipelineDesc& pipelineSettings = desc.mGraphicsDesc;
pipelineSettings.mPrimitiveTopo = PRIMITIVE_TOPO_TRI_LIST;
pipelineSettings.mRenderTargetCount = 1;
pipelineSettings.pDepthState = pDepth;
pipelineSettings.pColorFormats = &pSwapChain->ppSwapchainRenderTargets[0]->mDesc.mFormat;
pipelineSettings.pSrgbValues = &pSwapChain->ppSwapchainRenderTargets[0]->mDesc.mSrgb;
pipelineSettings.mSampleCount = pSwapChain->ppSwapchainRenderTargets[0]->mDesc.mSampleCount;
pipelineSettings.mSampleQuality = pSwapChain->ppSwapchainRenderTargets[0]->mDesc.mSampleQuality;
pipelineSettings.mDepthStencilFormat = pDepthBuffer->mDesc.mFormat;
pipelineSettings.pRootSignature = pRootSignature;
pipelineSettings.pShaderProgram = pSkeletonShader;
pipelineSettings.pVertexLayout = &vertexLayout;
pipelineSettings.pRasterizerState = pSkeletonRast;
addPipeline(pRenderer, &desc, &pSkeletonPipeline);
// Update the mSkeletonPipeline pointer now that the pipeline has been loaded
gSkeletonBatcher.LoadPipeline(pSkeletonPipeline);
//layout and pipeline for plane draw
vertexLayout = {};
vertexLayout.mAttribCount = 2;
vertexLayout.mAttribs[0].mSemantic = SEMANTIC_POSITION;
vertexLayout.mAttribs[0].mFormat = ImageFormat::RGBA32F;
vertexLayout.mAttribs[0].mBinding = 0;
vertexLayout.mAttribs[0].mLocation = 0;
vertexLayout.mAttribs[0].mOffset = 0;
vertexLayout.mAttribs[1].mSemantic = SEMANTIC_TEXCOORD0;
vertexLayout.mAttribs[1].mFormat = ImageFormat::RG32F;
vertexLayout.mAttribs[1].mBinding = 0;
vertexLayout.mAttribs[1].mLocation = 1;
vertexLayout.mAttribs[1].mOffset = 4 * sizeof(float);
pipelineSettings.pDepthState = NULL;
pipelineSettings.pRasterizerState = pPlaneRast;
pipelineSettings.pShaderProgram = pPlaneDrawShader;
addPipeline(pRenderer, &desc, &pPlaneDrawPipeline);
return true;
}
void Unload()
{
waitQueueIdle(pGraphicsQueue);
gAppUI.Unload();
#ifdef TARGET_IOS
gVirtualJoystick.Unload();
#endif
removePipeline(pRenderer, pPlaneDrawPipeline);
removePipeline(pRenderer, pSkeletonPipeline);
removeSwapChain(pRenderer, pSwapChain);
removeRenderTarget(pRenderer, pDepthBuffer);
}
void Update(float deltaTime)
{
/************************************************************************/
// Input
/************************************************************************/
if (InputSystem::GetBoolInput(KEY_BUTTON_X_TRIGGERED))
{
RecenterCameraView(170.0f);
}
pCameraController->update(deltaTime);
/************************************************************************/
// Scene Update
/************************************************************************/
// update camera with time
mat4 viewMat = pCameraController->getViewMatrix();
const float aspectInverse = (float)mSettings.mHeight / (float)mSettings.mWidth;
const float horizontal_fov = PI / 2.0f;
mat4 projMat = mat4::perspective(horizontal_fov, aspectInverse, 0.1f, 1000.0f);
mat4 projViewMat = projMat * viewMat;
vec3 lightPos = vec3(0.0f, 10.0f, 2.0f);
vec3 lightColor = vec3(1.0f, 1.0f, 1.0f);
/************************************************************************/
// Animation
/************************************************************************/
gAnimationUpdateTimer.Reset();
// Update the animated object for this frame
if (!gStickFigureAnimObject.Update(deltaTime))
InfoMsg("Animation NOT Updating!");
if (!gUIData.mGeneralSettings.mShowBindPose)
{
// Pose the rig based on the animated object's updated values
gStickFigureAnimObject.PoseRig();
}
else
{
// Ignore the updated values and pose in bind
gStickFigureAnimObject.PoseRigInBind();
}
// Record animation update time
gAnimationUpdateTimer.GetUSec(true);
// Update uniforms that will be shared between all skeletons
gSkeletonBatcher.SetSharedUniforms(projViewMat, lightPos, lightColor);
/************************************************************************/
// Attached object
/************************************************************************/
gUniformDataCuboid.mProjectView = projViewMat;
gUniformDataCuboid.mLightPosition = lightPos;
gUniformDataCuboid.mLightColor = lightColor;
// Set the transform of the attached object based on the updated world matrix of
// the joint in the rig specified by the UI
gCuboidTransformMat = gStickFigureRig.GetJointWorldMat(gUIData.mAttachedObject.mJointIndex);
// Compute the offset translation based on the UI values
mat4 offset =
mat4::translation(vec3(gUIData.mAttachedObject.mXOffset, gUIData.mAttachedObject.mYOffset, gUIData.mAttachedObject.mZOffset));
gUniformDataCuboid.mToWorldMat[0] = gCuboidTransformMat * offset * gCuboidScaleMat;
gUniformDataCuboid.mColor[0] = gCuboidColor;
BufferUpdateDesc cuboidViewProjCbv = { pCuboidUniformBuffer[gFrameIndex], &gUniformDataCuboid };
updateResource(&cuboidViewProjCbv);
/************************************************************************/
// Plane
/************************************************************************/
gUniformDataPlane.mProjectView = projMat * viewMat;
gUniformDataPlane.mToWorldMat = mat4::identity();
// ProfileSetDisplayMode()
// TODO: need to change this better way
if (bToggleMicroProfiler != bPrevToggleMicroProfiler)
{
Profile& S = *ProfileGet();
int nValue = bToggleMicroProfiler ? 1 : 0;
nValue = nValue >= 0 && nValue < P_DRAW_SIZE ? nValue : S.nDisplay;
S.nDisplay = nValue;
bPrevToggleMicroProfiler = bToggleMicroProfiler;
}
/************************************************************************/
// GUI
/************************************************************************/
gAppUI.Update(deltaTime);
}
void Draw()
{
// CPU profiler timer
static HiresTimer gTimer;
acquireNextImage(pRenderer, pSwapChain, pImageAcquiredSemaphore, NULL, &gFrameIndex);
// UPDATE UNIFORM BUFFERS
//
// Update all the instanced uniform data for each batch of joints and bones
gSkeletonBatcher.SetPerInstanceUniforms(gFrameIndex);
BufferUpdateDesc planeViewProjCbv = { pPlaneUniformBuffer[gFrameIndex], &gUniformDataPlane };
updateResource(&planeViewProjCbv);
// FRAME SYNC & ACQUIRE SWAPCHAIN RENDER TARGET
//
// Stall if CPU is running "Swap Chain Buffer Count" frames ahead of GPU
Fence* pNextFence = pRenderCompleteFences[gFrameIndex];
FenceStatus fenceStatus;
getFenceStatus(pRenderer, pNextFence, &fenceStatus);
if (fenceStatus == FENCE_STATUS_INCOMPLETE)
waitForFences(pRenderer, 1, &pNextFence);
// Acquire the main render target from the swapchain
RenderTarget* pRenderTarget = pSwapChain->ppSwapchainRenderTargets[gFrameIndex];
Semaphore* pRenderCompleteSemaphore = pRenderCompleteSemaphores[gFrameIndex];
Fence* pRenderCompleteFence = pRenderCompleteFences[gFrameIndex];
Cmd* cmd = ppCmds[gFrameIndex];
beginCmd(cmd); // start recording commands
// start gpu frame profiler
cmdBeginGpuFrameProfile(cmd, pGpuProfiler);
TextureBarrier barriers[] = // wait for resource transition
{
{ pRenderTarget->pTexture, RESOURCE_STATE_RENDER_TARGET },
{ pDepthBuffer->pTexture, RESOURCE_STATE_DEPTH_WRITE },
};
cmdResourceBarrier(cmd, 0, NULL, 2, barriers, false);
// bind and clear the render target
LoadActionsDesc loadActions = {}; // render target clean command
loadActions.mLoadActionsColor[0] = LOAD_ACTION_CLEAR;
loadActions.mClearColorValues[0] = { 0.39f, 0.41f, 0.37f, 1.0f };
loadActions.mLoadActionDepth = LOAD_ACTION_CLEAR;
loadActions.mClearDepth = { 1.0f, 0 };
cmdBindRenderTargets(cmd, 1, &pRenderTarget, pDepthBuffer, &loadActions, NULL, NULL, -1, -1);
cmdSetViewport(cmd, 0.0f, 0.0f, (float)pRenderTarget->mDesc.mWidth, (float)pRenderTarget->mDesc.mHeight, 0.0f, 1.0f);
cmdSetScissor(cmd, 0, 0, pRenderTarget->mDesc.mWidth, pRenderTarget->mDesc.mHeight);
//// draw plane
if (gUIData.mGeneralSettings.mDrawPlane)
{
cmdBeginDebugMarker(cmd, 1, 0, 1, "Draw Plane");
cmdBindPipeline(cmd, pPlaneDrawPipeline);
DescriptorData params[1] = {};
params[0].pName = "uniformBlock";
params[0].ppBuffers = &pPlaneUniformBuffer[gFrameIndex];
cmdBindDescriptors(cmd, pDescriptorBinderPlane, pRootSignature, 1, params);
cmdBindVertexBuffer(cmd, 1, &pPlaneVertexBuffer, NULL);
cmdDraw(cmd, 6, 0);
cmdEndDebugMarker(cmd);
}
//// draw the skeleton of the rig
cmdBeginDebugMarker(cmd, 1, 0, 1, "Draw Skeletons");
gSkeletonBatcher.Draw(cmd, gFrameIndex);
cmdEndDebugMarker(cmd);
//// draw the object attached to the rig
if (gUIData.mGeneralSettings.mDrawAttachedObject)
{
cmdBeginDebugMarker(cmd, 1, 0, 1, "Draw Cuboid");
cmdBindPipeline(cmd, pSkeletonPipeline);
DescriptorData params[1] = {};
params[0].pName = "uniformBlock";
params[0].ppBuffers = &pCuboidUniformBuffer[gFrameIndex];
cmdBindDescriptors(cmd, pDescriptorBinderPlane, pRootSignature, 1, params);
cmdBindVertexBuffer(cmd, 1, &pCuboidVertexBuffer, NULL);
cmdDrawInstanced(cmd, gNumberOfCuboidPoints / 6, 0, 1, 0);
cmdEndDebugMarker(cmd);
}
//// draw the UI
cmdBeginDebugMarker(cmd, 0, 1, 0, "Draw UI");
gTimer.GetUSec(true);
#ifdef TARGET_IOS
gVirtualJoystick.Draw(cmd, { 1.0f, 1.0f, 1.0f, 1.0f });
#endif
gAppUI.Gui(pStandaloneControlsGUIWindow); // adds the gui element to AppUI::ComponentsToUpdate list
gAppUI.DrawText(
cmd, float2(8, 15), eastl::string().sprintf("CPU %f ms", gTimer.GetUSecAverage() / 1000.0f).c_str(), &gFrameTimeDraw);
gAppUI.DrawText(
cmd, float2(8, 65), eastl::string().sprintf("Animation Update %f ms", gAnimationUpdateTimer.GetUSecAverage() / 1000.0f).c_str(),
&gFrameTimeDraw);
gAppUI.DrawText(
cmd, float2(8, 40), eastl::string().sprintf("GPU %f ms", (float)pGpuProfiler->mCumulativeTime * 1000.0f).c_str(),
&gFrameTimeDraw);
cmdDrawProfiler(cmd, mSettings.mWidth, mSettings.mHeight);
gAppUI.Draw(cmd);
cmdBindRenderTargets(cmd, 0, NULL, NULL, NULL, NULL, NULL, -1, -1);
cmdEndDebugMarker(cmd);
// PRESENT THE GRPAHICS QUEUE
//
barriers[0] = { pRenderTarget->pTexture, RESOURCE_STATE_PRESENT };
cmdResourceBarrier(cmd, 0, NULL, 1, barriers, true);
cmdEndGpuFrameProfile(cmd, pGpuProfiler);
endCmd(cmd);
queueSubmit(pGraphicsQueue, 1, &cmd, pRenderCompleteFence, 1, &pImageAcquiredSemaphore, 1, &pRenderCompleteSemaphore);
queuePresent(pGraphicsQueue, pSwapChain, gFrameIndex, 1, &pRenderCompleteSemaphore);
flipProfiler();
}
const char* GetName() { return "20_JointAttachment"; }
bool addSwapChain()
{
SwapChainDesc swapChainDesc = {};
swapChainDesc.pWindow = pWindow;
swapChainDesc.mPresentQueueCount = 1;
swapChainDesc.ppPresentQueues = &pGraphicsQueue;
swapChainDesc.mWidth = mSettings.mWidth;
swapChainDesc.mHeight = mSettings.mHeight;
swapChainDesc.mImageCount = gImageCount;
swapChainDesc.mSampleCount = SAMPLE_COUNT_1;
swapChainDesc.mColorFormat = getRecommendedSwapchainFormat(true);
swapChainDesc.mEnableVsync = false;
::addSwapChain(pRenderer, &swapChainDesc, &pSwapChain);
return pSwapChain != NULL;
}
bool addDepthBuffer()
{
// Add depth buffer
RenderTargetDesc depthRT = {};
depthRT.mArraySize = 1;
depthRT.mClearValue = { 1.0f, 0 };
depthRT.mDepth = 1;
depthRT.mFormat = ImageFormat::D32F;
depthRT.mHeight = mSettings.mHeight;
depthRT.mSampleCount = SAMPLE_COUNT_1;
depthRT.mSampleQuality = 0;
depthRT.mWidth = mSettings.mWidth;
addRenderTarget(pRenderer, &depthRT, &pDepthBuffer);
return pDepthBuffer != NULL;
}
void RecenterCameraView(float maxDistance, vec3 lookAt = vec3(0))
{
vec3 p = pCameraController->getViewPosition();
vec3 d = p - lookAt;
float lenSqr = lengthSqr(d);
if (lenSqr > (maxDistance * maxDistance))
{
d *= (maxDistance / sqrtf(lenSqr));
}
p = d + lookAt;
pCameraController->moveTo(p);
pCameraController->lookAt(lookAt);
}
static bool cameraInputEvent(const ButtonData* data)
{
pCameraController->onInputEvent(data);
return true;
}
};
DEFINE_APPLICATION_MAIN(JointAttachment)
| [
"jenkins@conffx.com"
] | jenkins@conffx.com |
6605ec0012e25e3e0a695e840e20c323f796da6b | cfeac52f970e8901871bd02d9acb7de66b9fb6b4 | /generated/src/aws-cpp-sdk-dax/source/model/DeleteClusterRequest.cpp | b6b7359b19db7388dfecfa9163b11d1e88cff221 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | aws/aws-sdk-cpp | aff116ddf9ca2b41e45c47dba1c2b7754935c585 | 9a7606a6c98e13c759032c2e920c7c64a6a35264 | refs/heads/main | 2023-08-25T11:16:55.982089 | 2023-08-24T18:14:53 | 2023-08-24T18:14:53 | 35,440,404 | 1,681 | 1,133 | Apache-2.0 | 2023-09-12T15:59:33 | 2015-05-11T17:57:32 | null | UTF-8 | C++ | false | false | 894 | cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/dax/model/DeleteClusterRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::DAX::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DeleteClusterRequest::DeleteClusterRequest() :
m_clusterNameHasBeenSet(false)
{
}
Aws::String DeleteClusterRequest::SerializePayload() const
{
JsonValue payload;
if(m_clusterNameHasBeenSet)
{
payload.WithString("ClusterName", m_clusterName);
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection DeleteClusterRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AmazonDAXV3.DeleteCluster"));
return headers;
}
| [
"sdavtaker@users.noreply.github.com"
] | sdavtaker@users.noreply.github.com |
f6021a89749bd8bcff24d1838d5e3ed45b0f0142 | f1c4f34338416287914f22be71de468c31a7c96b | /Source/FPS_Experimental/Weapons/Gun.cpp | 62d3c626168a7986c41a52f3fe4fe0f854e2b282 | [] | no_license | Mozart201221/InfiniteLevel | f0198bdbe259a29032b617e9983b31ecfedfdf40 | 23cd47f23678234318b426617ca894a2caf2fcee | refs/heads/master | 2023-02-06T21:43:46.374920 | 2020-12-21T18:09:39 | 2020-12-21T18:09:39 | 262,271,013 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,674 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "Gun.h"
#include "BallProjectile.h"
#include "Kismet/GameplayStatics.h"
#include "Animation/AnimInstance.h"
// Sets default values
AGun::AGun()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
// Create a gun mesh component
FP_Gun = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("FP_Gun"));
FP_Gun->bCastDynamicShadow = false;
FP_Gun->CastShadow = false;
// FP_Gun->SetupAttachment(Mesh1P, TEXT("GripPoint"));
FP_Gun->SetupAttachment(RootComponent);
FP_MuzzleLocation = CreateDefaultSubobject<USceneComponent>(TEXT("MuzzleLocation"));
FP_MuzzleLocation->SetupAttachment(FP_Gun);
FP_MuzzleLocation->SetRelativeLocation(FVector(0.2f, 48.4f, -10.6f));
}
// Called when the game starts or when spawned
void AGun::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AGun::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
void AGun::OnFire()
{
// try and fire a projectile
if (ProjectileClass != NULL)
{
UWorld* const World = GetWorld();
if (World != NULL)
{
/*if (bUsingMotionControllers)
{
const FRotator SpawnRotation = VR_MuzzleLocation->GetComponentRotation();
const FVector SpawnLocation = VR_MuzzleLocation->GetComponentLocation();
World->SpawnActor<ABallProjectile>(ProjectileClass, SpawnLocation, SpawnRotation);
}*/
{
const FRotator SpawnRotation = FP_MuzzleLocation->GetComponentRotation();
// MuzzleOffset is in camera space, so transform it to world space before offsetting from the character location to find the final muzzle position
const FVector SpawnLocation = FP_MuzzleLocation->GetComponentLocation();
//Set Spawn Collision Handling Override
FActorSpawnParameters ActorSpawnParams;
ActorSpawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButDontSpawnIfColliding;
// spawn the projectile at the muzzle
World->SpawnActor<ABallProjectile>(ProjectileClass, SpawnLocation, SpawnRotation, ActorSpawnParams);
}
}
}
// try and play the sound if specified
if (FireSound != NULL)
{
UGameplayStatics::PlaySoundAtLocation(this, FireSound, GetActorLocation());
}
// try and play a firing animation if specified
if (FireAnimation1P != nullptr && AnimInstance1P != nullptr)
{
AnimInstance1P->Montage_Play(FireAnimation1P, 1.f);
}
// try and play a firing animation if specified
if (FireAnimation3P != nullptr && AnimInstance3P != nullptr)
{
AnimInstance3P->Montage_Play(FireAnimation3P, 1.f);
}
} | [
"sartemy@mail.ru"
] | sartemy@mail.ru |
ea6217dfe7b2902a0f696681b85d8ae6aff84731 | 10ecd7454a082e341eb60817341efa91d0c7fd0b | /SDK/BP_CapstanRelease_functions.cpp | 5c0e998a6584485191dabe42448d8ae2c678f8cd | [] | no_license | Blackstate/Sot-SDK | 1dba56354524572894f09ed27d653ae5f367d95b | cd73724ce9b46e3eb5b075c468427aa5040daf45 | refs/heads/main | 2023-04-10T07:26:10.255489 | 2021-04-23T01:39:08 | 2021-04-23T01:39:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,066 | cpp | // Name: SoT, Version: 2.1.0.1
#include "../SDK.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function BP_CapstanRelease.BP_CapstanRelease_C.GetClosestInteractionPoint
// (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FVector ReferencePosition (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor)
// float OutInteractionPointRadius (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor)
// struct FVector ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor)
struct FVector ABP_CapstanRelease_C::GetClosestInteractionPoint(const struct FVector& ReferencePosition, float* OutInteractionPointRadius)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_CapstanRelease.BP_CapstanRelease_C.GetClosestInteractionPoint");
ABP_CapstanRelease_C_GetClosestInteractionPoint_Params params;
params.ReferencePosition = ReferencePosition;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (OutInteractionPointRadius != nullptr)
*OutInteractionPointRadius = params.OutInteractionPointRadius;
return params.ReturnValue;
}
// Function BP_CapstanRelease.BP_CapstanRelease_C.UserConstructionScript
// (Event, Public, BlueprintCallable, BlueprintEvent)
void ABP_CapstanRelease_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_CapstanRelease.BP_CapstanRelease_C.UserConstructionScript");
ABP_CapstanRelease_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"ploszjanos9844@gmail.com"
] | ploszjanos9844@gmail.com |
05f8d252ae36ee1e3a3f0e55f3fac0f7aa3e7e71 | 5bec385ff308b6d5e55d214deec1a7d1684227c8 | /hough.hpp | df732b5fec3de1c9d9423040aa4b7701e880f79a | [] | no_license | wlli/houghTransform | 300d382be838e63ba8f1effaadef1cdb73e4280b | 9ca152e626068a9355cc46d62be7043cb4869798 | refs/heads/master | 2021-01-10T02:21:47.320044 | 2016-02-12T03:56:42 | 2016-02-12T03:56:42 | 51,563,259 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,013 | hpp | //
// hough.hpp
// Hough
//
// Copyright © 2016 wanlong. All rights reserved.
//
#ifndef hough_hpp
#define hough_hpp
#include <stdio.h>
#include <opencv2/opencv.hpp>
#endif /* hough_hpp */
using namespace cv;
class Hough
{
public:
bool execute(const char* filePath, const char* outputFilePath, bool bMarkExtend,int threshold = 100, int thetaMin = 0, int thetaMax = 179);
Hough();
~Hough(){}
private:
bool prepareData(Mat& img_orig, Mat& img_edge, const char* filePath);
bool transform(cv::Mat& img_edge, std::vector<std::vector<int>>& accumulator);
void backMapping(Mat& img, Mat& imgOut, std::vector<std::vector<int>>& accumulator, bool bMarkExtend);
void findLocalMaxima(std::vector<std::vector<int>>& vec2d, int radiusX, int radiusY);
void displayMat(Mat& mat);
private:
int mShowWindowIndex;
int mWidth;
int mHeight;
int mDiagonal;
double sinVals[180];
double cosVals[180];
int mThetaMin;
int mThetaMax;
int mThreshold;
};
| [
"wanlong.li@autodesk.com"
] | wanlong.li@autodesk.com |
5a96a36eabd5bc49157e830a7366fb9306f3f330 | 8710f4b47da4386e401731efaa781ef3be10992c | /yolox_openvino_version2/openvino_toolkit_ubuntu18_2022.2.0.7713/runtime/include/ie/inference_engine.hpp | 9f00911cab7032e321e5a7274660d6fea314c07c | [] | no_license | yhwang-hub/dl_model_deploy | 3be62c00bd69cddbb1c17236238c31f62495b81b | 847dd097075ee25f817b393fd16f91083eb15500 | refs/heads/master | 2023-05-23T04:32:57.396575 | 2023-05-16T15:05:58 | 2023-05-16T15:05:58 | 578,062,937 | 65 | 18 | null | null | null | null | UTF-8 | C++ | false | false | 365 | hpp | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
/**
* @brief A header file that provides a set minimal required Inference Engine API.
* @file inference_engine.hpp
*/
#pragma once
#include "ie_compound_blob.h"
#include "ie_core.hpp"
#include "ie_transformations.hpp"
// remove in 2022.1 major release
#include <iostream>
| [
"yuehong.wang@uisee.com"
] | yuehong.wang@uisee.com |
f3dac54c47954905180f798415f6d2fcbaa86765 | 68119959a08c86ef72d092aa68f55feced9c7093 | /Assignment04/MainProg.cpp | ed46e7bc6609c55bb0ebfaa14a9d7b44e167bc35 | [] | no_license | switch900/C-Plus-Plus-Application-Development-1 | f1899dbca5977b5c2f8ea5c69e4dea6818e94f20 | 8bde8e0f7cd40d118ba4b759d723ceecc3ac431e | refs/heads/master | 2020-03-26T20:20:39.457708 | 2018-12-16T21:06:46 | 2018-12-16T21:06:46 | 145,318,223 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,793 | cpp | // Assign 4 Main Program - used to "test drive" the Fraction class
// File Name: MainProg.cpp
// Author: Bob Langelaan
// Date: Oct 29th, 2013
#include <iostream>
#include "Fraction.h" // include definition of class Fraction from Fraction.h
#include "GCD.h" // include definition of gcd template function
using namespace std;
int main()
{
// Test constructors
Fraction A; // create a Fraction object with default ctor
cout << "The default object is: ";
A.display();
Fraction B(1,1024); // create a Fraction object with the non-default ctor
cout << "\n\nThe non-default object is: ";
B.display();
Fraction C(8,-1024); // test to see if the simplify method is invoked from
// the non-default ctor
cout << "\n\n8/-1024 simplified is: ";
C.display();
// Test template gcd() function
// implicitly invoke template function
int intX = 1024;
int intY = 32;
int intAns = gcd(intX,intY); // implicit invocation
cout << "\n\nThe greatest common divisor of 1024 and 32 is: " << intAns;
// explicitly invoke template function
long longX = 1024;
long longY = 1048576;
long longAns = gcd<long>(longX, longY); // explicit invocation
cout << "\n\nThe greatest common divisor of 1024 and 1048576 is: " << longAns;
// Test timesEq()
cout << "\n\n- Test timesEq()";
A = Fraction(2,3); //Assign new values to Fraction objects
B = Fraction(3,5);
// Output "before" values
cout << "\nA = ";
A.display();
cout << "\nB = ";
B.display();
// NOTE: Equivalent to: C = A *= B;
C = A.timesEq(B);
// Output "after" values
cout << "\n\nA = ";
A.display();
cout << "\nB = ";
B.display();
cout << "\nC = ";
C.display();
// Test divideEq()
cout << "\n\n- Test divideEq()";
A = Fraction(2,3); //Assign new values to Fraction objects
B = Fraction(-7,3);
// Output "before" values
cout << "\nA = ";
A.display();
cout << "\nB = ";
B.display();
// NOTE: Equivalent to: C = A /= B;
C = A.divideEq(B);
// Output "after" values
cout << "\n\nA = ";
A.display();
cout << "\nB = ";
B.display();
cout << "\nC = ";
C.display();
// Test plusEq()
cout << "\n\n- Test plusEq()";
A = Fraction(-5,-6); //Assign new values to Fraction objects
B = Fraction(9,10);
// Output "before" values
cout << "\nA = ";
A.display();
cout << "\nB = ";
B.display();
// NOTE: Equivalent to: C = A += B;
C = A.plusEq(B);
// Output "after" values
cout << "\n\nA = ";
A.display();
cout << "\nB = ";
B.display();
cout << "\nC = ";
C.display();
// Test minusEq()
cout << "\n\n- Test minusEq()";
A = Fraction(2,3); //Assign new values to Fraction objects
B = Fraction(8,9);
// Output "before" values
cout << "\nA = ";
A.display();
cout << "\nB = ";
B.display();
// NOTE: Equivalent to: C = A -= B;
C = A.minusEq(B);
// Output "after" values
cout << "\n\nA = ";
A.display();
cout << "\nB = ";
B.display();
cout << "\nC = ";
C.display();
// Test negate()
cout << "\n\n- Test negateEq()";
A = Fraction(-2,3); //Assign new values to Fraction objects
B = Fraction(8,9);
// Output "before" values
cout << "\nA = ";
A.display();
cout << "\nB = ";
B.display();
// NOTE: Equivalent to: C = -A;
C = A.negate();
// Output "after" values
cout << "\n\nA = ";
A.display();
cout << "\nC = ";
C.display();
// Output "before" values
cout << "\n\nB = ";
B.display();
cout << "\nC = ";
C.display();
// NOTE: Equivalent to: C = -B;
C = B.negate();
// Output "after" values
cout << "\n\nB = ";
B.display();
cout << "\nC = ";
C.display();
cout << '\n' << endl;
system("pause");
return 0;
} // end main
| [
"noreply@github.com"
] | switch900.noreply@github.com |
3ef2fcd9819ffc1d11ac96dfb8a71c8cf13a948d | a39f9d3351494d3c979b96b01ec56973d2719e53 | /src/IntaRNA/PredictionTrackerPairMinE.h | 03acca1728ee37e8144d5c6452939a6b36b3e49d | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | BackofenLab/IntaRNA | 9b1442dd3b3862e6b833d53e1ac3d8b5aaf38bf1 | e5f8c1ea26dfd18e04840cf50f6d15475911df48 | refs/heads/master | 2023-05-31T13:03:16.371958 | 2023-04-28T13:27:37 | 2023-04-28T13:27:37 | 55,144,412 | 45 | 29 | NOASSERTION | 2023-01-31T11:16:32 | 2016-03-31T11:11:17 | C++ | UTF-8 | C++ | false | false | 4,215 | h |
#ifndef INTARNA_PREDICTIONTRACKERPAIRMINE_H_
#define INTARNA_PREDICTIONTRACKERPAIRMINE_H_
#include "IntaRNA/PredictionTracker.h"
#include "IntaRNA/InteractionEnergy.h"
#include <iostream>
#include <boost/algorithm/string.hpp>
#include <boost/numeric/ublas/matrix.hpp>
namespace IntaRNA {
/**
* Collects for each intermolecular index pair the minimal energy of any interaction
* covering this pair (even if not forming a base pair).
*
* The pair data is written to stream on destruction.
*/
class PredictionTrackerPairMinE: public PredictionTracker
{
public:
/**
* Constructs a PredictionTracker that collected for index pair of two
* sequences the minimal energy of any interaction covering this position.
*
* Note, if a filename is provided, its stream is closed on destruction of
* this object!
*
* @param energy the energy function used for energy calculation
* @param streamName the stream name where the data
* is to be written to. use STDOUT/STDERR for the respective stream.
* Otherwise, an according file is created (has to be non-empty)
* @param E_INF_string the output string representation of E_INF values in
* the profile output
* @param sep the column separator to be used in profile output
*/
PredictionTrackerPairMinE(
const InteractionEnergy & energy
, const std::string & streamName
, const std::string & E_INF_string = "NA"
, const std::string & sep = ";"
);
/**
* Constructs a PredictionTracker that collected for index pair of two
* sequences the minimal energy of any interaction covering this position.
*
* Note, the stream is NOT closed nor deleted on destruction of this object!
*
* @param energy the energy function used
* @param outStream the stream where the data
* is to be written to (has to be non-null)
* @param E_INF_string the output string representation of E_INF values in
* the profile output
* @param sep the column separator to be used in profile output
*/
PredictionTrackerPairMinE(
const InteractionEnergy & energy
, std::ostream * outStream
, const std::string & E_INF_string = "NA"
, const std::string & sep = ";"
);
/**
* destruction: write the pair information to the according stream.
*/
virtual ~PredictionTrackerPairMinE();
/**
* Updates the minE information for each Predictor.updateOptima() call.
*
* @param i1 the index of the first sequence interacting with i2
* @param j1 the index of the first sequence interacting with j2
* @param i2 the index of the second sequence interacting with i1
* @param j2 the index of the second sequence interacting with j1
* @param energy the overall energy of the interaction site
*/
virtual
void
updateOptimumCalled( const size_t i1, const size_t j1
, const size_t i2, const size_t j2
, const E_type energy
);
protected:
//! energy handler used for predictions
const InteractionEnergy & energy;
//! whether or not the streams are to be deleted on destruction
const bool deleteStreamsOnDestruction;
//! the stream to write the minE-data to
std::ostream * outStream;
//! the output string representation of E_INF values in the profile output
const std::string E_INF_string;
//! the output string representation of column separators
const std::string sep_string;
//! matrix type to hold the mfe energies and boundaries for interaction site starts
typedef boost::numeric::ublas::matrix<E_type> E2dMatrix;
//! the index-pair-wise minimal energy values
E2dMatrix pairMinE;
/**
* Writes minE data to stream.
*
* @param out the output stream to write to
* @param pairMinE the minE data to write
* @param energy the energy function used
* @param E_INF_string the string to be used for E_INF entries
* @param sep_string the output string representation of column separators
*/
static
void
writeData( std::ostream &out
, const E2dMatrix & pairMinE
, const InteractionEnergy & energy
, const std::string & E_INF_string
, const std::string & sep_string );
};
//////////////////////////////////////////////////////////////////////
} // namespace
#endif /* PREDICTIONTRACKERPAIRMINE_H_ */
| [
"qyu@gmx.de"
] | qyu@gmx.de |
a16a8dfb0e3ff7723c529550f1e81373a1139889 | c6b46606560a02d98ed816b74bb3d55f3bb64ea0 | /test/dkm/math/vector4_test.cpp | d1d710dfa8edd664304201934da48f2003b3e889 | [] | no_license | darkma773r/dkm | c772c331321fd7fbb8c5cb434f33607b3abf0d39 | 719d89792cfbabcb45067d64b32a270c6a432490 | refs/heads/master | 2021-08-16T05:46:53.260522 | 2017-11-19T03:33:24 | 2017-11-19T03:33:24 | 107,831,698 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,120 | cpp |
/**
* vector4_test.cpp
*
* Unit tests for the Vector 4 specialized template class.
*/
#include "dkm/math/vector4_test.h"
#include <iostream>
#include <gtest/gtest.h>
#include "dkm/math/matrix.h"
#include "dkm/math/math_test_helpers.h"
using namespace dkm;
// common inputs and outputs for testing
const double zeros4d[] = { 0, 0, 0, 0 };
const double base4d[] = { 1.1, 2.2, 3.3, 4.4 };
const double baseTimesTwo4d[] = { 2.2, 4.4, 6.6, 8.8 };
const double addend4d[] = { 2.2, 3.3, 4.4, 5.5 };
const double sum4d[] = { 3.3, 5.5, 7.7, 9.9 };
const int zeros4i[] = { 0, 0, 0, 0 };
const int base4i[] = { 1, 2, 3, 4 };
const int baseTimesTwo4i[] = { 2, 4, 6, 8 };
const int addend4i[] = { 2, 3, 4, 5 };
const int sum4i[] = { 3, 5, 7, 9 };
// double comparison accuracy
const double DoubleComparisonAccuracy = 0.01;
// size of array comparison
const int ArrayComparisonSize = 4;
// test suite for the specialized vector 4 template class
TEST_F(Vector4Test, xAxis){
// arrange
Vector<4, double> v = Vector<4, double>::xAxis();
// assert
double expected[] = { 1.0, 0.0, 0.0, 0.0 };
ASSERT_ARRAY_EQ(expected, v.data(), 4);
}
TEST_F(Vector4Test, yAxis){
// arrange
Vector<4, double> v = Vector<4, double>::yAxis();
// assert
double expected[] = { 0.0, 1.0, 0.0, 0.0 };
ASSERT_ARRAY_EQ(expected, v.data(), 4);
}
TEST_F(Vector4Test, zAxis){
// arrange
const Vector<4, double> v = Vector<4, double>::zAxis();
// assert
double expected[] = { 0.0, 0.0, 1.0, 0.0 };
ASSERT_ARRAY_EQ(expected, v.data(), 4);
}
TEST_F(Vector4Test, wAxis){
// arrange
const Vector<4, double> v = Vector<4, double>::wAxis();
// assert
double expected[] = { 0.0, 0.0, 0.0, 1.0 };
ASSERT_ARRAY_EQ(expected, v.data(), 4);
}
TEST_F(Vector4Test, defaultConstructor){
// act
Vector<4, double> v;
// assert
ASSERT_ARRAY_EQ(zeros4d, v.data(), ArrayComparisonSize);
}
TEST_F(Vector4Test, arrayParamConstructor){
// act
Vector<4, double> v(base4d);
// assert
ASSERT_TRUE(base4d != v.data());
ASSERT_ARRAY_EQ(base4d, v.data(), ArrayComparisonSize);
}
TEST_F(Vector4Test, valueParamConstructor){
// act
Vector<4, int> v(3, 4, 5, 6);
// assert
ASSERT_EQ(3, v.x());
ASSERT_EQ(4, v.y());
ASSERT_EQ(5, v.z());
ASSERT_EQ(6, v.w());
}
TEST_F(Vector4Test, implicitArrayConstruction){
// act
Vector<4, double> v = base4d;
// assert
ASSERT_TRUE(base4d != v.data());
ASSERT_ARRAY_EQ(base4d, v.data(), ArrayComparisonSize);
}
TEST_F(Vector4Test, copyConstructor){
// arrange
Vector<4, double> orig(base4d);
// act
Vector<4, double> clone(orig);
// assert
ASSERT_TRUE(orig.data() != clone.data());
ASSERT_ARRAY_EQ(base4d, clone.data(), ArrayComparisonSize);
}
TEST_F(Vector4Test, assignmentOperator){
// arrange
Vector<4, double> orig(base4d);
Vector<4, double> clone(zeros4d);
// act
Vector<4, double> chained = (clone = orig);
// assert
ASSERT_TRUE(orig.data() != clone.data());
ASSERT_ARRAY_EQ(base4d, clone.data(), ArrayComparisonSize);
ASSERT_ARRAY_EQ(base4d, chained.data(), ArrayComparisonSize);
}
TEST_F(Vector4Test, selfAssignment){
// arrange
Vector<4, double> v(base4d);
// act
v = v;
// assert
ASSERT_ARRAY_EQ(base4d, v.data(), ArrayComparisonSize);
}
TEST_F(Vector4Test, standardGetters){
// arrange
Vector<4, double> v;
// act/assert
ASSERT_EQ(4, v.size());
}
TEST_F(Vector4Test, copyTo){
// arrange
double dest[] = { 0.0, 0.0, 0.0, 0.0 };
Vector<4, double> v(base4d);
// act
v.copyTo(dest);
// assert
ASSERT_ARRAY_EQ(base4d, dest, ArrayComparisonSize);
ASSERT_ARRAY_EQ(base4d, v.data(), ArrayComparisonSize);
}
TEST_F(Vector4Test, copyFrom){
// arrange
double dest[] = { 0.1, 0.2, 0.3, 0.4 };
Vector<4, double> v(base4d);
// act
v.copyFrom(dest);
// assert
ASSERT_ARRAY_EQ(dest, v.data(), ArrayComparisonSize);
}
TEST_F(Vector4Test, subscriptOperator){
// arrange
Vector<4, int> v(zeros4i);
// act/assert
v[0] = 1;
v[1] = 2;
v[2] = 3;
v[3] = 4;
ASSERT_EQ(1, v[0]);
ASSERT_EQ(2, v[1]);
ASSERT_EQ(3, v[2]);
ASSERT_EQ(4, v[3]);
}
TEST_F(Vector4Test, subscriptOperator_const){
// arrange
const Vector<4, int> v(base4i);
// act/assert
ASSERT_EQ(1, v[0]);
ASSERT_EQ(2, v[1]);
ASSERT_EQ(3, v[2]);
ASSERT_EQ(4, v[3]);
}
TEST_F(Vector4Test, namedAccessors){
// arrange
Vector<4, int> v(zeros4i);
// act/assert
v.x(1);
v.y(2);
v.z(3);
v.w(4);
ASSERT_EQ(1, v.x());
ASSERT_EQ(2, v.y());
ASSERT_EQ(3, v.z());
ASSERT_EQ(4, v.w());
ASSERT_EQ(1, v[0]);
ASSERT_EQ(2, v[1]);
ASSERT_EQ(3, v[2]);
ASSERT_EQ(4, v[3]);
}
TEST_F(Vector4Test, namedAccessors_const){
// arrange
const Vector<4, int> v(base4i);
// act/assert
ASSERT_EQ(1, v.x());
ASSERT_EQ(2, v.y());
ASSERT_EQ(3, v.z());
ASSERT_EQ(4, v.w());
ASSERT_EQ(1, v[0]);
ASSERT_EQ(2, v[1]);
ASSERT_EQ(3, v[2]);
ASSERT_EQ(4, v[3]);
}
TEST_F(Vector4Test, namedAccessors_setByReferences){
// arrange
Vector<4, int> v(zeros4i);
// act/assert
v.x() = 1;
v.y() = 2;
v.z() = 3;
v.w() = 4;
ASSERT_EQ(1, v.x());
ASSERT_EQ(2, v.y());
ASSERT_EQ(3, v.z());
ASSERT_EQ(4, v.w());
ASSERT_EQ(1, v[0]);
ASSERT_EQ(2, v[1]);
ASSERT_EQ(3, v[2]);
ASSERT_EQ(4, v[3]);
}
TEST_F(Vector4Test, add){
// arrange
Vector<4, double> a(base4d);
Vector<4, double> b(addend4d);
// act
Vector<4, double> x = a.add(b);
// assert
ASSERT_ARRAY_NEAR(sum4d, x.data(), ArrayComparisonSize, DoubleComparisonAccuracy);
ASSERT_ARRAY_NEAR(base4d, a.data(), ArrayComparisonSize, DoubleComparisonAccuracy);
ASSERT_ARRAY_NEAR(addend4d, b.data(), ArrayComparisonSize, DoubleComparisonAccuracy);
}
TEST_F(Vector4Test, addOperator){
// arrange
Vector<4, double> a(base4d);
Vector<4, double> b(addend4d);
// act
Vector<4, double> x = a + b;
// assert
ASSERT_ARRAY_NEAR(sum4d, x.data(), ArrayComparisonSize, DoubleComparisonAccuracy);
ASSERT_ARRAY_NEAR(base4d, a.data(), ArrayComparisonSize, DoubleComparisonAccuracy);
ASSERT_ARRAY_NEAR(addend4d, b.data(), ArrayComparisonSize, DoubleComparisonAccuracy);
}
TEST_F(Vector4Test, addAssign){
// arrange
Vector<4, double> a(base4d);
Vector<4, double> b(addend4d);
// act
a.addAssign(b);
// assert
ASSERT_ARRAY_NEAR(sum4d, a.data(), ArrayComparisonSize, DoubleComparisonAccuracy);
ASSERT_ARRAY_NEAR(addend4d, b.data(), ArrayComparisonSize, DoubleComparisonAccuracy);
}
TEST_F(Vector4Test, addAssignOperator){
// arrange
Vector<4, double> a(base4d);
Vector<4, double> b(addend4d);
// act
Vector<4, double> x = a += b;
// assert
ASSERT_ARRAY_NEAR(sum4d, x.data(), ArrayComparisonSize, DoubleComparisonAccuracy);
ASSERT_ARRAY_NEAR(sum4d, a.data(), ArrayComparisonSize, DoubleComparisonAccuracy);
ASSERT_ARRAY_NEAR(addend4d, b.data(), ArrayComparisonSize, DoubleComparisonAccuracy);
}
TEST_F(Vector4Test, subtract){
// arrange
Vector<4, int> a(sum4i);
Vector<4, int> b(addend4i);
// act
Vector<4, int> x = a.subtract(b);
// assert
ASSERT_ARRAY_EQ(base4i, x.data(), ArrayComparisonSize);
ASSERT_ARRAY_EQ(sum4i, a.data(), ArrayComparisonSize);
ASSERT_ARRAY_EQ(addend4i, b.data(), ArrayComparisonSize);
}
TEST_F(Vector4Test, subtractOperator){
// arrange
Vector<4, int> a(sum4i);
Vector<4, int> b(addend4i);
// act
Vector<4, int> x = a - b;
// assert
ASSERT_ARRAY_EQ(base4i, x.data(), ArrayComparisonSize);
ASSERT_ARRAY_EQ(sum4i, a.data(), ArrayComparisonSize);
ASSERT_ARRAY_EQ(addend4i, b.data(), ArrayComparisonSize);
}
TEST_F(Vector4Test, subtractAssign){
// arrange
Vector<4, int> a(sum4i);
Vector<4, int> b(addend4i);
// act
a.subtractAssign(b);
// assert
ASSERT_ARRAY_EQ(base4i, a.data(), ArrayComparisonSize);
ASSERT_ARRAY_EQ(addend4i, b.data(), ArrayComparisonSize);
}
TEST_F(Vector4Test, subtractAssignOperator){
// arrange
Vector<4, int> a(sum4i);
Vector<4, int> b(addend4i);
// act
Vector<4, int> x = a -= b;
// assert
ASSERT_ARRAY_EQ(base4i, x.data(), ArrayComparisonSize);
ASSERT_ARRAY_EQ(base4i, a.data(), ArrayComparisonSize);
ASSERT_ARRAY_EQ(addend4i, b.data(), ArrayComparisonSize);
}
TEST_F(Vector4Test, scalarMultiply){
// arrange
Vector<4, double> a(base4d);
// act
Vector<4, double> x = a.scalarMultiply(2.0);
// assert
ASSERT_ARRAY_NEAR(baseTimesTwo4d, x.data(), ArrayComparisonSize, DoubleComparisonAccuracy);
ASSERT_ARRAY_EQ(base4d, a.data(), ArrayComparisonSize);
}
TEST_F(Vector4Test, scalarMultiplyOperator){
// arrange
Vector<4, double> a(base4d);
// act
Vector<4, double> x = a * 2.0;
// assert
ASSERT_ARRAY_NEAR(baseTimesTwo4d, x.data(), ArrayComparisonSize, DoubleComparisonAccuracy);
ASSERT_ARRAY_EQ(base4d, a.data(), ArrayComparisonSize);
}
TEST_F(Vector4Test, ScalarMultiplyOperator_ScalarFirst){
// arrange
Vector<4, double> a(base4d);
// act
Vector<4, double> x = 2.0 * a;
// assert
ASSERT_ARRAY_NEAR(baseTimesTwo4d, x.data(), ArrayComparisonSize, DoubleComparisonAccuracy);
ASSERT_ARRAY_EQ(base4d, a.data(), ArrayComparisonSize);
}
TEST_F(Vector4Test, scalarMultiplyAssign){
// arrange
Vector<4, double> a(base4d);
// act
a.scalarMultiplyAssign(2.0);
// assert
ASSERT_ARRAY_NEAR(baseTimesTwo4d, a.data(), ArrayComparisonSize, DoubleComparisonAccuracy);
}
TEST_F(Vector4Test, scalarMultiplyAssignOperator){
// arrange
Vector<4, double> a(base4d);
// act
Vector<4, double> x = a *= 2.0;
// assert
ASSERT_ARRAY_NEAR(baseTimesTwo4d, x.data(), ArrayComparisonSize, DoubleComparisonAccuracy);
ASSERT_ARRAY_NEAR(baseTimesTwo4d, a.data(), ArrayComparisonSize, DoubleComparisonAccuracy);
}
TEST_F(Vector4Test, magnitude){
// arrange
Vector<4, int> a(base4i);
// act
double mag = a.magnitude();
// assert
ASSERT_NEAR(5.4772, mag, DoubleComparisonAccuracy);
}
TEST_F(Vector4Test, magnitude_zeroVector){
// arrange
Vector<4, int> a(zeros4i);
// act
double mag = a.magnitude();
// assert
ASSERT_NEAR(0.0, mag, DoubleComparisonAccuracy);
}
TEST_F(Vector4Test, magnitude_negativeValues){
// arrange
int negArr[] = { -1, -2, -3, -4 };
Vector<4, int> a(negArr);
// act
double mag = a.magnitude();
// assert
ASSERT_NEAR(5.4772, mag, DoubleComparisonAccuracy);
}
TEST_F(Vector4Test, normalize){
// arrange
// magnitude = 6.0249
Vector<4, double> a(base4d);
// act
bool result = a.normalize();
// assert
ASSERT_EQ(true, result);
double normalized[] = { 0.1826, 0.3651, 0.5477, 0.7303 };
ASSERT_ARRAY_NEAR(normalized, a.data(), ArrayComparisonSize, DoubleComparisonAccuracy);
}
TEST_F(Vector4Test, normalize_zeroArray){
// arrange
Vector<4, double> a(zeros4d);
// act
bool result = a.normalize();
// assert
ASSERT_EQ(false, result);
ASSERT_ARRAY_NEAR(zeros4d, a.data(), ArrayComparisonSize, DoubleComparisonAccuracy);
}
TEST_F(Vector4Test, normalize_integerVector){
// arrange
Vector<4, int> a(base4i);
// act
bool result = a.normalize();
// assert
ASSERT_EQ(true, result);
// since every value will be less than one, the array ends up consisting
// entirely of zeros. This is something the caller will need to be aware of.
ASSERT_ARRAY_EQ(zeros4i, a.data(), ArrayComparisonSize);
}
TEST_F(Vector4Test, isNormalized_default){
// arrange
float normalizedArr[] = { 0.0, 0.0, 0.7071067811, 0.7071067811 };
float notNormalizedArr[] = { 0.0, 0.0, 1.0, 1.0 };
Vector<4, float> a(normalizedArr);
Vector<4, float> b(notNormalizedArr);
// act/assert
ASSERT_EQ(true, a.isNormalized());
ASSERT_EQ(false, b.isNormalized());
}
TEST_F(Vector4Test, isNormalized_epsilon){
// arrange
float arr[] = { 0.0, 0.0, 0.8, 0.8 };
Vector<4, float> a(arr);
// act/assert
ASSERT_EQ(true, a.isNormalized(0.5));
ASSERT_EQ(false, a.isNormalized(0.01));
}
TEST_F(Vector4Test, dotProduct){
// arrange
Vector<4, int> a(base4i);
Vector<4, int> b(base4i);
// act
double dotproduct = a.dot(b);
// assert
ASSERT_NEAR(30.0, dotproduct, DoubleComparisonAccuracy);
ASSERT_ARRAY_EQ(base4i, a.data(), ArrayComparisonSize);
ASSERT_ARRAY_EQ(base4i, b.data(), ArrayComparisonSize);
}
TEST_F(Vector4Test, toString){
// arrange
Vector<4, double> v;
v[0] = 0.012;
v[1] = 1.0;
v[2] = 2.0;
v[3] = 3.3333;
// act
std::string expected("[ 0.01, 1.00, 2.00, 3.33 ]");
std::string str = v.toString();
// assert
ASSERT_EQ(expected, str);
}
| [
"matt.juntunen@hotmail.com"
] | matt.juntunen@hotmail.com |
d44b7b01d6bb9000022f30367bd29e7f518e7de0 | c7f9f0e0b89bf40996a09759ac7aee017e202839 | /FIXGateway/src/AuthServiceHelper.cpp | e1da9d0671fa2130d9b2ee7b9636c0e0bb0bc34f | [
"MIT"
] | permissive | dsimba/DistributedATS | 546312bc25fc2be87265ecf4fab81d5940b0ded2 | 67ed23f7e9674012743b3fc45341d85fba0dbf36 | refs/heads/master | 2023-03-28T13:10:45.560997 | 2021-04-05T01:17:55 | 2021-04-05T01:17:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,963 | cpp | /*
Copyright (C) 2021 Mike Kipnis
This file is part of DistributedATS, a free-software/open-source project
that integrates QuickFIX and LiquiBook over OpenDDS. This project simplifies
the process of having multiple FIX gateways communicating with multiple
matching engines in realtime.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "AuthServiceHelper.h"
#include <strstream>
#include <ace/Log_Msg.h>
#include <ace/Log_Msg_Callback.h>
#include <ace/Log_Record.h>
#include <ace/streams.h>
#include <quickfix/fix44/Logout.h>
AuthServiceHelper::AuthServiceHelper(
std::shared_ptr<FIX::SessionSettings> settings,
std::shared_ptr<FIX::SessionFactory> sessionFactory,
const FIX::Dictionary *defaultDictionary, std::string senderCompID)
: _settings(settings), _sessionFactory(sessionFactory),
_defaultDictionary(defaultDictionary), _senderCompID(senderCompID) {}
//
// creates session id from provided message
//
const FIX::SessionID
AuthServiceHelper::SessionIDFromMessage(FIX::Message &message,
const std::string &sessionQualifier) {
FIX::BeginString beginString;
FIX::SenderCompID clSenderCompID;
FIX::TargetCompID clTargetCompID;
message.getHeader().getField(beginString);
message.getHeader().getField(clSenderCompID);
message.getHeader().getField(clTargetCompID);
FIX::SenderCompID senderCompID(clTargetCompID);
FIX::TargetCompID targetCompID(clSenderCompID);
return FIX::SessionID(beginString, senderCompID, targetCompID,
sessionQualifier);
}
//
// Messages from DataServer/Auth have AUTH in Source, we need to change it to
// Gateway Alias - i.e. EXECUTOR(Instance of the gateway) to proceed with login
//
FIX::Session *AuthServiceHelper::createSessionFromAuthMessage(
const FIX::SessionID newFixSessionID, FIX::Message &message,
const std::string &sessionQualifier) {
FIX::TargetCompID currentTargetCompID;
message.getHeader().getField(currentTargetCompID);
FIX::TargetCompID clTargetCompId(newFixSessionID.getSenderCompID());
message.getHeader().setField(clTargetCompId);
message.getHeader().setField(currentTargetCompID);
if (!_settings->has(newFixSessionID))
_settings->set(newFixSessionID, *_defaultDictionary);
FIX::Session *session = FIX::Session::lookupSession(newFixSessionID);
try {
if (session == NULL) {
session = _sessionFactory->create(newFixSessionID, *_defaultDictionary);
ACE_DEBUG((LM_INFO,
ACE_TEXT("(%P|%t|%D) Creating QuickFIX Session from message "
"from auth service : %s\n"),
session->getSessionID().toString().c_str()));
}
} catch (FIX::ConfigError &cfgError) {
std::cerr << "Config Exception in session create : " << cfgError.what()
<< std::endl;
};
return session;
};
void AuthServiceHelper::insertPendingConnection(
const std::string &connectionToken,
DistributedATS::SocketConnection *socketConnection) {
FIX::Locker lock(_pendingSessionMutex);
ACE_DEBUG(
(LM_INFO,
ACE_TEXT(
"(%P|%t|%D) Inserting pending connection : %s : Socket : [%d]\n"),
connectionToken.c_str(), socketConnection->getSocket()));
std::cout << "Connection Token: " << connectionToken << std::endl;
m_pendingLogonSocketConnection[connectionToken] = socketConnection;
socketConnection->setPendingConnectionToken(connectionToken);
}
// returns sender compID
std::string AuthServiceHelper::getConnectionToken(const FIX::Message &message) {
FIX::RawData rawData;
message.getField(rawData);
std::string connectionToken = rawData.getValue();
return connectionToken;
}
void AuthServiceHelper::processDDSLogon(FIX::Message &message) {
std::string connectionToken = getConnectionToken(message);
FIX::BeginString beginString;
FIX::TargetCompID clTargetCompID;
FIX::SenderCompID clLogonSenderCompID;
message.getHeader().getField(beginString);
message.getHeader().getField(clTargetCompID);
message.getHeader().getField(clLogonSenderCompID);
FIX::SessionID newFixSessionID(beginString, _senderCompID, clTargetCompID,
"");
ACE_DEBUG(
(LM_INFO,
ACE_TEXT(
"(%P|%t|%D) Received Session ID for Logon : %s : Session : [%s]\n"),
_senderCompID.c_str(), newFixSessionID.toString().c_str()));
FIX::Session *session = FIX::Session::lookupSession(newFixSessionID);
if (session != NULL) {
if (session->isLoggedOn() &&
clLogonSenderCompID.getValue().compare(_senderCompID) == 0) {
FIX44::Logout logoutMessage;
FIX::Text logoutText("New session logged in with your credentials");
logoutMessage.set(logoutText);
FIX::Session::sendToTarget(logoutMessage, newFixSessionID);
FIX::Locker lock(_pendingSessionMutex);
m_sessionReloginMap[newFixSessionID] = message;
return;
} else {
FIX44::Logout logoutMessage;
FIX::Text logoutText(
"New session logged in with your credentials from Another Gateway");
logoutMessage.set(logoutText);
FIX::Session::sendToTarget(logoutMessage, newFixSessionID);
}
} else if (clLogonSenderCompID.getValue().compare(_senderCompID) == 0) {
session = AuthServiceHelper::createSessionFromAuthMessage(newFixSessionID,
message, "");
if (session == NULL) {
std::cerr << "Something is wrong unable to create session object!!!!!"
<< std::endl;
return;
}
} else {
return;
}
loginSession(session, connectionToken);
}
void AuthServiceHelper::loginSession(FIX::Session *session,
std::string &connectionToken) {
FIX::Locker lock(_pendingSessionMutex);
ACE_DEBUG(
(LM_INFO, ACE_TEXT("(%P|%t|%D) Login-in Session : [%s] - Token [%s] \n"),
session->getSessionID().toString().c_str(), connectionToken.c_str()));
DistributedATS::SocketConnection *responder =
m_pendingLogonSocketConnection[connectionToken];
if (responder != NULL) {
responder->setSession(session);
session->setResponder(responder);
std::string pendingLogin = responder->getPendingLogin();
m_pendingLogonSocketConnection.erase(connectionToken);
try {
session->next(pendingLogin, UtcTimeStamp());
} catch (Exception &e) {
ACE_DEBUG(
(LM_ERROR,
ACE_TEXT("(%P|%t|%D) Exception in Logon : [%s] - Exception [%s] \n"),
session->getSessionID().toString().c_str(), e.what()));
};
} else {
ACE_DEBUG(
(LM_INFO,
ACE_TEXT("(%P|%t|%D) Responder not found : [%s] - Token [%s] \n"),
session->getSessionID().toString().c_str(), connectionToken.c_str()));
}
}
void AuthServiceHelper::processDDSLogout(std::string &connectionToken,
FIX::Message &message) {
FIX::Locker lock(_pendingSessionMutex);
DistributedATS::SocketConnection *responder =
m_pendingLogonSocketConnection[connectionToken];
if (responder == NULL)
return;
std::string pendingLoginStr = responder->getPendingLogin();
FIX::Message pendingLogin(pendingLoginStr);
FIX::BeginString beginString;
FIX::Username clUsername;
FIX::SenderCompID clSenderCompID;
FIX::TargetCompID clTargetCompID;
pendingLogin.getHeader().getField(beginString);
pendingLogin.getHeader().getField(clTargetCompID);
pendingLogin.getHeader().getField(clSenderCompID);
FIX::MsgSeqNum msgSeqNum(1);
FIX::SendingTime sendingTime;
FIX::TargetCompID targetCompID(clSenderCompID.getValue());
FIX::SenderCompID senderCompID(clTargetCompID.getValue());
message.getHeader().setField(msgSeqNum);
message.getHeader().setField(targetCompID);
message.getHeader().setField(senderCompID);
message.getHeader().setField(sendingTime);
ACE_DEBUG((LM_INFO,
ACE_TEXT("(%P|%t|%D) Logout : Original SessionID Token [%s] : "
"Logout Message ID: %s\n"),
connectionToken.c_str(), message.toString().c_str()));
responder->send(message.toString());
responder->disconnect();
}
void AuthServiceHelper::processDisconnect(
const FIX::SessionID &sessionID,
DistributedATS::SocketConnection *pSocketConnection) {
FIX::Locker lock(_pendingSessionMutex);
ACE_DEBUG(
(LM_INFO,
ACE_TEXT("(%P|%t|%D) Disconnecting Pending Connection Token: %s \n"),
pSocketConnection->getPendingConnectionToken().c_str()));
// lets check if its a pending connection
auto responder_iterator = m_pendingLogonSocketConnection.find(
pSocketConnection->getPendingConnectionToken());
if (responder_iterator != m_pendingLogonSocketConnection.end()) {
// it a pending connection disconnect
m_pendingLogonSocketConnection.erase(responder_iterator);
return;
}
ACE_DEBUG((LM_INFO, ACE_TEXT("(%P|%t|%D) Disconneting : [%s]\n"),
sessionID.toString().c_str()));
SessionReLoginMap::iterator pendingLoginIn =
m_sessionReloginMap.find(sessionID);
if (pendingLoginIn != m_sessionReloginMap.end()) {
ACE_DEBUG(
(LM_INFO,
ACE_TEXT("(%P|%t|%D) There is a session to relogin : [%s] : [%s]\n"),
sessionID.toString().c_str(),
pendingLoginIn->second.toString().c_str()));
FIX::Session *session = FIX::Session::lookupSession(sessionID);
session->logon();
std::string connectionToken = getConnectionToken(pendingLoginIn->second);
ACE_DEBUG((LM_INFO, ACE_TEXT("(%P|%t|%D) Connection Token : [%s]\n"),
connectionToken.c_str()));
loginSession(session, connectionToken);
m_sessionReloginMap.erase(pendingLoginIn);
} else {
FIX::Session *session = FIX::Session::lookupSession(sessionID);
session->setResponder(NULL);
session->logout("Disconnected");
_sessionFactory->destroy(session);
}
}
| [
"mike.kipnis@gmail.com.com"
] | mike.kipnis@gmail.com.com |
5d6c72f4905306672b4d8967d7fdae94bdc77d1d | add71c266be24dd41ee24e53c86fa585a555bf49 | /src/international.cpp | e183e675315e963adfd9e99e3e263a0418b2444c | [
"BSD-2-Clause"
] | permissive | copperspice/kitchensink | 8b924e04ea38a7490813c7caf826a21e0fab016c | ab6fdedcc09c1d37bf89ee312e63f09b6a8ac1e4 | refs/heads/master | 2023-07-10T09:53:23.605192 | 2023-05-22T19:46:13 | 2023-05-22T19:46:13 | 101,581,627 | 27 | 14 | BSD-2-Clause | 2023-08-28T17:44:32 | 2017-08-27T21:31:51 | C++ | UTF-8 | C++ | false | false | 3,233 | cpp | /***********************************************************************
*
* Copyright (c) 2012-2023 Barbara Geller
* Copyright (c) 2012-2023 Ansel Sermersheim
* Copyright (c) 2015 The Qt Company Ltd.
*
* This file is part of KitchenSink.
*
* KitchenSink is free software, released under the BSD 2-Clause license.
* For license details refer to LICENSE provided with this project.
*
* KitchenSink 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.
*
* https://opensource.org/licenses/BSD-2-Clause
*
***********************************************************************/
#include "util.h"
#include "international.h"
#include <QStringListModel>
#include <QTranslator>
static const QString qmPath = ":/resources";
QTranslator *International::m_translator = new QTranslator;
International::International()
: QWidget(), ui(new Ui::International )
{
ui->setupUi(this);
setWindowTitle(tr("International"));
// add the model
m_model = new QStringListModel();
ui->listView->setModel(m_model);
// add data
ui->nameCB->addItem("Amy Pond");
ui->nameCB->addItem("Jack Harkness");
ui->nameCB->addItem("River Song");
ui->nameCB->addItem("Rose Tyler");
ui->nameCB->addItem("Martha Jones");
this->getListData();
//
connect(ui->englishRB, &QPushButton::clicked, this, &International::actionEnglish);
connect(ui->frenchRB, &QPushButton::clicked, this, &International::actionFrench);
connect(ui->germanRB, &QPushButton::clicked, this, &International::actionGerman);
connect(ui->okPB, &QPushButton::clicked, this, &International::actionClose);
connect(ui->closePB, &QPushButton::clicked, this, &International::actionClose);
// force
ui->nameCB->setFocus();
}
International::~International()
{
delete ui;
}
void International::actionEnglish()
{
if (m_translator->load("ks_en.qm", qmPath)) {
qApp->installTranslator(m_translator);
} else {
ksMsg(this, tr("International"), tr("Error while loading English international file."));
}
}
void International::actionFrench()
{
if (m_translator->load("ks_fr.qm", qmPath)) {
qApp->installTranslator(m_translator);
} else {
ksMsg(this, tr("International"), tr("Error while loading French international file."));
}
}
void International::actionGerman()
{
if (m_translator->load("ks_de.qm", qmPath)) {
qApp->installTranslator(m_translator);
} else {
ksMsg(this, tr("International"), tr("Error while loading German international file."));
}
}
void International::changeEvent(QEvent *event)
{
if (event->type() == QEvent::LanguageChange) {
ui->retranslateUi(this);
this->getListData();
}
QWidget::changeEvent(event);
}
void International::getListData()
{
QStringList list;
list.append(tr("Chocolate Cake"));
list.append(tr("Lemon Bars"));
list.append(tr("Oatmeal Raisin Cookies"));
list.append(tr("Peach Cobbler"));
list.append(tr("Pumpkin Cheesecake"));
list.append(tr("Sticky Buns"));
m_model->setStringList(list);
}
void International::actionClose()
{
this->parentWidget()->close();
}
| [
"barbara@copperspice.com"
] | barbara@copperspice.com |
64da1fdebe2b898a02f409a9e9b9820e4aa1ead4 | 3a8adb89fb9b5b78f8d88cb020fc1bf0a875f23c | /src/qt/askpassphrasedialog.cpp | fe7c5f7b2cc9864440b33ac8683c926a64fefa6d | [
"MIT"
] | permissive | koheihamada/hamacoin | c1645e3d243325eec01d63a9eaec110eba0c9b04 | 20143668150d5b32cab41a705cf44b32148ccf99 | refs/heads/master | 2021-08-28T13:22:04.635266 | 2017-12-12T09:19:25 | 2017-12-12T09:19:25 | 113,942,874 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,914 | cpp | // Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include <QMessageBox>
#include <QPushButton>
#include <QKeyEvent>
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->passLabel1->hide();
ui->passEdit1->hide();
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>."));
setWindowTitle(tr("Encrypt wallet"));
break;
case Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
break;
}
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
delete ui;
}
void AskPassphraseDialog::setModel(WalletModel *model)
{
this->model = model;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if(!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
switch(mode)
{
case Encrypt: {
if(newpass1.empty() || newpass2.empty())
{
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR LITECOINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
if(newpass1 == newpass2)
{
if(model->setWalletEncrypted(true, newpass1))
{
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("Hamacoin will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your hamacoins from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
}
else
{
QDialog::reject(); // Cancelled
}
} break;
case Unlock:
if(!model->setWalletLocked(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case Decrypt:
if(!model->setWalletEncrypted(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case ChangePass:
if(newpass1 == newpass2)
{
if(model->changePassphrase(oldpass, newpass1))
{
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch(mode)
{
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case Unlock: // Old passphrase x1
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
| [
"kohei.hamada@yahoo.com"
] | kohei.hamada@yahoo.com |
d80a3f5a7129a5b1822fd6072a0d106fa5ebe801 | 544f81c2e77900757a70b58d5174739680d427f8 | /sketch_dec18a.ino | 4d412d9c542492f08d2e2d69f1ea12ad86b067e6 | [] | no_license | evolvingkid/audrino | 672cd66d75637edff173f49fd12e060afc37a70b | c98be5940af8ada8184108785e51090f36939bab | refs/heads/master | 2022-11-30T12:59:53.473082 | 2020-08-10T06:30:41 | 2020-08-10T06:30:41 | 286,394,318 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 528 | ino |
int led = 3;
//int brightness = 0;
//int fadeAmount = 5;
//int conut=0;
//int i=0;
void setup() {
pinMode(led, OUTPUT);
}
void loop() {
if(conut ==1){
for(i=0; i< 10; i++){
digitalWrite(led, HIGH);
delay(50);
digitalWrite(led, LOW);
delay(50);
}
conut=0;
}
analogWrite(led, brightness);
brightness = brightness + fadeAmount;
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
conut=1;
}
delay(20);
}
| [
"fayezmohammed23@gmail.com"
] | fayezmohammed23@gmail.com |
0a3111d006ed13abb70f6f89a6c706798a8b014d | 1cf429baa77207674033d6d5d771a6155800c6b4 | /LuaCpp/LuaCpp/LuaCpp/LuaEngine.cpp | 5d267f7d3c0e5811c7a521fa35f5842cdf3f55e3 | [
"MIT"
] | permissive | Revenaant/CppLuaEngine | bef066b1b4ef9d01e74c726ca3472c607bf79202 | 7057cb98cddf8c46f1784e9241fd20e2e3b79b7c | refs/heads/master | 2020-05-31T12:30:48.310339 | 2019-06-04T21:37:34 | 2019-06-04T21:37:34 | 190,282,225 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 333 | cpp | #include <iostream>
#include "AbstractGame.h"
#include "LuaCardGame.h"
int main(void)
{
std::cout << "Starting LuaEngineGame, close with Escape" << '\n';
AbstractGame* game = new LuaCardGame();
game->initialize();
game->run();
game->close();
delete game;
std::cout << "Closed Game" << '\n';
//std::cin.get();
return 0;
}
| [
"rodrigo_jsd@hotmail.com"
] | rodrigo_jsd@hotmail.com |
d12d81e19df4a2696cac825f171d4b970900cf14 | c25041e4f522202c1214ce8f5a8fca72748d3689 | /Source/SIMPLib/FilterParameters/LinkedBooleanFilterParameter.h | ed1da12a7d2b9a94ff6c8ac124f11200c75823a5 | [
"BSD-3-Clause"
] | permissive | wlenthe/DREAM3D | aa304c81b48e01f4adc0dd581ed2104c077c3cdd | c5689b1035f9559316e3f8a38aa16c473df0ea58 | refs/heads/develop | 2021-01-22T14:45:22.899704 | 2015-10-23T21:19:15 | 2015-10-23T21:19:15 | 37,750,385 | 0 | 1 | null | 2015-06-19T23:18:20 | 2015-06-19T23:18:20 | null | UTF-8 | C++ | false | false | 3,239 | h | /* ============================================================================
* Copyright (c) 2009-2015 BlueQuartz Software, LLC
*
* 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 BlueQuartz Software, the US Air Force, 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.
*
* The code contained herein was partially funded by the followig contracts:
* United States Air Force Prime Contract FA8650-07-D-5800
* United States Air Force Prime Contract FA8650-10-D-5210
* United States Prime Contract Navy N00173-07-C-2068
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#ifndef _LinkedBooleanFilterParameter_H_
#define _LinkedBooleanFilterParameter_H_
#include "SIMPLib/FilterParameters/FilterParameter.h"
class SIMPLib_EXPORT LinkedBooleanFilterParameter : public FilterParameter
{
public:
SIMPL_SHARED_POINTERS(LinkedBooleanFilterParameter)
SIMPL_STATIC_NEW_MACRO(LinkedBooleanFilterParameter)
SIMPL_TYPE_MACRO_SUPER(LinkedBooleanFilterParameter, FilterParameter)
static Pointer New(const QString& humanLabel, const QString& propertyName,
const bool& defaultValue,
QStringList conditionalProperties,
Category category,
int groupIndex = -1);
virtual ~LinkedBooleanFilterParameter();
SIMPL_INSTANCE_PROPERTY(QStringList, ConditionalProperties)
/**
* @brief getWidgetType Returns the type of widget that displays and controls
* this FilterParameter subclass
* @return
*/
QString getWidgetType();
protected:
LinkedBooleanFilterParameter();
private:
LinkedBooleanFilterParameter(const LinkedBooleanFilterParameter&); // Copy Constructor Not Implemented
void operator=(const LinkedBooleanFilterParameter&); // Operator '=' Not Implemented
};
#endif /* _LinkedBooleanFilterParameter_H_ */
| [
"mike.jackson@bluequartz.net"
] | mike.jackson@bluequartz.net |
2a9f358b30ef0106fe7cc3d667dbe417a5afa20d | 4e80ccd652bc37acf9db47683ac22e1c4dce38b4 | /src/misc/ParticleCustomizer.cpp | 5a585c9a41d0e3769b0818e2d92b78b9d26eb535 | [
"MIT"
] | permissive | pavankumarallu/ALZparticles | 1a5628d438baeda6553ba8e4e3389d09f5c3d73e | 8684d8c92e71825c727c0a76b6a29486e6e4e3de | refs/heads/master | 2020-08-28T03:31:06.418875 | 2019-10-20T18:43:28 | 2019-10-20T18:43:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,883 | cpp | #include <pch.h>
#include "ParticleCustomizer.h"
namespace ALZ {
ParticleCustomizer::ParticleCustomizer() :
mt(std::random_device{}())
{
m_Line.Color = glm::vec4(0.0f, 0.7f, 0.0f, 0.85f);
m_CircleOutline.Color = glm::vec4(0.0f, 0.7f, 0.0f, 0.85f);
m_CircleOutline.Position = { 0.5f, 0.5f };
}
ParticleCustomizer::ParticleCustomizer(const ParticleCustomizer& customizer) :
m_TextureCustomizer(customizer.m_TextureCustomizer)
{
m_VelocityCustomizer = customizer.m_VelocityCustomizer;
m_NoiseCustomizer = customizer.m_NoiseCustomizer;
m_LifetimeCustomizer = customizer.m_LifetimeCustomizer;
m_ColorCustomizer = customizer.m_ColorCustomizer;
m_ScaleCustomizer = customizer.m_ScaleCustomizer;
m_ForceCustomizer = customizer.m_ForceCustomizer;
m_Line = customizer.m_Line;
m_LineAngle = customizer.m_LineAngle;
m_LinePosition = customizer.m_LinePosition;
m_CircleOutline = customizer.m_CircleOutline;
mt = customizer.mt;
}
ParticleCustomizer ParticleCustomizer::operator=(const ParticleCustomizer& customizer)
{
return ParticleCustomizer(customizer);
}
std::string GetModeAsText(const SpawnMode& mode)
{
switch (mode)
{
case SpawnMode::SpawnOnPoint:
return "Spawn On Point";
case SpawnMode::SpawnOnLine:
return "Spawn On Line";
case SpawnMode::SpawnOnCircle:
return "Spawn On Circle";
case SpawnMode::SpawnInsideCircle:
return "Spawn Inside Circle";
default:
return "";
}
}
SpawnMode GetTextAsMode(const std::string& mode)
{
if (mode == "Spawn On Point")
return SpawnMode::SpawnOnPoint;
else if (mode == "Spawn On Line")
return SpawnMode::SpawnOnLine;
else if (mode == "Spawn On Circle")
return SpawnMode::SpawnOnCircle;
else if (mode == "Spawn Inside Circle")
return SpawnMode::SpawnInsideCircle;
else {
assert(false);
return SpawnMode::SpawnOnPoint;
}
}
void ParticleCustomizer::DisplayGUI(const std::string& windowName, bool& windowOpen)
{
ImGui::SetNextWindowSizeConstraints(ImVec2(575.0f, 500.0f), ImVec2(std::numeric_limits<float>().max(), std::numeric_limits<float>().max()));
ImGui::Begin((windowName.size() > 0) ? (windowName + "##" + std::to_string(ImGui::GetID(this))).c_str() : "No Name", &windowOpen, ImGuiWindowFlags_NoSavedSettings);
ImGui::Text("Spawn\n Mode");
ImGui::SameLine();
if (ImGui::BeginCombo("##Spawn Mode", GetModeAsText(Mode).c_str())) {
{
bool is_active = Mode == SpawnMode::SpawnOnPoint;
if (ImGui::Selectable(GetModeAsText(SpawnMode::SpawnOnPoint).c_str(), &is_active)) {
ImGui::SetItemDefaultFocus();
Mode = SpawnMode::SpawnOnPoint;
}
}
{
bool is_active = Mode == SpawnMode::SpawnOnLine;
if (ImGui::Selectable(GetModeAsText(SpawnMode::SpawnOnLine).c_str(), &is_active)) {
ImGui::SetItemDefaultFocus();
Mode = SpawnMode::SpawnOnLine;
}
}
{
bool is_active = Mode == SpawnMode::SpawnOnCircle;
if (ImGui::Selectable(GetModeAsText(SpawnMode::SpawnOnCircle).c_str(), &is_active)) {
ImGui::SetItemDefaultFocus();
Mode = SpawnMode::SpawnOnCircle;
}
}
{
bool is_active = Mode == SpawnMode::SpawnInsideCircle;
if (ImGui::Selectable(GetModeAsText(SpawnMode::SpawnInsideCircle).c_str(), &is_active)) {
ImGui::SetItemDefaultFocus();
Mode = SpawnMode::SpawnInsideCircle;
}
}
ImGui::EndCombo();
}
m_TextureCustomizer.DisplayGUI();
if (ImGui::TreeNode("Emission")) {
ImGui::Text("Particles\nPer Second: ");
ImGui::SameLine();
ImGui::DragFloat("##Particles\nPer Second: ", &m_ParticlesPerSecond, 1.0f, 0.1f, 1000.0f);
ImGui::TreePop();
}
if (Mode == SpawnMode::SpawnOnPoint) {
if (ImGui::TreeNode("Position")) {
ImGui::Text("Starting Position:");
ImGui::SameLine();
ImGui::DragFloat2("##Starting Position:", &m_SpawnPosition.x, 0.001f);
ImGui::TreePop();
}
}
else if (Mode == SpawnMode::SpawnOnLine)
{
if (ImGui::TreeNode("Position")) {
ImGui::Text("Line Position: ");
ImGui::SameLine();
float xPos = ImGui::GetCursorPosX();
ImGui::DragFloat2("##Line Position: ", &m_LinePosition.x, 0.001f);
ImGui::Text("Line Length: ");
ImGui::SameLine();
ImGui::SetCursorPosX(xPos);
ImGui::DragFloat("##Line Length: ", &m_LineLength, 0.001f);
ImGui::Text("Line Rotation :");
ImGui::SameLine();
ImGui::SetCursorPosX(xPos);
ImGui::DragFloat("##Line Rotation: ", &m_LineAngle, 1.0f, 0.0f, 360.0f);
ImGui::TreePop();
}
}
else if (Mode == SpawnMode::SpawnOnCircle || Mode == SpawnMode::SpawnInsideCircle)
{
if (ImGui::TreeNode("Position"))
{
ImGui::Text("Circle Position: ");
ImGui::SameLine();
float xPos = ImGui::GetCursorPosX();
ImGui::DragFloat2("##Circle Position: ", &m_CircleOutline.Position.x, 0.001f);
ImGui::Text("Circle Radius: ");
ImGui::SameLine();
ImGui::SetCursorPosX(xPos);
ImGui::DragFloat("##Circle Radius: ", &m_CircleOutline.Radius, 0.001f);
m_CircleOutline.Radius = std::clamp(m_CircleOutline.Radius, 0.001f, 10000.0f);
ImGui::TreePop();
}
}
m_NoiseCustomizer.DisplayGUI();
m_VelocityCustomizer.DisplayGUI();
m_ColorCustomizer.DisplayGUI();
m_LifetimeCustomizer.DisplayGUI();
m_ScaleCustomizer.DisplayGUI();
m_ForceCustomizer.DisplayGUI();
ImGui::End();
}
void ParticleCustomizer::Update()
{
switch (Mode)
{
case SpawnMode::SpawnOnPoint: {
glm::vec2 spawnPosition = { m_SpawnPosition.x * GlobalScaleFactor, m_SpawnPosition.y * GlobalScaleFactor };
m_Particle.m_Position = spawnPosition;
break;
}
case SpawnMode::SpawnOnLine: {
std::uniform_real_distribution<float> dest(0.0f, 1.0f);
m_Particle.m_Position = m_Line.GetPointInLine(dest(mt));
break;
}
case SpawnMode::SpawnOnCircle: {
//random angle between 0 and 2pi (360 degrees)
std::uniform_real_distribution<float> dest(0.0f, 2.0f * 3.14159f);
m_Particle.m_Position = m_CircleOutline.GetPointByAngle(dest(mt));
break;
}
case SpawnMode::SpawnInsideCircle: {
std::uniform_real_distribution<float> dest(0.0f, 1.0f);
float r = m_CircleOutline.Radius * sqrt(dest(mt));
float theta = dest(mt) * 2 * PI; //in radians
m_Particle.m_Position = glm::vec2(m_CircleOutline.Position.x + r * cos(theta), m_CircleOutline.Position.y + r * sin(theta));
m_Particle.m_Position *= GlobalScaleFactor;
break;
}
}
m_Particle.m_Velocity = m_VelocityCustomizer.GetVelocity();
m_Particle.m_ColorInterpolator = m_ColorCustomizer.GetColorInterpolator();
m_Particle.SetLifeTime(m_LifetimeCustomizer.GetLifetime());
m_Particle.m_ScaleInterpolator = m_ScaleCustomizer.GetScaleInterpolator();
if (m_ScaleCustomizer.GetScaleInterpolator().Type == Custom)
{
m_Particle.CustomScaleCurve = m_ScaleCustomizer.m_Curve;
}
}
Particle& ParticleCustomizer::GetParticle()
{
Update();
return m_Particle;
}
} | [
"abdullrohman514@gmail.com"
] | abdullrohman514@gmail.com |
2290afac0085e0ed2fe3c1b7157cde75cfbace24 | b84aa8a1745f3346f22b9a0ae1c977a244dfb3cd | /SDK/RC_WBP_RoundRecap_Entry_classes.hpp | de888ddfe806b5517101054b72cdc79042ad95b0 | [] | no_license | frankie-11/Rogue-SDK-11.8 | 615a9e51f280a504bb60a4cbddb8dfc4de6239d8 | 20becc4b2fff71cfec160fb7f2ee3a9203031d09 | refs/heads/master | 2023-01-10T06:00:59.427605 | 2020-11-08T16:13:01 | 2020-11-08T16:13:01 | 311,102,184 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 773 | hpp | #pragma once
// RogueCompany (4.24) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// WidgetBlueprintGeneratedClass WBP_RoundRecap_Entry.WBP_RoundRecap_Entry_C
// 0xFFFFFFFFC6E02700 (0x219F2980 - 0x5ABF0280)
class UWBP_RoundRecap_Entry_C : public UUserWidget
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass WBP_RoundRecap_Entry.WBP_RoundRecap_Entry_C");
return ptr;
}
void SetVisualState();
void RoundDataSet();
void ExecuteUbergraph_WBP_RoundRecap_Entry();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"60810131+frankie-11@users.noreply.github.com"
] | 60810131+frankie-11@users.noreply.github.com |
6d0a60dc5150446fb9e48eea4b16377afd011e1e | 94b1ec9eb7fe20da049fe8ac63df672bf7fb4eb8 | /21_bbc_20203054.ino | f1eb5cf3ff1d14c4c018d3369134edfcb7d6f2ac | [] | no_license | T-WK/kmu-Arduino | 34ecc96c62076c1c600476bcd864251a2d8dd62e | 4c65a69113f32e2b92e4e07c543809c16ff0db5d | refs/heads/master | 2023-01-29T16:16:33.407056 | 2020-12-14T00:19:29 | 2020-12-14T00:19:29 | 294,575,332 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,471 | ino | // Arduino pin assignment
#include <Servo.h>
#define PIN_IR A0
#define PIN_LED 9
#define PIN_SERVO 10
#define Horizontal_Angle 2160
#define Max_Variable_Angle 100
Servo myservo;
int a, b, angle; // unit: mm
void setup() {
// initialize GPIO pins
pinMode(PIN_LED,OUTPUT);
digitalWrite(PIN_LED, 1);
// initialize serial port
Serial.begin(57600);
myservo.attach(PIN_SERVO);
myservo.write(Horizontal_Angle);
a = 68;
b = 245;
}
float ir_distance(void){ // return value unit: mm
float val;
float volt = float(analogRead(PIN_IR));
val = ((6762.0/(volt-9.0))-4.0) * 10.0;
return val;
}
void loop() {
float raw_dist = ir_distance();
float dist_cali = 100 + 300.0 / (b - a) * (raw_dist - a);
if (dist_cali > 255) {
// for (angle = 0; angle <= Max_Variable_Angle; angle++){
myservo.write(Horizontal_Angle - Max_Variable_Angle);
// if (angle > -100)
// angle--;
// Serial.println(angle);
// }
}
else if (dist_cali < 255) {
// for (angle = 0; angle <= Max_Variable_Angle; angle++){
myservo.write(Horizontal_Angle + Max_Variable_Angle/2);
// if (angle < 100 )
// angle++;
// }
}
Serial.print("min:0,max:500,dist:");
Serial.print(raw_dist);
Serial.print(",dist_cali:");
Serial.println(dist_cali);
if(raw_dist > 156 && raw_dist <224) digitalWrite(PIN_LED, 0);
else digitalWrite(PIN_LED, 255);
delay(20);
}
| [
"noreply@github.com"
] | T-WK.noreply@github.com |
15926e3b9210319ee785906466c6d6493155b040 | c7c4ac450c0150fa443ea879aab7e867c61ada73 | /src/bench/bench_bayemcoin.cpp | 7cfe3fb764103732189bb3d323c914e545f29ccc | [
"MIT"
] | permissive | randboy/BAYEMCOIN | 1a408701bcaf152f0f26ba988861c58b4956bbbc | d0f19e1e38a5bebeb9a7a230e1f0054134720250 | refs/heads/master | 2022-12-03T14:59:07.156104 | 2020-08-24T02:07:53 | 2020-08-24T02:07:53 | 289,723,637 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 620 | cpp | // Copyright (c) 2015-2016 The Bitcoin Core developers
// Copyright (c) 2017 The Ravencoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bench.h"
#include "crypto/sha256.h"
#include "key.h"
#include "validation.h"
#include "util.h"
#include "random.h"
int
main(int argc, char** argv)
{
SHA256AutoDetect();
RandomInit();
ECC_Start();
SetupEnvironment();
fPrintToDebugLog = false; // don't want to write to debug.log file
benchmark::BenchRunner::RunAll();
ECC_Stop();
}
| [
"root@vps-5c20fa9d.vps.ovh.net.novalocal"
] | root@vps-5c20fa9d.vps.ovh.net.novalocal |
bbdcf1adb564ac9b6f459cef6b442e9339e560a8 | dd656493066344e70123776c2cc31dd13f31c1d8 | /MITK/Utilities/Poco/Foundation/include/Poco/Environment_WIN32.h | b2e3b513dbe1e266e3356e808b96dee517c769fd | [
"BSL-1.0"
] | permissive | david-guerrero/MITK | e9832b830cbcdd94030d2969aaed45da841ffc8c | e5fbc9993f7a7032fc936f29bc59ca296b4945ce | refs/heads/master | 2020-04-24T19:08:37.405353 | 2011-11-13T22:25:21 | 2011-11-13T22:25:21 | 2,372,730 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,289 | h | //
// Environment_WIN32.h
//
// $Id$
//
// Library: Foundation
// Package: Core
// Module: Environment
//
// Definition of the EnvironmentImpl class for WIN32.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Foundation_Environment_WIN32_INCLUDED
#define Foundation_Environment_WIN32_INCLUDED
#include "Poco/Foundation.h"
namespace Poco {
class Foundation_API EnvironmentImpl
{
public:
typedef UInt8 NodeId[6]; /// Ethernet address.
static std::string getImpl(const std::string& name);
static bool hasImpl(const std::string& name);
static void setImpl(const std::string& name, const std::string& value);
static std::string osNameImpl();
static std::string osVersionImpl();
static std::string osArchitectureImpl();
static std::string nodeNameImpl();
static void nodeIdImpl(NodeId& id);
};
} // namespace Poco
#endif // Foundation_Environment_WIN32_INCLUDED
| [
"dav@live.ca"
] | dav@live.ca |
d428ee2ae273a4a9b4c643f715306bae8cc7337a | 19ab40452cff93a9e5720a46d85bac7ccba11788 | /CodeForces/CodeForces_1037/Packets.cpp | 06737ba45cc1f88f146f1227d2569a6231c8da48 | [] | no_license | kyduke/Coding | 8728e19d40872d82da20f813e12ec5fea7cd6742 | 4f6ae9aa144dfe3171a00a572980d2b5cc3a81a9 | refs/heads/master | 2022-03-05T16:16:06.608380 | 2022-02-18T01:38:31 | 2022-02-18T01:38:31 | 25,638,209 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 235 | cpp | // https://codeforces.com/contest/1037/problem/A
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int n;
scanf("%d", &n);
printf("%d", (int)log2((double)n) + 1);
return 0;
}
/*
6
=====
3
2
=====
2
*/
| [
"noreply@github.com"
] | kyduke.noreply@github.com |
63aee8052a262b7ac50e22fa014b7b8841750891 | 2a03ae4619fb48bcb827136ad4cbd52697b26093 | /Examples/PrintValsGrid/PrintValsGrid.ino | c053b7d3bc7ea15ce747098fbefa9ed3f4d45941 | [
"Apache-2.0"
] | permissive | BlackSparkk/MLX90641_IR_Array | 808cf264e290eb352892182cab74fc89e8f08632 | 88364c7455bceae65dae7a7450bb437a932af955 | refs/heads/master | 2020-06-13T18:32:36.318295 | 2019-07-01T23:20:52 | 2019-07-01T23:20:52 | 194,750,132 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,054 | ino | #include <MLX90641_API.h>
#include <MLX90641_I2C_Driver.h>
#define slave_addr 0x33
#define TA_SHIFT 5
float emissivity = 0.95;
float tr;
static uint16_t eeprom[832];
static uint16_t frame[242];
paramsMLX90641 params;
static float temperatures[192];
void setup() {
SerialUSB.begin(115200);
MLX90641_I2CInit();
MLX90641_I2CFreqSet(1000);
}
void loop() {
delay(2000);
get_pixels();
print_pixels();
}
void get_pixels()
{
MLX90641_DumpEE(slave_addr,eeprom);
MLX90641_ExtractParameters(eeprom, ¶ms);
MLX90641_GetFrameData(slave_addr, frame);
tr = MLX90641_GetTa(frame,¶ms) - TA_SHIFT;
MLX90641_CalculateTo(frame,¶ms,emissivity,tr,temperatures);
}
void print_pixels()
{
for(int i = 0 ; i < 12 ; i++){
for(int j = 0 ; j < 16 ; j++)
{
SerialUSB.print(temperatures[j+16*i]);
SerialUSB.print(" : ");
}
SerialUSB.print("\n\n");
}
SerialUSB.println("---------------------------------------------------------------------------------------------------------------------------------");
}
| [
"lance@foundry-lab.com"
] | lance@foundry-lab.com |
a0dbf37aa7bf5212d8cea33c370b37297848da7f | a029903af967d1d6331d265bbabe60e200f21b09 | /stl/src/stack_queue.cpp | 2996d7676edfdbc918f7fda66d80ece039836d4b | [
"MIT"
] | permissive | pvavercak/cpp_course_sources | b693ec61ff668c2c522eb2a8d9b4ce20cf97beaa | 6e17b8b05173c8ee41d329492c3e02200bad054f | refs/heads/master | 2023-02-05T12:23:30.914463 | 2020-12-26T13:32:22 | 2020-12-26T13:32:22 | 320,414,112 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,203 | cpp | #include <iostream>
#include <stack>
#include <queue>
class Test
{
private:
int id;
std::string name;
public:
Test():
id(0), name("")
{
;
}
Test(int id, std::string name):
id(id),
name(name)
{
;
}
void print() const
{
std::cout << id << ": " << name << std::flush;
}
bool operator<(const Test &other)
{
return name < other.name;
}
};
void stack_exercise()
{
std::stack<Test> testStack;
testStack.push(Test(5, "John"));
testStack.push(Test(3, "Marc"));
testStack.push(Test(1, "Patrik"));
while(testStack.size() > 0)
{
Test &t = testStack.top();
t.print();
std::cout << std::endl;
testStack.pop();
}
}
void queue_exercise()
{
std::queue<std::string> testQueue;
testQueue.push("Marc");
testQueue.push("Bill");
testQueue.push("Eric");
testQueue.push("Sophie");
while(testQueue.size() > 0)
{
std::string &q = testQueue.front();
std::cout << q << std::endl;
testQueue.pop();
}
}
int main()
{
stack_exercise();
queue_exercise();
return EXIT_SUCCESS;
} | [
"patrik.vavercak@innovatrics.com"
] | patrik.vavercak@innovatrics.com |
20cac56a9c580a3f04d23e65edc2a8f5646935c9 | f7ecbfa1b8fd2de9212b1eba801a849165b666de | /UnRegularDialog/InstrumentTest/httpclient.h | d1733d826a33cc9543a97f6427563ed4ba46e43f | [] | no_license | panyibin/Experiment | f669eee58734fa50319b586cb2c5c7c5ac0e1a2a | 896c4dc1513a4df8e7848af0a022bd12c59cb421 | refs/heads/master | 2016-09-05T13:31:42.351116 | 2014-09-12T10:46:41 | 2014-09-12T10:46:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,661 | h | #ifndef httpclient_h
#define httpclient_h
#include "common/httpdefs.h"
class CHttpClient
{
public:
CHttpClient();
~CHttpClient();
typedef VOID (*RequestCompleteCallback)(_In_ VOID * pvContext);
HRESULT Initialize(_In_opt_z_ wchar_t * wszUserAgent);
HRESULT Shutdown();
HRESULT Get(
const wchar_t * wszHostName,
INTERNET_PORT port,
const wchar_t * wszQuery,
RequestCompleteCallback fnRequestCompleteCallback,
_In_ VOID * pvContext);
private:
struct RequestInfo
{
RequestInfo(RequestCompleteCallback fnRequestCompleteCallback, _In_ VOID * pvContext) :
hConnect(NULL),
hRequest(NULL),
fnRequestCompleteCallback(fnRequestCompleteCallback),
pvContext(pvContext)
{
}
~RequestInfo()
{
CLOSE_INTERNET_HANDLE(hConnect);
hConnect = NULL;
CLOSE_INTERNET_HANDLE(hRequest);
hRequest = NULL;
}
HINTERNET hConnect;
HINTERNET hRequest;
CHttpClient::RequestCompleteCallback fnRequestCompleteCallback;
VOID * pvContext;
};
static VOID CALLBACK
HttpRequestStatusCallback(
_Inout_ HINTERNET hInternet,
_Inout_ DWORD_PTR dwContext,
DWORD dwInternetStatus,
_Inout_ LPVOID lpvStatusInformation,
DWORD dwStatusInformationLength);
bool m_fInitialized;
HINTERNET m_hInternet;
STATUS_CALLBACK_TYPE m_pfnStatusCallback;
};
#endif // httpclient_h
| [
"panyibin@outlook.com"
] | panyibin@outlook.com |
0ccd51091731a03ffe2c678a6d59e1f8fd3f8658 | 73ee941896043f9b3e2ab40028d24ddd202f695f | /external/chromium_org/chrome/browser/policy/cloud/user_cloud_policy_manager_factory.cc | 9f9fea7236068a54cd4845b383e05488651ee5a9 | [
"BSD-3-Clause"
] | permissive | CyFI-Lab-Public/RetroScope | d441ea28b33aceeb9888c330a54b033cd7d48b05 | 276b5b03d63f49235db74f2c501057abb9e79d89 | refs/heads/master | 2022-04-08T23:11:44.482107 | 2016-09-22T20:15:43 | 2016-09-22T20:15:43 | 58,890,600 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,628 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "chrome/browser/policy/cloud/user_cloud_policy_manager.h"
#include "chrome/browser/policy/cloud/user_cloud_policy_store.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_switches.h"
#include "components/browser_context_keyed_service/browser_context_dependency_manager.h"
namespace policy {
// static
UserCloudPolicyManagerFactory* UserCloudPolicyManagerFactory::GetInstance() {
return Singleton<UserCloudPolicyManagerFactory>::get();
}
// static
UserCloudPolicyManager* UserCloudPolicyManagerFactory::GetForProfile(
Profile* profile) {
return GetInstance()->GetManagerForProfile(profile);
}
// static
scoped_ptr<UserCloudPolicyManager>
UserCloudPolicyManagerFactory::CreateForProfile(Profile* profile,
bool force_immediate_load) {
return GetInstance()->CreateManagerForProfile(profile, force_immediate_load);
}
UserCloudPolicyManagerFactory::UserCloudPolicyManagerFactory()
: BrowserContextKeyedBaseFactory(
"UserCloudPolicyManager",
BrowserContextDependencyManager::GetInstance()) {}
UserCloudPolicyManagerFactory::~UserCloudPolicyManagerFactory() {}
UserCloudPolicyManager* UserCloudPolicyManagerFactory::GetManagerForProfile(
Profile* profile) {
// Get the manager for the original profile, since the PolicyService is
// also shared between the incognito Profile and the original Profile.
ManagerMap::const_iterator it = managers_.find(profile->GetOriginalProfile());
return it != managers_.end() ? it->second : NULL;
}
scoped_ptr<UserCloudPolicyManager>
UserCloudPolicyManagerFactory::CreateManagerForProfile(
Profile* profile,
bool force_immediate_load) {
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableCloudPolicyOnSignin)) {
return scoped_ptr<UserCloudPolicyManager>();
}
scoped_ptr<UserCloudPolicyStore> store(UserCloudPolicyStore::Create(profile));
if (force_immediate_load)
store->LoadImmediately();
scoped_ptr<UserCloudPolicyManager> manager(
new UserCloudPolicyManager(profile, store.Pass()));
manager->Init();
return manager.Pass();
}
void UserCloudPolicyManagerFactory::BrowserContextShutdown(
content::BrowserContext* context) {
Profile* profile = static_cast<Profile*>(context);
if (profile->IsOffTheRecord())
return;
UserCloudPolicyManager* manager = GetManagerForProfile(profile);
if (manager) {
manager->CloudPolicyManager::Shutdown();
manager->BrowserContextKeyedService::Shutdown();
}
}
void UserCloudPolicyManagerFactory::SetEmptyTestingFactory(
content::BrowserContext* profile) {
}
void UserCloudPolicyManagerFactory::CreateServiceNow(
content::BrowserContext* profile) {
}
void UserCloudPolicyManagerFactory::Register(Profile* profile,
UserCloudPolicyManager* instance) {
UserCloudPolicyManager*& entry = managers_[profile];
DCHECK(!entry);
entry = instance;
}
void UserCloudPolicyManagerFactory::Unregister(
Profile* profile,
UserCloudPolicyManager* instance) {
ManagerMap::iterator entry = managers_.find(profile);
if (entry != managers_.end()) {
DCHECK_EQ(instance, entry->second);
managers_.erase(entry);
} else {
NOTREACHED();
}
}
} // namespace policy
| [
"ProjectRetroScope@gmail.com"
] | ProjectRetroScope@gmail.com |
729c9e4a05ecaad1fd7cd7d8205fb8d4f16e95ef | 7e9267adca65db8beef2531586c3460e5ffbf5ef | /src/zmq_node.h | d29e0bdb6f9b450ae8fbe74572943618a5a4d53a | [
"MIT"
] | permissive | YungSang/node-zmq | 736dec92a739c5344ee711a358247053a446aec4 | 53a772704aaed853453a0084a78baa82680a916a | refs/heads/master | 2020-12-24T13:52:50.331591 | 2010-11-29T07:35:38 | 2010-11-29T07:35:38 | 1,036,697 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 782 | h | #ifndef ZMQ_NODE_H
#define ZMQ_NODE_H
#include <v8.h>
#include <node.h>
#include <zmq.hpp>
#include <zmq_utils.h>
#include <time.h>
//using namespace node;
//using namespace v8;
namespace zmq_node {
#define ZMQ_NODE_DEFINE_CONSTANT(target, symbol, constant) \
(target)->Set(v8::String::NewSymbol(symbol), \
v8::Integer::New(constant), \
static_cast<v8::PropertyAttribute>(v8::ReadOnly|v8::DontDelete))
void Init (v8::Handle<v8::Object>);
v8::Handle<v8::Value> Version (const v8::Arguments &);
v8::Handle<v8::Value> Sleep (const v8::Arguments &);
v8::Handle<v8::Value> NanoSleep (const v8::Arguments &);
} // namespace zmq_node
#endif // ZMQ_NODE_H
| [
"yungsang@gmail.com"
] | yungsang@gmail.com |
0fc1c04b2441ab4ccfecf2f436db3f3ff9f3bf1a | e74f6c3b0d224c799d069b86bb99a42aa87b3833 | /cpp/scramble_encoder/SCR_Encoder/main_br.cpp | f74e2813cb828b500f80b7738f174eb1094f6ff6 | [] | no_license | llGuy/msdev | 1e42272fdd97a3322c41406f83dabe07ee766b6f | 9db03513fc0febcaccb542bc75f40f28a26c1721 | refs/heads/master | 2021-05-01T19:16:45.684277 | 2018-05-15T20:14:03 | 2018-05-15T20:14:03 | 121,017,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,021 | cpp | #include <iostream>
#include <string>
#include "SCR_Encoder.h"
using namespace std;
const char * char_to_binary(char x){
static char buf[sizeof(char)*8+1] = {0};
int y;
long long z;
for( z=1LL<<(sizeof(char)*8-1),y=0;z>0;z>>=1,y++){
buf[y] = (((x&z)==z) ? '1' : '0');
}
buf[y] = 0;
return buf;
}
unsigned char br_encode_decode(unsigned char input,bool decode){
size_t order_[8] = {2,0,7,5,6,1,4,3};
size_t order[8] ;
for (size_t i=0; i<8; i++) {
if( decode){
order[ 7-order_[i]] = 7-i;
}else{
order[ i]= order_[i];
}
}
char output = 0x00;
for (size_t i=0; i<8; i++) {
size_t from = 7-i;
size_t to = order[i];
unsigned char from_bit = input & (1<<from);
unsigned char to_bit = (from_bit>>from) ;
to_bit = to_bit << to;
output |= to_bit;
}
return output;
}
unsigned char br_encode(unsigned char input){
return br_encode_decode(input, false);
}
unsigned char br_decode(unsigned char input){
return br_encode_decode(input, true);
}
int main()
{
string input = string("cryptography");
SCR_Encoder Encoder = input;
Encoder.DefineArrOrder("20756143");
string thing = Encoder.EncodeInput();
cout << "cryptography = " << thing << endl;
cout << thing.length() << endl;
for (int i = 0; i < input.length(); i++){
char c = input[i];
cout <<c << ": "<< char_to_binary(c) << " "<< char_to_binary(br_encode(c)) << " "
<< char_to_binary(br_decode(br_encode(c))) << " " << br_decode(br_encode(c)) << endl;
}
cout<<endl;
for (int i = 0; i < thing.length(); i++){
if( i < input.length()){
cout << i << ": " << input[i] << " " << br_decode(thing[i]) << " " << Encoder.BinaryConverter(thing[i]) << endl;
}else{
cout << i << ": " << Encoder.BinaryConverter(thing[i]) << endl;
}
}
}
| [
"luc.rosenzweig@yahoo.com"
] | luc.rosenzweig@yahoo.com |
a906745e49804a54eec6ca186b1da0cf9a105cad | a07d55cbd5a6c93af7aa02fc9b1478ab8dc73e05 | /src/python/magnum/math.range.cpp | d9ae3b41664d5eac8bc7b5eaca5c0dc6321b6df9 | [
"MIT"
] | permissive | hi-ogawa/magnum-bindings | 4cc8defacfdb81405e68c7c78b9d56aef51d7f2b | 5f324bdcde828d9ffc3bcd8e562480875586c54b | refs/heads/master | 2020-09-07T21:18:12.919682 | 2019-11-13T06:29:28 | 2019-11-13T06:34:12 | 220,915,268 | 0 | 0 | NOASSERTION | 2019-11-11T06:25:25 | 2019-11-11T06:25:24 | null | UTF-8 | C++ | false | false | 16,363 | cpp | /*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019
Vladimír Vondruš <mosra@centrum.cz>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <pybind11/pybind11.h>
#include <pybind11/operators.h>
#include <Magnum/Magnum.h>
#include <Magnum/Math/Range.h>
#include "magnum/bootstrap.h"
#include "magnum/math.h"
namespace magnum {
namespace {
template<class T> void range(py::module& m, py::class_<T>& c) {
/*
Missing APIs:
VectorType
*/
py::implicitly_convertible<std::pair<typename T::VectorType, typename T::VectorType>, T>();
c
/* Constructors */
.def_static("from_size", &T::fromSize, "Create a range from minimal coordinates and size")
.def_static("from_center", &T::fromCenter, "Create a range from center and half size")
.def_static("zero_init", []() {
return T{Math::ZeroInit};
}, "Construct a zero range")
.def(py::init(), "Default constructor")
.def(py::init<typename T::VectorType, typename T::VectorType>(), "Construct a range from minimal and maximal coordiantes")
.def(py::init<std::pair<typename T::VectorType, typename T::VectorType>>(), "Construct a range from minimal and maximal coordiantes")
/* Comparison */
.def(py::self == py::self, "Equality comparison")
.def(py::self != py::self, "Non-equality comparison")
/* Properties */
.def_property("min",
static_cast<const typename T::VectorType(T::*)() const>(&T::min),
[](T& self, const typename T::VectorType& value) { self.min() = value; },
"Minimal coordinates (inclusive)")
.def_property("max",
static_cast<const typename T::VectorType(T::*)() const>(&T::max),
[](T& self, const typename T::VectorType& value) { self.max() = value; },
"Maximal coordinates (exclusive)")
/* Methods */
.def("size", &T::size, "Range size")
.def("center", &T::center, "Range center")
.def("translated", &T::translated, "Translated range")
.def("padded", &T::padded, "Padded ange")
.def("scaled", &T::scaled, "Scaled range")
.def("scaled_from_center", &T::scaledFromCenter, "Range scaled from the center")
.def("contains", static_cast<bool(T::*)(const typename T::VectorType&) const>(&T::contains),
"Whether given point is contained inside the range")
.def("contains", [](const T& self, const T& other) {
return self.contains(other);
}, "Whether another range is fully contained inside this range")
.def("__repr__", repr<T>, "Object representation");
m
/* Free functions */
.def("join", [](const T& a, const T& b) -> T {
return Math::join(a, b);
}, "Join two ranges")
.def("intersect", [](const T& a, const T& b) -> T {
return Math::intersect(a, b);
}, "intersect two ranges")
.def("intersects", [](const T& a, const T& b) {
return Math::intersects(a, b);
}, "Whether two ranges intersect");
}
template<class T> void range2D(py::class_<T>& c) {
py::implicitly_convertible<std::pair<std::tuple<typename T::VectorType::Type, typename T::VectorType::Type>, std::tuple<typename T::VectorType::Type, typename T::VectorType::Type>>, T>();
c
/* Constructors */
.def(py::init([](const std::pair<std::tuple<typename T::VectorType::Type, typename T::VectorType::Type>, std::tuple<typename T::VectorType::Type, typename T::VectorType::Type>>& value) {
return T{{typename T::VectorType{std::get<0>(value.first), std::get<1>(value.first)},
typename T::VectorType{std::get<0>(value.second), std::get<1>(value.second)}}};
}), "Construct a range from a pair of minimal and maximal coordinates")
/* Properties */
.def_property("bottom_left",
static_cast<typename T::VectorType(T::*)() const>(&T::bottomLeft),
[](T& self, const typename T::VectorType& value) {
self.bottomLeft() = value;
},
"Bottom left corner")
.def_property("bottom_right",
static_cast<typename T::VectorType(T::*)() const>(&T::bottomRight),
[](T& self, const typename T::VectorType& value) {
self.max().x() = value.x();
self.min().y() = value.y();
},
"Bottom right corner")
.def_property("top_left",
static_cast<typename T::VectorType(T::*)() const>(&T::topLeft),
[](T& self, const typename T::VectorType& value) {
self.min().x() = value.x();
self.max().y() = value.y();
},
"Top left corner")
.def_property("top_right",
static_cast<typename T::VectorType(T::*)() const>(&T::topRight),
[](T& self, const typename T::VectorType& value) {
self.topRight() = value;
},
"Top right corner")
.def_property("left",
static_cast<typename T::VectorType::Type(T::*)() const>(&T::left),
[](T& self, const typename T::VectorType::Type& value) {
self.left() = value;
},
"Left edge")
.def_property("right",
static_cast<typename T::VectorType::Type(T::*)() const>(&T::right),
[](T& self, const typename T::VectorType::Type& value) {
self.right() = value;
},
"Right edge")
.def_property("bottom",
static_cast<typename T::VectorType::Type(T::*)() const>(&T::bottom),
[](T& self, const typename T::VectorType::Type& value) {
self.bottom() = value;
},
"Bottom edge")
.def_property("top",
static_cast<typename T::VectorType::Type(T::*)() const>(&T::top),
[](T& self, const typename T::VectorType::Type& value) {
self.top() = value;
},
"Top edge")
/* Methods */
.def("x", &T::x, "Range in the X axis")
.def("y", &T::y, "Range in the Y axis")
.def("size_x", &T::sizeX, "Range width")
.def("size_y", &T::sizeY, "Range height")
.def("center_x", &T::sizeX, "Range center on X axis")
.def("center_y", &T::sizeY, "Range center on Y axis");
}
template<class T> void range3D(py::class_<T>& c) {
py::implicitly_convertible<std::pair<std::tuple<typename T::VectorType::Type, typename T::VectorType::Type, typename T::VectorType::Type>, std::tuple<typename T::VectorType::Type, typename T::VectorType::Type, typename T::VectorType::Type>>, T>();
c
/* Constructors */
.def(py::init([](const std::pair<std::tuple<typename T::VectorType::Type, typename T::VectorType::Type, typename T::VectorType::Type>, std::tuple<typename T::VectorType::Type, typename T::VectorType::Type, typename T::VectorType::Type>>& value) {
return T{{typename T::VectorType{std::get<0>(value.first), std::get<1>(value.first), std::get<2>(value.first)},
typename T::VectorType{std::get<0>(value.second), std::get<1>(value.second), std::get<2>(value.second)}}};
}), "Construct a range from a pair of minimal and maximal coordinates")
/* Properties */
.def_property("back_bottom_left",
static_cast<typename T::VectorType(T::*)() const>(&T::backBottomLeft),
[](T& self, const typename T::VectorType& value) {
self.backBottomLeft() = value;
},
"Back bottom left corner")
.def_property("back_bottom_right",
static_cast<typename T::VectorType(T::*)() const>(&T::backBottomRight),
[](T& self, const typename T::VectorType& value) {
self.max().x() = value.x();
self.min().y() = value.y();
self.min().z() = value.z();
},
"Back bottom right corner")
.def_property("back_top_left",
static_cast<typename T::VectorType(T::*)() const>(&T::backTopLeft),
[](T& self, const typename T::VectorType& value) {
self.min().x() = value.x();
self.max().y() = value.y();
self.min().z() = value.z();
},
"Back top left corner")
.def_property("back_top_right",
static_cast<typename T::VectorType(T::*)() const>(&T::backTopRight),
[](T& self, const typename T::VectorType& value) {
self.max().x() = value.x();
self.max().y() = value.y();
self.min().z() = value.z();
},
"Back top right corner")
.def_property("front_bottom_left",
static_cast<typename T::VectorType(T::*)() const>(&T::frontBottomLeft),
[](T& self, const typename T::VectorType& value) {
self.min().x() = value.x();
self.min().y() = value.y();
self.max().z() = value.z();
},
"Front bottom left corner")
.def_property("front_bottom_right",
static_cast<typename T::VectorType(T::*)() const>(&T::frontBottomRight),
[](T& self, const typename T::VectorType& value) {
self.max().x() = value.x();
self.min().y() = value.y();
self.max().z() = value.z();
},
"Front bottom right corner")
.def_property("front_top_right",
static_cast<typename T::VectorType(T::*)() const>(&T::frontTopRight),
[](T& self, const typename T::VectorType& value) {
self.frontTopRight() = value;
},
"Front top right corner")
.def_property("front_top_left",
static_cast<typename T::VectorType(T::*)() const>(&T::frontTopLeft),
[](T& self, const typename T::VectorType& value) {
self.min().x() = value.x();
self.max().y() = value.y();
self.max().z() = value.z();
},
"Front top left corner")
.def_property("left",
static_cast<typename T::VectorType::Type(T::*)() const>(&T::left),
[](T& self, const typename T::VectorType::Type& value) {
self.left() = value;
},
"Left edge")
.def_property("right",
static_cast<typename T::VectorType::Type(T::*)() const>(&T::right),
[](T& self, const typename T::VectorType::Type& value) {
self.right() = value;
},
"Right edge")
.def_property("bottom",
static_cast<typename T::VectorType::Type(T::*)() const>(&T::bottom),
[](T& self, const typename T::VectorType::Type& value) {
self.bottom() = value;
},
"Bottom edge")
.def_property("top",
static_cast<typename T::VectorType::Type(T::*)() const>(&T::top),
[](T& self, const typename T::VectorType::Type& value) {
self.top() = value;
},
"Top edge")
.def_property("back",
static_cast<typename T::VectorType::Type(T::*)() const>(&T::back),
[](T& self, const typename T::VectorType::Type& value) {
self.back() = value;
},
"Back edge")
.def_property("front",
static_cast<typename T::VectorType::Type(T::*)() const>(&T::front),
[](T& self, const typename T::VectorType::Type& value) {
self.front() = value;
},
"Front edge")
/* Methods */
.def("x", &T::x, "Range in the X axis")
.def("y", &T::y, "Range in the Y axis")
.def("z", &T::y, "Range in the Z axis")
.def("xy", &T::xy, "Range in the XY plane")
.def("size_x", &T::sizeX, "Range width")
.def("size_y", &T::sizeY, "Range height")
.def("size_z", &T::sizeZ, "Range depth")
.def("center_x", &T::sizeX, "Range center on X axis")
.def("center_y", &T::sizeY, "Range center on Y axis")
.def("center_z", &T::sizeY, "Range center on Z axis");
}
template<class U, template<UnsignedInt, class> class Type, UnsignedInt dimensions, class T, class ...Args> void convertibleImplementation(py::class_<Type<dimensions, T>, Args...>& c, std::false_type) {
c.def(py::init<Type<dimensions, U>>(), "Construct from different underlying type");
}
template<class U, template<class> class Type, class T, class ...Args> void convertibleImplementation(py::class_<Type<T>, Args...>& c, std::false_type) {
c.def(py::init<Type<U>>(), "Construct from different underlying type");
}
template<class U, template<UnsignedInt, class> class Type, UnsignedInt dimensions, class T, class ...Args> void convertibleImplementation(py::class_<Type<dimensions, T>, Args...>&, std::true_type) {}
template<class U, template<class> class Type, class T, class ...Args> void convertibleImplementation(py::class_<Type<T>, Args...>&, std::true_type) {}
template<template<UnsignedInt, class> class Type, UnsignedInt dimensions, class T, class ...Args> void convertible(py::class_<Type<dimensions, T>, Args...>& c) {
convertibleImplementation<Int>(c, std::is_same<T, Int>{});
convertibleImplementation<Float>(c, std::is_same<T, Float>{});
convertibleImplementation<Double>(c, std::is_same<T, Double>{});
}
template<template<class> class Type, class T, class ...Args> void convertible(py::class_<Type<T>, Args...>& c) {
convertibleImplementation<Int>(c, std::is_same<T, Int>{});
convertibleImplementation<Float>(c, std::is_same<T, Float>{});
convertibleImplementation<Double>(c, std::is_same<T, Double>{});
}
}
void mathRange(py::module& root, py::module& m) {
py::class_<Range1D> range1D_{root, "Range1D", "One-dimensional float range"};
py::class_<Range2D> range2D_{root, "Range2D", "Two-dimensional float range"};
py::class_<Range3D> range3D_{root, "Range3D", "Three-dimensional float range"};
py::class_<Range1Di> range1Di{root, "Range1Di", "One-dimensional float range"};
py::class_<Range2Di> range2Di{root, "Range2Di", "Two-dimensional float range"};
py::class_<Range3Di> range3Di{root, "Range3Di", "Three-dimensional float range"};
py::class_<Range1Dd> range1Dd{root, "Range1Dd", "One-dimensional double range"};
py::class_<Range2Dd> range2Dd{root, "Range2Dd", "Two-dimensional double range"};
py::class_<Range3Dd> range3Dd{root, "Range3Dd", "Three-dimensional double range"};
convertible(range1D_);
convertible(range2D_);
convertible(range3D_);
convertible(range1Di);
convertible(range2Di);
convertible(range3Di);
convertible(range1Dd);
convertible(range2Dd);
convertible(range3Dd);
range(m, range1D_);
range(m, range2D_);
range(m, range3D_);
range(m, range1Di);
range(m, range2Di);
range(m, range3Di);
range(m, range1Dd);
range(m, range2Dd);
range(m, range3Dd);
range2D(range2D_);
range2D(range2Di);
range2D(range2Dd);
range3D(range3D_);
range3D(range3Di);
range3D(range3Dd);
}
}
| [
"mosra@centrum.cz"
] | mosra@centrum.cz |
7bb01787f46eeba174fbdac85f527e7a230f04d0 | fe49310e137717b3319a56ed02fc6736c648bfb6 | /src/bounding_host.cc | 9811ae12c3cfdd80eaadc8e2fe1b1ec08054fc7f | [] | no_license | nustxujun/voxelizer | 4d4863c321576c38d641217869edd5256f5b447a | 6129fa7068a565e34d50353ae36abbb632348e13 | refs/heads/master | 2020-12-25T03:29:39.723748 | 2013-08-25T15:47:08 | 2013-08-25T15:47:08 | 32,716,310 | 1 | 0 | null | 2015-03-23T07:08:44 | 2015-03-23T07:08:42 | C++ | UTF-8 | C++ | false | false | 4,148 | cc | #include "voxel/bounding.h"
#include <boost/thread.hpp>
#include "axle/core/types.h"
//#include <boost/mpi/collectives.hpp>
namespace voxel {
class MaxOp {
public:
void operator()(const float f, float *res) const {
assert(NULL != res);
if (f > *res) *res = f;
}
static const float s_init_val;
};
const float MaxOp::s_init_val = -FLT_MAX;
class MinOp {
public:
void operator()(const float f, float *res) const {
assert(NULL != res);
if (f < *res) *res = f;
}
static const float s_init_val;
};
const float MinOp::s_init_val = FLT_MAX;
template<typename Op>
inline int Reduce(const float *h_in, int N, const Op &op, float *h_out) {
assert(NULL != h_out);
*h_out = op.s_init_val;
for (int i = 0; i < N; ++i) {
op(h_in[i], h_out);
}
return ax::kOK;
}
int UnionBoundHost(const float *h_tri_bbox0, const float *h_tri_bbox1, const int N,
float *h_bbox0, float *h_bbox1) {
if (N < 1) return ax::kOK;
MinOp min_op;
MaxOp max_op;
for (int i = 0, offset = 0; i < 3; ++i, offset += N) {
Reduce(h_tri_bbox0 + offset, N, min_op, &h_bbox0[i]);
Reduce(h_tri_bbox1 + offset, N, max_op, &h_bbox1[i]);
}
return ax::kOK;
}
void UpdateBound(const float f, const int c_idx, float *bbox0, float *bbox1) {
if (f < bbox0[c_idx]) bbox0[c_idx] = f;
if (f > bbox1[c_idx]) bbox1[c_idx] = f;
}
void UpdateBound(const float *vertex, const int tri_idx, const int N,
float *bbox0, float *bbox1) {
int c_idx = tri_idx;
UpdateBound(vertex[0], c_idx, bbox0, bbox1);
c_idx += N;
UpdateBound(vertex[1], c_idx, bbox0, bbox1);
c_idx += N;
UpdateBound(vertex[2], c_idx, bbox0, bbox1);
}
int ComputeBoundSerial(const float *vertices, const int *triangles,
const int N, const int begin, const int end,
float *bbox0, float *bbox1);
class ComputeBoundTask {
public:
ComputeBoundTask(const float *vertices, const int *triangles, const int N,
const int begin, const int end, float *bbox0, float *bbox1)
: vertices_(vertices), triangles_(triangles), N_(N),
begin_(begin), end_(end), bbox0_(bbox0), bbox1_(bbox1) { }
void operator()() {
ComputeBoundSerial(vertices_, triangles_, N_, begin_, end_, bbox0_, bbox1_);
}
private:
const int begin_, end_;
const float *vertices_;
const int *triangles_;
const int N_;
float *bbox0_;
float *bbox1_;
};
int ComputeBoundSerial(const float *vertices, const int *triangles,
const int N, const int begin, const int end,
float *bbox0, float *bbox1) {
for (int tri_idx = begin; tri_idx < end; ++tri_idx) {
for (int c = 0, c_idx = tri_idx; c < 3; ++c, c_idx += N) {
bbox0[c_idx] = FLT_MAX; bbox1[c_idx] = -FLT_MAX;
}
for (int c = 0, vert_idx = tri_idx; c < 3; ++c, vert_idx += N) {
UpdateBound(&vertices[3 * triangles[vert_idx]], tri_idx, N,
bbox0, bbox1);
}
}
return ax::kOK;
}
int ComputeBoundParallel(const float *vertices, const int *triangles,
const int N, const int n_cores,
float *bbox0, float *bbox1) {
const int n_threads = n_cores;
const int thread_size = N / n_threads;
boost::thread_group tg;
int begin = 0;
for (int i = 0; i < n_threads - 1; ++i) {
int end = begin + thread_size;
tg.create_thread(ComputeBoundTask(vertices, triangles, N, begin, end,
bbox0, bbox1));
begin = end;
}
tg.create_thread(ComputeBoundTask(vertices, triangles, N, begin, N,
bbox0, bbox1));
tg.join_all();
return ax::kOK;
}
int ComputeBoundHost(const float *h_vertices, const int *h_triangles, const int N,
float *h_tri_bbox0, float *h_tri_bbox1) {
int n_cores = 4;
if (n_cores > 1) {
return ComputeBoundParallel(h_vertices, h_triangles, N, n_cores,
h_tri_bbox0, h_tri_bbox1);
} else {
return ComputeBoundSerial(h_vertices, h_triangles, N, 0, N,
h_tri_bbox0, h_tri_bbox1);
}
}
} // voxel
| [
"hpsoar@gmail.com"
] | hpsoar@gmail.com |
fbadbb9c6b129c3ffe72758ca08efb3ee799c494 | 5036dd94c43470e476544bd3867893f41b6435a0 | /SURF&FeatureDetection/SURF&FeatureDetection/main.cpp | c1869b457cb439a17df244d21e27576103dbfb99 | [] | no_license | ZHHJemotion/opencv_RemapAndSURF | 580a2e54703d2b7c7d118bcd347d5a02aff7de45 | 53604a1eab60e3075a93ab5c56ef508ef977f443 | refs/heads/master | 2021-01-12T10:54:38.374777 | 2016-11-05T20:31:50 | 2016-11-05T20:31:50 | 72,752,566 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,102 | cpp | //
// main.cpp
// SURF&FeatureDetection --- SURF特征点检测
//
// Created by ZHHJemotion on 2016/11/3.
// Copyright © 2016年 Lukas_Zhang. All rights reserved.
//
#include <iostream>
#include "opencv2/core/core.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/nonfree/nonfree.hpp"
#include <string>
#define PATH string("/Users/zhangxingjian/Desktop/Programming/C++/OpenCV/opencv_RemapAndSURF/SURF&FeatureDetection/SURF&FeatureDetection/")
using namespace cv;
using namespace std;
//--------------------------- 全局函数申明部分 --------------------------
// 全局函数申明
//--------------------------------------------------------------------
static void showHelpText(); //输出帮助文字
//--------------------------- main() function -----------------------------
int main(int argc, const char * argv[])
{
// insert code here...
std::cout << "Hello, World!\n";
//显示帮助文字
showHelpText();
//载入源图片
Mat srcImage1 = imread(PATH+string("1.jpg"),1);
Mat srcImage2 = imread(PATH+string("2.jpg"),1);
//异常处理
if (!srcImage1.data || !srcImage2.data)
{
printf("error: we cannot read the source image!!! please check if it is effective!!! \n");
return false;
}
//显示源图像
namedWindow("the original image 1");
namedWindow("the original image 2");
imshow("the original iamge 1", srcImage1);
imshow("the original image 2", srcImage2);
//定义需要用到的变量和类
int minHessian = 400; //定义 SURF 中的 hessian 阈值特征点检测算子
SurfFeatureDetector detector(minHessian); //定义一个 SurfFeatureDetector(SURF)特征检测类对象
std::vector<KeyPoint> keyPoints1, keyPoints2; //vector 模板类是能够存放任意类型的动态数组,能够增加和减少数据
//调用detect函数
detector.detect(srcImage1, keyPoints1);
detector.detect(srcImage2, keyPoints2);
//绘制特征点
Mat imgKeyPoint1, imgKeyPoint2;
drawKeypoints(srcImage1, keyPoints1, imgKeyPoint1, Scalar::all(-1), DrawMatchesFlags::DEFAULT);
drawKeypoints(srcImage2, keyPoints2, imgKeyPoint2);
//显示效果图
imshow("the destination image 1", imgKeyPoint1);
imshow("the destination image 2", imgKeyPoint2);
waitKey(0);
return 0;
}
//-----------------------------------【showHelpText( )函数】----------------------------------
// 描述:输出一些帮助信息
//----------------------------------------------------------------------------------------------
void showHelpText()
{
//输出一些帮助信息
printf("\n\n\n\t欢迎来到【SURF特征点检测】示例程序~\n\n");
//printf("\t当前使用的OpenCV版本为 OpenCV "CV_VERSION);
std::cout<<"\t当前使用的OpenCV版本为 OpenCV"<<CV_VERSION;
printf( "\n\n\t按键操作说明: \n\n"
"\t\t键盘按键任意键- 退出程序\n\n"
"\n\n\t\t\t\t\t\t\t\t byZHHJemotion\n\n\n");
}
| [
"zhhjemotoin@hotmail.com"
] | zhhjemotoin@hotmail.com |
7c6a773f1607f7aa84683043e02be4bd9be9e260 | bc6cd18a13992f425bb97406c5c5e7e3b8d8cb03 | /src/tracker/object_detector.h | 1e6d0dbf687762342e726470e49ebd89b0cfa7d3 | [
"MIT"
] | permissive | collinej/Vulcan | 4ef1e2fc1b383b2b3a9ee59d78dc3c027d4cae24 | fa314bca7011d81b9b83f44edc5a51b617d68261 | refs/heads/master | 2022-09-19T01:59:45.905392 | 2022-09-18T02:41:22 | 2022-09-18T02:41:22 | 186,317,314 | 3 | 3 | NOASSERTION | 2022-04-29T02:06:12 | 2019-05-13T00:04:38 | C++ | UTF-8 | C++ | false | false | 4,922 | h | /* Copyright (C) 2010-2019, The Regents of The University of Michigan.
All rights reserved.
This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab
under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an
MIT-style License that can be found at "https://github.com/h2ssh/Vulcan".
*/
/**
* \file tracking_laser_scan.h
* \author Collin Johnson
*
* Declaration of ObjectDetector.
*/
#ifndef TRACKER_TRACKING_LASER_SCAN_H
#define TRACKER_TRACKING_LASER_SCAN_H
#include "core/laser_scan.h"
#include "tracker/laser_object_collection.h"
#include <fstream>
namespace vulcan
{
struct pose_distribution_t;
namespace hssh
{
class LocalPerceptualMap;
}
namespace laser
{
class MovingLaserScan;
}
namespace laser
{
struct adjusted_ray_t;
}
namespace utils
{
class ConfigFile;
}
namespace tracker
{
/**
* object_detector_params_t defines the parameters that control the laser objects being detected.
*
* The configuration file parameters for the LaserObjectDetector are:
*
* [ObjectDetectionParameters]
* max_adjacent_ray_distance_m = maximum distance between adjacent rays for the rays to be considered in the same
* cluster (meters) min_cluster_rays = minimum number of consecutive range measurements within the distance
* threshold for an object to counted as a cluster max_tracking_distance_m = maximum distance from the robot to
* track an object (meters) laser_variance = variance of the laser points measuring the detected objects
* should_filter_glass_rays = flag indicating if rays intersecting glass cells should be filtered out
* should_save_positions = flag indicating if the detected object positions should be saved to file for analysis
*/
struct object_detector_params_t
{
float maxAdjacentRayDistance;
std::size_t minClusterSize;
float maxTrackingDistance;
float laserVariance;
bool filterGlassRays;
bool savePositions;
object_detector_params_t(void) = default;
object_detector_params_t(const utils::ConfigFile& config);
};
/**
* ObjectDetector represents a single laser scan gathered by the robot. The laser scan is taken while the robot is
* exploring an environment that contains both static and dynamic objects. The ObjectDetector segregates the static
* from dynamic objects by first determining which rays from the laser scan fall in free space. These scan points can
* then be segmented into distinct objects via the detectObjects method.
*
* Objects are detected in a laser scan by locating clusters of adjacent range measurements that
* all fall within some threshold distance of one another. The intuition behind the clustering approach is
* that connected components in the scan can be identified by two metrics:
*
* 1) Two rays in scan is connected if a slope dr/dRay is nearly normal to direction of the rays.
* 2) The connected component, or a cluster, is valid only when it is larger than a typical leg diameter.
*
* These two simple criteria segment a laser scan into relatively a small number of clusters. Two
* legs are frequently identified as independent clusters, so the clusters that are closer than size of a typical human
* body are merged.
*/
class ObjectDetector
{
public:
/**
* Constructor for ObjectDetector.
*/
ObjectDetector(const object_detector_params_t& params);
/**
* detectObjects segments a laser scan into a set of LaserObjects representing the clusters of similar adjacent
* measurements found in the scan. The objects found are represented in the global coordinate frame of the robot.
*
* \param scans Raw laser scans to find dynamic rays and cluster
* \param pose Pose of the robot when the scan was taken
* \param lpm LPM of the current environment
* \return A LaserObjectCollection of objects detected in the scan.
*/
LaserObjectCollection detectObjects(const std::vector<laser::MovingLaserScan>& scans,
const pose_distribution_t& pose,
const hssh::LocalPerceptualMap& lpm);
private:
const object_detector_params_t params_;
Position laserPosition_;
std::vector<bool> isDynamic_;
std::vector<Point<float>> laserEndpoints_;
std::ofstream positionOut_;
void identifyDynamicRays(const laser::MovingLaserScan& scan, const hssh::LocalPerceptualMap& lpm);
bool doesRayIntersectGlass(const laser::adjusted_ray_t& ray, const hssh::LocalPerceptualMap& lpm);
std::vector<LaserObject> segmentScan(const laser::MovingLaserScan& scan, const pose_distribution_t& robotPose);
LaserObjectCollection mergeCollections(const std::vector<LaserObjectCollection>& collections);
};
} // namespace tracker
} // namespace vulcan
#endif // TRACKER_TRACKING_LASER_SCAN_H
| [
"collinej@umich.edu"
] | collinej@umich.edu |
8a5dd5f246d49e59aca5561c9c05a14e5c837643 | 9059c276510e6a0724e89ca8f7c2071562a02a4b | /src/rpcwallet.cpp | 56d7c1e829f12f096caf69bde491cefb4cd64f3f | [
"MIT"
] | permissive | Marloondev/dicenode | 4ed6b3445d7a480cebc8fdbf360f7749b54df939 | 2d4dcfb5c90010ccde495d53db4d3ae4887a2248 | refs/heads/main | 2023-01-20T11:59:54.892094 | 2020-11-30T23:06:20 | 2020-11-30T23:06:20 | 317,294,610 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 110,081 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "amount.h"
#include "base58.h"
#include "core_io.h"
#include "init.h"
#include "net.h"
#include "netbase.h"
#include "rpcserver.h"
#include "timedata.h"
#include "util.h"
#include "utilmoneystr.h"
#include "wallet.h"
#include "walletdb.h"
#include <stdint.h>
#include "spork.h"
#include <boost/assign/list_of.hpp>
#include <univalue.h>
using namespace std;
using namespace boost;
using namespace boost::assign;
int64_t nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;
std::string HelpRequiringPassphrase()
{
return pwalletMain && pwalletMain->IsCrypted() ? "\nRequires wallet passphrase to be set with walletpassphrase call." : "";
}
void EnsureWalletIsUnlocked()
{
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
}
void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry)
{
int confirms = wtx.GetDepthInMainChain(false);
int confirmsTotal = GetIXConfirmations(wtx.GetHash()) + confirms;
entry.push_back(Pair("confirmations", confirmsTotal));
entry.push_back(Pair("bcconfirmations", confirms));
if (wtx.IsCoinBase() || wtx.IsCoinStake())
entry.push_back(Pair("generated", true));
if (confirms > 0) {
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
entry.push_back(Pair("blocktime", mapBlockIndex[wtx.hashBlock]->GetBlockTime()));
}
uint256 hash = wtx.GetHash();
entry.push_back(Pair("txid", hash.GetHex()));
UniValue conflicts(UniValue::VARR);
BOOST_FOREACH (const uint256& conflict, wtx.GetConflicts())
conflicts.push_back(conflict.GetHex());
entry.push_back(Pair("walletconflicts", conflicts));
entry.push_back(Pair("time", wtx.GetTxTime()));
entry.push_back(Pair("timereceived", (int64_t)wtx.nTimeReceived));
BOOST_FOREACH (const PAIRTYPE(string, string) & item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
string AccountFromValue(const UniValue& value)
{
string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
return strAccount;
}
UniValue getnewaddress(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress ( \"account\" )\n"
"\nReturns a new DNO address for receiving payments.\n"
"If 'account' is specified (recommended), it is added to the address book \n"
"so payments received with the address will be credited to 'account'.\n"
"\nArguments:\n"
"1. \"account\" (string, optional) The account name for the address to be linked to. if not provided, the default account \"\" is used. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created if there is no account by the given name.\n"
"\nResult:\n"
"\"bulpaddress\" (string) The new bulp address\n"
"\nExamples:\n" +
HelpExampleCli("getnewaddress", "") + HelpExampleCli("getnewaddress", "\"\"") + HelpExampleCli("getnewaddress", "\"myaccount\"") + HelpExampleRpc("getnewaddress", "\"myaccount\""));
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBook(keyID, strAccount, "receive");
return CBitcoinAddress(keyID).ToString();
}
CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew = false)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
walletdb.ReadAccount(strAccount, account);
bool bKeyUsed = false;
// Check if the current key has been used
if (account.vchPubKey.IsValid()) {
CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
++it) {
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH (const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
// Generate a new key
if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed) {
if (!pwalletMain->GetKeyFromPool(account.vchPubKey))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
walletdb.WriteAccount(strAccount, account);
}
return CBitcoinAddress(account.vchPubKey.GetID());
}
UniValue getaccountaddress(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccountaddress \"account\"\n"
"\nReturns the current DNO address for receiving payments to this account.\n"
"\nArguments:\n"
"1. \"account\" (string, required) The account name for the address. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created and a new address created if there is no account by the given name.\n"
"\nResult:\n"
"\"bulpaddress\" (string) The account bulp address\n"
"\nExamples:\n" +
HelpExampleCli("getaccountaddress", "") + HelpExampleCli("getaccountaddress", "\"\"") + HelpExampleCli("getaccountaddress", "\"myaccount\"") + HelpExampleRpc("getaccountaddress", "\"myaccount\""));
// Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(params[0]);
UniValue ret(UniValue::VSTR);
ret = GetAccountAddress(strAccount).ToString();
return ret;
}
UniValue getrawchangeaddress(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getrawchangeaddress\n"
"\nReturns a new DNO address, for receiving change.\n"
"This is for use with raw transactions, NOT normal use.\n"
"\nResult:\n"
"\"address\" (string) The address\n"
"\nExamples:\n" +
HelpExampleCli("getrawchangeaddress", "") + HelpExampleRpc("getrawchangeaddress", ""));
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
CReserveKey reservekey(pwalletMain);
CPubKey vchPubKey;
if (!reservekey.GetReservedKey(vchPubKey))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
reservekey.KeepKey();
CKeyID keyID = vchPubKey.GetID();
return CBitcoinAddress(keyID).ToString();
}
UniValue setaccount(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setaccount \"bulpaddress\" \"account\"\n"
"\nSets the account associated with the given address.\n"
"\nArguments:\n"
"1. \"bulpaddress\" (string, required) The bulp address to be associated with an account.\n"
"2. \"account\" (string, required) The account to assign the address to.\n"
"\nExamples:\n" +
HelpExampleCli("setaccount", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" \"tabby\"") + HelpExampleRpc("setaccount", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", \"tabby\""));
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid DNO address");
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Only add the account if the address is yours.
if (IsMine(*pwalletMain, address.Get())) {
// Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwalletMain->mapAddressBook.count(address.Get())) {
string strOldAccount = pwalletMain->mapAddressBook[address.Get()].name;
if (address == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
pwalletMain->SetAddressBook(address.Get(), strAccount, "receive");
} else
throw JSONRPCError(RPC_MISC_ERROR, "setaccount can only be used with own address");
return NullUniValue;
}
UniValue getaccount(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccount \"bulpaddress\"\n"
"\nReturns the account associated with the given address.\n"
"\nArguments:\n"
"1. \"bulpaddress\" (string, required) The bulp address for account lookup.\n"
"\nResult:\n"
"\"accountname\" (string) the account address\n"
"\nExamples:\n" +
HelpExampleCli("getaccount", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"") + HelpExampleRpc("getaccount", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\""));
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid DNO address");
string strAccount;
map<CTxDestination, CAddressBookData>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.name.empty())
strAccount = (*mi).second.name;
return strAccount;
}
UniValue getaddressesbyaccount(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaddressesbyaccount \"account\"\n"
"\nReturns the list of addresses for the given account.\n"
"\nArguments:\n"
"1. \"account\" (string, required) The account name.\n"
"\nResult:\n"
"[ (json array of string)\n"
" \"bulpaddress\" (string) a bulp address associated with the given account\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("getaddressesbyaccount", "\"tabby\"") + HelpExampleRpc("getaddressesbyaccount", "\"tabby\""));
string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
UniValue ret(UniValue::VARR);
BOOST_FOREACH (const PAIRTYPE(CBitcoinAddress, CAddressBookData) & item, pwalletMain->mapAddressBook) {
const CBitcoinAddress& address = item.first;
const string& strName = item.second.name;
if (strName == strAccount)
ret.push_back(address.ToString());
}
return ret;
}
void SendMoney(const CTxDestination& address, CAmount nValue, CWalletTx& wtxNew, bool fUseIX = false)
{
// Check amount
if (nValue <= 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount");
if (nValue > pwalletMain->GetBalance())
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
string strError;
if (pwalletMain->IsLocked()) {
strError = "Error: Wallet locked, unable to create transaction!";
LogPrintf("SendMoney() : %s", strError);
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
// Parse DNO address
CScript scriptPubKey = GetScriptForDestination(address);
// Create and send the transaction
CReserveKey reservekey(pwalletMain);
CAmount nFeeRequired;
if (!pwalletMain->CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired, strError, NULL, ALL_COINS, fUseIX, (CAmount)0)) {
if (nValue + nFeeRequired > pwalletMain->GetBalance())
strError = strprintf("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!", FormatMoney(nFeeRequired));
LogPrintf("SendMoney() : %s\n", strError);
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
if (!pwalletMain->CommitTransaction(wtxNew, reservekey, (!fUseIX ? "tx" : "ix")))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
}
UniValue sendtoaddress(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendtoaddress \"bulpaddress\" amount ( \"comment\" \"comment-to\" )\n"
"\nSend an amount to a given address. The amount is a real and is rounded to the nearest 0.00000001\n" +
HelpRequiringPassphrase() +
"\nArguments:\n"
"1. \"bulpaddress\" (string, required) The bulp address to send to.\n"
"2. \"amount\" (numeric, required) The amount in btc to send. eg 0.1\n"
"3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
" This is not part of the transaction, just kept in your wallet.\n"
"4. \"comment-to\" (string, optional) A comment to store the name of the person or organization \n"
" to which you're sending the transaction. This is not part of the \n"
" transaction, just kept in your wallet.\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id.\n"
"\nExamples:\n" +
HelpExampleCli("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1") + HelpExampleCli("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1 \"donation\" \"seans outpost\"") + HelpExampleRpc("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", 0.1, \"donation\", \"seans outpost\""));
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid DNO address");
// Amount
CAmount nAmount = AmountFromValue(params[1]);
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && !params[2].isNull() && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
EnsureWalletIsUnlocked();
SendMoney(address.Get(), nAmount, wtx);
return wtx.GetHash().GetHex();
}
UniValue sendtoaddressix(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendtoaddressix \"bulpaddress\" amount ( \"comment\" \"comment-to\" )\n"
"\nSend an amount to a given address. The amount is a real and is rounded to the nearest 0.00000001\n" +
HelpRequiringPassphrase() +
"\nArguments:\n"
"1. \"bulpaddress\" (string, required) The bulp address to send to.\n"
"2. \"amount\" (numeric, required) The amount in btc to send. eg 0.1\n"
"3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
" This is not part of the transaction, just kept in your wallet.\n"
"4. \"comment-to\" (string, optional) A comment to store the name of the person or organization \n"
" to which you're sending the transaction. This is not part of the \n"
" transaction, just kept in your wallet.\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id.\n"
"\nExamples:\n" +
HelpExampleCli("sendtoaddressix", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1") + HelpExampleCli("sendtoaddressix", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1 \"donation\" \"seans outpost\"") + HelpExampleRpc("sendtoaddressix", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", 0.1, \"donation\", \"seans outpost\""));
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid DNO address");
// Amount
CAmount nAmount = AmountFromValue(params[1]);
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && !params[2].isNull() && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
EnsureWalletIsUnlocked();
SendMoney(address.Get(), nAmount, wtx, true);
return wtx.GetHash().GetHex();
}
UniValue listaddressgroupings(const UniValue& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listaddressgroupings\n"
"\nLists groups of addresses which have had their common ownership\n"
"made public by common use as inputs or as the resulting change\n"
"in past transactions\n"
"\nResult:\n"
"[\n"
" [\n"
" [\n"
" \"bulpaddress\", (string) The bulp address\n"
" amount, (numeric) The amount in btc\n"
" \"account\" (string, optional) The account\n"
" ]\n"
" ,...\n"
" ]\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("listaddressgroupings", "") + HelpExampleRpc("listaddressgroupings", ""));
UniValue jsonGroupings(UniValue::VARR);
map<CTxDestination, CAmount> balances = pwalletMain->GetAddressBalances();
BOOST_FOREACH (set<CTxDestination> grouping, pwalletMain->GetAddressGroupings()) {
UniValue jsonGrouping(UniValue::VARR);
BOOST_FOREACH (CTxDestination address, grouping) {
UniValue addressInfo(UniValue::VARR);
addressInfo.push_back(CBitcoinAddress(address).ToString());
addressInfo.push_back(ValueFromAmount(balances[address]));
{
LOCK(pwalletMain->cs_wallet);
if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end())
addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second.name);
}
jsonGrouping.push_back(addressInfo);
}
jsonGroupings.push_back(jsonGrouping);
}
return jsonGroupings;
}
UniValue signmessage(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"signmessage \"bulpaddress\" \"message\"\n"
"\nSign a message with the private key of an address" +
HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"bulpaddress\" (string, required) The bulp address to use for the private key.\n"
"2. \"message\" (string, required) The message to create a signature of.\n"
"\nResult:\n"
"\"signature\" (string) The signature of the message encoded in base 64\n"
"\nExamples:\n"
"\nUnlock the wallet for 30 seconds\n" +
HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
"\nCreate the signature\n" + HelpExampleCli("signmessage", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" \"my message\"") +
"\nVerify the signature\n" + HelpExampleCli("verifymessage", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" \"signature\" \"my message\"") +
"\nAs json rpc\n" + HelpExampleRpc("signmessage", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", \"my message\""));
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
string strMessage = params[1].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
CKey key;
if (!pwalletMain->GetKey(keyID, key))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
UniValue getreceivedbyaddress(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaddress \"bulpaddress\" ( minconf )\n"
"\nReturns the total amount received by the given bulpaddress in transactions with at least minconf confirmations.\n"
"\nArguments:\n"
"1. \"bulpaddress\" (string, required) The bulp address for transactions.\n"
"2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
"\nResult:\n"
"amount (numeric) The total amount in btc received at this address.\n"
"\nExamples:\n"
"\nThe amount from transactions with at least 1 confirmation\n" +
HelpExampleCli("getreceivedbyaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"") +
"\nThe amount including unconfirmed transactions, zero confirmations\n" + HelpExampleCli("getreceivedbyaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0") +
"\nThe amount with at least 6 confirmation, very safe\n" + HelpExampleCli("getreceivedbyaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 6") +
"\nAs a json rpc call\n" + HelpExampleRpc("getreceivedbyaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", 6"));
// bulp address
CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid DNO address");
CScript scriptPubKey = GetScriptForDestination(address.Get());
if (!IsMine(*pwalletMain, scriptPubKey))
return (double)0.0;
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Tally
CAmount nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) {
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !IsFinalTx(wtx))
continue;
BOOST_FOREACH (const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
UniValue getreceivedbyaccount(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaccount \"account\" ( minconf )\n"
"\nReturns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.\n"
"\nArguments:\n"
"1. \"account\" (string, required) The selected account, may be the default account using \"\".\n"
"2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
"\nResult:\n"
"amount (numeric) The total amount in btc received for this account.\n"
"\nExamples:\n"
"\nAmount received by the default account with at least 1 confirmation\n" +
HelpExampleCli("getreceivedbyaccount", "\"\"") +
"\nAmount received at the tabby account including unconfirmed amounts with zero confirmations\n" + HelpExampleCli("getreceivedbyaccount", "\"tabby\" 0") +
"\nThe amount with at least 6 confirmation, very safe\n" + HelpExampleCli("getreceivedbyaccount", "\"tabby\" 6") +
"\nAs a json rpc call\n" + HelpExampleRpc("getreceivedbyaccount", "\"tabby\", 6"));
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Get the set of pub keys assigned to account
string strAccount = AccountFromValue(params[0]);
set<CTxDestination> setAddress = pwalletMain->GetAccountAddresses(strAccount);
// Tally
CAmount nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) {
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !IsFinalTx(wtx))
continue;
BOOST_FOREACH (const CTxOut& txout, wtx.vout) {
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
}
return (double)nAmount / (double)COIN;
}
CAmount GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth, const isminefilter& filter)
{
CAmount nBalance = 0;
// Tally wallet transactions
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) {
const CWalletTx& wtx = (*it).second;
if (!IsFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0)
continue;
CAmount nReceived, nSent, nFee;
wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee, filter);
if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
nBalance += nReceived;
nBalance -= nSent + nFee;
}
// Tally internal accounting entries
nBalance += walletdb.GetAccountCreditDebit(strAccount);
return nBalance;
}
CAmount GetAccountBalance(const string& strAccount, int nMinDepth, const isminefilter& filter)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth, filter);
}
UniValue getbalance(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"getbalance ( \"account\" minconf includeWatchonly )\n"
"\nIf account is not specified, returns the server's total available balance.\n"
"If account is specified, returns the balance in the account.\n"
"Note that the account \"\" is not the same as leaving the parameter out.\n"
"The server total may be different to the balance in the default \"\" account.\n"
"\nArguments:\n"
"1. \"account\" (string, optional) The selected account, or \"*\" for entire wallet. It may be the default account using \"\".\n"
"2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
"3. includeWatchonly (bool, optional, default=false) Also include balance in watchonly addresses (see 'importaddress')\n"
"\nResult:\n"
"amount (numeric) The total amount in btc received for this account.\n"
"\nExamples:\n"
"\nThe total amount in the server across all accounts\n" +
HelpExampleCli("getbalance", "") +
"\nThe total amount in the server across all accounts, with at least 5 confirmations\n" + HelpExampleCli("getbalance", "\"*\" 6") +
"\nThe total amount in the default account with at least 1 confirmation\n" + HelpExampleCli("getbalance", "\"\"") +
"\nThe total amount in the account named tabby with at least 6 confirmations\n" + HelpExampleCli("getbalance", "\"tabby\" 6") +
"\nAs a json rpc call\n" + HelpExampleRpc("getbalance", "\"tabby\", 6"));
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
isminefilter filter = ISMINE_SPENDABLE;
if (params.size() > 2)
if (params[2].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
if (params[0].get_str() == "*") {
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and "getbalance * 1 true" should return the same number
CAmount nBalance = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) {
const CWalletTx& wtx = (*it).second;
if (!IsFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0)
continue;
CAmount allFee;
string strSentAccount;
list<COutputEntry> listReceived;
list<COutputEntry> listSent;
wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
if (wtx.GetDepthInMainChain() >= nMinDepth) {
BOOST_FOREACH (const COutputEntry& r, listReceived)
nBalance += r.amount;
}
BOOST_FOREACH (const COutputEntry& s, listSent)
nBalance -= s.amount;
nBalance -= allFee;
}
return ValueFromAmount(nBalance);
}
string strAccount = AccountFromValue(params[0]);
CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, filter);
return ValueFromAmount(nBalance);
}
UniValue getunconfirmedbalance(const UniValue ¶ms, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"getunconfirmedbalance\n"
"Returns the server's total unconfirmed balance\n");
return ValueFromAmount(pwalletMain->GetUnconfirmedBalance());
}
UniValue movecmd(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 5)
throw runtime_error(
"move \"fromaccount\" \"toaccount\" amount ( minconf \"comment\" )\n"
"\nMove a specified amount from one account in your wallet to another.\n"
"\nArguments:\n"
"1. \"fromaccount\" (string, required) The name of the account to move funds from. May be the default account using \"\".\n"
"2. \"toaccount\" (string, required) The name of the account to move funds to. May be the default account using \"\".\n"
"3. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n"
"4. \"comment\" (string, optional) An optional comment, stored in the wallet only.\n"
"\nResult:\n"
"true|false (boolean) true if successfull.\n"
"\nExamples:\n"
"\nMove 0.01 btc from the default account to the account named tabby\n" +
HelpExampleCli("move", "\"\" \"tabby\" 0.01") +
"\nMove 0.01 btc timotei to akiko with a comment and funds have 6 confirmations\n" + HelpExampleCli("move", "\"timotei\" \"akiko\" 0.01 6 \"happy birthday!\"") +
"\nAs a json rpc call\n" + HelpExampleRpc("move", "\"timotei\", \"akiko\", 0.01, 6, \"happy birthday!\""));
string strFrom = AccountFromValue(params[0]);
string strTo = AccountFromValue(params[1]);
CAmount nAmount = AmountFromValue(params[2]);
if (params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)params[3].get_int();
string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CWalletDB walletdb(pwalletMain->strWalletFile);
if (!walletdb.TxnBegin())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
int64_t nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
walletdb.WriteAccountingEntry(debit);
// Credit
CAccountingEntry credit;
credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
walletdb.WriteAccountingEntry(credit);
if (!walletdb.TxnCommit())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
return true;
}
UniValue sendfrom(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 6)
throw runtime_error(
"sendfrom \"fromaccount\" \"tobulpaddress\" amount ( minconf \"comment\" \"comment-to\" )\n"
"\nSent an amount from an account to a bulp address.\n"
"The amount is a real and is rounded to the nearest 0.00000001." +
HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"fromaccount\" (string, required) The name of the account to send funds from. May be the default account using \"\".\n"
"2. \"tobulpaddress\" (string, required) The bulp address to send funds to.\n"
"3. amount (numeric, required) The amount in btc. (transaction fee is added on top).\n"
"4. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n"
"5. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
" This is not part of the transaction, just kept in your wallet.\n"
"6. \"comment-to\" (string, optional) An optional comment to store the name of the person or organization \n"
" to which you're sending the transaction. This is not part of the transaction, \n"
" it is just kept in your wallet.\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id.\n"
"\nExamples:\n"
"\nSend 0.01 btc from the default account to the address, must have at least 1 confirmation\n" +
HelpExampleCli("sendfrom", "\"\" \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.01") +
"\nSend 0.01 from the tabby account to the given address, funds must have at least 6 confirmations\n" + HelpExampleCli("sendfrom", "\"tabby\" \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.01 6 \"donation\" \"seans outpost\"") +
"\nAs a json rpc call\n" + HelpExampleRpc("sendfrom", "\"tabby\", \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", 0.01, 6, \"donation\", \"seans outpost\""));
string strAccount = AccountFromValue(params[0]);
CBitcoinAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid DNO address");
CAmount nAmount = AmountFromValue(params[2]);
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && !params[4].isNull() && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && !params[5].isNull() && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
EnsureWalletIsUnlocked();
// Check funds
CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE);
if (nAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
SendMoney(address.Get(), nAmount, wtx);
return wtx.GetHash().GetHex();
}
UniValue sendmany(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendmany \"fromaccount\" {\"address\":amount,...} ( minconf \"comment\" )\n"
"\nSend multiple times. Amounts are double-precision floating point numbers." +
HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"fromaccount\" (string, required) The account to send the funds from, can be \"\" for the default account\n"
"2. \"amounts\" (string, required) A json object with addresses and amounts\n"
" {\n"
" \"address\":amount (numeric) The bulp address is the key, the numeric amount in btc is the value\n"
" ,...\n"
" }\n"
"3. minconf (numeric, optional, default=1) Only use the balance confirmed at least this many times.\n"
"4. \"comment\" (string, optional) A comment\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id for the send. Only 1 transaction is created regardless of \n"
" the number of addresses.\n"
"\nExamples:\n"
"\nSend two amounts to two different addresses:\n" +
HelpExampleCli("sendmany", "\"tabby\" \"{\\\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\\\":0.01,\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\":0.02}\"") +
"\nSend two amounts to two different addresses setting the confirmation and comment:\n" + HelpExampleCli("sendmany", "\"tabby\" \"{\\\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\\\":0.01,\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\":0.02}\" 6 \"testing\"") +
"\nAs a json rpc call\n" + HelpExampleRpc("sendmany", "\"tabby\", \"{\\\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\\\":0.01,\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\":0.02}\", 6, \"testing\""));
string strAccount = AccountFromValue(params[0]);
UniValue sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
set<CBitcoinAddress> setAddress;
vector<pair<CScript, CAmount> > vecSend;
CAmount totalAmount = 0;
vector<string> keys = sendTo.getKeys();
BOOST_FOREACH(const string& name_, keys) {
CBitcoinAddress address(name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid DNO address: ")+name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+name_);
setAddress.insert(address);
CScript scriptPubKey = GetScriptForDestination(address.Get());
CAmount nAmount = AmountFromValue(sendTo[name_]);
totalAmount += nAmount;
vecSend.push_back(make_pair(scriptPubKey, nAmount));
}
EnsureWalletIsUnlocked();
// Check funds
CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE);
if (totalAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
CAmount nFeeRequired = 0;
string strFailReason;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, strFailReason);
if (!fCreated)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
if (!pwalletMain->CommitTransaction(wtx, keyChange))
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
return wtx.GetHash().GetHex();
}
// Defined in rpcmisc.cpp
extern CScript _createmultisig_redeemScript(const UniValue& params);
UniValue addmultisigaddress(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3) {
string msg = "addmultisigaddress nrequired [\"key\",...] ( \"account\" )\n"
"\nAdd a nrequired-to-sign multisignature address to the wallet.\n"
"Each key is a DNO address or hex-encoded public key.\n"
"If 'account' is specified, assign address to that account.\n"
"\nArguments:\n"
"1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
"2. \"keysobject\" (string, required) A json array of bulp addresses or hex-encoded public keys\n"
" [\n"
" \"address\" (string) bulp address or hex-encoded public key\n"
" ...,\n"
" ]\n"
"3. \"account\" (string, optional) An account to assign the addresses to.\n"
"\nResult:\n"
"\"bulpaddress\" (string) A bulp address associated with the keys.\n"
"\nExamples:\n"
"\nAdd a multisig address from 2 addresses\n" +
HelpExampleCli("addmultisigaddress", "2 \"[\\\"Xt4qk9uKvQYAonVGSZNXqxeDmtjaEWgfrs\\\",\\\"XoSoWQkpgLpppPoyyzbUFh1fq2RBvW6UK1\\\"]\"") +
"\nAs json rpc call\n" + HelpExampleRpc("addmultisigaddress", "2, \"[\\\"Xt4qk9uKvQYAonVGSZNXqxeDmtjaEWgfrs\\\",\\\"XoSoWQkpgLpppPoyyzbUFh1fq2RBvW6UK1\\\"]\"");
throw runtime_error(msg);
}
string strAccount;
if (params.size() > 2)
strAccount = AccountFromValue(params[2]);
// Construct using pay-to-script-hash:
CScript inner = _createmultisig_redeemScript(params);
CScriptID innerID(inner);
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBook(innerID, strAccount, "send");
return CBitcoinAddress(innerID).ToString();
}
struct tallyitem {
CAmount nAmount;
int nConf;
int nBCConf;
vector<uint256> txids;
bool fIsWatchonly;
tallyitem()
{
nAmount = 0;
nConf = std::numeric_limits<int>::max();
nBCConf = std::numeric_limits<int>::max();
fIsWatchonly = false;
}
};
UniValue ListReceived(const UniValue& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 1)
fIncludeEmpty = params[1].get_bool();
isminefilter filter = ISMINE_SPENDABLE;
if (params.size() > 2)
if (params[2].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
// Tally
map<CBitcoinAddress, tallyitem> mapTally;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) {
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !IsFinalTx(wtx))
continue;
int nDepth = wtx.GetDepthInMainChain();
int nBCDepth = wtx.GetDepthInMainChain(false);
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH (const CTxOut& txout, wtx.vout) {
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address))
continue;
isminefilter mine = IsMine(*pwalletMain, address);
if (!(mine & filter))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = min(item.nConf, nDepth);
item.nBCConf = min(item.nBCConf, nBCDepth);
item.txids.push_back(wtx.GetHash());
if (mine & ISMINE_WATCH_ONLY)
item.fIsWatchonly = true;
}
}
// Reply
UniValue ret(UniValue::VARR);
map<string, tallyitem> mapAccountTally;
BOOST_FOREACH (const PAIRTYPE(CBitcoinAddress, CAddressBookData) & item, pwalletMain->mapAddressBook) {
const CBitcoinAddress& address = item.first;
const string& strAccount = item.second.name;
map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
CAmount nAmount = 0;
int nConf = std::numeric_limits<int>::max();
int nBCConf = std::numeric_limits<int>::max();
bool fIsWatchonly = false;
if (it != mapTally.end()) {
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
nBCConf = (*it).second.nBCConf;
fIsWatchonly = (*it).second.fIsWatchonly;
}
if (fByAccounts) {
tallyitem& item = mapAccountTally[strAccount];
item.nAmount += nAmount;
item.nConf = min(item.nConf, nConf);
item.nBCConf = min(item.nBCConf, nBCConf);
item.fIsWatchonly = fIsWatchonly;
} else {
UniValue obj(UniValue::VOBJ);
if (fIsWatchonly)
obj.push_back(Pair("involvesWatchonly", true));
obj.push_back(Pair("address", address.ToString()));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
obj.push_back(Pair("bcconfirmations", (nBCConf == std::numeric_limits<int>::max() ? 0 : nBCConf)));
UniValue transactions(UniValue::VARR);
if (it != mapTally.end()) {
BOOST_FOREACH (const uint256& item, (*it).second.txids) {
transactions.push_back(item.GetHex());
}
}
obj.push_back(Pair("txids", transactions));
ret.push_back(obj);
}
}
if (fByAccounts) {
for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it) {
CAmount nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
int nBCConf = (*it).second.nBCConf;
UniValue obj(UniValue::VOBJ);
if ((*it).second.fIsWatchonly)
obj.push_back(Pair("involvesWatchonly", true));
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
obj.push_back(Pair("bcconfirmations", (nBCConf == std::numeric_limits<int>::max() ? 0 : nBCConf)));
ret.push_back(obj);
}
}
return ret;
}
UniValue listreceivedbyaddress(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listreceivedbyaddress ( minconf includeempty includeWatchonly)\n"
"\nList balances by receiving address.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
"2. includeempty (numeric, optional, default=false) Whether to include addresses that haven't received any payments.\n"
"3. includeWatchonly (bool, optional, default=false) Whether to include watchonly addresses (see 'importaddress').\n"
"\nResult:\n"
"[\n"
" {\n"
" \"involvesWatchonly\" : \"true\", (bool) Only returned if imported addresses were involved in transaction\n"
" \"address\" : \"receivingaddress\", (string) The receiving address\n"
" \"account\" : \"accountname\", (string) The account of the receiving address. The default account is \"\".\n"
" \"amount\" : x.xxx, (numeric) The total amount in btc received by the address\n"
" \"confirmations\" : n (numeric) The number of confirmations of the most recent transaction included\n"
" \"bcconfirmations\" : n (numeric) The number of blockchain confirmations of the most recent transaction included\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("listreceivedbyaddress", "") + HelpExampleCli("listreceivedbyaddress", "6 true") + HelpExampleRpc("listreceivedbyaddress", "6, true, true"));
return ListReceived(params, false);
}
UniValue listreceivedbyaccount(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listreceivedbyaccount ( minconf includeempty includeWatchonly)\n"
"\nList balances by account.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
"2. includeempty (boolean, optional, default=false) Whether to include accounts that haven't received any payments.\n"
"3. includeWatchonly (bool, optional, default=false) Whether to include watchonly addresses (see 'importaddress').\n"
"\nResult:\n"
"[\n"
" {\n"
" \"involvesWatchonly\" : \"true\", (bool) Only returned if imported addresses were involved in transaction\n"
" \"account\" : \"accountname\", (string) The account name of the receiving account\n"
" \"amount\" : x.xxx, (numeric) The total amount received by addresses with this account\n"
" \"confirmations\" : n (numeric) The number of confirmations of the most recent transaction included\n"
" \"bcconfirmations\" : n (numeric) The number of blockchain confirmations of the most recent transaction included\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("listreceivedbyaccount", "") + HelpExampleCli("listreceivedbyaccount", "6 true") + HelpExampleRpc("listreceivedbyaccount", "6, true, true"));
return ListReceived(params, true);
}
static void MaybePushAddress(UniValue & entry, const CTxDestination &dest)
{
CBitcoinAddress addr;
if (addr.Set(dest))
entry.push_back(Pair("address", addr.ToString()));
}
void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, UniValue& ret, const isminefilter& filter)
{
CAmount nFee;
string strSentAccount;
list<COutputEntry> listReceived;
list<COutputEntry> listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, filter);
bool fAllAccounts = (strAccount == string("*"));
bool involvesWatchonly = wtx.IsFromMe(ISMINE_WATCH_ONLY);
// Sent
if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount)) {
BOOST_FOREACH (const COutputEntry& s, listSent) {
UniValue entry(UniValue::VOBJ);
if (involvesWatchonly || (::IsMine(*pwalletMain, s.destination) & ISMINE_WATCH_ONLY))
entry.push_back(Pair("involvesWatchonly", true));
entry.push_back(Pair("account", strSentAccount));
MaybePushAddress(entry, s.destination);
std::map<std::string, std::string>::const_iterator it = wtx.mapValue.find("DS");
entry.push_back(Pair("category", (it != wtx.mapValue.end() && it->second == "1") ? "darksent" : "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.amount)));
entry.push_back(Pair("vout", s.vout));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) {
BOOST_FOREACH (const COutputEntry& r, listReceived) {
string account;
if (pwalletMain->mapAddressBook.count(r.destination))
account = pwalletMain->mapAddressBook[r.destination].name;
if (fAllAccounts || (account == strAccount)) {
UniValue entry(UniValue::VOBJ);
if (involvesWatchonly || (::IsMine(*pwalletMain, r.destination) & ISMINE_WATCH_ONLY))
entry.push_back(Pair("involvesWatchonly", true));
entry.push_back(Pair("account", account));
MaybePushAddress(entry, r.destination);
if (wtx.IsCoinBase()) {
if (wtx.GetDepthInMainChain() < 1)
entry.push_back(Pair("category", "orphan"));
else if (wtx.GetBlocksToMaturity() > 0)
entry.push_back(Pair("category", "immature"));
else
entry.push_back(Pair("category", "generate"));
} else {
entry.push_back(Pair("category", "receive"));
}
entry.push_back(Pair("amount", ValueFromAmount(r.amount)));
entry.push_back(Pair("vout", r.vout));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
}
}
void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, UniValue& ret)
{
bool fAllAccounts = (strAccount == string("*"));
if (fAllAccounts || acentry.strAccount == strAccount) {
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
}
}
UniValue listtransactions(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 4)
throw runtime_error(
"listtransactions ( \"account\" count from includeWatchonly)\n"
"\nReturns up to 'count' most recent transactions skipping the first 'from' transactions for account 'account'.\n"
"\nArguments:\n"
"1. \"account\" (string, optional) The account name. If not included, it will list all transactions for all accounts.\n"
" If \"\" is set, it will list transactions for the default account.\n"
"2. count (numeric, optional, default=10) The number of transactions to return\n"
"3. from (numeric, optional, default=0) The number of transactions to skip\n"
"4. includeWatchonly (bool, optional, default=false) Include transactions to watchonly addresses (see 'importaddress')\n"
"\nResult:\n"
"[\n"
" {\n"
" \"account\":\"accountname\", (string) The account name associated with the transaction. \n"
" It will be \"\" for the default account.\n"
" \"address\":\"bulpaddress\", (string) The bulp address of the transaction. Not present for \n"
" move transactions (category = move).\n"
" \"category\":\"send|receive|move\", (string) The transaction category. 'move' is a local (off blockchain)\n"
" transaction between accounts, and not associated with an address,\n"
" transaction id or block. 'send' and 'receive' transactions are \n"
" associated with an address, transaction id and block details\n"
" \"amount\": x.xxx, (numeric) The amount in btc. This is negative for the 'send' category, and for the\n"
" 'move' category for moves outbound. It is positive for the 'receive' category,\n"
" and for the 'move' category for inbound funds.\n"
" \"vout\" : n, (numeric) the vout value\n"
" \"fee\": x.xxx, (numeric) The amount of the fee in btc. This is negative and only available for the \n"
" 'send' category of transactions.\n"
" \"confirmations\": n, (numeric) The number of confirmations for the transaction. Available for 'send' and \n"
" 'receive' category of transactions.\n"
" \"bcconfirmations\": n, (numeric) The number of blockchain confirmations for the transaction. Available for 'send'\n"
" and 'receive' category of transactions.\n"
" \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive'\n"
" category of transactions.\n"
" \"blockindex\": n, (numeric) The block index containing the transaction. Available for 'send' and 'receive'\n"
" category of transactions.\n"
" \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n"
" \"time\": xxx, (numeric) The transaction time in seconds since epoch (midnight Jan 1 1970 GMT).\n"
" \"timereceived\": xxx, (numeric) The time received in seconds since epoch (midnight Jan 1 1970 GMT). Available \n"
" for 'send' and 'receive' category of transactions.\n"
" \"comment\": \"...\", (string) If a comment is associated with the transaction.\n"
" \"otheraccount\": \"accountname\", (string) For the 'move' category of transactions, the account the funds came \n"
" from (for receiving funds, positive amounts), or went to (for sending funds,\n"
" negative amounts).\n"
" }\n"
"]\n"
"\nExamples:\n"
"\nList the most recent 10 transactions in the systems\n" +
HelpExampleCli("listtransactions", "") +
"\nList the most recent 10 transactions for the tabby account\n" + HelpExampleCli("listtransactions", "\"tabby\"") +
"\nList transactions 100 to 120 from the tabby account\n" + HelpExampleCli("listtransactions", "\"tabby\" 20 100") +
"\nAs a json rpc call\n" + HelpExampleRpc("listtransactions", "\"tabby\", 20, 100"));
string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
isminefilter filter = ISMINE_SPENDABLE;
if (params.size() > 3)
if (params[3].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
if (nCount < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
if (nFrom < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
UniValue ret(UniValue::VARR);
std::list<CAccountingEntry> acentries;
CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount);
// iterate backwards until we have nCount items to return:
for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
CWalletTx* const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret, filter);
CAccountingEntry* const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if ((int)ret.size() >= (nCount + nFrom)) break;
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
vector<UniValue> arrTmp = ret.getValues();
vector<UniValue>::iterator first = arrTmp.begin();
std::advance(first, nFrom);
vector<UniValue>::iterator last = arrTmp.begin();
std::advance(last, nFrom+nCount);
if (last != arrTmp.end()) arrTmp.erase(last, arrTmp.end());
if (first != arrTmp.begin()) arrTmp.erase(arrTmp.begin(), first);
std::reverse(arrTmp.begin(), arrTmp.end()); // Return oldest to newest
ret.clear();
ret.setArray();
ret.push_backV(arrTmp);
return ret;
}
UniValue listaccounts(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listaccounts ( minconf includeWatchonly)\n"
"\nReturns Object that has account names as keys, account balances as values.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) Only include transactions with at least this many confirmations\n"
"2. includeWatchonly (bool, optional, default=false) Include balances in watchonly addresses (see 'importaddress')\n"
"\nResult:\n"
"{ (json object where keys are account names, and values are numeric balances\n"
" \"account\": x.xxx, (numeric) The property name is the account name, and the value is the total balance for the account.\n"
" ...\n"
"}\n"
"\nExamples:\n"
"\nList account balances where there at least 1 confirmation\n" +
HelpExampleCli("listaccounts", "") +
"\nList account balances including zero confirmation transactions\n" + HelpExampleCli("listaccounts", "0") +
"\nList account balances for 6 or more confirmations\n" + HelpExampleCli("listaccounts", "6") +
"\nAs json rpc call\n" + HelpExampleRpc("listaccounts", "6"));
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
isminefilter includeWatchonly = ISMINE_SPENDABLE;
if (params.size() > 1)
if (params[1].get_bool())
includeWatchonly = includeWatchonly | ISMINE_WATCH_ONLY;
map<string, CAmount> mapAccountBalances;
BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & entry, pwalletMain->mapAddressBook) {
if (IsMine(*pwalletMain, entry.first) & includeWatchonly) // This address belongs to me
mapAccountBalances[entry.second.name] = 0;
}
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) {
const CWalletTx& wtx = (*it).second;
CAmount nFee;
string strSentAccount;
list<COutputEntry> listReceived;
list<COutputEntry> listSent;
int nDepth = wtx.GetDepthInMainChain();
if (wtx.GetBlocksToMaturity() > 0 || nDepth < 0)
continue;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, includeWatchonly);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH (const COutputEntry& s, listSent)
mapAccountBalances[strSentAccount] -= s.amount;
if (nDepth >= nMinDepth) {
BOOST_FOREACH (const COutputEntry& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.destination))
mapAccountBalances[pwalletMain->mapAddressBook[r.destination].name] += r.amount;
else
mapAccountBalances[""] += r.amount;
}
}
list<CAccountingEntry> acentries;
CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
BOOST_FOREACH (const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
UniValue ret(UniValue::VOBJ);
BOOST_FOREACH (const PAIRTYPE(string, CAmount) & accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
}
UniValue listsinceblock(const UniValue& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listsinceblock ( \"blockhash\" target-confirmations includeWatchonly)\n"
"\nGet all transactions in blocks since block [blockhash], or all transactions if omitted\n"
"\nArguments:\n"
"1. \"blockhash\" (string, optional) The block hash to list transactions since\n"
"2. target-confirmations: (numeric, optional) The confirmations required, must be 1 or more\n"
"3. includeWatchonly: (bool, optional, default=false) Include transactions to watchonly addresses (see 'importaddress')"
"\nResult:\n"
"{\n"
" \"transactions\": [\n"
" \"account\":\"accountname\", (string) The account name associated with the transaction. Will be \"\" for the default account.\n"
" \"address\":\"bulpaddress\", (string) The bulp address of the transaction. Not present for move transactions (category = move).\n"
" \"category\":\"send|receive\", (string) The transaction category. 'send' has negative amounts, 'receive' has positive amounts.\n"
" \"amount\": x.xxx, (numeric) The amount in btc. This is negative for the 'send' category, and for the 'move' category for moves \n"
" outbound. It is positive for the 'receive' category, and for the 'move' category for inbound funds.\n"
" \"vout\" : n, (numeric) the vout value\n"
" \"fee\": x.xxx, (numeric) The amount of the fee in btc. This is negative and only available for the 'send' category of transactions.\n"
" \"confirmations\": n, (numeric) The number of confirmations for the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"bcconfirmations\" : n, (numeric) The number of blockchain confirmations for the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"blockindex\": n, (numeric) The block index containing the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n"
" \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n"
" \"time\": xxx, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT).\n"
" \"timereceived\": xxx, (numeric) The time received in seconds since epoch (Jan 1 1970 GMT). Available for 'send' and 'receive' category of transactions.\n"
" \"comment\": \"...\", (string) If a comment is associated with the transaction.\n"
" \"to\": \"...\", (string) If a comment to is associated with the transaction.\n"
" ],\n"
" \"lastblock\": \"lastblockhash\" (string) The hash of the last block\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("listsinceblock", "") + HelpExampleCli("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\" 6") + HelpExampleRpc("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\", 6"));
CBlockIndex* pindex = NULL;
int target_confirms = 1;
isminefilter filter = ISMINE_SPENDABLE;
if (params.size() > 0) {
uint256 blockId = 0;
blockId.SetHex(params[0].get_str());
BlockMap::iterator it = mapBlockIndex.find(blockId);
if (it != mapBlockIndex.end())
pindex = it->second;
}
if (params.size() > 1) {
target_confirms = params[1].get_int();
if (target_confirms < 1)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
}
if (params.size() > 2)
if (params[2].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
int depth = pindex ? (1 + chainActive.Height() - pindex->nHeight) : -1;
UniValue transactions(UniValue::VARR);
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++) {
CWalletTx tx = (*it).second;
if (depth == -1 || tx.GetDepthInMainChain(false) < depth)
ListTransactions(tx, "*", 0, true, transactions, filter);
}
CBlockIndex* pblockLast = chainActive[chainActive.Height() + 1 - target_confirms];
uint256 lastblock = pblockLast ? pblockLast->GetBlockHash() : 0;
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
UniValue gettransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"gettransaction \"txid\" ( includeWatchonly )\n"
"\nGet detailed information about in-wallet transaction <txid>\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. \"includeWatchonly\" (bool, optional, default=false) Whether to include watchonly addresses in balance calculation and details[]\n"
"\nResult:\n"
"{\n"
" \"amount\" : x.xxx, (numeric) The transaction amount in btc\n"
" \"confirmations\" : n, (numeric) The number of confirmations\n"
" \"bcconfirmations\" : n, (numeric) The number of blockchain confirmations\n"
" \"blockhash\" : \"hash\", (string) The block hash\n"
" \"blockindex\" : xx, (numeric) The block index\n"
" \"blocktime\" : ttt, (numeric) The time in seconds since epoch (1 Jan 1970 GMT)\n"
" \"txid\" : \"transactionid\", (string) The transaction id.\n"
" \"time\" : ttt, (numeric) The transaction time in seconds since epoch (1 Jan 1970 GMT)\n"
" \"timereceived\" : ttt, (numeric) The time received in seconds since epoch (1 Jan 1970 GMT)\n"
" \"details\" : [\n"
" {\n"
" \"account\" : \"accountname\", (string) The account name involved in the transaction, can be \"\" for the default account.\n"
" \"address\" : \"bulpaddress\", (string) The bulp address involved in the transaction\n"
" \"category\" : \"send|receive\", (string) The category, either 'send' or 'receive'\n"
" \"amount\" : x.xxx (numeric) The amount in btc\n"
" \"vout\" : n, (numeric) the vout value\n"
" }\n"
" ,...\n"
" ],\n"
" \"hex\" : \"data\" (string) Raw data for transaction\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"") + HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\" true") + HelpExampleRpc("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\""));
uint256 hash;
hash.SetHex(params[0].get_str());
isminefilter filter = ISMINE_SPENDABLE;
if (params.size() > 1)
if (params[1].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
UniValue entry(UniValue::VOBJ);
if (!pwalletMain->mapWallet.count(hash))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
CAmount nCredit = wtx.GetCredit(filter);
CAmount nDebit = wtx.GetDebit(filter);
CAmount nNet = nCredit - nDebit;
CAmount nFee = (wtx.IsFromMe(filter) ? wtx.GetValueOut() - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe(filter))
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(wtx, entry);
UniValue details(UniValue::VARR);
ListTransactions(wtx, "*", 0, false, details, filter);
entry.push_back(Pair("details", details));
string strHex = EncodeHexTx(static_cast<CTransaction>(wtx));
entry.push_back(Pair("hex", strHex));
return entry;
}
UniValue backupwallet(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"backupwallet \"destination\"\n"
"\nSafely copies wallet.dat to destination, which can be a directory or a path with filename.\n"
"\nArguments:\n"
"1. \"destination\" (string) The destination directory or file\n"
"\nExamples:\n" +
HelpExampleCli("backupwallet", "\"backup.dat\"") + HelpExampleRpc("backupwallet", "\"backup.dat\""));
string strDest = params[0].get_str();
if (!BackupWallet(*pwalletMain, strDest))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
return NullUniValue;
}
UniValue keypoolrefill(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"keypoolrefill ( newsize )\n"
"\nFills the keypool." +
HelpRequiringPassphrase() + "\n"
"\nArguments\n"
"1. newsize (numeric, optional, default=100) The new keypool size\n"
"\nExamples:\n" +
HelpExampleCli("keypoolrefill", "") + HelpExampleRpc("keypoolrefill", ""));
// 0 is interpreted by TopUpKeyPool() as the default keypool size given by -keypool
unsigned int kpSize = 0;
if (params.size() > 0) {
if (params[0].get_int() < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size.");
kpSize = (unsigned int)params[0].get_int();
}
EnsureWalletIsUnlocked();
pwalletMain->TopUpKeyPool(kpSize);
if (pwalletMain->GetKeyPoolSize() < kpSize)
throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
return NullUniValue;
}
static void LockWallet(CWallet* pWallet)
{
LOCK(cs_nWalletUnlockTime);
nWalletUnlockTime = 0;
pWallet->Lock();
}
UniValue walletpassphrase(const UniValue& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3))
throw runtime_error(
"walletpassphrase \"passphrase\" timeout\n"
"\nStores the wallet decryption key in memory for 'timeout' seconds.\n"
"This is needed prior to performing transactions related to private keys such as sending DNOs\n"
"\nArguments:\n"
"1. \"passphrase\" (string, required) The wallet passphrase\n"
"2. timeout (numeric, required) The time to keep the decryption key in seconds.\n"
"\nNote:\n"
"Issuing the walletpassphrase command while the wallet is already unlocked will set a new unlock\n"
"time that overrides the old one. A timeout of \"0\" unlocks until the wallet is closed.\n"
"\nExamples:\n"
"\nUnlock the wallet for 60 seconds\n" +
HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60") +
"\nUnlock the wallet for 60 seconds but allow Obfuscation only\n" + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60 true") +
"\nLock the wallet again (before 60 seconds)\n" + HelpExampleCli("walletlock", "") +
"\nAs json rpc call\n" + HelpExampleRpc("walletpassphrase", "\"my pass phrase\", 60"));
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
// Note that the walletpassphrase is stored in params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
strWalletPass = params[0].get_str().c_str();
if (!pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked.");
if (!pwalletMain->Unlock(strWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
pwalletMain->TopUpKeyPool();
int64_t nSleepTime = params[1].get_int64();
LOCK(cs_nWalletUnlockTime);
nWalletUnlockTime = GetTime() + nSleepTime;
if (nSleepTime > 0) {
nWalletUnlockTime = GetTime () + nSleepTime;
RPCRunLater ("lockwallet", boost::bind (LockWallet, pwalletMain), nSleepTime);
}
return NullUniValue;
}
UniValue walletpassphrasechange(const UniValue& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrasechange \"oldpassphrase\" \"newpassphrase\"\n"
"\nChanges the wallet passphrase from 'oldpassphrase' to 'newpassphrase'.\n"
"\nArguments:\n"
"1. \"oldpassphrase\" (string) The current passphrase\n"
"2. \"newpassphrase\" (string) The new passphrase\n"
"\nExamples:\n" +
HelpExampleCli("walletpassphrasechange", "\"old one\" \"new one\"") + HelpExampleRpc("walletpassphrasechange", "\"old one\", \"new one\""));
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
return NullUniValue;
}
UniValue walletlock(const UniValue& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
throw runtime_error(
"walletlock\n"
"\nRemoves the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.\n"
"\nExamples:\n"
"\nSet the passphrase for 2 minutes to perform a transaction\n" +
HelpExampleCli("walletpassphrase", "\"my pass phrase\" 120") +
"\nPerform a send (requires passphrase set)\n" + HelpExampleCli("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 1.0") +
"\nClear the passphrase since we are done before 2 minutes is up\n" + HelpExampleCli("walletlock", "") +
"\nAs json rpc call\n" + HelpExampleRpc("walletlock", ""));
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
{
LOCK(cs_nWalletUnlockTime);
pwalletMain->Lock();
nWalletUnlockTime = 0;
}
return NullUniValue;
}
UniValue encryptwallet(const UniValue& params, bool fHelp)
{
if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
throw runtime_error(
"encryptwallet \"passphrase\"\n"
"\nEncrypts the wallet with 'passphrase'. This is for first time encryption.\n"
"After this, any calls that interact with private keys such as sending or signing \n"
"will require the passphrase to be set prior the making these calls.\n"
"Use the walletpassphrase call for this, and then walletlock call.\n"
"If the wallet is already encrypted, use the walletpassphrasechange call.\n"
"Note that this will shutdown the server.\n"
"\nArguments:\n"
"1. \"passphrase\" (string) The pass phrase to encrypt the wallet with. It must be at least 1 character, but should be long.\n"
"\nExamples:\n"
"\nEncrypt you wallet\n" +
HelpExampleCli("encryptwallet", "\"my pass phrase\"") +
"\nNow set the passphrase to use the wallet, such as for signing or sending DNOs\n" + HelpExampleCli("walletpassphrase", "\"my pass phrase\"") +
"\nNow we can so something like sign\n" + HelpExampleCli("signmessage", "\"bulpaddress\" \"test message\"") +
"\nNow lock the wallet again by removing the passphrase\n" + HelpExampleCli("walletlock", "") +
"\nAs a json rpc call\n" + HelpExampleRpc("encryptwallet", "\"my pass phrase\""));
if (fHelp)
return true;
if (pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() < 1)
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (!pwalletMain->EncryptWallet(strWalletPass))
throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "wallet encrypted; dicenode server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup.";
}
UniValue lockunspent(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"lockunspent unlock [{\"txid\":\"txid\",\"vout\":n},...]\n"
"\nUpdates list of temporarily unspendable outputs.\n"
"Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.\n"
"A locked transaction output will not be chosen by automatic coin selection, when spending DNOs.\n"
"Locks are stored in memory only. Nodes start with zero locked outputs, and the locked output list\n"
"is always cleared (by virtue of process exit) when a node stops or fails.\n"
"Also see the listunspent call\n"
"\nArguments:\n"
"1. unlock (boolean, required) Whether to unlock (true) or lock (false) the specified transactions\n"
"2. \"transactions\" (string, required) A json array of objects. Each object the txid (string) vout (numeric)\n"
" [ (json array of json objects)\n"
" {\n"
" \"txid\":\"id\", (string) The transaction id\n"
" \"vout\": n (numeric) The output number\n"
" }\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"true|false (boolean) Whether the command was successful or not\n"
"\nExamples:\n"
"\nList the unspent transactions\n" +
HelpExampleCli("listunspent", "") +
"\nLock an unspent transaction\n" + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nList the locked transactions\n" + HelpExampleCli("listlockunspent", "") +
"\nUnlock the transaction again\n" + HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nAs a json rpc call\n" + HelpExampleRpc("lockunspent", "false, \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\""));
if (params.size() == 1)
RPCTypeCheck(params, boost::assign::list_of(UniValue::VBOOL));
else
RPCTypeCheck(params, boost::assign::list_of(UniValue::VBOOL)(UniValue::VARR));
bool fUnlock = params[0].get_bool();
if (params.size() == 1) {
if (fUnlock)
pwalletMain->UnlockAllCoins();
return true;
}
UniValue outputs = params[1].get_array();
for (unsigned int idx = 0; idx < outputs.size(); idx++) {
const UniValue& output = outputs[idx];
if (!output.isObject())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected object");
const UniValue& o = output.get_obj();
RPCTypeCheckObj(o, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM));
string txid = find_value(o, "txid").get_str();
if (!IsHex(txid))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
int nOutput = find_value(o, "vout").get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
COutPoint outpt(uint256(txid), nOutput);
if (fUnlock)
pwalletMain->UnlockCoin(outpt);
else
pwalletMain->LockCoin(outpt);
}
return true;
}
UniValue listlockunspent(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"listlockunspent\n"
"\nReturns list of temporarily unspendable outputs.\n"
"See the lockunspent call to lock and unlock transactions for spending.\n"
"\nResult:\n"
"[\n"
" {\n"
" \"txid\" : \"transactionid\", (string) The transaction id locked\n"
" \"vout\" : n (numeric) The vout value\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n"
"\nList the unspent transactions\n" +
HelpExampleCli("listunspent", "") +
"\nLock an unspent transaction\n" + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nList the locked transactions\n" + HelpExampleCli("listlockunspent", "") +
"\nUnlock the transaction again\n" + HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nAs a json rpc call\n" + HelpExampleRpc("listlockunspent", ""));
vector<COutPoint> vOutpts;
pwalletMain->ListLockedCoins(vOutpts);
UniValue ret(UniValue::VARR);
BOOST_FOREACH (COutPoint& outpt, vOutpts) {
UniValue o(UniValue::VOBJ);
o.push_back(Pair("txid", outpt.hash.GetHex()));
o.push_back(Pair("vout", (int)outpt.n));
ret.push_back(o);
}
return ret;
}
UniValue settxfee(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"settxfee amount\n"
"\nSet the transaction fee per kB.\n"
"\nArguments:\n"
"1. amount (numeric, required) The transaction fee in DNO/kB rounded to the nearest 0.00000001\n"
"\nResult\n"
"true|false (boolean) Returns true if successful\n"
"\nExamples:\n" +
HelpExampleCli("settxfee", "0.00001") + HelpExampleRpc("settxfee", "0.00001"));
// Amount
CAmount nAmount = 0;
if (params[0].get_real() != 0.0)
nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts
payTxFee = CFeeRate(nAmount, 1000);
return true;
}
UniValue getwalletinfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getwalletinfo\n"
"Returns an object containing various wallet state info.\n"
"\nResult:\n"
"{\n"
" \"walletversion\": xxxxx, (numeric) the wallet version\n"
" \"balance\": xxxxxxx, (numeric) the total DNO balance of the wallet\n"
" \"txcount\": xxxxxxx, (numeric) the total number of transactions in the wallet\n"
" \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n"
" \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n"
" \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getwalletinfo", "") + HelpExampleRpc("getwalletinfo", ""));
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("txcount", (int)pwalletMain->mapWallet.size()));
obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
if (pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", nWalletUnlockTime));
return obj;
}
// ppcoin: reserve balance from being staked for network protection
UniValue reservebalance(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"reservebalance ( reserve amount )\n"
"\nShow or set the reserve amount not participating in network protection\n"
"If no parameters provided current setting is printed.\n"
"\nArguments:\n"
"1. reserve (boolean, optional) is true or false to turn balance reserve on or off.\n"
"2. amount (numeric, optional) is a real and rounded to cent.\n"
"\nResult:\n"
"{\n"
" \"reserve\": true|false, (boolean) Status of the reserve balance\n"
" \"amount\": x.xxxx (numeric) Amount reserved\n"
"\nExamples:\n" +
HelpExampleCli("reservebalance", "true 5000") + HelpExampleRpc("reservebalance", "true 5000"));
if (params.size() > 0) {
bool fReserve = params[0].get_bool();
if (fReserve) {
if (params.size() == 1)
throw runtime_error("must provide amount to reserve balance.\n");
CAmount nAmount = AmountFromValue(params[1]);
nAmount = (nAmount / CENT) * CENT; // round to cent
if (nAmount < 0)
throw runtime_error("amount cannot be negative.\n");
nReserveBalance = nAmount;
} else {
if (params.size() > 1)
throw runtime_error("cannot specify amount to turn off reserve.\n");
nReserveBalance = 0;
}
}
UniValue result(UniValue::VOBJ);
result.push_back(Pair("reserve", (nReserveBalance > 0)));
result.push_back(Pair("amount", ValueFromAmount(nReserveBalance)));
return result;
}
// presstab HyperStake
UniValue setstakesplitthreshold(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"setstakesplitthreshold value\n"
"\nThis will set the output size of your stakes to never be below this number\n"
"\nArguments:\n"
"1. value (numeric, required) Threshold value between 1 and 999999\n"
"\nResult:\n"
"{\n"
" \"threshold\": n, (numeric) Threshold value set\n"
" \"saved\": true|false (boolean) 'true' if successfully saved to the wallet file\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("setstakesplitthreshold", "5000") + HelpExampleRpc("setstakesplitthreshold", "5000"));
uint64_t nStakeSplitThreshold = params[0].get_int();
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Unlock wallet to use this feature");
if (nStakeSplitThreshold > 999999)
throw runtime_error("Value out of range, max allowed is 999999");
CWalletDB walletdb(pwalletMain->strWalletFile);
LOCK(pwalletMain->cs_wallet);
{
bool fFileBacked = pwalletMain->fFileBacked;
UniValue result(UniValue::VOBJ);
pwalletMain->nStakeSplitThreshold = nStakeSplitThreshold;
result.push_back(Pair("threshold", int(pwalletMain->nStakeSplitThreshold)));
if (fFileBacked) {
walletdb.WriteStakeSplitThreshold(nStakeSplitThreshold);
result.push_back(Pair("saved", "true"));
} else
result.push_back(Pair("saved", "false"));
return result;
}
}
// presstab HyperStake
UniValue getstakesplitthreshold(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getstakesplitthreshold\n"
"Returns the threshold for stake splitting\n"
"\nResult:\n"
"n (numeric) Threshold value\n"
"\nExamples:\n" +
HelpExampleCli("getstakesplitthreshold", "") + HelpExampleRpc("getstakesplitthreshold", ""));
return int(pwalletMain->nStakeSplitThreshold);
}
UniValue autocombinerewards(const UniValue& params, bool fHelp)
{
bool fEnable;
if (params.size() >= 1)
fEnable = params[0].get_bool();
if (fHelp || params.size() < 1 || (fEnable && params.size() != 2) || params.size() > 2)
throw runtime_error(
"autocombinerewards true|false ( threshold )\n"
"\nWallet will automatically monitor for any coins with value below the threshold amount, and combine them if they reside with the same DNO address\n"
"When autocombinerewards runs it will create a transaction, and therefore will be subject to transaction fees.\n"
"\nArguments:\n"
"1. true|false (boolean, required) Enable auto combine (true) or disable (false)\n"
"2. threshold (numeric, optional) Threshold amount (default: 0)\n"
"\nExamples:\n" +
HelpExampleCli("autocombinerewards", "true 500") + HelpExampleRpc("autocombinerewards", "true 500"));
CWalletDB walletdb(pwalletMain->strWalletFile);
CAmount nThreshold = 0;
if (fEnable)
nThreshold = params[1].get_int();
pwalletMain->fCombineDust = fEnable;
pwalletMain->nAutoCombineThreshold = nThreshold;
if (!walletdb.WriteAutoCombineSettings(fEnable, nThreshold))
throw runtime_error("Changed settings in wallet but failed to save to database\n");
return NullUniValue;
}
UniValue printMultiSend()
{
UniValue ret(UniValue::VARR);
UniValue act(UniValue::VOBJ);
act.push_back(Pair("MultiSendStake Activated?", pwalletMain->fMultiSendStake));
act.push_back(Pair("MultiSendMasternode Activated?", pwalletMain->fMultiSendMasternodeReward));
ret.push_back(act);
if (pwalletMain->vDisabledAddresses.size() >= 1) {
UniValue disAdd(UniValue::VOBJ);
for (unsigned int i = 0; i < pwalletMain->vDisabledAddresses.size(); i++) {
disAdd.push_back(Pair("Disabled From Sending", pwalletMain->vDisabledAddresses[i]));
}
ret.push_back(disAdd);
}
ret.push_back("MultiSend Addresses to Send To:");
UniValue vMS(UniValue::VOBJ);
for (unsigned int i = 0; i < pwalletMain->vMultiSend.size(); i++) {
vMS.push_back(Pair("Address " + boost::lexical_cast<std::string>(i), pwalletMain->vMultiSend[i].first));
vMS.push_back(Pair("Percent", pwalletMain->vMultiSend[i].second));
}
ret.push_back(vMS);
return ret;
}
UniValue printAddresses()
{
std::vector<COutput> vCoins;
pwalletMain->AvailableCoins(vCoins);
std::map<std::string, double> mapAddresses;
BOOST_FOREACH (const COutput& out, vCoins) {
CTxDestination utxoAddress;
ExtractDestination(out.tx->vout[out.i].scriptPubKey, utxoAddress);
std::string strAdd = CBitcoinAddress(utxoAddress).ToString();
if (mapAddresses.find(strAdd) == mapAddresses.end()) //if strAdd is not already part of the map
mapAddresses[strAdd] = (double)out.tx->vout[out.i].nValue / (double)COIN;
else
mapAddresses[strAdd] += (double)out.tx->vout[out.i].nValue / (double)COIN;
}
UniValue ret(UniValue::VARR);
for (map<std::string, double>::const_iterator it = mapAddresses.begin(); it != mapAddresses.end(); ++it) {
UniValue obj(UniValue::VOBJ);
const std::string* strAdd = &(*it).first;
const double* nBalance = &(*it).second;
obj.push_back(Pair("Address ", *strAdd));
obj.push_back(Pair("Balance ", *nBalance));
ret.push_back(obj);
}
return ret;
}
unsigned int sumMultiSend()
{
unsigned int sum = 0;
for (unsigned int i = 0; i < pwalletMain->vMultiSend.size(); i++)
sum += pwalletMain->vMultiSend[i].second;
return sum;
}
UniValue multisend(const UniValue& params, bool fHelp)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
bool fFileBacked;
//MultiSend Commands
if (params.size() == 1) {
string strCommand = params[0].get_str();
UniValue ret(UniValue::VOBJ);
if (strCommand == "print") {
return printMultiSend();
} else if (strCommand == "printaddress" || strCommand == "printaddresses") {
return printAddresses();
} else if (strCommand == "clear") {
LOCK(pwalletMain->cs_wallet);
{
bool erased = false;
if (pwalletMain->fFileBacked) {
if (walletdb.EraseMultiSend(pwalletMain->vMultiSend))
erased = true;
}
pwalletMain->vMultiSend.clear();
pwalletMain->setMultiSendDisabled();
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("Erased from database", erased));
obj.push_back(Pair("Erased from RAM", true));
return obj;
}
} else if (strCommand == "enablestake" || strCommand == "activatestake") {
if (pwalletMain->vMultiSend.size() < 1)
throw JSONRPCError(RPC_INVALID_REQUEST, "Unable to activate MultiSend, check MultiSend vector");
if (CBitcoinAddress(pwalletMain->vMultiSend[0].first).IsValid()) {
pwalletMain->fMultiSendStake = true;
if (!walletdb.WriteMSettings(true, pwalletMain->fMultiSendMasternodeReward, pwalletMain->nLastMultiSendHeight)) {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("error", "MultiSend activated but writing settings to DB failed"));
UniValue arr(UniValue::VARR);
arr.push_back(obj);
arr.push_back(printMultiSend());
return arr;
} else
return printMultiSend();
}
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to activate MultiSend, check MultiSend vector");
} else if (strCommand == "enablemasternode" || strCommand == "activatemasternode") {
if (pwalletMain->vMultiSend.size() < 1)
throw JSONRPCError(RPC_INVALID_REQUEST, "Unable to activate MultiSend, check MultiSend vector");
if (CBitcoinAddress(pwalletMain->vMultiSend[0].first).IsValid()) {
pwalletMain->fMultiSendMasternodeReward = true;
if (!walletdb.WriteMSettings(pwalletMain->fMultiSendStake, true, pwalletMain->nLastMultiSendHeight)) {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("error", "MultiSend activated but writing settings to DB failed"));
UniValue arr(UniValue::VARR);
arr.push_back(obj);
arr.push_back(printMultiSend());
return arr;
} else
return printMultiSend();
}
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to activate MultiSend, check MultiSend vector");
} else if (strCommand == "disable" || strCommand == "deactivate") {
pwalletMain->setMultiSendDisabled();
if (!walletdb.WriteMSettings(false, false, pwalletMain->nLastMultiSendHeight))
throw JSONRPCError(RPC_DATABASE_ERROR, "MultiSend deactivated but writing settings to DB failed");
return printMultiSend();
} else if (strCommand == "enableall") {
if (!walletdb.EraseMSDisabledAddresses(pwalletMain->vDisabledAddresses))
return "failed to clear old vector from walletDB";
else {
pwalletMain->vDisabledAddresses.clear();
return printMultiSend();
}
}
}
if (params.size() == 2 && params[0].get_str() == "delete") {
int del = boost::lexical_cast<int>(params[1].get_str());
if (!walletdb.EraseMultiSend(pwalletMain->vMultiSend))
throw JSONRPCError(RPC_DATABASE_ERROR, "failed to delete old MultiSend vector from database");
pwalletMain->vMultiSend.erase(pwalletMain->vMultiSend.begin() + del);
if (!walletdb.WriteMultiSend(pwalletMain->vMultiSend))
throw JSONRPCError(RPC_DATABASE_ERROR, "walletdb WriteMultiSend failed!");
return printMultiSend();
}
if (params.size() == 2 && params[0].get_str() == "disable") {
std::string disAddress = params[1].get_str();
if (!CBitcoinAddress(disAddress).IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "address you want to disable is not valid");
else {
pwalletMain->vDisabledAddresses.push_back(disAddress);
if (!walletdb.EraseMSDisabledAddresses(pwalletMain->vDisabledAddresses))
throw JSONRPCError(RPC_DATABASE_ERROR, "disabled address from sending, but failed to clear old vector from walletDB");
if (!walletdb.WriteMSDisabledAddresses(pwalletMain->vDisabledAddresses))
throw JSONRPCError(RPC_DATABASE_ERROR, "disabled address from sending, but failed to store it to walletDB");
else
return printMultiSend();
}
}
//if no commands are used
if (fHelp || params.size() != 2)
throw runtime_error(
"multisend <command>\n"
"****************************************************************\n"
"WHAT IS MULTISEND?\n"
"MultiSend allows a user to automatically send a percent of their stake reward to as many addresses as you would like\n"
"The MultiSend transaction is sent when the staked coins mature (100 confirmations)\n"
"****************************************************************\n"
"TO CREATE OR ADD TO THE MULTISEND VECTOR:\n"
"multisend <DNO Address> <percent>\n"
"This will add a new address to the MultiSend vector\n"
"Percent is a whole number 1 to 100.\n"
"****************************************************************\n"
"MULTISEND COMMANDS (usage: multisend <command>)\n"
" print - displays the current MultiSend vector \n"
" clear - deletes the current MultiSend vector \n"
" enablestake/activatestake - activates the current MultiSend vector to be activated on stake rewards\n"
" enablemasternode/activatemasternode - activates the current MultiSend vector to be activated on masternode rewards\n"
" disable/deactivate - disables the current MultiSend vector \n"
" delete <Address #> - deletes an address from the MultiSend vector \n"
" disable <address> - prevents a specific address from sending MultiSend transactions\n"
" enableall - enables all addresses to be eligible to send MultiSend transactions\n"
"****************************************************************\n");
//if the user is entering a new MultiSend item
string strAddress = params[0].get_str();
CBitcoinAddress address(strAddress);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid DNO address");
if (boost::lexical_cast<int>(params[1].get_str()) < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid percentage");
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
unsigned int nPercent = boost::lexical_cast<unsigned int>(params[1].get_str());
LOCK(pwalletMain->cs_wallet);
{
fFileBacked = pwalletMain->fFileBacked;
//Error if 0 is entered
if (nPercent == 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Sending 0% of stake is not valid");
}
//MultiSend can only send 100% of your stake
if (nPercent + sumMultiSend() > 100)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Failed to add to MultiSend vector, the sum of your MultiSend is greater than 100%");
for (unsigned int i = 0; i < pwalletMain->vMultiSend.size(); i++) {
if (pwalletMain->vMultiSend[i].first == strAddress)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Failed to add to MultiSend vector, cannot use the same address twice");
}
if (fFileBacked)
walletdb.EraseMultiSend(pwalletMain->vMultiSend);
std::pair<std::string, int> newMultiSend;
newMultiSend.first = strAddress;
newMultiSend.second = nPercent;
pwalletMain->vMultiSend.push_back(newMultiSend);
if (fFileBacked) {
if (!walletdb.WriteMultiSend(pwalletMain->vMultiSend))
throw JSONRPCError(RPC_DATABASE_ERROR, "walletdb WriteMultiSend failed!");
}
}
return printMultiSend();
}
| [
"75269119+Marloondev@users.noreply.github.com"
] | 75269119+Marloondev@users.noreply.github.com |
6486aba4f3e7dcdcae0542568f2eb3260db41878 | 2a6f884fc90831e60fba2baa60c81df34eaa2228 | /ArduinoCode/Autosteer_UDP/AutosteerPID.ino | 655e40da4224d1cee6258c8ab5c4e5d12cc931a5 | [
"MIT"
] | permissive | ArBe-AU/AgOpenGPS | 2b79d2c9ec787a332c5d81b8e502c441c44357e2 | 0b5e672fdb679c6dde127d6f998df80ac6959186 | refs/heads/master | 2021-05-19T04:17:55.837714 | 2020-04-01T21:47:24 | 2020-04-01T21:47:24 | 199,355,356 | 0 | 0 | NOASSERTION | 2019-07-29T01:16:14 | 2019-07-29T01:16:14 | null | UTF-8 | C++ | false | false | 1,633 | ino | void calcSteeringPID(void)
{
//Proportional only
pValue = steerSettings.Kp * steerAngleError *steerSettings.Ko;
pwmDrive = (constrain(pValue, -255, 255));
//add min throttle factor so no delay from motor resistance.
if (pwmDrive < 0 ) pwmDrive -= steerSettings.minPWMValue;
else if (pwmDrive > 0 ) pwmDrive += steerSettings.minPWMValue;
if (pwmDrive > 255) pwmDrive = 255;
if (pwmDrive < -255) pwmDrive = -255;
if (aogSettings.MotorDriveDirection) pwmDrive *= -1;
}
//#########################################################################################
void motorDrive(void)
{
// Used with Cytron MD30C Driver
// Steering Motor
// Dir + PWM Signal
if (aogSettings.CytronDriver)
{
pwmDisplay = pwmDrive;
//fast set the direction accordingly (this is pin DIR1_RL_ENABLE, port D, 4)
if (pwmDrive >= 0) bitSet(PORTD, 4); //set the correct direction
else
{
bitClear(PORTD, 4);
pwmDrive = -1 * pwmDrive;
}
//write out the 0 to 255 value
analogWrite(PWM1_LPWM, pwmDrive);
}
else
{
// Used with IBT 2 Driver for Steering Motor
// Dir1 connected to BOTH enables
// PWM Left + PWM Right Signal
pwmDisplay = pwmDrive;
if (pwmDrive > 0)
{
analogWrite(PWM2_RPWM, 0);//Turn off before other one on
analogWrite(PWM1_LPWM, pwmDrive);
}
else
{
pwmDrive = -1 * pwmDrive;
analogWrite(PWM1_LPWM, 0);//Turn off before other one on
analogWrite(PWM2_RPWM, pwmDrive);
}
}
}
| [
"yesgogit@gmail.com"
] | yesgogit@gmail.com |
80ec4fb80902892562c219f1482b1152b50da3c6 | 330a6d99df194712b5b07f715198d971276a8102 | /Tracer/librt/include/rt/BxDF/IBxDF.h | dd591cf83711b4c980c9edbd23dd974e46e5cdad | [] | no_license | CaSchmidt/Tracer | 2c777561664012222306fb35c172299c5ccaccea | 0fc189bb9e5b01dfc5af0b319962b721a14ebbbe | refs/heads/master | 2021-11-21T19:12:12.432455 | 2021-09-04T19:06:35 | 2021-09-04T19:06:35 | 206,944,499 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,106 | h | /****************************************************************************
** Copyright (c) 2021, Carsten Schmidt. All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
**
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
**
** 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 IBXDF_H
#define IBXDF_H
#include "rt/Sampler/Sample.h"
namespace rt {
class IBxDF {
public:
enum Flags : uint_t {
InvalidFlags = 0,
Reflection = 1 << 0,
Transmission = 1 << 1,
Diffuse = 1 << 2,
Glossy = 1 << 3,
Specular = 1 << 4,
AllFlags = 0x1F
};
IBxDF(const Flags flags) noexcept;
virtual ~IBxDF();
Color color() const;
void setColor(const Color& c);
Flags flags() const;
bool matchFlags(const Flags f) const;
bool isReflection() const;
bool isSpecular() const;
bool isTransmission() const;
virtual Color eval(const Direction& wo, const Direction& wi) const = 0;
virtual real_t pdf(const Direction& wo, const Direction& wi) const;
virtual Color sample(const Direction& wo, Direction *wi, const Sample2D& xi, real_t *pdf) const;
protected:
Color _color{1, 1, 1};
private:
Flags _flags{InvalidFlags};
};
inline bool isReflection(const IBxDF::Flags flags)
{
return (flags & IBxDF::Reflection) == IBxDF::Reflection;
}
inline bool isSpecular(const IBxDF::Flags flags)
{
return (flags & IBxDF::Specular) == IBxDF::Specular;
}
inline bool isTransmission(const IBxDF::Flags flags)
{
return (flags & IBxDF::Transmission) == IBxDF::Transmission;
}
} // namespace rt
#endif // IBXDF_H
| [
"CaSchmidt@users.noreply.github.com"
] | CaSchmidt@users.noreply.github.com |
3fda0e28b7a1aa569e914055056f275537830c4c | a9142d45aaa4f417f7927038efc0e00dad083a6f | /Atmega328 code (.ino files and versions)/3Dof_Version_2/3Dof_Version_2.ino | f0859ca82954d86d3a2e72e18b212a4b52a90d37 | [
"MIT"
] | permissive | ykevin/Inverse-Kinematics-3-DOF-Robotic-arm | de6fa7008c222242211a0bed63271e14c4ac16e1 | 4f9adf3e8c556d0a1050da7e6c5c8a9802260c54 | refs/heads/master | 2021-05-25T23:24:33.649844 | 2019-11-29T07:01:49 | 2019-11-29T07:01:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,612 | ino | //for atan2(y,x)
#include <math.h>
//for servo control
#include <Servo.h>
//declare my three servos (pins are declared later)
Servo Ser_1;
Servo Ser_2;
Servo Ser_3;
//if you use a led for error indicator:
int led=5;
//all variables
//change l1, l2 and l3 according to your robotic arm lengths.
double l1=7.6, l2=7.9, l3=10.9; //the lengths of the arms
int x, y, z; //for the position in space
double Th1=90, Th2=90, Th3=90; //initial angles (when arduino starts)
double Final_Deg=0, Diff =0;
bool Th3_Ph_Range_Error=false, Th2_Ph_Range_Error=false, C3_Error=false;
int k=0;
double Th1_Calc_1, Th2_Calc_1, Th3_Calc_1; //usef for first solution
double Th1_Calc_2, Th2_Calc_2, Th3_Calc_2; //used for second solution
//below, the functions that convert from the practical values to the theoritical values, change them accoridingly.
double TH1(int Deg){
return Deg;
}
double TH2(int Deg){
return (-Deg) + 140;
}
double TH3(int Deg){
return Deg +125;
}
//Angle limits, change accordingly
float Th2_max_negative= -47;
float Th2_max_positive= 67;
float Th3_max_positive= +153;
float Th3_max_negative= -135.5;
int i;
double C3_Result;
//all functions
//function used many times to convert from rad to deg
double Rad_To_Deg(double Conv){
return Conv* 57.2957;
}
//will be needed for the rest of functions
double C3(int x,int y,int z){
C3_Result = (sq(x)+sq(y)+sq(z-l1)-sq(l2)-sq(l3))/(2*l2*l3);
//C3 has limitation due to square root. these limitations should not be exceeded (dont enter big x,y,z)
if(C3_Result<(-1) || C3_Result>1){
Serial.println("out of range, C3_Error");
C3_Error = true;
}
else{
C3_Error=false;
return C3_Result;
}
}
//will be needed for the rest of functions. for Up elbow solution, let last parameter be false by default. For down elbow solution, S3 should be <0 so let change last parameter to true.
//the limitations of the sqrt have already been solved to the C3_Result, so there is no need to check the S3 sqrt limitation.
double S3(int x,int y,int z, bool Second_Solution=false){
if (Second_Solution==false){//up elbow slution
return sqrt(1-sq(C3(x,y,z)));
}
else if(Second_Solution==true){//down elbow solution
return -sqrt(1-sq(C3(x,y,z)));
}
}
//Angle Th1(base)
double Th_1(int x,int y) {
if (C3_Error==false){//if sqrt limitations are not violated..
return Rad_To_Deg(atan2 (y,x)); //reverse x and y cause the library is reversed
}
}
//Angle Th2
double Th_2(int x, int y, int z, bool Second_Solution=false){
if (C3_Error==false){//if sqrt limitations are not violated..
return Rad_To_Deg(atan2(z-l1, sqrt(sq(x)+ sq(y))) - atan2(l3*S3(x,y,z,Second_Solution), l2+(l3*C3(x,y,z))));
}
}
//Angle Th3
double Th_3(int x,int y,int z,bool Second_Solution=false){
if (C3_Error == false){//if sqrt limitations are not violated..
return Rad_To_Deg(atan2(S3(x,y,z, Second_Solution),C3(x,y,z)));
}
}
//Function that checks the physical limitations of th1, th2, th3 angles. i needed to use a function, because i will use it twice every time we calculate the angles (up albow solution and down elbow solution)
void Physical_Limitations_Check(double Th2_Calc, double Th3_Calc){
//in case you are using a different arm, you should change te physical angle range limitations
//physical limitations should change according to calibration settings
if(Th2_Calc<(Th2_max_negative) || Th2_Calc>(Th3_max_positive)){//if there is a physical limitation, then Ph_Range_error=true
Th2_Ph_Range_Error=true;
Serial.println("Th2_Calc range violation");
}
else{
Th2_Ph_Range_Error=false;
}
if(Th3_Calc< (Th3_max_negative) || Th3_Calc>(Th2_max_positive)){
Th3_Ph_Range_Error=true;
Serial.println("Th3_Calc range violation");
}
else{
Th3_Ph_Range_Error=false;
}
}
//OUR MAIN Function where we will give the coordinates and will unite all the Th_ functions to save the desired degrees
void Inverse_Calc(int x,int y,int z){
//checking if C3(x,y,z)'s limitations are not violated (c3 has a limitation due to sqrt)
C3(x,y,z);// if there will be an error, C3_Error variable will change to true.
if(C3_Error == false){//if the c3 limitation is not violated (due to S3 sqrt)...
//Save each degree values to the corresponding variables. Solve for both up elbow solution and down elbow solution (2nd slution)
//first solution
Th1_Calc_1=Th_1(x,y);
Th2_Calc_1=Th_2(x,y,z);
Th3_Calc_1=Th_3(x,y,z);
//second solution
Th1_Calc_2=Th_1(x,y);
Th2_Calc_2=Th_2(x,y,z,true);
Th3_Calc_2=Th_3(x,y,z,true);
Serial.print("Th1_Calc_1= ");
Serial.println(Th1_Calc_1);
Serial.print("Th2_Calc_1= ");
Serial.println(Th2_Calc_1);
Serial.print("Th3_Calc_1= ");
Serial.println(Th3_Calc_1);
}
else{
Serial.println("C3_Error occured");
digitalWrite(led,1);
}
Physical_Limitations_Check(Th2_Calc_1, Th3_Calc_1);
if (((C3_Error==false) && (Th2_Ph_Range_Error==false)) && (Th3_Ph_Range_Error==false) && y>=0){//if there is no error, continue..
Servo_Mov(1,Th1_Calc_1);
Servo_Mov(3,Th3_Calc_1);
Servo_Mov(2,Th2_Calc_1);
}
else{
Serial.println("Limitations Violated for first solution");
Th2_Ph_Range_Error=false;
Th3_Ph_Range_Error=false;
if(C3_Error==false){
Serial.println("Since C3_Error==false, we can Check second solution");
Physical_Limitations_Check(Th2_Calc_2, Th3_Calc_2);
if (((C3_Error==false) && (Th2_Ph_Range_Error==false)) && (Th3_Ph_Range_Error==false) && y>=0){//if there is no error, continue..
Serial.print("Th1_Calc_2= ");
Serial.println(Th1_Calc_2);
Serial.print("Th_Calc_2= ");
Serial.println(Th2_Calc_2);
Serial.print("Th3_Calc_2= ");
Serial.println(Th3_Calc_2);
Servo_Mov(1,Th1_Calc_2);
Servo_Mov(3,Th3_Calc_2);
Servo_Mov(2,Th2_Calc_2);
}
else {
Serial.println("Physical limitations cannot cope with 1st or 2nd solution");
digitalWrite(led,1);
}
}
}
C3_Error= false;
Th2_Ph_Range_Error=false;
Th3_Ph_Range_Error=false;
}
//Calibration and Function that helps the servos go smoothly from one position to another. We need this so that servos wont move violently from one position to another
void Servo_Mov(int Ser_Num, double Deg){
//calibration
//First Servo ======================================
if (Ser_Num == 1){
//Servo 1 doesnt need calibration, deg we give are the degs it outputs
Final_Deg= TH1(Deg);
//check if the Deg we want is already the one it has (it doesnt need to move in this case)
Diff= Th1-Final_Deg;
if (Diff == 0){
Ser_1.write(Th1);
}
else if (Diff<0){ //if the degs are different(either smaller of bigger, it will move accordingly)
for (i=Th1; i<=Final_Deg; i++){
Ser_1.write(i);
delay(50);//delay is the key to make it move smoothly.
}
Th1=Final_Deg;
}
else if(Diff>0){
for (i=Th1; i>=Final_Deg; i--){
Ser_1.write(i);
delay(50);
}
Th1=Final_Deg;
}
}
//Second Servo========================================
else if(Ser_Num == 2){
Final_Deg= TH2(Deg); //the second and third servo need calibradion. This is the optimal i came up with.
Diff= Th2-Final_Deg;
if (Diff == 0){
Ser_2.write(Th2);
}
else if (Diff<0){
for (i=Th2; i<=Final_Deg; i++){
Ser_2.write(i);
delay(50);
}
Th2=Final_Deg;
}
else if(Diff>0){
for (i=Th2; i>=Final_Deg; i--){
Ser_2.write(i);
delay(50);
}
Th2=Final_Deg;
}
}
//Servo 3============================================
else if(Ser_Num == 3){
Final_Deg= TH3(Deg);
Diff= Th3-Final_Deg;
if (Diff == 0){
Ser_3.write(Th3);
}
else if (Diff<0){
for (i=Th3; i<=Final_Deg; i++){
Ser_3.write(i);
delay(50);
}
Th3=Final_Deg;
}
else if(Diff>0){
for (i=Th3; i>=Final_Deg; i--){
Ser_3.write(i);
delay(50);
}
Th3=Final_Deg;
}
}
}
void setup() {
//declare which pin are my servos attached
Ser_1.attach(2);
Ser_2.attach(3);
Ser_3.attach(4);
//if ur using a led for error indicator
pinMode(led,OUTPUT);
delay(3000);
//Start serial port
Serial.begin(9600);
Inverse_Calc(14,10,3);
}
void loop() {
//add a delay
delay(1000);
}
| [
"basilisvirus@hotmail.com"
] | basilisvirus@hotmail.com |
ee608052efa5be321f683aad00ee016910e7edc7 | 85ad6d89c4c941da4ce25f121516eb4f60de8b1d | /opencvproject/img-import.cpp | 02e97e3f16ad03f428ffdfabb1629e9b2cf81f40 | [] | no_license | rparth07/opencv-project-Basic | 6ac8eef2870db0a598566cb8612d3aa775d4a68b | 14a1fa55da8cdb4fa5c9d858bacd9f267ec72340 | refs/heads/main | 2023-06-25T03:01:45.461217 | 2021-07-22T11:47:07 | 2021-07-22T11:47:07 | 386,503,016 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 351 | cpp | #include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
using namespace cv;
using namespace std;
/// <summary>
/// /////////////////////// How to import images //////////////////////////////
/// </summary>
void main() {
string path = "Resources/test.png";
Mat img = imread(path);
imshow("Image", img);
waitKey(0);
} | [
"pmr642001@gmail.com"
] | pmr642001@gmail.com |
65aa24207fe26f27d974895f8fc547432305d6a5 | 74450d2e5c5d737ab8eb3f3f2e8b7d2e8b40bb5e | /github_code/b-tree/cpp/65.c | 352d0bc5899545b340a9c11b749e0fe5dc31fc40 | [] | no_license | ulinka/tbcnn-attention | 10466b0925987263f722fbc53de4868812c50da7 | 55990524ce3724d5bfbcbc7fd2757abd3a3fd2de | refs/heads/master | 2020-08-28T13:59:25.013068 | 2019-05-10T08:05:37 | 2019-05-10T08:05:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 709 | c | /**
@file bTree.h
@brief bTree class
@author Brandon Theisen, Jason Pederson, Kelvin Schutz, Chris Scholl, Jared Kareniemi
*/
#ifndef BTREE_H
#define BTREE_H
#include "Node.h"
#include "LeafNode.h"
#include "InteriorNode.h"
using namespace std;
template <class T>
class bTree
{
private:
Node<T>* rootPtr;
public:
bTree();
Node<T>* searchLeaf(Node<T>* aNodePtr, int keyToFind);
bool treeContains(int keyToFind);
void printRecord(int key);
bool insertRecord(key, value);
bool deleteRecord(int key);
bool checkTree(bTree aTree);
void rebuildTree(bTree &aTree);
~bTree();
};
//#include "bTree.cpp"
#endif // BTREE_H
| [
"bdqnghi@gmail.com"
] | bdqnghi@gmail.com |
02a3b986201ff0999d642f811ee1d875f8cb75f9 | e57ebdae3e20c5bbc88bbfe1644b2dd4d2fc1b4b | /Cuda9/include/x86-64-decoder/extern.h | 34161083446966dc2329fc826a612cee79df982c | [] | no_license | CarpAlberto/CudaProject | 2bdec483cbe3d6ddc895bb70a7705cef82bee74b | 7e6e05b49b68c5bd1af331776e62322ac0d723f5 | refs/heads/master | 2021-09-15T06:03:38.403294 | 2018-05-27T13:44:07 | 2018-05-27T13:44:07 | 106,919,131 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,449 | h | /* -----------------------------------------------------------------------------
* extern.h
*
* Copyright (c) 2004, 2005, 2006, Vivek Mohan <vivek@sig9.com>
* All rights reserved. See LICENSE
* -----------------------------------------------------------------------------
*/
#ifndef UD_EXTERN_H
#define UD_EXTERN_H
#include <stdio.h>
#include "types.h"
using namespace types;
extern void ud_init(struct ud*);
extern void ud_set_mode(struct ud*, types::uint8_t);
extern void ud_set_pc(struct ud*, types::uint64_t);
extern void ud_set_input_hook(struct ud*, int (*)(struct ud*));
extern void ud_set_input_buffer(struct ud*, types::uint8_t*, size_t);
#ifndef __UD_STANDALONE__
extern void ud_set_input_file(struct ud*, FILE*);
#endif /* __UD_STANDALONE__ */
extern void ud_set_vendor(struct ud*, unsigned);
extern void ud_set_syntax(struct ud*, void (*)(struct ud*));
extern void ud_input_skip(struct ud*, size_t);
extern int ud_input_end(struct ud*);
extern unsigned int ud_decode(struct ud*);
extern unsigned int ud_disassemble(struct ud*);
extern void ud_translate_intel(struct ud*);
extern void ud_translate_att(struct ud*);
extern char* ud_insn_asm(struct ud* u);
extern types::uint8_t* ud_insn_ptr(struct ud* u);
extern types::uint64_t ud_insn_off(struct ud*);
extern char* ud_insn_hex(struct ud*);
extern unsigned int ud_insn_len(struct ud* u);
extern const char* ud_lookup_mnemonic(enum ud_mnemonic_code c);
#endif
| [
"alberto_carp@yahoo.com"
] | alberto_carp@yahoo.com |
63f3368c0cb87bd23c30da6e068d94f531bd3990 | 7c8b7702de4f490deaaf084873de7dd311555a00 | /One-Linked-List-two-pointers-more-func/one_linked_list_two_pointers/main.cpp | 52056cb7716d96715a206331f35ca4445dc6d02d | [] | no_license | dgetskova/SD-Cplusplus | 3786787bce1aa989ffb71138b6be870ae272d7c0 | 86fc050bc1bc10a1a8726456438f45d09492e0f7 | refs/heads/master | 2016-09-05T22:58:25.629316 | 2015-10-10T10:52:35 | 2015-10-10T10:52:35 | 39,434,349 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 262 | cpp | #include"List.h"
int main()
{
List<int> list;
list.push(1);
list.push(2);
list.push(3);
list.removeElem(1, 3); // middle
list.removeElem(1, 2); // last
list.removeElem(0, 1); // first
list.push(1);
list.push(2);
//list.removeElem(0, 2);
list.pop();
} | [
"dgetskova@gmail.com"
] | dgetskova@gmail.com |
6b9d43003587e9b5eca871097413cd0ea0d8f297 | 2f7b2a1f880f39b167c3610179f5682942c0162a | /recursion/search.cpp | 84e5e438fcf551c4fb02a04074dcf4b0f034949f | [] | no_license | agnik2019/Data-Structure-Algorithm | 368d38d2f7268bcae198e965ff97db0843b3b56b | 12c068599c3799d63b275fa17a833483bcbac293 | refs/heads/main | 2023-06-19T05:59:45.307158 | 2021-07-03T05:23:42 | 2021-07-03T05:23:42 | 327,957,262 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 610 | cpp | //find firsr & last occurance of a number
//return the index
#include<iostream>
using namespace std;
int first_ocur(int arr[],int n,int i, int key)
{
if(i==n) return -1;
if(arr[i] == key) return i;
return first_ocur(arr,n,i+1,key);
}
int last_ocur(int arr[],int n,int i, int key)
{
if(i==n) return -1; //base condition
int restArray = last_ocur(arr,n,i+1,key);
if(restArray != -1) return restArray;
if(arr[i] == key) return i;
return -1;
}
int main()
{
int arr[]={5,7,3,4,2,3,1};
cout<<first_ocur(arr,7,0,3)<<endl;
cout<<last_ocur(arr,7,0,3)<<endl;
return 0;
} | [
"agniksaha2019@gmail.com"
] | agniksaha2019@gmail.com |
f511a9802f8a6788911648068a2957aed4711142 | 897ad01e10f02d1b92df25e45e91a9955c64564b | /mainwindow.h | 5c46a15f3f75be76d2f1cdf7ba36109b0d33ec8e | [
"MIT"
] | permissive | EVARATE/pw_practice | 5af08870bfbb4f97f4a5dc4e43f51acf2c440043 | b269fbbd2dd359917bd3103b43abf614ba7f8ed6 | refs/heads/main | 2023-03-21T22:55:33.011502 | 2021-03-10T15:05:36 | 2021-03-10T15:05:36 | 342,618,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,185 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <random>
#include <chrono>
#include <QMessageBox>
#include <QClipboard>
#include "misc.cpp"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
std::string currPassword;
int correctCounter = 0;
std::string generatePassword(const int length,
const bool lower,
const bool upper,
const bool numbers,
const bool symbols,
const bool useFewSymbols = false);
private slots:
void setNewPW();
void updateInterface();
void resetInterface();
void togglePreviewHide();
void generateNewPassword();
void toggleGeneratorView();
void giveTooShortWarning();
void viewGeneratorInfo();
void changePWCheckboxes();
void changeSymbolsCheckbox();
void copyPWToClipboard();
void setNewPWFromGen();
};
#endif // MAINWINDOW_H
| [
"GreeeNLambda@googlemail.com"
] | GreeeNLambda@googlemail.com |
3bc8fabd5df5b61d2432929e4e5d11dda1442238 | d40efadec5724c236f1ec681ac811466fcf848d8 | /tags/fs2_open_3_6_10_RC2/code/network/multi_options.cpp | 8d1e6e2285e065a71857e77116f59338e8127d33 | [] | no_license | svn2github/fs2open | 0fcbe9345fb54d2abbe45e61ef44a41fa7e02e15 | c6d35120e8372c2c74270c85a9e7d88709086278 | refs/heads/master | 2020-05-17T17:37:03.969697 | 2015-01-08T15:24:21 | 2015-01-08T15:24:21 | 14,258,345 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,579 | cpp | /*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
/*
* $Logfile: /Freespace2/code/Network/multi_options.cpp $
* $Revision: 2.10.2.2 $
* $Date: 2007-10-15 06:43:17 $
* $Author: taylor $
*
* $Log: not supported by cvs2svn $
* Revision 2.10.2.1 2007/04/06 12:55:57 karajorma
* Add the -cap_object_update command line to force multiplayer clients to a more server friendly object update setting.
*
* Revision 2.10 2006/04/20 06:32:15 Goober5000
* proper capitalization according to Volition
*
* Revision 2.9 2005/10/10 17:21:07 taylor
* remove NO_NETWORK
*
* Revision 2.8 2005/07/13 03:35:32 Goober5000
* remove PreProcDefine #includes in FS2
* --Goober5000
*
* Revision 2.7 2005/03/02 21:18:19 taylor
* better support for Inferno builds (in PreProcDefines.h now, no networking support)
* make sure NO_NETWORK builds are as friendly on Windows as it is on Linux/OSX
* revert a timeout in Client.h back to the original value before Linux merge
*
* Revision 2.6 2005/02/04 10:12:31 taylor
* merge with Linux/OSX tree - p0204
*
* Revision 2.5 2004/07/26 20:47:42 Kazan
* remove MCD complete
*
* Revision 2.4 2004/07/12 16:32:57 Kazan
* MCD - define _MCD_CHECK to use memory tracking
*
* Revision 2.3 2004/03/05 09:02:02 Goober5000
* Uber pass at reducing #includes
* --Goober5000
*
* Revision 2.2 2002/08/01 01:41:08 penguin
* The big include file move
*
* Revision 2.1 2002/07/22 01:22:25 penguin
* Linux port -- added NO_STANDALONE ifdefs
*
* Revision 2.0 2002/06/03 04:02:26 penguin
* Warpcore CVS sync
*
* Revision 1.1 2002/05/02 18:03:11 mharris
* Initial checkin - converted filenames and includes to lower case
*
*
* 22 8/27/99 12:32a Dave
* Allow the user to specify a local port through the launcher.
*
* 21 8/22/99 1:19p Dave
* Fixed up http proxy code. Cleaned up scoring code. Reverse the order in
* which d3d cards are detected.
*
* 20 8/04/99 6:01p Dave
* Oops. Make sure standalones log in.
*
* 19 7/09/99 9:51a Dave
* Added thick polyline code.
*
* 18 5/03/99 8:32p Dave
* New version of multi host options screen.
*
* 17 4/25/99 7:43p Dave
* Misc small bug fixes. Made sun draw properly.
*
* 16 4/20/99 6:39p Dave
* Almost done with artillery targeting. Added support for downloading
* images on the PXO screen.
*
* 15 3/10/99 6:50p Dave
* Changed the way we buffer packets for all clients. Optimized turret
* fired packets. Did some weapon firing optimizations.
*
* 14 3/09/99 6:24p Dave
* More work on object update revamping. Identified several sources of
* unnecessary bandwidth.
*
* 13 3/08/99 7:03p Dave
* First run of new object update system. Looks very promising.
*
* 12 2/21/99 6:01p Dave
* Fixed standalone WSS packets.
*
* 11 2/19/99 2:55p Dave
* Temporary checking to report the winner of a squad war match.
*
* 10 2/12/99 6:16p Dave
* Pre-mission Squad War code is 95% done.
*
* 9 2/11/99 3:08p Dave
* PXO refresh button. Very preliminary squad war support.
*
* 8 11/20/98 11:16a Dave
* Fixed up IPX support a bit. Making sure that switching modes and
* loading/saving pilot files maintains proper state.
*
* 7 11/19/98 4:19p Dave
* Put IPX sockets back in psnet. Consolidated all multiplayer config
* files into one.
*
* 6 11/19/98 8:03a Dave
* Full support for D3-style reliable sockets. Revamped packet lag/loss
* system, made it receiver side and at the lowest possible level.
*
* 5 11/17/98 11:12a Dave
* Removed player identification by address. Now assign explicit id #'s.
*
* 4 10/13/98 9:29a Dave
* Started neatening up freespace.h. Many variables renamed and
* reorganized. Added AlphaColors.[h,cpp]
*
* 3 10/07/98 6:27p Dave
* Globalized mission and campaign file extensions. Removed Silent Threat
* special code. Moved \cache \players and \multidata into the \data
* directory.
*
* 2 10/07/98 10:53a Dave
* Initial checkin.
*
* 1 10/07/98 10:50a Dave
*
* 20 9/10/98 1:17p Dave
* Put in code to flag missions and campaigns as being MD or not in Fred
* and FreeSpace. Put in multiplayer support for filtering out MD
* missions. Put in multiplayer popups for warning of non-valid missions.
*
* 19 7/07/98 2:49p Dave
* UI bug fixes.
*
* 18 6/04/98 11:04a Allender
* object update level stuff. Don't reset to high when becoming an
* observer of any type. default to low when guy is a dialup customer
*
* 17 5/24/98 3:45a Dave
* Minor object update fixes. Justify channel information on PXO. Add a
* bunch of configuration stuff for the standalone.
*
* 16 5/19/98 1:35a Dave
* Tweaked pxo interface. Added rankings url to pxo.cfg. Make netplayer
* local options update dynamically in netgames.
*
* 15 5/08/98 5:05p Dave
* Go to the join game screen when quitting multiplayer. Fixed mission
* text chat bugs. Put mission type symbols on the create game list.
* Started updating standalone gui controls.
*
* 14 5/06/98 12:36p Dave
* Make sure clients can leave the debrief screen easily at all times. Fix
* respawn count problem.
*
* 13 5/03/98 7:04p Dave
* Make team vs. team work mores smoothly with standalone. Change how host
* interacts with standalone for picking missions. Put in a time limit for
* ingame join ship select. Fix ingame join ship select screen for Vasudan
* ship icons.
*
* 12 5/03/98 2:52p Dave
* Removed multiplayer furball mode.
*
* 11 4/23/98 6:18p Dave
* Store ETS values between respawns. Put kick feature in the text
* messaging system. Fixed text messaging system so that it doesn't
* process or trigger ship controls. Other UI fixes.
*
* 10 4/22/98 5:53p Dave
* Large reworking of endgame sequencing. Updated multi host options
* screen for new artwork. Put in checks for host or team captains leaving
* midgame.
*
* 9 4/16/98 11:39p Dave
* Put in first run of new multiplayer options screen. Still need to
* complete final tab.
*
* 8 4/13/98 4:50p Dave
* Maintain status of weapon bank/links through respawns. Put # players on
* create game mission list. Make observer not have engine sounds. Make
* oberver pivot point correct. Fixed respawn value getting reset every
* time host options screen started.
*
* 7 4/09/98 11:01p Dave
* Put in new multi host options screen. Tweaked multiplayer options a
* bit.
*
* 6 4/09/98 5:43p Dave
* Remove all command line processing from the demo. Began work fixing up
* the new multi host options screen.
*
* 5 4/06/98 6:37p Dave
* Put in max_observers netgame server option. Make sure host is always
* defaulted to alpha 1 or zeta 1. Changed create game so that MAX_PLAYERS
* can always join but need to be kicked before commit can happen. Put in
* support for server ending a game and notifying clients of a special
* condition.
*
* 4 4/04/98 4:22p Dave
* First rev of UDP reliable sockets is done. Seems to work well if not
* overly burdened.
*
* 3 4/03/98 1:03a Dave
* First pass at unreliable guaranteed delivery packets.
*
* 2 3/31/98 4:51p Dave
* Removed medals screen and multiplayer buttons from demo version. Put in
* new pilot popup screen. Make ships in mp team vs. team have proper team
* ids. Make mp respawns a permanent option saved in the player file.
*
* 1 3/30/98 6:24p Dave
*
*
* $NoKeywords: $
*/
#include "cmdline/cmdline.h"
#include "osapi/osregistry.h"
#include "network/multi.h"
#include "network/multimsgs.h"
#include "network/multi_oo.h"
#include "freespace2/freespace.h"
#include "network/stand_gui.h"
#include "network/multiutil.h"
#include "network/multi_voice.h"
#include "network/multi_options.h"
#include "network/multi_team.h"
#include "mission/missioncampaign.h"
#include "mission/missionparse.h"
#include "parse/parselo.h"
#include "playerman/player.h"
#include "cfile/cfile.h"
#include "fs2netd/fs2netd_client.h"
// ----------------------------------------------------------------------------------
// MULTI OPTIONS DEFINES/VARS
//
// packet codes
#define MULTI_OPTION_SERVER 0 // server update follows
#define MULTI_OPTION_LOCAL 1 // local netplayer options follow
#define MULTI_OPTION_START_GAME 2 // host's start game options on the standalone server
#define MULTI_OPTION_MISSION 3 // host's mission selection stuff on a standalone server
// global options
#define MULTI_CFG_FILE NOX("multi.cfg")
multi_global_options Multi_options_g;
char Multi_options_proxy[512] = "";
ushort Multi_options_proxy_port = 0;
// ----------------------------------------------------------------------------------
// MULTI OPTIONS FUNCTIONS
//
// load in the config file
#define NEXT_TOKEN() do { tok = strtok(NULL, "\n"); if(tok != NULL){ drop_leading_white_space(tok); drop_trailing_white_space(tok); } } while(0);
#define SETTING(s) ( !stricmp(tok, s) )
void multi_options_read_config()
{
CFILE *in;
char str[512];
char *tok = NULL;
// set default value for the global multi options
memset(&Multi_options_g, 0, sizeof(multi_global_options));
Multi_options_g.protocol = NET_TCP;
// do we have a forced port via commandline or registry?
ushort forced_port = (ushort)os_config_read_uint(NULL, "ForcePort", 0);
Multi_options_g.port = (Cmdline_network_port >= 0) ? (ushort)Cmdline_network_port : forced_port == 0 ? (ushort)DEFAULT_GAME_PORT : forced_port;
Multi_options_g.log = (Cmdline_multi_log) ? 1 : 0;
Multi_options_g.datarate_cap = OO_HIGH_RATE_DEFAULT;
strcpy(Multi_options_g.user_tracker_ip, "");
strcpy(Multi_options_g.game_tracker_ip, "");
strcpy(Multi_options_g.tracker_port, "");
strcpy(Multi_options_g.pxo_ip, "");
strcpy(Multi_options_g.pxo_rank_url, "");
strcpy(Multi_options_g.pxo_create_url, "");
strcpy(Multi_options_g.pxo_verify_url, "");
strcpy(Multi_options_g.pxo_banner_url, "");
// standalone values
Multi_options_g.std_max_players = -1;
Multi_options_g.std_datarate = OBJ_UPDATE_HIGH;
Multi_options_g.std_voice = 1;
memset(Multi_options_g.std_passwd, 0, STD_PASSWD_LEN);
memset(Multi_options_g.std_pname, 0, STD_NAME_LEN);
Multi_options_g.std_framecap = 30;
// read in the config file
in = cfopen(MULTI_CFG_FILE, "rt", CFILE_NORMAL, CF_TYPE_DATA);
// if we failed to open the config file, user default settings
if (in == NULL) {
nprintf(("Network","Failed to open network config file, using default settings\n"));
} else {
while ( !cfeof(in) ) {
// read in the game info
memset(str, 0, 512);
cfgets(str, 512, in);
// parse the first line
tok = strtok(str, " \t");
// check the token
if (tok != NULL) {
drop_leading_white_space(tok);
drop_trailing_white_space(tok);
} else {
continue;
}
// all possible options
// only standalone cares about the following options
if (Is_standalone) {
// setup PXO mode
if ( SETTING("+pxo") ) {
NEXT_TOKEN();
if (tok != NULL) {
strncpy(Multi_fs_tracker_channel, tok, MAX_PATH);
}
} else
// set the standalone server's permanent name
if ( SETTING("+name") ) {
NEXT_TOKEN();
if (tok != NULL) {
strncpy(Multi_options_g.std_pname, tok, STD_NAME_LEN);
}
} else
// standalone won't allow voice transmission
if ( SETTING("+no_voice") ) {
Multi_options_g.std_voice = 0;
} else
// set the max # of players on the standalone
if ( SETTING("+max_players") ) {
NEXT_TOKEN();
if (tok != NULL) {
if ( !((atoi(tok) < 1) || (atoi(tok) > MAX_PLAYERS)) ) {
Multi_options_g.std_max_players = atoi(tok);
}
}
} else
// ban a player
if ( SETTING("+ban") ) {
NEXT_TOKEN();
if (tok != NULL) {
std_add_ban(tok);
}
} else
// set the standalone host password
if ( SETTING("+passwd") ) {
NEXT_TOKEN();
if (tok != NULL) {
strncpy(Multi_options_g.std_passwd, tok, STD_PASSWD_LEN);
#ifdef _WIN32
// yuck
extern HWND Multi_std_host_passwd;
SetWindowText(Multi_std_host_passwd, Multi_options_g.std_passwd);
#else
// TODO: get password ?
// argh, gonna have to figure out how to do this - mharris 07/07/2002
#endif
}
} else
// set standalone to low updates
if ( SETTING("+low_update") ) {
Multi_options_g.std_datarate = OBJ_UPDATE_LOW;
} else
// set standalone to medium updates
if ( SETTING("+med_update") ) {
Multi_options_g.std_datarate = OBJ_UPDATE_MEDIUM;
} else
// set standalone to high updates
if ( SETTING("+high_update") ) {
Multi_options_g.std_datarate = OBJ_UPDATE_HIGH;
} else
// set standalone to high updates
if ( SETTING("+lan_update") ) {
Multi_options_g.std_datarate = OBJ_UPDATE_LAN;
} else
// standalone pxo login user
if ( SETTING("+pxo_login") ) {
NEXT_TOKEN();
if (tok != NULL) {
strncpy(Multi_options_g.std_pxo_login, tok, MULTI_TRACKER_STRING_LEN);
}
} else
// standalone pxo login password
if ( SETTING("+pxo_password") ) {
NEXT_TOKEN();
if (tok != NULL) {
strncpy(Multi_options_g.std_pxo_password, tok, MULTI_TRACKER_STRING_LEN);
}
}
}
// ... common to all modes ...
// ip addr of user tracker
if ( SETTING("+user_server") ) {
NEXT_TOKEN();
if (tok != NULL) {
strcpy(Multi_options_g.user_tracker_ip, tok);
}
} else
// ip addr of game tracker
if ( SETTING("+game_server") ) {
NEXT_TOKEN();
if (tok != NULL) {
strcpy(Multi_options_g.game_tracker_ip, tok);
}
} else
// port to use for the game/user tracker (FS2NetD)
if ( SETTING("+server_port") ) {
NEXT_TOKEN();
if (tok != NULL) {
strncpy(Multi_options_g.tracker_port, tok, STD_NAME_LEN);
}
} else
// ip addr of pxo chat server
if ( SETTING("+chat_server") ) {
NEXT_TOKEN();
if (tok != NULL) {
strcpy(Multi_options_g.pxo_ip, tok);
}
} else
// url of pilot rankings page
if ( SETTING("+rank_url") ) {
NEXT_TOKEN();
if (tok != NULL) {
strcpy(Multi_options_g.pxo_rank_url, tok);
}
} else
// url of pxo account create page
if ( SETTING("+create_url") ) {
NEXT_TOKEN();
if (tok != NULL) {
strcpy(Multi_options_g.pxo_create_url, tok);
}
} else
// url of pxo account verify page
if ( SETTING("+verify_url") ) {
NEXT_TOKEN();
if (tok != NULL) {
strcpy(Multi_options_g.pxo_verify_url, tok);
}
} else
// url of pxo banners
if ( SETTING("+banner_url") ) {
NEXT_TOKEN();
if (tok != NULL) {
strcpy(Multi_options_g.pxo_banner_url, tok);
}
} else
// set the max datarate for high updates
if ( SETTING("+datarate") ) {
NEXT_TOKEN();
if (tok != NULL) {
if ( atoi(tok) >= 4000 ) {
Multi_options_g.datarate_cap = atoi(tok);
}
}
} else
// get the proxy server
if ( SETTING("+http_proxy") ) {
NEXT_TOKEN();
if (tok != NULL) {
char *ip = strtok(tok, ":");
if (ip != NULL) {
strcpy(Multi_options_proxy, ip);
}
ip = strtok(NULL, "");
if (ip != NULL) {
Multi_options_proxy_port = (ushort)atoi(ip);
} else {
strcpy(Multi_options_proxy, "");
}
}
}
}
// close the config file
cfclose(in);
in = NULL;
}
}
// set netgame defaults
// NOTE : should be used when creating a newpilot
void multi_options_set_netgame_defaults(multi_server_options *options)
{
// any player can do squadmate messaging
options->squad_set = MSO_SQUAD_ANY;
// only the host can end the game
options->endgame_set = MSO_END_HOST;
// allow ingame file xfer and custom pilot pix
options->flags = (MSO_FLAG_INGAME_XFER | MSO_FLAG_ACCEPT_PIX);
// set the default time limit to be -1 (no limit)
options->mission_time_limit = fl2f(-1.0f);
// set the default max kills for a mission
options->kill_limit = 9999;
// set the default # of respawns
options->respawn = 2;
// set the default # of max observers
options->max_observers = 2;
// set the default netgame qos
options->voice_qos = 10;
// set the default token timeout
options->voice_token_wait = 2000; // he must wait 2 seconds between voice gets
// set the default max voice record time
options->voice_record_time = 5000;
}
// set local netplayer defaults
// NOTE : should be used when creating a newpilot
void multi_options_set_local_defaults(multi_local_options *options)
{
// accept pix by default and broadcast on the local subnet
options->flags = (MLO_FLAG_ACCEPT_PIX | MLO_FLAG_LOCAL_BROADCAST);
// set the object update level based on the type of network connection specified by the user
// at install (or launcher) time.
if ( Psnet_connection == NETWORK_CONNECTION_DIALUP ) {
options->obj_update_level = OBJ_UPDATE_LOW;
} else {
options->obj_update_level = OBJ_UPDATE_HIGH;
}
}
// fill in the passed netgame options struct with the data from my player file data (only host/server should do this)
void multi_options_netgame_load(multi_server_options *options)
{
if(options != NULL){
memcpy(options,&Player->m_server_options,sizeof(multi_server_options));
}
}
// fill in the passed local options struct with the data from my player file data (all machines except standalone should do this)
void multi_options_local_load(multi_local_options *options, net_player *pxo_pl)
{
if(options != NULL){
memcpy(options,&Player->m_local_options,sizeof(multi_local_options));
}
// stuff pxo squad info
if(pxo_pl != NULL){
strcpy(pxo_pl->p_info.pxo_squad_name, Multi_tracker_squad_name);
}
}
// add data from a multi_server_options struct
void add_server_options(ubyte *data, int *size, multi_server_options *mso)
{
int packet_size = *size;
multi_server_options mso_tmp;
memcpy(&mso_tmp, mso, sizeof(multi_server_options));
mso_tmp.flags = INTEL_INT(mso->flags);
mso_tmp.respawn = INTEL_INT(mso->respawn);
mso_tmp.voice_token_wait = INTEL_INT(mso->voice_token_wait);
mso_tmp.voice_record_time = INTEL_INT(mso->voice_record_time);
// mso_tmp.mission_time_limit = INTEL_INT(mso->mission_time_limit);
mso_tmp.kill_limit = INTEL_INT(mso->kill_limit);
ADD_DATA(mso_tmp);
*size = packet_size;
}
// add data from a multi_local_options struct
void add_local_options(ubyte *data, int *size, multi_local_options *mlo)
{
int packet_size = *size;
multi_local_options mlo_tmp;
memcpy(&mlo_tmp, mlo, sizeof(multi_local_options));
mlo_tmp.flags = INTEL_INT(mlo->flags);
mlo_tmp.obj_update_level = INTEL_INT(mlo->obj_update_level);
ADD_DATA(mlo_tmp);
*size = packet_size;
}
// get data from multi_server_options struct
void get_server_options(ubyte *data, int *size, multi_server_options *mso)
{
int offset = *size;
GET_DATA(*mso);
mso->flags = INTEL_INT(mso->flags);
mso->respawn = INTEL_INT(mso->respawn);
mso->voice_token_wait = INTEL_INT(mso->voice_token_wait);
mso->voice_record_time = INTEL_INT(mso->voice_record_time);
// mso->mission_time_limit = INTEL_INT(mso->mission_time_limit);
mso->kill_limit = INTEL_INT(mso->kill_limit);
*size = offset;
}
// get data from multi_local_options struct
void get_local_options(ubyte *data, int *size, multi_local_options *mlo)
{
int offset = *size;
GET_DATA(*mlo);
mlo->flags = INTEL_INT(mlo->flags);
mlo->obj_update_level = INTEL_INT(mlo->obj_update_level);
*size = offset;
}
// update everyone on the current netgame options
void multi_options_update_netgame()
{
ubyte data[MAX_PACKET_SIZE],code;
int packet_size = 0;
Assert(Net_player->flags & NETINFO_FLAG_GAME_HOST);
// build the header and add the opcode
BUILD_HEADER(OPTIONS_UPDATE);
code = MULTI_OPTION_SERVER;
ADD_DATA(code);
// add the netgame options
add_server_options(data, &packet_size, &Netgame.options);
// send the packet
if(Net_player->flags & NETINFO_FLAG_AM_MASTER){
multi_io_send_to_all_reliable(data, packet_size);
} else {
multi_io_send_reliable(Net_player, data, packet_size);
}
}
// update everyone with my local settings
void multi_options_update_local()
{
ubyte data[MAX_PACKET_SIZE],code;
int packet_size = 0;
// if i'm the server, don't do anything
if(Net_player->flags & NETINFO_FLAG_AM_MASTER){
return;
}
// build the header and add the opcode
BUILD_HEADER(OPTIONS_UPDATE);
code = MULTI_OPTION_LOCAL;
ADD_DATA(code);
// add the netgame options
add_local_options(data, &packet_size, &Net_player->p_info.options);
// send the packet
multi_io_send_reliable(Net_player, data, packet_size);
}
// update the standalone with the settings I have picked at the "start game" screen
void multi_options_update_start_game(netgame_info *ng)
{
ubyte data[MAX_PACKET_SIZE],code;
int packet_size = 0;
// should be a host on a standalone
Assert((Net_player->flags & NETINFO_FLAG_GAME_HOST) && !(Net_player->flags & NETINFO_FLAG_AM_MASTER));
// build the header
BUILD_HEADER(OPTIONS_UPDATE);
code = MULTI_OPTION_START_GAME;
ADD_DATA(code);
// add the start game options
ADD_STRING(ng->name);
ADD_INT(ng->mode);
ADD_INT(ng->security);
// add mode-specific data
switch(ng->mode){
case NG_MODE_PASSWORD:
ADD_STRING(ng->passwd);
break;
case NG_MODE_RANK_ABOVE:
case NG_MODE_RANK_BELOW:
ADD_INT(ng->rank_base);
break;
}
// send to the standalone server
multi_io_send_reliable(Net_player, data, packet_size);
}
// update the standalone with the mission settings I have picked (mission filename, etc)
void multi_options_update_mission(netgame_info *ng, int campaign_mode)
{
ubyte data[MAX_PACKET_SIZE],code;
int packet_size = 0;
// should be a host on a standalone
Assert((Net_player->flags & NETINFO_FLAG_GAME_HOST) && !(Net_player->flags & NETINFO_FLAG_AM_MASTER));
// build the header
BUILD_HEADER(OPTIONS_UPDATE);
code = MULTI_OPTION_MISSION;
ADD_DATA(code);
// type (coop or team vs. team)
ADD_INT(ng->type_flags);
// respawns
ADD_UINT(ng->respawn);
// add the mission/campaign filename
code = (ubyte)campaign_mode;
ADD_DATA(code);
if(campaign_mode){
ADD_STRING(ng->campaign_name);
} else {
ADD_STRING(ng->mission_name);
}
// send to the server
multi_io_send_reliable(Net_player, data, packet_size);
}
// ----------------------------------------------------------------------------------
// MULTI OPTIONS FUNCTIONS
//
// process an incoming multi options packet
void multi_options_process_packet(unsigned char *data, header *hinfo)
{
ubyte code;
multi_local_options bogus;
int idx,player_index;
char str[255];
int offset = HEADER_LENGTH;
// find out who is sending this data
player_index = find_player_id(hinfo->id);
// get the packet code
GET_DATA(code);
switch(code){
// get the start game options
case MULTI_OPTION_START_GAME:
Assert(Game_mode & GM_STANDALONE_SERVER);
// get the netgame name
GET_STRING(Netgame.name);
// get the netgame mode
GET_INT(Netgame.mode);
// get the security #
GET_INT(Netgame.security);
// get mode specific data
switch(Netgame.mode){
case NG_MODE_PASSWORD:
GET_STRING(Netgame.passwd);
break;
case NG_MODE_RANK_ABOVE:
case NG_MODE_RANK_BELOW:
GET_INT(Netgame.rank_base);
break;
}
// update standalone stuff
std_connect_set_gamename(Netgame.name);
std_multi_update_netgame_info_controls();
break;
// get mission choice options
case MULTI_OPTION_MISSION:
netgame_info ng;
char title[NAME_LENGTH+1];
int campaign_type,max_players;
memset(&ng,0,sizeof(netgame_info));
Assert(Game_mode & GM_STANDALONE_SERVER);
// coop or team vs. team mode
GET_INT(ng.type_flags);
if((ng.type_flags & NG_TYPE_TEAM) && !(Netgame.type_flags & NG_TYPE_TEAM)){
multi_team_reset();
}
// if squad war was switched on
if((ng.type_flags & NG_TYPE_SW) && !(Netgame.type_flags & NG_TYPE_SW)){
mprintf(("STANDALONE TURNED ON SQUAD WAR!!\n"));
}
Netgame.type_flags = ng.type_flags;
// new respawn count
GET_UINT(Netgame.respawn);
// name string
memset(str,0,255);
GET_DATA(code);
// campaign mode
if(code){
GET_STRING(ng.campaign_name);
// set the netgame max players here if the filename has changed
if(strcmp(Netgame.campaign_name,ng.campaign_name)){
memset(title,0,NAME_LENGTH+1);
if(!mission_campaign_get_info(ng.campaign_name,title,&campaign_type,&max_players)){
Netgame.max_players = 0;
} else {
Netgame.max_players = max_players;
}
strcpy(Netgame.campaign_name,ng.campaign_name);
}
Netgame.campaign_mode = 1;
// put brackets around the campaign name
if(Game_mode & GM_STANDALONE_SERVER){
strcpy(str,"(");
strcat(str,Netgame.campaign_name);
strcat(str,")");
std_multi_set_standalone_mission_name(str);
}
}
// non-campaign mode
else {
GET_STRING(ng.mission_name);
if(strcmp(Netgame.mission_name,ng.mission_name)){
if(strlen(ng.mission_name)){
Netgame.max_players = mission_parse_get_multi_mission_info( ng.mission_name );
} else {
// setting this to -1 will prevent us from being seen on the network
Netgame.max_players = -1;
}
strcpy(Netgame.mission_name,ng.mission_name);
strcpy(Game_current_mission_filename,Netgame.mission_name);
}
Netgame.campaign_mode = 0;
// set the mission name
if(Game_mode & GM_STANDALONE_SERVER){
std_multi_set_standalone_mission_name(Netgame.mission_name);
}
}
// update FS2NetD as well
if (MULTI_IS_TRACKER_GAME) {
fs2netd_gameserver_update(true);
}
send_netgame_update_packet();
break;
// get the netgame options
case MULTI_OPTION_SERVER:
get_server_options(data, &offset, &Netgame.options);
// if we're a standalone set for no sound, do so here
if((Game_mode & GM_STANDALONE_SERVER) && !Multi_options_g.std_voice){
Netgame.options.flags |= MSO_FLAG_NO_VOICE;
} else {
// maybe update the quality of sound
multi_voice_maybe_update_vars(Netgame.options.voice_qos,Netgame.options.voice_record_time);
}
// set the skill level
Game_skill_level = Netgame.options.skill_level;
if((Game_mode & GM_STANDALONE_SERVER) && !(Game_mode & GM_CAMPAIGN_MODE)){
Netgame.respawn = Netgame.options.respawn;
}
// if we have the "temp closed" flag toggle
if(Netgame.options.flags & MLO_FLAG_TEMP_CLOSED){
Netgame.flags ^= NG_FLAG_TEMP_CLOSED;
}
Netgame.options.flags &= ~(MLO_FLAG_TEMP_CLOSED);
// if i'm the standalone server, I should rebroadcast to all other players
if(Game_mode & GM_STANDALONE_SERVER){
for(idx=0;idx<MAX_PLAYERS;idx++){
if(MULTI_CONNECTED(Net_players[idx]) && (Net_player != &Net_players[idx]) && (&Net_players[idx] != &Net_players[player_index]) ){
multi_io_send_reliable(&Net_players[idx], data, offset);
}
}
send_netgame_update_packet();
}
break;
// local netplayer options
case MULTI_OPTION_LOCAL:
if(player_index == -1){
get_local_options(data, &offset, &bogus);
} else {
get_local_options(data, &offset, &Net_players[player_index].p_info.options);
//If the client has sent an object update higher than that which the server allows, reset it
if (Net_player->flags & NETINFO_FLAG_AM_MASTER) {
if (Net_players[player_index].p_info.options.obj_update_level > Cmdline_objupd) {
Net_players[player_index].p_info.options.obj_update_level = Cmdline_objupd;
}
}
}
break;
}
PACKET_SET_SIZE();
}
| [
"Goober5000@387891d4-d844-0410-90c0-e4c51a9137d3"
] | Goober5000@387891d4-d844-0410-90c0-e4c51a9137d3 |
a645cdefbcc7684af0ce707e555538fd1ea89155 | 9061c1a19fe1f31deb1f222e2f11d5c7cce57cea | /Dijkstra.cpp | b66b2272cc8ac6ef6fb13e35e59e6f09bce737b1 | [
"MIT"
] | permissive | ruchika-swain/Hacktoberfest2020 | 8ec37482c2e7f13ceb072fae36bd5b6cf9cb4635 | 28ce4ac1586ed8773dcdc450c8709b6c444e7022 | refs/heads/master | 2022-12-28T23:20:19.201038 | 2020-10-16T07:02:27 | 2020-10-16T07:02:27 | 300,290,807 | 0 | 1 | MIT | 2020-10-16T07:02:28 | 2020-10-01T13:33:10 | HTML | UTF-8 | C++ | false | false | 3,441 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <limits.h>
using namespace std;
// Node of the adjacency list
class node {
int vertex, weight;
struct node * next;
};
// Follows head insertion to give O(1) insertion
node * addEdge(struct node * head, int vertex, int weight)
{
node * newNode = new node;
newNode->vertex = vertex;
newNode->weight = weight;
newNode->next = head;
return newNode;
}
// Retuns the vertex which is not visited and has least distance
int getMinVertex(int distances[], int visited[], int vertices)
{
int min = INT_MAX, index = -1, i;
for (i = 1; i <= vertices; ++i) {
if (visited[i] == 0 && min > distances[i]) {
min = distances[i];
index = i;
}
}
return index;
}
// Dijkstra's Algorithm function
void dijkstra(node * adjacencyList[], int vertices, int startVertex, int distances[], int parent[])
{
int i, visited[vertices + 1];
// Initially no routes to vertices are know, so all are infinity
for (i = 1; i <= vertices; ++i) {
distances[i] = INT_MAX;
parent[i] = 0;
visited[i] = 0;
}
// Setting distance to source to zero
distances[startVertex] = 0;
for (i = 1; i <= vertices; ++i) { // Untill there are vertices to be processed
int minVertex = getMinVertex(distances, visited, vertices); // Greedily process the nearest vertex
node * trav = adjacencyList[minVertex]; // Checking all the vertices adjacent to 'min'
visited[minVertex] = 1;
while (trav != NULL) {
int u = minVertex;
int v = trav->vertex;
int w = trav->weight;
if (distances[u] != INT_MAX && distances[v] > distances[u] + w) {
// We have discovered a new shortest route, make the neccesary adjustments in data
distances[v] = distances[u] + w;
parent[v] = u;
}
trav = trav->next;
}
}
}
// Recursively looks at a vertex's parent to print the path
void printPath(int parent[], int vertex, int startVertex)
{
if (vertex == startVertex) { // reached the source vertex
cout << startVertex << endl;
return;
} else if (parent[vertex] == 0) { // current vertex has no parent
cout << vertex) << endl;
return;
} else { // go for the current vertex's parent
printPath(parent, parent[vertex], startVertex);
cout << vertex << endl;
}
}
int main()
{
int vertices, edges, i, j, v1, v2, w, startVertex;
int q;
cin >> q;
while(q--)
{
cin >> &vertices >> &edges;
node * adjacencyList[vertices + 1]; // to use the array as 1-indexed for simplicity
int distances[vertices + 1];
int parent[vertices + 1];
for (i = 0; i <= vertices; ++i) { // Must initialize your array
adjacencyList[i] = NULL;
}
for (i = 1; i <= edges; ++i) {
cin >> &v1 >> &v2;
adjacencyList[v1] = addEdge(adjacencyList[v1], v2, 6);
}
cin >> &startVertex;
dijkstra(adjacencyList, vertices, startVertex, distances, parent);
for(i=1;i<=vertices;++i)
{
if(i==startVertex)
continue;
if(distances[i]>10000)
distances[i]=-1;
cout << distances[i];
}
}
return 0;
}
| [
"aggarwalsneha1999@gmail.com"
] | aggarwalsneha1999@gmail.com |
d7865613aa725ee5dadfc5207c12edafd9e6dacb | df9848b9f7118b855402e2ed25f4c01c6027820b | /src/threshold/threLPCollapse.cpp | e48b2843512de22415a97ab1b5c29dd0f9b57f42 | [
"MIT-Modern-Variant"
] | permissive | lee30sonia/threABC | 9ffe41898edb4e6d792f0246bfafce52c92d6197 | 5c24cea7b42b0788fd0460eb0ae3e7c6736944dc | refs/heads/master | 2021-01-09T06:58:18.714836 | 2019-03-28T03:59:53 | 2019-03-28T03:59:53 | 81,161,759 | 2 | 0 | null | 2017-02-07T03:23:49 | 2017-02-07T03:23:49 | null | UTF-8 | C++ | false | false | 19,218 | cpp | #ifndef THRELP_CPP
#define THRELP_CPP
#include <iostream>
#include <fstream>
#include <vector>
#include <set>
#include <map>
#include <utility>
#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <iomanip>
#include <climits>
#include "threshold.h"
#include "base/abc/abc.h"
#include "misc/vec/vec.h"
using namespace std;
#define M 1000
#define completeSolve 1
#define recursiveSolve 1 // if completeSolve==1, use recursive 2^n (1) or encode to constraints(0)
bool lp_Collapse_cpp(Thre_S* f_ori, Thre_S* l_ori, Thre_S* t);
void mux_tree_traverse(Thre_S* f, Thre_S* l, vector<int> selection, int k, vector< vector<int> >& A, vector<int>& B, vector<int>& minus, vector< pair<int,int> >& sharedFanin);
void mux_tree_traverse_front(Thre_S* f, Thre_S* l, vector<int> selection, int k, vector< vector<int> >& A, vector<int>& B, vector<int>& minus, int ori_cur_weight, vector< pair<int,int> >& sharedFanin);
void determine(Thre_S* f, Thre_S* l, vector<int>& selection, int k, vector< vector<int> >& A, vector<int>& B, vector<int>& minus, vector< pair<int,int> >& sharedFanin);
void determineF(Thre_S* f, Thre_S* l, vector<int> selection, int k, vector< vector<int> >& A, vector<int>& B, vector<int>& minus, int ori_cur_weight, vector< pair<int,int> >& sharedFanin);
void leaf0(vector<int>& selection, vector< vector<int> >& A, vector<int>& B);
void leaf1(vector<int>& selection, vector< vector<int> >& A, vector<int>& B);
int max(Vec_Int_t* weights);
int min(Vec_Int_t* weights);
void threSort(Thre_S* t);
int solveLpRescursive(vector< vector<int> >& A, vector<int>& B, vector<int>& ans, vector< pair<int,int> >& sharedFanin, vector<int>& minus, int i);
int solveLpMultiConstraint(vector< vector<int> >& A, vector<int>& B, vector<int>& ans, vector< pair<int,int> >& sharedFanin, vector<int>& minus);
extern int solveLp(vector< vector<int> >& A, vector<int>& B, vector<int>& ans, int n);
extern int solveLpBlock(vector< vector<int> >& A, vector<int>& B, vector<int>& ans, map<int,int>& symm);
extern int solveLpCanonical(vector< vector<int> >& A, vector<int>& B, vector<int>& ans, map<int,int>& symm);
void Vec_IntPopFront( Vec_Int_t* p )
{
assert(p->nSize>0);
for (int i=0; i<p->nSize-1; ++i)
p->pArray[i]=p->pArray[i+1];
--p->nSize;
}
Thre_S* copyThre(Thre_S* t) //copy constructer
{
Thre_S* cp = new Thre_S;
cp->thre=t->thre;
cp->Type=t->Type;
cp->Ischoose=t->Ischoose;
cp->Id=t->Id;
cp->oId=t->oId;
cp->nId=t->nId;
cp->cost=t->cost;
cp->level=t->level;
cp->pName=t->pName;
cp->weights=Vec_IntDup(t->weights);
cp->Fanins=Vec_IntDup(t->Fanins);
cp->Fanouts=Vec_IntDup(t->Fanouts);
cp->pCopy=t->pCopy;
return cp;
}
extern "C" bool Th_Collapse_LP(Thre_S* f_ori, Thre_S* l_ori, Thre_S* t)
{
return lp_Collapse_cpp(f_ori, l_ori, t);
}
bool lp_Collapse_cpp(Thre_S* f_ori, Thre_S* l_ori, Thre_S* t)
{
if (f_ori==NULL || l_ori==NULL){
cout<<"gate not exist"<<endl;
return 0;
}
Thre_S* f=copyThre(f_ori);
Thre_S* l=copyThre(l_ori);
threSort(f); threSort(l);
int k=-1;
for (int i=0; i<Vec_IntSize(l->Fanins); ++i)
{
if (Vec_IntEntry(l->Fanins,i)==f->Id)
{
k=i;
break;
}
}
if (k==-1){
cout<<"the gates are not connected"<<endl;
delete f;
delete l;
return 0;
}
vector<int> minus;
for (int i=0; i<k; ++i)
{
if (Vec_IntEntry(l->weights,i)<0) minus.push_back(1);
else minus.push_back(0);
}
for (int i=0; i<Vec_IntSize(f->weights); ++i)
{
if (Vec_IntEntry(l->weights,k)<0)
{
if (Vec_IntEntry(f->weights,i)<0) minus.push_back(0);
else minus.push_back(1);
}
else
{
if (Vec_IntEntry(f->weights,i)<0) minus.push_back(1);
else minus.push_back(0);
}
}
for (int i=k+1; i<Vec_IntSize(l->weights); ++i)
{
if (Vec_IntEntry(l->weights,i)<0) minus.push_back(1);
else minus.push_back(0);
}
vector< pair<int,int> > sharedFanin;
for (int i=0; i<Vec_IntSize(f->Fanins); ++i)
{
for (int j=0; j<Vec_IntSize(l->Fanins); ++j)
{
if (Vec_IntEntry(f->Fanins,i)==Vec_IntEntry(l->Fanins,j))
{
//cout<<"shared fanin"<<endl;
int a=j<k?j:j-1+Vec_IntSize(f->Fanins);
int b=k+i;
if (a<b) swap(a,b);
sharedFanin.push_back(pair<int,int>(a, b));
break;
}
}
}
vector<int> selection;
vector< vector<int> > A;
vector<int> vec;
vec.resize(Vec_IntSize(f->weights) + Vec_IntSize(l->weights));
A.push_back(vec);
vector<int> B;
mux_tree_traverse(f,l,selection,k,A,B,minus,sharedFanin);
A.erase(A.begin());
for (int i=0; i<sharedFanin.size(); ++i)
{
for (int j=0; j<A.size(); ++j)
A[j][sharedFanin[i].first]=0;
}
#if 0
if (sharedFanin.size()!=0){
cout<<sharedFanin[0].first<<" "<<sharedFanin[0].second<<" "<<k<<endl;
cout<<"original front:"<<endl;
printGate(f_ori);
cout<<"original later:"<<endl;
printGate(l_ori);
for (int i=0; i<minus.size(); ++i)
cout<<minus[i]<<" "; cout<<endl;
for (int i=0; i<k; ++i)
cout<<Vec_IntEntry(l->Fanins,i)<<" ";
for (int i=0; i<Vec_IntSize(f->Fanins); ++i)
cout<<Vec_IntEntry(f->Fanins,i)<<" ";
for (int i=k+1; i<Vec_IntSize(l->Fanins); ++i)
cout<<Vec_IntEntry(l->Fanins,i)<<" ";
cout<<endl;
for (int i=0; i<A.size(); ++i)
{
for (int j=0; j<A[i].size(); ++j)
cout<<setw(2)<<A[i][j]<<" ";
cout<<"| "<<B[i]<<endl;
}
cout<<endl;}
#endif
for(int j=0; j<A[0].size(); ++j)
{
bool skip=false;
for (int m=0; m<sharedFanin.size(); ++m)
{
if (j==sharedFanin[m].second && minus[j]!=minus[sharedFanin[m].first])
{
skip=true;
break;
}
}
if (!completeSolve) skip=false;
if (!skip)
{
for (int i=0; i<A.size(); ++i)
{
if (A[i][j]==2) A[i][j]=0;
else if (A[i][j]==-2) A[i][j]=-1;
}
}
}
#if 0
cout<<endl;
for (int i=0; i<sharedFanin.size(); ++i) cout<<sharedFanin[i].second<<" "; cout<<endl;
cout<<"original A"<<endl;
for (int i=0; i<minus.size(); ++i) cout<<minus[i]<<" "; cout<<endl;
for (int i=0; i<A.size(); ++i)
{
for (int j=0; j<A[i].size(); ++j)
cout<<setw(2)<<A[i][j]<<" ";
cout<<"| "<<B[i]<<endl;
}
#endif
vector<int> ans;
int res;
if (completeSolve && recursiveSolve)
res = solveLpRescursive(A,B,ans,sharedFanin,minus,0);
else if (completeSolve && !recursiveSolve)
res = solveLpMultiConstraint(A,B,ans,sharedFanin,minus);
else
res = solveLp(A,B,ans,0);
if (res!=0) // solve failed
{
#ifdef checkCononical
if (res==-1)
{
cout<<"original front:"<<endl;
printGate(f_ori);
cout<<"original later:"<<endl;
printGate(l_ori);
}
#endif
if (res!=5)
cout<<"Abnormal error in solving lp..."<<endl;
delete f;
delete l;
return 0;
}
else
{
if (!t)
{
delete f;
delete l;
return 1;
}
/*for (int i=0; i<ans.size(); ++i)
cout<<ans[i]<<" ";
cout<<endl;*/
//cout<<ans.size()<<" "<<minus.size()<<" "<<Vec_IntSize(f->Fanins)+Vec_IntSize(l->Fanins)<<endl;
assert(ans.size()-1==minus.size());
t->thre=ans.back();
for (int i=0; i<ans.size()-1; ++i)
{
Vec_IntPush(t->weights,ans[i]);
if (minus[i]==1)
{
Vec_IntWriteEntry(t->weights,i,-1*ans[i]);
t->thre -= ans[i];
}
}
for (int i=0; i<k; ++i)
Vec_IntPush(t->Fanins,Vec_IntEntry(l->Fanins,i));
for (int i=0; i<Vec_IntSize(f->Fanins); ++i)
Vec_IntPush(t->Fanins,Vec_IntEntry(f->Fanins,i));
for (int i=k+1; i<Vec_IntSize(l->Fanins); ++i)
Vec_IntPush(t->Fanins,Vec_IntEntry(l->Fanins,i));
t->Fanouts=Vec_IntDup(l->Fanouts);
sort(sharedFanin.begin(),sharedFanin.end());
for (int i=sharedFanin.size()-1; i>=0; --i)
{
Vec_IntDrop(t->Fanins,sharedFanin[i].first);
Vec_IntDrop(t->weights,sharedFanin[i].first);
}
#if 0
if (1){
cout<<"original front:"<<endl;
printGate(f_ori);
cout<<"original later:"<<endl;
printGate(l_ori);
cout<<"merged gate:"<<endl;
printGate(t);
cout<<endl;}
#endif
delete f;
delete l;
//cout<<t->Id<<" built"<<endl;
return 1;
}
}
void mux_tree_traverse(Thre_S* f, Thre_S* l, vector<int> selection, int k, vector< vector<int> >& A, vector<int>& B, vector<int>& minus, vector< pair<int,int> >& sharedFanin)
{
int cur_weight=Vec_IntEntry(l->weights,0);
Vec_IntPopFront(l->weights);
if (k==0)
{
Thre_S* f2=copyThre(f);
mux_tree_traverse_front(f2,l,selection,k-1,A,B,minus,cur_weight,sharedFanin);
delete f2;
}
else
{
int skip = -1;
for (int i=0; i<sharedFanin.size(); ++i)
{
if (selection.size()==sharedFanin[i].first)
{
skip=sharedFanin[i].second;
break;
}
}
if (skip==-1)
{
// 0 branch
if (cur_weight>0)
selection.push_back(0);
else
selection.push_back(1);
Thre_S* l2=copyThre(l);
determine(f,l2,selection,k-1,A,B,minus,sharedFanin);
delete l2;
// 1 branch
if (cur_weight>0)
selection.back()=1;
else
selection.back()=0;
l->thre-=cur_weight;
determine(f,l,selection,k-1,A,B,minus,sharedFanin);
}
else
{
if (selection[skip]==2) // not determined
{
// 0 branch
if (minus[skip]==0)
selection[skip]=0;
else
selection[skip]=1;
selection.push_back(0);
//for (int i=0; i<selection.size();++i) cout<<selection[i]<<" "; cout<<endl;
Thre_S* l2=copyThre(l);
determine(f,l2,selection,k-1,A,B,minus,sharedFanin);
delete l2;
// 1 branch
if (selection[skip]==0)
selection[skip]=1;
else
selection[skip]=0;
//for (int i=0; i<selection.size();++i) cout<<selection[i]<<" "; cout<<endl;
l->thre-=cur_weight;
determine(f,l,selection,k-1,A,B,minus,sharedFanin);
}
else
{
selection.push_back(0);
//for (int i=0; i<selection.size();++i) cout<<selection[i]<<" "; cout<<endl;
if (selection[skip]+minus[skip]==1) //chose 1 and not minus or chose 0 and minus
l->thre-=cur_weight;
determine(f,l,selection,k-1,A,B,minus,sharedFanin);
}
}
}
}
void mux_tree_traverse_front(Thre_S* f, Thre_S* l, vector<int> selection, int k, vector< vector<int> >& A, vector<int>& B, vector<int>& minus, int ori_cur_weight, vector< pair<int,int> >& sharedFanin)
{
int cur_weight=Vec_IntEntry(f->weights,0);
Vec_IntPopFront(f->weights);
int skip = -1;
for (int i=0; i<sharedFanin.size(); ++i)
{
if (selection.size()==sharedFanin[i].first)
{
skip=sharedFanin[i].second;
break;
}
}
if (skip==-1)
{
// 0 branch
if (ori_cur_weight<0)
{
if (cur_weight>0)
selection.push_back(1);
else
selection.push_back(0);
}
else
{
if (cur_weight>0)
selection.push_back(0);
else
selection.push_back(1);
}
Thre_S* f2=copyThre(f);
Thre_S* l2=copyThre(l);
determineF(f2,l2,selection,k,A,B,minus,ori_cur_weight,sharedFanin);
delete f2;
delete l2;
// 1 branch
if (selection.back()==1) selection.back()=0;
else selection.back()=1;
f->thre-=cur_weight;
determineF(f,l,selection,k,A,B,minus,ori_cur_weight,sharedFanin);
}
else
{
selection.push_back(0);
if (selection[skip]+minus[skip]==1) //chose 1 and not minus or chose 0 and minus
f->thre-=cur_weight;
determineF(f,l,selection,k,A,B,minus,ori_cur_weight,sharedFanin);
}
}
void determine(Thre_S* f, Thre_S* l, vector<int>& selection, int k, vector< vector<int> >& A, vector<int>& B, vector<int>& minus, vector< pair<int,int> >& sharedFanin)
{
if (max(l->weights) < l->thre)
leaf0(selection,A,B);
else if (min(l->weights) >= l->thre)
leaf1(selection,A,B);
else
mux_tree_traverse(f,l,selection,k,A,B,minus,sharedFanin);
}
void determineF(Thre_S* f, Thre_S* l, vector<int> selection, int k, vector< vector<int> >& A, vector<int>& B, vector<int>& minus, int ori_cur_weight, vector< pair<int,int> >& sharedFanin)
{
if (max(f->weights) < f->thre) // 0 leaf of front --> 0 branch of late
{
while (Vec_IntSize(f->weights)>0)
{
selection.push_back(2);
Vec_IntPopFront(f->weights);
}
determine(f,l,selection,k,A,B,minus,sharedFanin);
}
else if (min(f->weights) >= f->thre)
{
l->thre-=ori_cur_weight;
while (Vec_IntSize(f->weights)>0)
{
selection.push_back(2);
Vec_IntPopFront(f->weights);
}
determine(f,l,selection,k,A,B,minus,sharedFanin);
}
else
mux_tree_traverse_front(f,l,selection,k,A,B,minus,ori_cur_weight,sharedFanin);
}
void leaf0(vector<int>& selection, vector< vector<int> >& A, vector<int>& B)
{
vector<int> row;
for (int i=0; i<selection.size(); ++i)
{
row.push_back(selection[i]*-1);
//if (row.back()==-2)
//row.back()=-1;
}
while (row.size()<A[0].size())
row.push_back(-2);//-1);
row.back()=1;
A.push_back(row);
B.push_back(1);
/*cout<<"selection:";
for (int i=0; i<selection.size(); ++i)
cout<<selection[i]<<" ";
cout<<"leaf0"<<endl<<"row: ";
for (int i=0; i<row.size(); ++i)
cout<<row[i]<<" ";
cout<<"| 1"<<endl;*/
}
void leaf1(vector<int>& selection, vector< vector<int> >& A, vector<int>& B)
{
vector<int> row;
for (int i=0; i<selection.size(); ++i)
{
row.push_back(selection[i]);
//if (row.back()==2)
//row.back()=0;
}
while (row.size()<A[0].size())
row.push_back(2);//0);
row.back()=-1;
A.push_back(row);
B.push_back(0);
/*cout<<"selection:";
for (int i=0; i<selection.size(); ++i)
cout<<selection[i]<<" ";
cout<<"leaf1"<<endl<<"row: ";
for (int i=0; i<row.size(); ++i)
cout<<row[i]<<" ";
cout<<"| 0"<<endl;*/
}
int max(Vec_Int_t * weights)
{
int ans=0;
for (int i=0; i<Vec_IntSize(weights); ++i)
{
if (Vec_IntEntry(weights,i)>0)
ans+=Vec_IntEntry(weights,i);
}
return ans;
}
int min(Vec_Int_t* weights)
{
int ans=0;
for (int i=Vec_IntSize(weights)-1; i>=0; --i)
{
if (Vec_IntEntry(weights,i)<0)
ans+=Vec_IntEntry(weights,i);
}
return ans;
}
const bool absSort(pair<int,int> a, pair<int,int> b)
{
return abs(a.first)<abs(b.first);
}
void threSort(Thre_S* t)
{
assert(Vec_IntSize(t->weights)==Vec_IntSize(t->Fanins));
vector< pair<int,int> > Wpair;
for (int i=0; i<Vec_IntSize(t->weights); ++i)
Wpair.push_back(pair<int,int>(Vec_IntEntry(t->weights,i),Vec_IntEntry(t->Fanins,i)));
sort(Wpair.begin(),Wpair.end(),absSort);
for (int i=0; i<Vec_IntSize(t->weights); ++i)
{
Vec_IntWriteEntry(t->weights,i,Wpair[Vec_IntSize(t->weights)-i-1].first);
Vec_IntWriteEntry(t->Fanins,i,Wpair[Vec_IntSize(t->weights)-i-1].second);
}
}
int solveLpRescursive(vector< vector<int> >& A, vector<int>& B, vector<int>& ans, vector< pair<int,int> >& sharedFanin, vector<int>& minus, int s)
{
if (s==sharedFanin.size())
{
#if 0
for (int jj=0; jj<minus.size(); ++jj) cout<<minus[jj]<<" "; cout<<endl;
for (int ii=0; ii<A.size(); ++ii)
{
for (int jj=0; jj<A[ii].size(); ++jj)
cout<<setw(2)<<A[ii][jj]<<" ";
cout<<"| "<<B[ii]<<endl;
}
#endif
return solveLp(A,B,ans,0);
}
int j=sharedFanin[s].second;
int res;
vector< vector<int> > A2=A;
for (int i=0; i<A.size(); ++i)
{
if (A[i][j]==2) A2[i][j]=0;
else if (A[i][j]==-2) A2[i][j]=-1;
}
res = solveLpRescursive(A2,B,ans,sharedFanin,minus,s+1);
if (res==0) return 0;
if (minus[sharedFanin[s].first]==minus[sharedFanin[s].second]) return res;
for (int i=0; i<A.size(); ++i)
{
if (A[i][j]==2) A2[i][j]=0;
else if (A[i][j]==-2) A2[i][j]=-1;
else if (A[i][j]==1) A2[i][j]=0;
else if (A[i][j]==-1) A2[i][j]=0;
else if (A[i][j]==0 && B[i]==0) A2[i][j]=1; //l-leaf
else if (A[i][j]==0 && B[i]==1) A2[i][j]=-1; //0-leaf
else assert(0);
}
if (minus[sharedFanin[s].second]==0) minus[sharedFanin[s].second]=1;
else minus[sharedFanin[s].second]=0;
res = solveLpRescursive(A2,B,ans,sharedFanin,minus,s+1);
if (res==0) return 0;
else
{
if (minus[sharedFanin[s].second]==0) minus[sharedFanin[s].second]=1;
else minus[sharedFanin[s].second]=0;
return res;
}
}
int solveLpMultiConstraint(vector< vector<int> >& A, vector<int>& B, vector<int>& ans, vector< pair<int,int> >& sharedFanin, vector<int>& minus)
{
vector<int> sfId;
for (int s=0; s<sharedFanin.size(); ++s)
{
#if 0
for (int i=0; i<A.size(); ++i)
{
for (int j=0; j<A[i].size(); ++j)
cout<<setw(2)<<A[i][j]<<" ";
cout<<"| "<<B[i]<<endl;
}cout<<endl;
#endif
if (minus[sharedFanin[s].first]==minus[sharedFanin[s].second]) continue;
sfId.push_back(s);
A.insert(A.end(),A.begin(),A.end());
B.insert(B.end(),B.begin(),B.end());
int j=sharedFanin[s].second;
for (int i=0; i<A.size()/2; ++i)
{
if (A[i][j]==2) A[i][j]=0;
else if (A[i][j]==-2) A[i][j]=-1;
A[i].insert(A[i].end()-1,M);
}
for (int i=A.size()/2; i<A.size(); ++i)
{
if (A[i][j]==2) A[i][j]=0;
else if (A[i][j]==-2) A[i][j]=-1;
else if (A[i][j]==1) A[i][j]=0;
else if (A[i][j]==-1) A[i][j]=0;
else if (A[i][j]==0 && A[i].back()==-1) A[i][j]=1; //l-leaf
else if (A[i][j]==0 && A[i].back()==1) A[i][j]=-1; //0-leaf
else assert(0);
A[i].insert(A[i].end()-1,-1*M);
B[i]-=M;
}
}
#if 0
for (int i=0; i<A.size(); ++i)
{
for (int j=0; j<A[i].size(); ++j)
cout<<setw(2)<<A[i][j]<<" ";
cout<<"| "<<B[i]<<endl;
}cout<<endl;
#endif
int res = solveLp(A,B,ans,sfId.size());
if (res==0)
{
for (int i=0; i<sfId.size(); ++i)
{
if (ans[A[0].size()-sfId.size()-1]==1)
{
int s=sfId[i];
if (minus[sharedFanin[s].second]==0) minus[sharedFanin[s].second]=1;
else minus[sharedFanin[s].second]=0;
}
ans.erase(ans.begin()+(A[0].size()-sfId.size()-1));
}
}
return res;
}
#endif
| [
"lee30sonia@gmail.com"
] | lee30sonia@gmail.com |
87c12c8fac481c94839286787f150f704ab7d5f1 | 34e0cd76aca2165857291b076e9f54dcb4156da3 | /SystemExplorer/ProcessObjectType.cpp | e8312b411a0d6af96cb8d296bc3f2d02b0fe5f16 | [
"MIT"
] | permissive | killvxk/SystemExplorer | 64385d3cb0aa9a0c0224d10abee42c6afb1cf4c1 | 7bfba28af4e543ffac0f289bc178d8421edecf0a | refs/heads/master | 2022-12-23T05:19:53.501991 | 2020-09-27T11:19:41 | 2020-09-27T11:19:41 | 299,828,765 | 0 | 1 | MIT | 2020-09-30T06:30:03 | 2020-09-30T06:30:03 | null | UTF-8 | C++ | false | false | 876 | cpp | #include "pch.h"
#include "ProcessObjectType.h"
#include "ProcessHelper.h"
ProcessObjectType::ProcessObjectType(const WinSys::ProcessManager& pm, int index, PCWSTR name) :
ObjectType(index, name), _pm(pm) {
}
CString ProcessObjectType::GetDetails(HANDLE hProcess) {
CString details;
auto pid = ::GetProcessId(hProcess);
auto name = ProcessHelper::GetProcessName(hProcess);
if (name.IsEmpty()) {
auto info = _pm.GetProcessById(pid);
if (info)
name = info->GetImageName().c_str();
}
FILETIME create, exit{}, dummy;
if (::GetProcessTimes(hProcess, &create, &exit, &dummy, &dummy)) {
details.Format(L"PID: %d (%s) Created: %s Exited: %s", pid, name,
CTime(create).Format(L"%D %X"),
exit.dwHighDateTime + exit.dwLowDateTime == 0 ? L"(running)" : CTime(exit).Format(L"%D %X"));
}
else {
details.Format(L"PID: %d (%s)", pid, name);
}
return details;
}
| [
"zodiacon@live.com"
] | zodiacon@live.com |
1bc00b4be5dda384e820d44f5f20fe53d76262d4 | b2653dd4f8fa95ff1f16117ddc523c1da503b0f8 | /src/util.h | edc042e77e6b966c15cb02784edaf243b2ec2388 | [
"MIT"
] | permissive | armcoin1857/MIRQ | e86a9e1c4adc84c87de8892b9660ac3c17fee17e | 9ebd730762fdbc8f145cb9df1beb9be64d7a353e | refs/heads/master | 2020-03-28T17:50:33.050109 | 2018-11-22T14:14:12 | 2018-11-22T14:14:12 | 148,827,863 | 1 | 7 | MIT | 2018-11-21T07:14:10 | 2018-09-14T18:34:49 | C++ | UTF-8 | C++ | false | false | 8,844 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018 MRQ Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
/**
* Server/client environment: argument handling, config file parsing,
* logging, thread wrappers
*/
#ifndef BITCOIN_UTIL_H
#define BITCOIN_UTIL_H
#if defined(HAVE_CONFIG_H)
#include "config/mrq-config.h"
#endif
#include "compat.h"
#include "tinyformat.h"
#include "utiltime.h"
#include <exception>
#include <map>
#include <stdint.h>
#include <string>
#include <vector>
#include <iterator>
#include <sstream>
#include <boost/filesystem/path.hpp>
#include <boost/thread/exceptions.hpp>
using namespace std;
//MRQ only features
extern bool fMasterNode;
extern bool fLiteMode;
extern bool fEnableSwiftTX;
extern int nSwiftTXDepth;
extern int nObfuscationRounds;
extern int nAnonymizeMrqAmount;
extern int nLiquidityProvider;
extern bool fEnableObfuscation;
extern int64_t enforceMasternodePaymentsTime;
extern std::string strMasterNodeAddr;
extern int keysLoaded;
extern bool fSucessfullyLoaded;
extern std::vector<int64_t> obfuScationDenominations;
extern std::string strBudgetMode;
extern std::map<std::string, std::string> mapArgs;
extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
extern bool fDebug;
extern bool fPrintToConsole;
extern bool fPrintToDebugLog;
extern bool fServer;
extern std::string strMiscWarning;
extern bool fLogTimestamps;
extern bool fLogIPs;
extern volatile bool fReopenDebugLog;
void SetupEnvironment();
/** Return true if log accepts specified category */
bool LogAcceptCategory(const char* category);
/** Send a string to the log output */
int LogPrintStr(const std::string& str);
#define LogPrintf(...) LogPrint(NULL, __VA_ARGS__)
/**
* When we switch to C++11, this can be switched to variadic templates instead
* of this macro-based construction (see tinyformat.h).
*/
#define MAKE_ERROR_AND_LOG_FUNC(n) \
/** Print to debug.log if -debug=category switch is given OR category is NULL. */ \
template <TINYFORMAT_ARGTYPES(n)> \
static inline int LogPrint(const char* category, const char* format, TINYFORMAT_VARARGS(n)) \
{ \
if (!LogAcceptCategory(category)) return 0; \
return LogPrintStr(tfm::format(format, TINYFORMAT_PASSARGS(n))); \
} \
/** Log error and return false */ \
template <TINYFORMAT_ARGTYPES(n)> \
static inline bool error(const char* format, TINYFORMAT_VARARGS(n)) \
{ \
LogPrintStr("ERROR: " + tfm::format(format, TINYFORMAT_PASSARGS(n)) + "\n"); \
return false; \
}
TINYFORMAT_FOREACH_ARGNUM(MAKE_ERROR_AND_LOG_FUNC)
/**
* Zero-arg versions of logging and error, these are not covered by
* TINYFORMAT_FOREACH_ARGNUM
*/
static inline int LogPrint(const char* category, const char* format)
{
if (!LogAcceptCategory(category)) return 0;
return LogPrintStr(format);
}
static inline bool error(const char* format)
{
LogPrintStr(std::string("ERROR: ") + format + "\n");
return false;
}
void PrintExceptionContinue(std::exception* pex, const char* pszThread);
void ParseParameters(int argc, const char* const argv[]);
void FileCommit(FILE* fileout);
bool TruncateFile(FILE* file, unsigned int length);
int RaiseFileDescriptorLimit(int nMinFD);
void AllocateFileRange(FILE* file, unsigned int offset, unsigned int length);
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest);
bool TryCreateDirectory(const boost::filesystem::path& p);
boost::filesystem::path GetDefaultDataDir();
const boost::filesystem::path& GetDataDir(bool fNetSpecific = true);
boost::filesystem::path GetConfigFile();
boost::filesystem::path GetMasternodeConfigFile();
#ifndef WIN32
boost::filesystem::path GetPidFile();
void CreatePidFile(const boost::filesystem::path& path, pid_t pid);
#endif
void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
#ifdef WIN32
boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate = true);
#endif
boost::filesystem::path GetTempPath();
void ShrinkDebugFile();
void runCommand(std::string strCommand);
inline bool IsSwitchChar(char c)
{
#ifdef WIN32
return c == '-' || c == '/';
#else
return c == '-';
#endif
}
/**
* Return string argument or default value
*
* @param strArg Argument to get (e.g. "-foo")
* @param default (e.g. "1")
* @return command-line argument or default value
*/
std::string GetArg(const std::string& strArg, const std::string& strDefault);
/**
* Return integer argument or default value
*
* @param strArg Argument to get (e.g. "-foo")
* @param default (e.g. 1)
* @return command-line argument (0 if invalid number) or default value
*/
int64_t GetArg(const std::string& strArg, int64_t nDefault);
/**
* Return boolean argument or default value
*
* @param strArg Argument to get (e.g. "-foo")
* @param default (true or false)
* @return command-line argument or default value
*/
bool GetBoolArg(const std::string& strArg, bool fDefault);
/**
* Set an argument if it doesn't already have a value
*
* @param strArg Argument to set (e.g. "-foo")
* @param strValue Value (e.g. "1")
* @return true if argument gets set, false if it already had a value
*/
bool SoftSetArg(const std::string& strArg, const std::string& strValue);
/**
* Set a boolean argument if it doesn't already have a value
*
* @param strArg Argument to set (e.g. "-foo")
* @param fValue Value (e.g. false)
* @return true if argument gets set, false if it already had a value
*/
bool SoftSetBoolArg(const std::string& strArg, bool fValue);
/**
* Format a string to be used as group of options in help messages
*
* @param message Group name (e.g. "RPC server options:")
* @return the formatted string
*/
std::string HelpMessageGroup(const std::string& message);
/**
* Format a string to be used as option description in help messages
*
* @param option Option message (e.g. "-rpcuser=<user>")
* @param message Option description (e.g. "Username for JSON-RPC connections")
* @return the formatted string
*/
std::string HelpMessageOpt(const std::string& option, const std::string& message);
void SetThreadPriority(int nPriority);
void RenameThread(const char* name);
/**
* Standard wrapper for do-something-forever thread functions.
* "Forever" really means until the thread is interrupted.
* Use it like:
* new boost::thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, 900000));
* or maybe:
* boost::function<void()> f = boost::bind(&FunctionWithArg, argument);
* threadGroup.create_thread(boost::bind(&LoopForever<boost::function<void()> >, "nothing", f, milliseconds));
*/
template <typename Callable>
void LoopForever(const char* name, Callable func, int64_t msecs)
{
std::string s = strprintf("mrq-%s", name);
RenameThread(s.c_str());
LogPrintf("%s thread start\n", name);
try {
while (1) {
MilliSleep(msecs);
func();
}
} catch (boost::thread_interrupted) {
LogPrintf("%s thread stop\n", name);
throw;
} catch (std::exception& e) {
PrintExceptionContinue(&e, name);
throw;
} catch (...) {
PrintExceptionContinue(NULL, name);
throw;
}
}
/**
* .. and a wrapper that just calls func once
*/
template <typename Callable>
void TraceThread(const char* name, Callable func)
{
std::string s = strprintf("mrq-%s", name);
RenameThread(s.c_str());
try {
LogPrintf("%s thread start\n", name);
func();
LogPrintf("%s thread exit\n", name);
} catch (boost::thread_interrupted) {
LogPrintf("%s thread interrupt\n", name);
throw;
} catch (std::exception& e) {
PrintExceptionContinue(&e, name);
throw;
} catch (...) {
PrintExceptionContinue(NULL, name);
throw;
}
}
#endif // BITCOIN_UTIL_H
| [
"dbraford@gmail.com"
] | dbraford@gmail.com |
a9a04426f53e80bf31af9fe3b5a5b41f43bbd861 | 58ef4939342d5253f6fcb372c56513055d589eb8 | /LemonPlayer_2nd/Source/LPView/src/MainView.cpp | 32b90bb0d89a31e02ce1d3e0768374f14f1c933c | [] | no_license | flaithbheartaigh/lemonplayer | 2d77869e4cf787acb0aef51341dc784b3cf626ba | ea22bc8679d4431460f714cd3476a32927c7080e | refs/heads/master | 2021-01-10T11:29:49.953139 | 2011-04-25T03:15:18 | 2011-04-25T03:15:18 | 50,263,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,866 | cpp | /*
============================================================================
Name : FileListView.cpp
Author : zengcity
Version : 1.0
Copyright : Your copyright notice
Description : CFileListView implementation
============================================================================
*/
#include <aknViewAppUi.h>
#include "MainView.h"
#include "MainContainer.h"
CMainView::~CMainView()
{
if (iContainer)
{
// AppUi()->RemoveFromViewStack( *this, iContainer);
delete iContainer;
}
}
void CMainView::ConstructL(CUIViewData *aData)
{
BaseConstructL();
iData = aData;
iContainer = new (ELeave) CMainContainer;
iContainer->SetData(iData);
iContainer->SetMopParent(this);
iContainer->ConstructL(ClientRect());
}
// ---------------------------------------------------------
// TUid CSymbian1View::Id()
//
// ---------------------------------------------------------
//
TUid CMainView::Id() const
{
// return KMainViewId;
return TUid::Uid(EMainView);
}
// ---------------------------------------------------------
// CSymbian1View::HandleCommandL(TInt aCommand)
// takes care of view command handling
// ---------------------------------------------------------
//
void CMainView::HandleCommandL(TInt aCommand)
{
switch (aCommand)
{
case ELemonPlayerCmdAppSaveData:
iContainer->SaveData();
break;
default:
{
AppUi()->HandleCommandL(aCommand);
break;
}
}
}
// ---------------------------------------------------------
// CSymbian1View::HandleClientRectChange()
// ---------------------------------------------------------
//
void CMainView::HandleClientRectChange()
{
if (iContainer)
{
iContainer->SetRect(ClientRect() );
}
}
// ---------------------------------------------------------
// CSymbian1View::DoActivateL(...)
//
// ---------------------------------------------------------
//
void CMainView::DoActivateL(const TVwsViewId& /*aPrevViewId*/,
TUid /*aCustomMessageId*/, const TDesC8& /*aCustomMessage*/)
{
if (iContainer)
{
// iContainer = new (ELeave) CMainContainer;
// iContainer->SetData(iData);
iContainer->SetMopParent(this);
// iContainer->ConstructL(ClientRect());
AppUi()->AddToStackL( *this, iContainer);
PlayFile();
}
}
// ---------------------------------------------------------
// CSymbian1View::DoDeactivate()
//
// ---------------------------------------------------------
//
void CMainView::DoDeactivate()
{
if (iContainer)
{
AppUi()->RemoveFromViewStack( *this, iContainer);
// delete iContainer;
// iContainer = NULL;
}
}
void CMainView::SetData(CUIViewData *aData)
{
iData = aData;
iContainer->SetData(iData);
}
void CMainView::PlayFile()
{
iContainer->PlayFile();
} | [
"zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494"
] | zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494 |
a0f2fbb4db5b51c735b5dab53f151a9544b5d30e | 63daf46402347503bdd75c9f942c93d8c807f008 | /main.cpp | 756bec961165bac810c28d2e36acb638d585bcaf | [] | no_license | KrugJu/Shrooms | 75752eddfdd747f9fa546859433016f84096b553 | 862c603a0d95deabb9b2dfda3efcae1b6698b465 | refs/heads/master | 2020-04-15T03:23:28.791113 | 2019-01-08T12:23:19 | 2019-01-08T12:23:19 | 164,345,768 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,769 | cpp | #include <stdio.h>
static int W, N, M;
static int psa[1002][1002]= {0};
static int a[1002][1002]= {0};
static int res[2];
struct coord{
int x;
int y;
};
void GetPrefixSum();
int SumOfCoords(coord array[]);
void GenerateQuader();
int main() {
int xi, yi, mi;
scanf("%d %d %d", &W, &N, &M);
for (int i = 0; i < N; i++) {
scanf("%d %d %d", &xi, &yi, &mi);
a[xi+1][yi+1] = mi;
}
GetPrefixSum();
GenerateQuader();
printf("%d %d",res[0],res[1]);
}
void GetPrefixSum()
{
for (int x = 1; x <= W; x++)
{
for (int y = 1; y <= W; y++)
{
psa[x][y] = psa[x - 1][y] + psa[x][y - 1] - psa[x - 1][y - 1] + a[x][y];
}
}
}
int SumOfCoords(coord array[])
{
int c1 = array[0].x;
int c2 = array[1].x;
int r1 = array[0].y;
int r2 = array[1].y;
return psa[c2][r2]-psa[c2][r1-1]-psa[c1-1][r2]+psa[c1-1][r1-1];
}
void GenerateQuader()
{
for(int i = 1;i<=W;i++)
{
//row
for(int i1=1;(i1+(i-1))<W;i1++)
{
//column
for(int i2=1;(i2+(i-1))<W;i2++)
{
//implement checks if size of quader is not out of bounds
//check i1+i and i2+1 to be smaller than size of forrest
coord coords[] = {{i1,i2},{i1+(i-1),i2+(i-1)}};
if(coords[0].x < W && coords[0].y < W && coords[1].x < W && coords[1].y < W) {
long sum = SumOfCoords(coords);
if (sum == M){res[0]=sum; res[1] = i; return;}
else if (sum > res[0] && sum < M) {
res[0] = sum;
res[1] = i;
}
}
}
}
}
return;
} | [
"40146720160317@litec.ac.at"
] | 40146720160317@litec.ac.at |
df1f8eb7e09aee3b81e6ac2a453e803b2b7e230c | cfeac52f970e8901871bd02d9acb7de66b9fb6b4 | /generated/src/aws-cpp-sdk-shield/source/model/CreateSubscriptionRequest.cpp | cddfb0bfdbc5d9eebcac1bfffebfc0874669e774 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | aws/aws-sdk-cpp | aff116ddf9ca2b41e45c47dba1c2b7754935c585 | 9a7606a6c98e13c759032c2e920c7c64a6a35264 | refs/heads/main | 2023-08-25T11:16:55.982089 | 2023-08-24T18:14:53 | 2023-08-24T18:14:53 | 35,440,404 | 1,681 | 1,133 | Apache-2.0 | 2023-09-12T15:59:33 | 2015-05-11T17:57:32 | null | UTF-8 | C++ | false | false | 758 | cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/shield/model/CreateSubscriptionRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Shield::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
CreateSubscriptionRequest::CreateSubscriptionRequest()
{
}
Aws::String CreateSubscriptionRequest::SerializePayload() const
{
return "{}";
}
Aws::Http::HeaderValueCollection CreateSubscriptionRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSShield_20160616.CreateSubscription"));
return headers;
}
| [
"sdavtaker@users.noreply.github.com"
] | sdavtaker@users.noreply.github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.