hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
86dff121a4ec4b6e167c4a3c5bc9ebaa9800f091 | 32,540 | cc | C++ | asv_wave_sim_gazebo_plugins/src/HydrodynamicsPlugin.cc | minzlee/asv_wave_sim | d9426e1b7b75d43f0c1bd3201e6ba62e54af968f | [
"Apache-2.0"
] | 25 | 2019-05-29T04:55:19.000Z | 2022-03-18T19:07:07.000Z | asv_wave_sim_gazebo_plugins/src/HydrodynamicsPlugin.cc | minzlee/asv_wave_sim | d9426e1b7b75d43f0c1bd3201e6ba62e54af968f | [
"Apache-2.0"
] | 12 | 2019-02-14T16:26:57.000Z | 2022-03-30T19:44:33.000Z | asv_wave_sim_gazebo_plugins/src/HydrodynamicsPlugin.cc | minzlee/asv_wave_sim | d9426e1b7b75d43f0c1bd3201e6ba62e54af968f | [
"Apache-2.0"
] | 11 | 2019-05-29T04:55:22.000Z | 2022-02-23T11:55:32.000Z | // Copyright (C) 2019 Rhys Mainwaring
//
// 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 <https://www.gnu.org/licenses/>.
#include "asv_wave_sim_gazebo_plugins/HydrodynamicsPlugin.hh"
#include "asv_wave_sim_gazebo_plugins/CGALTypes.hh"
#include "asv_wave_sim_gazebo_plugins/Convert.hh"
#include "asv_wave_sim_gazebo_plugins/Grid.hh"
#include "asv_wave_sim_gazebo_plugins/MeshTools.hh"
#include "asv_wave_sim_gazebo_plugins/Physics.hh"
#include "asv_wave_sim_gazebo_plugins/Utilities.hh"
#include "asv_wave_sim_gazebo_plugins/Wavefield.hh"
#include "asv_wave_sim_gazebo_plugins/WavefieldEntity.hh"
#include <gazebo/common/Assert.hh>
#include <gazebo/physics/physics.hh>
#include <gazebo/physics/MeshShape.hh>
#include <gazebo/physics/Shape.hh>
#include <ignition/math/Pose3.hh>
#include <ignition/math/Triangle3.hh>
#include <ignition/math/Vector3.hh>
#include <ignition/transport.hh>
#include <iostream>
#include <iomanip>
#include <string>
#include <exception>
using namespace gazebo;
namespace asv
{
GZ_REGISTER_MODEL_PLUGIN(HydrodynamicsPlugin)
///////////////////////////////////////////////////////////////////////////////
// Utilties
/// \brief Iterate over the links in a model, and create a CGAL SurfaceMesh
/// for each collison in each link.
///
/// \param[in] _model The model being processed.
/// \param[out] _links A vector holding a copy of pointers to the the model's links.
/// \param[out] _meshes A vector of vectors containing a surface mesh for each collision in a link.
void CreateCollisionMeshes(
physics::ModelPtr _model,
std::vector<physics::LinkPtr>& _links,
std::vector<std::vector<std::shared_ptr<Mesh>>>& _meshes)
{
// There will be more than one mesh per link if the link contains mutiple collisions.
// Model
GZ_ASSERT(_model != nullptr, "Invalid parameter _model");
std::string modelName(_model->GetName());
// Links
for (auto&& link : _model->GetLinks())
{
GZ_ASSERT(link != nullptr, "Link must be valid");
_links.push_back(link);
std::string linkName(link->GetName());
std::vector<std::shared_ptr<Mesh>> linkMeshes;
// Collisions
for (auto&& collision : link->GetCollisions())
{
GZ_ASSERT(collision != nullptr, "Collision must be valid");
std::string collisionName(collision->GetName());
// Shape
physics::ShapePtr shape = collision->GetShape();
GZ_ASSERT(shape != nullptr, "Shape must be valid");
gzmsg << "Shape: " << shape->TypeStr() << std::endl;
gzmsg << "Scale: " << shape->Scale() << std::endl;
gzmsg << "Type: " << std::hex << shape->GetType() << std::dec << std::endl;
if (shape->HasType(physics::Base::EntityType::BOX_SHAPE))
{
// BoxShape
gzmsg << "Type: " << "BOX_SHAPE" << std::endl;
physics::BoxShapePtr box = boost::dynamic_pointer_cast<physics::BoxShape>(shape);
GZ_ASSERT(box != nullptr, "Failed to cast Shape to BoxShape");
gzmsg << "Size: " << box->Size() << std::endl;
// Mesh
std::string meshName = std::string(modelName)
.append(".").append(linkName)
.append(".").append(collisionName)
.append(".box");
common::MeshManager::Instance()->CreateBox(
meshName,
box->Size(),
ignition::math::Vector2d(1, 1));
GZ_ASSERT(common::MeshManager::Instance()->HasMesh(meshName),
"Failed to create Mesh for BoxShape");
std::shared_ptr<Mesh> mesh = std::make_shared<Mesh>();
MeshTools::MakeSurfaceMesh(
*common::MeshManager::Instance()->GetMesh(meshName), *mesh);
GZ_ASSERT(mesh != nullptr, "Invalid Suface Mesh");
linkMeshes.push_back(mesh);
// gzmsg << "Mesh: " << mesh->GetName() << std::endl;
gzmsg << "Vertex: " << mesh->number_of_vertices() << std::endl;
}
if (shape->HasType(physics::Base::EntityType::CYLINDER_SHAPE))
{
// CylinderShape
gzmsg << "Type: " << "CYLINDER_SHAPE" << std::endl;
physics::CylinderShapePtr cylinder = boost::dynamic_pointer_cast<physics::CylinderShape>(shape);
GZ_ASSERT(cylinder != nullptr, "Failed to cast Shape to CylinderShape");
gzmsg << "Radius: " << cylinder->GetRadius() << std::endl;
gzmsg << "Length: " << cylinder->GetLength() << std::endl;
// Mesh
std::string meshName = std::string(modelName)
.append("::").append(linkName)
.append("::").append(collisionName)
.append("::cylinder");
common::MeshManager::Instance()->CreateCylinder(
meshName,
cylinder->GetRadius(), // radius
cylinder->GetLength(), // length,
1, // rings
32); // segments
GZ_ASSERT(common::MeshManager::Instance()->HasMesh(meshName),
"Failed to create Mesh for Cylinder");
std::shared_ptr<Mesh> mesh = std::make_shared<Mesh>();
MeshTools::MakeSurfaceMesh(
*common::MeshManager::Instance()->GetMesh(meshName), *mesh);
GZ_ASSERT(mesh != nullptr, "Invalid Suface Mesh");
linkMeshes.push_back(mesh);
gzmsg << "Mesh: " << meshName << std::endl;
gzmsg << "Vertex: " << mesh->number_of_vertices() << std::endl;
}
if (shape->HasType(physics::Base::EntityType::SPHERE_SHAPE))
{
// SphereShape
gzmsg << "Type: " << "SPHERE_SHAPE" << std::endl;
physics::SphereShapePtr sphere = boost::dynamic_pointer_cast<physics::SphereShape>(shape);
GZ_ASSERT(sphere != nullptr, "Failed to cast Shape to SphereShape");
gzmsg << "Radius: " << sphere->GetRadius() << std::endl;
// Mesh
std::string meshName = std::string(modelName)
.append(".").append(linkName)
.append(".").append(collisionName)
.append(".cylinder");
common::MeshManager::Instance()->CreateSphere(
meshName,
sphere->GetRadius(), // radius
8, // rings
8); // segments
GZ_ASSERT(common::MeshManager::Instance()->HasMesh(meshName),
"Failed to create Mesh for Cylinder");
std::shared_ptr<Mesh> mesh = std::make_shared<Mesh>();
MeshTools::MakeSurfaceMesh(
*common::MeshManager::Instance()->GetMesh(meshName), *mesh);
GZ_ASSERT(mesh != nullptr, "Invalid Suface Mesh");
linkMeshes.push_back(mesh);
gzmsg << "Mesh: " << meshName << std::endl;
gzmsg << "Vertex: " << mesh->number_of_vertices() << std::endl;
}
if (shape->HasType(physics::Base::EntityType::MESH_SHAPE))
{
// MeshShape
gzmsg << "Type: " << "MESH_SHAPE" << std::endl;
physics::MeshShapePtr meshShape = boost::dynamic_pointer_cast<physics::MeshShape>(shape);
GZ_ASSERT(meshShape != nullptr, "Failed to cast Shape to MeshShape");
std::string meshUri = meshShape->GetMeshURI();
std::string meshStr = common::find_file(meshUri);
gzmsg << "MeshURI: " << meshUri << std::endl;
gzmsg << "MeshStr: " << meshStr << std::endl;
// Mesh
if (!common::MeshManager::Instance()->HasMesh(meshStr))
{
gzerr << "Mesh: " << meshStr << " was not loaded"<< std::endl;
return;
}
std::shared_ptr<Mesh> mesh = std::make_shared<Mesh>();
MeshTools::MakeSurfaceMesh(
*common::MeshManager::Instance()->GetMesh(meshStr), *mesh);
GZ_ASSERT(mesh != nullptr, "Invalid Suface Mesh");
linkMeshes.push_back(mesh);
gzmsg << "Mesh: " << meshStr << std::endl;
gzmsg << "Vertex: " << mesh->number_of_vertices() << std::endl;
}
}
// Add meshes for this link
_meshes.push_back(linkMeshes);
}
}
/// \brief Transform a meshes vertex points in the world frame according to a Pose.
///
/// \param[in] _pose A pose defining a translation and rotation in the world frame.
/// \param[in] _source The original mesh to transform.
/// \param[out] _target The transformed mesh.
void ApplyPose(
const ignition::math::Pose3d& _pose,
const Mesh& _source,
Mesh& _target)
{
for (
auto&& it = std::make_pair(std::begin(_source.vertices()), std::begin(_target.vertices()));
it.first != std::end(_source.vertices()) && it.second != std::end(_target.vertices());
++it.first, ++it.second)
{
auto& v0 = *it.first;
auto& v1 = *it.second;
const Point3& p0 = _source.point(v0);
// Affine transformation
ignition::math::Vector3d ignP0(p0.x(), p0.y(), p0.z());
ignition::math::Vector3d ignP1 = _pose.Rot().RotateVector(ignP0) + _pose.Pos();
Point3& p1 = _target.point(v1);
p1 = Point3(ignP1.X(), ignP1.Y(), ignP1.Z());
}
}
/// \brief Retrive a pointer to a wavefield from the Wavefield plugin.
///
/// \param _world A pointer to the world containing the wave field.
/// \param _waveModelName The name of the wavefield model containing the wave field.
/// \return A valid wavefield if found and nullptr if not.
std::shared_ptr<const Wavefield> GetWavefield(
physics::WorldPtr _world,
const std::string& _waveModelName)
{
GZ_ASSERT(_world != nullptr, "World is null");
physics::ModelPtr wavefieldModel = _world->ModelByName(_waveModelName);
if(wavefieldModel == nullptr)
{
gzerr << "No Wavefield Model found with name '" << _waveModelName << "'." << std::endl;
return nullptr;
}
std::string wavefieldEntityName(WavefieldEntity::MakeName(_waveModelName));
physics::BasePtr base = wavefieldModel->GetChild(wavefieldEntityName);
boost::shared_ptr<WavefieldEntity> wavefieldEntity
= boost::dynamic_pointer_cast<WavefieldEntity>(base);
if (wavefieldEntity == nullptr)
{
gzerr << "Wavefield Entity is null: " << wavefieldEntityName << std::endl;
return nullptr;
}
GZ_ASSERT(wavefieldEntity->GetWavefield() != nullptr, "Wavefield is null.");
return wavefieldEntity->GetWavefield();
}
///////////////////////////////////////////////////////////////////////////////
// HydrodynamicsLinkData
/// \internal
/// \brief A class to hold data required for hydrodynamics calculations
/// for each link in a model.
class HydrodynamicsLinkData
{
/// \brief A Link pointer.
public: physics::LinkPtr link;
/// \brief The wavefield sampler for this link.
public: std::shared_ptr<WavefieldSampler> wavefieldSampler;
/// \brief The initial meshes for this link.
public: std::vector<std::shared_ptr<Mesh>> initLinkMeshes;
/// \brief The transformed meshes for this link.
public: std::vector<std::shared_ptr<Mesh>> linkMeshes;
/// \brief Objects to compute the hydrodynamics forces for each link mesh.
public: std::vector<std::shared_ptr<Hydrodynamics>> hydrodynamics;
/// \brief Marker messages for the water patch.
public: ignition::msgs::Marker waterPatchMsg;
/// \brief Marker messages for the waterline.
public: std::vector<ignition::msgs::Marker> waterlineMsgs;
/// \brief Marker messages for the underwater portion of the mesh.
public: std::vector<ignition::msgs::Marker> underwaterSurfaceMsgs;
};
///////////////////////////////////////////////////////////////////////////////
// HydrodynamicsPluginPrivate
/// \internal
/// \brief A class to manage the private data required by the HydrodynamicsPlugin.
class HydrodynamicsPluginPrivate
{
/// \brief World pointer.
public: physics::WorldPtr world;
/// \brief Model pointer.
public: physics::ModelPtr model;
/// \brief Pointer to the World wavefield.
public: std::shared_ptr<const Wavefield> wavefield;
/// \brief Hydrodynamics parameters for the entire model.
public: std::shared_ptr<HydrodynamicsParameters> hydroParams;
/// \brief Hydrodynamic physics for each Link.
public: std::vector<std::shared_ptr<HydrodynamicsLinkData>> hydroData;
/// \brief The wave model name. This is used to retrieve a pointer to the wave field.
public: std::string waveModelName;
/// \brief Show the water patch markers.
public: bool showWaterPatch;
/// \brief Show the waterline markers.
public: bool showWaterline;
/// \brief Show the underwater surface.
public: bool showUnderwaterSurface;
/// \brief The update rate for visual markers.
public: double updateRate;
/// \brief Previous update time.
public: common::Time prevTime;
/// \brief Connection to the World Update events.
public: event::ConnectionPtr updateConnection;
/// \brief Ignition transport node for igntopic "/marker".
public: ignition::transport::Node ignNode;
/// \brief Gazebo transport node.
public: transport::NodePtr gzNode;
/// \brief Subscribe to gztopic "~/hydrodynamics".
public: transport::SubscriberPtr hydroSub;
};
///////////////////////////////////////////////////////////////////////////////
// HydrodynamicsPlugin
HydrodynamicsPlugin::~HydrodynamicsPlugin()
{
this->Fini();
}
HydrodynamicsPlugin::HydrodynamicsPlugin() :
ModelPlugin(),
data(new HydrodynamicsPluginPrivate())
{
}
void HydrodynamicsPlugin::Load(physics::ModelPtr _model, sdf::ElementPtr _sdf)
{
// @DEBUG_INFO
// gzmsg << "Load HydrodynamicsPlugin" << std::endl;
GZ_ASSERT(_model != nullptr, "Invalid parameter _model");
GZ_ASSERT(_sdf != nullptr, "Invalid parameter _sdf");
// Capture the Model & World pointers
this->data->model = _model;
this->data->world = _model->GetWorld();
GZ_ASSERT(this->data->world != nullptr, "Model has invalid World");
// Transport
this->data->gzNode = transport::NodePtr(new transport::Node());
this->data->gzNode->Init(this->data->world->Name() + "/" + this->data->model->GetName());
// Subscribers
this->data->hydroSub = this->data->gzNode->Subscribe(
"~/hydrodynamics", &HydrodynamicsPlugin::OnHydrodynamicsMsg, this);
// Bind the update callback to the world update event
this->data->updateConnection = event::Events::ConnectWorldUpdateBegin(
std::bind(&HydrodynamicsPlugin::OnUpdate, this));
// Wave Model
this->data->waveModelName = Utilities::SdfParamString(*_sdf, "wave_model", "");
// Hydrodynamics parameters
this->data->hydroParams.reset(new HydrodynamicsParameters());
this->data->hydroParams->SetFromSDF(*_sdf);
// Markers
if (_sdf->HasElement("markers"))
{
sdf::ElementPtr sdfMarkers = _sdf->GetElement("markers");
this->data->updateRate = Utilities::SdfParamDouble(*sdfMarkers, "update_rate", 30.0);
this->data->showWaterPatch = Utilities::SdfParamBool(*sdfMarkers, "water_patch", false);
this->data->showWaterline = Utilities::SdfParamBool(*sdfMarkers, "waterline", false);
this->data->showUnderwaterSurface = Utilities::SdfParamBool(*sdfMarkers, "underwater_surface", false);
}
}
void HydrodynamicsPlugin::OnUpdate()
{
this->UpdatePhysics();
this->UpdateMarkers();
}
void HydrodynamicsPlugin::UpdatePhysics()
{
// Update wavefield
this->data->wavefield = GetWavefield(
this->data->world, this->data->waveModelName);
if (this->data->wavefield == nullptr)
{
gzerr << "Wavefield is NULL" << std::endl;
return;
}
for (auto&& hd : this->data->hydroData)
{
GZ_ASSERT(hd->link != nullptr, "Link is NULL");
// The link pose is required for the water patch, the CoM pose for dynamics.
ignition::math::Pose3d linkPose = hd->link->WorldPose();
ignition::math::Pose3d linkCoMPose = hd->link->WorldCoGPose();
// Update water patch
hd->wavefieldSampler->ApplyPose(linkPose);
hd->wavefieldSampler->UpdatePatch();
// auto waterPatch = hd->wavefieldSampler->GetWaterPatch();
// RigidBody - the pose of the CoM is required for the dynamics.
Vector3 linVelocity = ToVector3(hd->link->WorldLinearVel());
Vector3 angVelocity = ToVector3(hd->link->WorldAngularVel());
Vector3 linVelocityCoM = ToVector3(hd->link->WorldCoGLinearVel());
// Meshes
size_t nSubTri = 0;
for (size_t j=0; j<hd->linkMeshes.size(); ++j)
{
// Update link mesh
ApplyPose(linkPose, *hd->initLinkMeshes[j], *hd->linkMeshes[j]);
// Update hydrodynamics
hd->hydrodynamics[j]->Update(
hd->wavefieldSampler, linkCoMPose, linVelocity, angVelocity);
// Apply forces to the Link
auto force = ToIgn(hd->hydrodynamics[j]->Force());
if (force.IsFinite())
{
hd->link->AddForce(force);
}
// Apply torques to the link
auto torque = ToIgn(hd->hydrodynamics[j]->Torque());
if (torque.IsFinite())
{
hd->link->AddTorque(torque);
}
// Info for Markers
nSubTri += hd->hydrodynamics[j]->GetSubmergedTriangles().size();
// @DEBUG_INFO
// gzmsg << "Link: " << hd->link->GetName() << std::endl;
// gzmsg << "Position: " << linkPose.Pos() << std::endl;
// gzmsg << "Rotation: " << linkPose.Rot().Euler() << std::endl;
// gzmsg << "SubTriCount: " << nSubTri << std::endl;
// gzmsg << "Force: " << force << std::endl;
// gzmsg << "Torque: " << torque << std::endl;
}
}
}
void HydrodynamicsPlugin::UpdateMarkers()
{
std::string topicName("/marker");
// Throttle update [30 FPS by default]
auto updatePeriod = 1.0/this->data->updateRate;
auto currentTime = this->data->world->SimTime();
if ((currentTime - this->data->prevTime).Double() < updatePeriod)
{
return;
}
this->data->prevTime = currentTime;
if (this->data->showWaterPatch)
this->UpdateWaterPatchMarkers();
if (this->data->showWaterline)
this->UpdateWaterlineMarkers();
if (this->data->showUnderwaterSurface)
this->UpdateUnderwaterSurfaceMarkers();
}
void HydrodynamicsPlugin::UpdateWaterPatchMarkers()
{
std::string topicName("/marker");
for (auto&& hd : this->data->hydroData)
{
auto& grid = *hd->wavefieldSampler->GetWaterPatch();
hd->waterPatchMsg.mutable_point()->Clear();
for (size_t ix=0; ix<grid.GetCellCount()[0]; ++ix)
{
for (size_t iy=0; iy<grid.GetCellCount()[1]; ++iy)
{
for (size_t k=0; k<2; ++k)
{
Triangle tri = grid.GetTriangle(ix, iy, k);
ignition::msgs::Set(hd->waterPatchMsg.add_point(), ToIgn(tri[0]));
ignition::msgs::Set(hd->waterPatchMsg.add_point(), ToIgn(tri[1]));
ignition::msgs::Set(hd->waterPatchMsg.add_point(), ToIgn(tri[2]));
}
}
}
this->data->ignNode.Request(topicName, hd->waterPatchMsg);
}
}
void HydrodynamicsPlugin::UpdateWaterlineMarkers()
{
std::string topicName("/marker");
for (auto&& hd : this->data->hydroData)
{
for (size_t j=0; j<hd->linkMeshes.size(); ++j)
{
hd->waterlineMsgs[j].mutable_point()->Clear();
if (hd->hydrodynamics[j]->GetWaterline().empty())
{
// @TODO workaround. The previous marker is not cleared if a cleared point list is published.
ignition::msgs::Set(hd->waterlineMsgs[j].add_point(), ignition::math::Vector3d::Zero);
ignition::msgs::Set(hd->waterlineMsgs[j].add_point(), ignition::math::Vector3d::Zero);
}
for (auto&& line : hd->hydrodynamics[j]->GetWaterline())
{
ignition::msgs::Set(hd->waterlineMsgs[j].add_point(), ToIgn(line.point(0)));
ignition::msgs::Set(hd->waterlineMsgs[j].add_point(), ToIgn(line.point(1)));
}
this->data->ignNode.Request(topicName, hd->waterlineMsgs[j]);
}
}
}
void HydrodynamicsPlugin::UpdateUnderwaterSurfaceMarkers()
{
std::string topicName("/marker");
for (auto&& hd : this->data->hydroData)
{
for (size_t j=0; j<hd->linkMeshes.size(); ++j)
{
hd->underwaterSurfaceMsgs[j].mutable_point()->Clear();
if (hd->hydrodynamics[j]->GetSubmergedTriangles().empty())
{
ignition::msgs::Set(hd->underwaterSurfaceMsgs[j].add_point(), ignition::math::Vector3d::Zero);
ignition::msgs::Set(hd->underwaterSurfaceMsgs[j].add_point(), ignition::math::Vector3d::Zero);
ignition::msgs::Set(hd->underwaterSurfaceMsgs[j].add_point(), ignition::math::Vector3d::Zero);
}
for (auto&& tri : hd->hydrodynamics[j]->GetSubmergedTriangles())
{
ignition::msgs::Set(hd->underwaterSurfaceMsgs[j].add_point(), ToIgn(tri[0]));
ignition::msgs::Set(hd->underwaterSurfaceMsgs[j].add_point(), ToIgn(tri[1]));
ignition::msgs::Set(hd->underwaterSurfaceMsgs[j].add_point(), ToIgn(tri[2]));
}
this->data->ignNode.Request(topicName, hd->underwaterSurfaceMsgs[j]);
}
}
}
void HydrodynamicsPlugin::Init()
{
// @DEBUG_INFO
// gzmsg << "Init HydrodynamicsPlugin" << std::endl;
this->HydrodynamicsPlugin::InitPhysics();
this->HydrodynamicsPlugin::InitMarkers();
}
void HydrodynamicsPlugin::InitPhysics()
{
// Wavefield
this->data->wavefield = GetWavefield(
this->data->world, this->data->waveModelName);
if (this->data->wavefield == nullptr)
{
gzerr << "Wavefield is NULL" << std::endl;
return;
}
std::string modelName(this->data->model->GetName());
// Populate link meshes
std::vector<physics::LinkPtr> links;
std::vector<std::vector<std::shared_ptr<Mesh>>> meshes;
CreateCollisionMeshes(this->data->model, links, meshes);
gzmsg << "links: " << links.size() << std::endl;
gzmsg << "meshes: " << meshes.size() << std::endl;
for (size_t i=0; i<links.size(); ++i)
{
// Create storage
size_t meshCount = meshes[i].size();
std::shared_ptr<HydrodynamicsLinkData> hd(new HydrodynamicsLinkData);
this->data->hydroData.push_back(hd);
hd->initLinkMeshes.resize(meshCount);
hd->linkMeshes.resize(meshCount);
hd->hydrodynamics.resize(meshCount);
hd->waterlineMsgs.resize(meshCount);
hd->underwaterSurfaceMsgs.resize(meshCount);
// Wavefield and Link
hd->link = links[i];
// The link pose is required for the water patch, the CoM pose for dynamics.
ignition::math::Pose3d linkPose = hd->link->WorldPose();
ignition::math::Pose3d linkCoMPose = hd->link->WorldCoGPose();
// Water patch grid
ignition::math::Box boundingBox = hd->link->CollisionBoundingBox();
double patchSize = 1.5 * boundingBox.Size().Length();
gzmsg << "Water patch size: " << patchSize << std::endl;
std::shared_ptr<Grid> initWaterPatch(new Grid({patchSize, patchSize}, { 4, 4 }));
// WavefieldSampler - this is updated by the pose of the link (not the CoM).
hd->wavefieldSampler.reset(new WavefieldSampler(
this->data->wavefield, initWaterPatch));
hd->wavefieldSampler->ApplyPose(linkPose);
hd->wavefieldSampler->UpdatePatch();
// RigidBody - the pose of the CoM is required for the dynamics.
Vector3 linVelocity = ToVector3(hd->link->WorldLinearVel());
Vector3 angVelocity = ToVector3(hd->link->WorldAngularVel());
Vector3 linVelocityCoM = ToVector3(hd->link->WorldCoGLinearVel());
for (size_t j=0; j<meshCount; ++j)
{
// Mesh (SurfaceMesh copy performs a deep copy of all properties)
std::shared_ptr<Mesh> initLinkMesh = meshes[i][j];
std::shared_ptr<Mesh> linkMesh = std::make_shared<Mesh>(*initLinkMesh);
GZ_ASSERT(linkMesh != nullptr, "Invalid Mesh returned from CopyMesh");
// Mesh
hd->initLinkMeshes[j] = initLinkMesh;
hd->linkMeshes[j] = linkMesh;
// Update link mesh
ApplyPose(linkPose, *hd->initLinkMeshes[j], *hd->linkMeshes[j]);
// Initialise Hydrodynamics
hd->hydrodynamics[j].reset(
new Hydrodynamics(
this->data->hydroParams,
hd->linkMeshes[j],
hd->wavefieldSampler));
hd->hydrodynamics[j]->Update(
hd->wavefieldSampler, linkCoMPose, linVelocity, angVelocity);
}
}
}
void HydrodynamicsPlugin::InitMarkers()
{
if (this->data->showWaterPatch)
this->InitWaterPatchMarkers();
if (this->data->showWaterline)
this->InitWaterlineMarkers();
if (this->data->showUnderwaterSurface)
this->InitUnderwaterSurfaceMarkers();
}
void HydrodynamicsPlugin::InitWaterPatchMarkers()
{
std::string modelName(this->data->model->GetName());
int markerId = 0;
for (auto&& hd : this->data->hydroData)
{
hd->waterPatchMsg.set_ns(modelName + "::water_patch");
hd->waterPatchMsg.set_id(markerId++);
hd->waterPatchMsg.set_action(ignition::msgs::Marker::ADD_MODIFY);
hd->waterPatchMsg.set_type(ignition::msgs::Marker::TRIANGLE_LIST);
std::string waveMat("Gazebo/BlueTransparent");
ignition::msgs::Material *waveMatMsg = hd->waterPatchMsg.mutable_material();
GZ_ASSERT(waveMatMsg != nullptr, "Invalid Material pointer from waterPatchMsg");
waveMatMsg->mutable_script()->set_name(waveMat);
}
}
void HydrodynamicsPlugin::InitWaterlineMarkers()
{
std::string modelName(this->data->model->GetName());
int markerId = 0;
for (auto&& hd : this->data->hydroData)
{
for (size_t j=0; j<hd->linkMeshes.size(); ++j)
{
hd->waterlineMsgs[j].set_ns(modelName + "::waterline");
hd->waterlineMsgs[j].set_id(markerId++);
hd->waterlineMsgs[j].set_action(ignition::msgs::Marker::ADD_MODIFY);
hd->waterlineMsgs[j].set_type(ignition::msgs::Marker::LINE_LIST);
std::string lineMat("Gazebo/Black");
ignition::msgs::Material *lineMatMsg = hd->waterlineMsgs[j].mutable_material();
GZ_ASSERT(lineMatMsg != nullptr, "Invalid Material pointer from waterlineMsgs");
lineMatMsg->mutable_script()->set_name(lineMat);
}
}
}
void HydrodynamicsPlugin::InitUnderwaterSurfaceMarkers()
{
std::string modelName(this->data->model->GetName());
int markerId = 0;
for (auto&& hd : this->data->hydroData)
{
for (size_t j=0; j<hd->linkMeshes.size(); ++j)
{
hd->underwaterSurfaceMsgs[j].set_ns(modelName + "::submerged_triangles");
hd->underwaterSurfaceMsgs[j].set_id(markerId++);
hd->underwaterSurfaceMsgs[j].set_action(ignition::msgs::Marker::ADD_MODIFY);
hd->underwaterSurfaceMsgs[j].set_type(ignition::msgs::Marker::TRIANGLE_LIST);
std::string triMat("Gazebo/Blue");
ignition::msgs::Material *triMatMsg = hd->underwaterSurfaceMsgs[j].mutable_material();
GZ_ASSERT(triMatMsg != nullptr, "Invalid Material pointer from underwaterSurfaceMsgs");
triMatMsg->mutable_script()->set_name(triMat);
}
}
}
void HydrodynamicsPlugin::Reset()
{
// Reset time
this->data->prevTime = this->data->world->SimTime();
this->ResetPhysics();
this->ResetMarkers();
}
void HydrodynamicsPlugin::ResetPhysics()
{
// no-op
}
void HydrodynamicsPlugin::ResetMarkers()
{
// Reset markers
if (this->data->showWaterPatch)
this->ResetWaterPatchMarkers();
if (this->data->showWaterline)
this->ResetWaterlineMarkers();
if (this->data->showUnderwaterSurface)
this->ResetUnderwaterSurfaceMarkers();
}
void HydrodynamicsPlugin::ResetWaterPatchMarkers()
{
std::string topicName("/marker");
for (auto&& hd : this->data->hydroData)
{
hd->waterPatchMsg.mutable_point()->Clear();
ignition::msgs::Set(hd->waterPatchMsg.add_point(), ignition::math::Vector3d::Zero);
ignition::msgs::Set(hd->waterPatchMsg.add_point(), ignition::math::Vector3d::Zero);
ignition::msgs::Set(hd->waterPatchMsg.add_point(), ignition::math::Vector3d::Zero);
this->data->ignNode.Request(topicName, hd->waterPatchMsg);
}
}
void HydrodynamicsPlugin::ResetWaterlineMarkers()
{
std::string topicName("/marker");
for (auto&& hd : this->data->hydroData)
{
for (size_t j=0; j<hd->linkMeshes.size(); ++j)
{
hd->waterlineMsgs[j].mutable_point()->Clear();
ignition::msgs::Set(hd->waterlineMsgs[j].add_point(), ignition::math::Vector3d::Zero);
ignition::msgs::Set(hd->waterlineMsgs[j].add_point(), ignition::math::Vector3d::Zero);
this->data->ignNode.Request(topicName, hd->waterlineMsgs[j]);
}
}
}
void HydrodynamicsPlugin::ResetUnderwaterSurfaceMarkers()
{
std::string topicName("/marker");
for (auto&& hd : this->data->hydroData)
{
for (size_t j=0; j<hd->linkMeshes.size(); ++j)
{
hd->underwaterSurfaceMsgs[j].mutable_point()->Clear();
ignition::msgs::Set(hd->underwaterSurfaceMsgs[j].add_point(), ignition::math::Vector3d::Zero);
ignition::msgs::Set(hd->underwaterSurfaceMsgs[j].add_point(), ignition::math::Vector3d::Zero);
ignition::msgs::Set(hd->underwaterSurfaceMsgs[j].add_point(), ignition::math::Vector3d::Zero);
this->data->ignNode.Request(topicName, hd->underwaterSurfaceMsgs[j]);
}
}
}
void HydrodynamicsPlugin::Fini()
{
this->FiniPhysics();
this->FiniMarkers();
}
void HydrodynamicsPlugin::FiniPhysics()
{
// no-op
}
void HydrodynamicsPlugin::FiniMarkers()
{
if (this->data->showWaterPatch)
this->FiniWaterPatchMarkers();
if (this->data->showWaterline)
this->FiniWaterlineMarkers();
if (this->data->showUnderwaterSurface)
this->FiniUnderwaterSurfaceMarkers();
}
void HydrodynamicsPlugin::FiniWaterPatchMarkers()
{
std::string topicName("/marker");
for (auto&& hd : this->data->hydroData)
{
hd->waterPatchMsg.set_action(ignition::msgs::Marker::DELETE_MARKER);
this->data->ignNode.Request(topicName, hd->waterPatchMsg);
}
}
void HydrodynamicsPlugin::FiniWaterlineMarkers()
{
std::string topicName("/marker");
for (auto&& hd : this->data->hydroData)
{
for (size_t j=0; j<hd->linkMeshes.size(); ++j)
{
hd->waterlineMsgs[j].set_action(ignition::msgs::Marker::DELETE_MARKER);
this->data->ignNode.Request(topicName, hd->waterlineMsgs[j]);
}
}
}
void HydrodynamicsPlugin::FiniUnderwaterSurfaceMarkers()
{
std::string topicName("/marker");
for (auto&& hd : this->data->hydroData)
{
for (size_t j=0; j<hd->linkMeshes.size(); ++j)
{
hd->underwaterSurfaceMsgs[j].set_action(ignition::msgs::Marker::DELETE_MARKER);
this->data->ignNode.Request(topicName, hd->underwaterSurfaceMsgs[j]);
}
}
}
void HydrodynamicsPlugin::OnHydrodynamicsMsg(ConstParam_VPtr &_msg)
{
GZ_ASSERT(_msg != nullptr, "Hydrodynamics message must not be null");
// Update hydrodynamics params
auto& hydroParams = *this->data->hydroParams;
hydroParams.SetFromMsg(*_msg);
// @DEBUG_INFO
gzmsg << "Hydrodynamics Model received message on topic ["
<< this->data->hydroSub->GetTopic() << "]" << std::endl;
hydroParams.DebugPrint();
}
} // namespace gazebo
| 35.837004 | 111 | 0.619852 | minzlee |
86e0b4c1b97c1c8ba62c9f80f7a981c8a15b2a9b | 6,431 | cpp | C++ | src/Libraries/Analytics.FaceAnalyzer/FaceAnalyzer.cpp | digitalmacgyver/viblio_faces | a1066a59bf2f7dba434013588519f2486eac976d | [
"Xnet",
"Linux-OpenIB",
"X11"
] | null | null | null | src/Libraries/Analytics.FaceAnalyzer/FaceAnalyzer.cpp | digitalmacgyver/viblio_faces | a1066a59bf2f7dba434013588519f2486eac976d | [
"Xnet",
"Linux-OpenIB",
"X11"
] | null | null | null | src/Libraries/Analytics.FaceAnalyzer/FaceAnalyzer.cpp | digitalmacgyver/viblio_faces | a1066a59bf2f7dba434013588519f2486eac976d | [
"Xnet",
"Linux-OpenIB",
"X11"
] | null | null | null | /*
The entry point into the application. Parses command line options (or config files) and sets up the program
flow based on said options
Date: 01/07/2013
Author: Jason Catchpole (jason@viblio.com)
*/
#include "FaceAnalyzer.h"
#include "FaceAnalyzerConfiguration.h"
#include "TrackingController.h"
#include "FaceDetectionDetails.h"
#include "FaceDetector_Orbeus.h"
#include "FileSystem/FileSystem.h"
#include <boost/any.hpp>
#include <stdexcept>
#include <opencv2/opencv.hpp>
#include <chrono>
#include <future>
#include <iostream>
#include <boost/log/trivial.hpp>
using namespace std;
using namespace cv;
namespace Analytics
{
namespace FaceAnalyzer
{
// pass in some config information or have a global configuration settings object
FaceAnalysis::FaceAnalysis(FaceAnalyzerConfiguration *faceAnalyzerConfig)
{
if( faceAnalyzerConfig == NULL )
{
BOOST_LOG_TRIVIAL(error) << "Error: Face analyzer config was NULL, cannot continue analysis";
throw runtime_error("Face analyzer config was NULL");
}
if( !faceAnalyzerConfig->faceThumbnailOutputPath.empty() )
{
// if they specified an output path for thumbnails then make sure it exists, if it doesn't
// its an error so we will throw an exception (perhaps in future we could create the path?)
if( !FileSystem::DirectoryExists(faceAnalyzerConfig->faceThumbnailOutputPath) )
FileSystem::CreateDirectory(faceAnalyzerConfig->faceThumbnailOutputPath);
//throw runtime_error("Specified output thumbnail directory does not exist");
}
//m_faceDetector.reset( new FaceDetector_OpenCV(faceAnalyzerConfig->faceDetectorCascadeFile, faceAnalyzerConfig->eyeDetectorCascadeFile) );
if( faceAnalyzerConfig->faceDetectorType == FaceDetector::FaceDetector_Neurotech )
m_faceDetector.reset( new FaceDetector_Neurotech(faceAnalyzerConfig));
else if( faceAnalyzerConfig->faceDetectorType == FaceDetector::FaceDetector_Orbeus )
m_faceDetector.reset( new FaceDetector_Orbeus(faceAnalyzerConfig));
else if( faceAnalyzerConfig->faceDetectorType == FaceDetector::FaceDetector_OpenCV )
m_faceDetector.reset( new FaceDetector_OpenCV(faceAnalyzerConfig));
else
throw runtime_error("Unknown face detector type");
m_trackingController.reset( new TrackingController(faceAnalyzerConfig) );
m_faceDetectionFrequency = faceAnalyzerConfig->faceDetectionFrequency;
m_currentFrameNumber = 0;
m_imageRescaleFactor = faceAnalyzerConfig->imageRescaleFactor;
m_renderVisualization = faceAnalyzerConfig->renderVisualization;
}
FaceAnalysis::~FaceAnalysis()
{
}
void FaceAnalysis::Process(const Mat &frame, uint64_t frameTimestamp)
{
Mat resizedFrame;
Frame frameInfo(frame);
//const int DETECTION_WIDTH = 960;
// Performs much faster and doesn't seem to lose much in the
// way of faces.
const int DETECTION_WIDTH = 480;
float scale;
if(frame.cols > DETECTION_WIDTH)
scale = frame.cols/(float) DETECTION_WIDTH;
else
scale = 1.0;
frameInfo.setscale((scale));
resizedFrame = frameInfo.GetScaledMat();
auto start = std::chrono::monotonic_clock::now();
// multithreaded version - do 2 things in parallel here
// 1. Perform face detection
std::future<vector<FaceDetectionDetails>> detectedFacesFuture;
if( m_currentFrameNumber%m_faceDetectionFrequency == 0 )
{
try
{
// its a pity but we have to make use of the underlying Face Detector that is managed by the unique_ptr, but
// std::async doesn't seem to like it any other way
detectedFacesFuture = std::async(std::launch::async, &Analytics::FaceAnalyzer::FaceDetector::Detect, m_faceDetector.get(), resizedFrame,false);
}
catch(Exception e)
{
BOOST_LOG_TRIVIAL(error) << "Exception caught while attempting to perform face detection: " << e.msg;
}
}
// 2. Pass the frame off to the tracking controller to update any active trackers
std::future<void> trackingFuture = std::async(std::launch::async, &Analytics::FaceAnalyzer::TrackingController::Process, m_trackingController.get(),frameTimestamp,frameInfo);
// make sure the detector and the tracking controller have been called
if( detectedFacesFuture.valid() )
detectedFacesFuture.wait();
trackingFuture.wait();
vector<FaceDetectionDetails> detectedFaces;
if( detectedFacesFuture.valid() )
{
try
{
detectedFaces = detectedFacesFuture.get();
}
catch(Exception e)
{
BOOST_LOG_TRIVIAL(error) << "Exception caught while attempting to get face detection results: " << e.msg;
}
}
/* // Single threaded version
vector<FaceDetectionDetails> detectedFaces;
if( m_currentFrameNumber%m_faceDetectionFrequency == 0 )
detectedFaces = m_faceDetector->Detect(resizedFrame);
m_trackingController->Process(resizedFrame, frameTimestamp);
*/
auto end = std::chrono::monotonic_clock::now();
auto diff = end - start;
//std::cout << "Detection + tracking update took " << std::chrono::duration <double, std::milli> (diff).count() << " ms" << std::endl;
// Now examine any detected faces to determine if they are new faces or ones that are already being tracked (the tracking controller can tell you if they are new or not)
if( detectedFaces.size() > 0 )
{
//cout <<"Detected Faces: "<<detectedFaces.size()<<endl;
// iterate over all the new detections for this frame
for( auto startIter=detectedFaces.begin(); startIter!=detectedFaces.end(); ++startIter)
{
// determine if we have detected a new object to track or an existing one we are already tracking
if( !m_trackingController->IsAlreadyBeingTracked((*startIter).faceRect) )
{
// we've found a new object, better start tracking it
m_trackingController->AddNewTrack(resizedFrame, frameTimestamp, (*startIter).faceRect);
}
// else do nothing as we are already tracking this one
}
}
// now see if we need to render any visualizations
if( m_renderVisualization )
{
Mat frameCopy = resizedFrame.clone();
m_trackingController->RenderVisualization(frameCopy);
if( detectedFaces.size() > 0 )
m_faceDetector->RenderVisualization(frameCopy, detectedFaces);
namedWindow("Visualization");
imshow("Visualization", frameCopy);
waitKey(2);
}
m_currentFrameNumber++;
}
void FaceAnalysis::GetOutput(Jzon::Object*& root)
{
m_trackingController->GetOutput(root);
}
// end of namespaces
}
}
| 33.321244 | 176 | 0.735033 | digitalmacgyver |
86e7afa82e18b86e1b68a3d1ca0e4161a7aaccf2 | 3,019 | hpp | C++ | src/auth.hpp | planetbeing/cpp-driver | 90b683cb7fce9ab480765f8ed50185af53df791c | [
"Apache-2.0"
] | null | null | null | src/auth.hpp | planetbeing/cpp-driver | 90b683cb7fce9ab480765f8ed50185af53df791c | [
"Apache-2.0"
] | null | null | null | src/auth.hpp | planetbeing/cpp-driver | 90b683cb7fce9ab480765f8ed50185af53df791c | [
"Apache-2.0"
] | null | null | null | /*
Copyright (c) 2015 DataStax
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __CASS_AUTH_HPP_INCLUDED__
#define __CASS_AUTH_HPP_INCLUDED__
#include "macros.hpp"
#include "address.hpp"
#include "buffer.hpp"
#include "ref_counted.hpp"
#include <map>
#include <string>
namespace cass {
class V1Authenticator {
public:
V1Authenticator() {}
virtual ~V1Authenticator() {}
typedef std::map<std::string, std::string> Credentials;
virtual void get_credentials(Credentials* credentials) = 0;
private:
DISALLOW_COPY_AND_ASSIGN(V1Authenticator);
};
class Authenticator {
public:
Authenticator() {}
virtual ~Authenticator() {}
virtual std::string initial_response() = 0;
// TODO(mpenick): Do these need to know the difference between a
// NULL token and an empty token?
virtual std::string evaluate_challenge(const std::string& challenge) = 0;
virtual void on_authenticate_success(const std::string& token) = 0;
private:
DISALLOW_COPY_AND_ASSIGN(Authenticator);
};
class PlainTextAuthenticator : public V1Authenticator, public Authenticator {
public:
PlainTextAuthenticator(const std::string& username,
const std::string& password)
: username_(username)
, password_(password) {}
virtual void get_credentials(Credentials* credentials);
virtual std::string initial_response();
virtual std::string evaluate_challenge(const std::string& challenge);
virtual void on_authenticate_success(const std::string& token);
private:
const std::string& username_;
const std::string& password_;
};
class AuthProvider : public RefCounted<AuthProvider> {
public:
AuthProvider()
: RefCounted<AuthProvider>() {}
virtual ~AuthProvider() {}
virtual V1Authenticator* new_authenticator_v1(Address host) const { return NULL; }
virtual Authenticator* new_authenticator(Address host) const { return NULL; }
private:
DISALLOW_COPY_AND_ASSIGN(AuthProvider);
};
class PlainTextAuthProvider : public AuthProvider {
public:
PlainTextAuthProvider(const std::string& username,
const std::string& password)
: username_(username)
, password_(password) {}
virtual V1Authenticator* new_authenticator_v1(Address host) const {
return new PlainTextAuthenticator(username_, password_);
}
virtual Authenticator* new_authenticator(Address host) const {
return new PlainTextAuthenticator(username_, password_);
}
private:
std::string username_;
std::string password_;
};
} // namespace cass
#endif
| 26.955357 | 84 | 0.741968 | planetbeing |
86e8170aa89ead1bc561f5d3049344f1d5b59f38 | 2,464 | cc | C++ | src/engine/json/test/TestEnumMapLoader.cc | aburgm/freeisle | 5175897b31e471b4cf9bc2a9be7a88f8b4201d2a | [
"MIT"
] | 1 | 2021-05-24T00:31:20.000Z | 2021-05-24T00:31:20.000Z | src/engine/json/test/TestEnumMapLoader.cc | aburgm/freeisle | 5175897b31e471b4cf9bc2a9be7a88f8b4201d2a | [
"MIT"
] | null | null | null | src/engine/json/test/TestEnumMapLoader.cc | aburgm/freeisle | 5175897b31e471b4cf9bc2a9be7a88f8b4201d2a | [
"MIT"
] | null | null | null | #include "core/EnumMap.hh"
#include "json/LoadUtil.hh"
#include "json/Loader.hh"
#include "core/test/util/Util.hh"
#include <gtest/gtest.h>
namespace {
enum class TestEnum { Enum1, Enum2, Enum3, Num };
constexpr freeisle::core::EnumEntry<TestEnum> entries[] = {
{TestEnum::Enum1, "Enum1"},
{TestEnum::Enum2, "Enum2"},
{TestEnum::Enum3, "Enum3"}};
constexpr freeisle::core::EnumMap<const char *, TestEnum> names =
get_enum_names(entries);
struct TestStruct {
freeisle::core::EnumMap<uint32_t, TestEnum> map{};
};
struct TestHandler {
TestStruct &test;
void load(freeisle::json::loader::Context &ctx, Json::Value &value) {
freeisle::json::loader::EnumMapLoader<uint32_t, TestEnum> enum_map_loader(
test.map, names);
freeisle::json::loader::load_object(ctx, value, "map", enum_map_loader);
}
};
} // namespace
TEST(EnumMapLoader, NotExist) {
TestStruct test;
TestHandler handler{test};
const std::string text = "{}";
std::vector<uint8_t> data(text.begin(), text.end());
ASSERT_THROW_KEEP_AS_E(
freeisle::json::loader::load_root_object(data, handler),
freeisle::json::loader::Error) {
EXPECT_EQ(e.path(), "");
EXPECT_EQ(e.message(), "Mandatory field \"map\" is missing");
EXPECT_EQ(e.line(), 1);
EXPECT_EQ(e.col(), 1);
}
EXPECT_EQ(test.map[TestEnum::Enum1], 0);
EXPECT_EQ(test.map[TestEnum::Enum2], 0);
EXPECT_EQ(test.map[TestEnum::Enum3], 0);
}
TEST(EnumMapLoader, Empty) {
TestStruct test;
TestHandler handler{test};
const std::string text = "{\"map\": {}}";
std::vector<uint8_t> data(text.begin(), text.end());
ASSERT_THROW_KEEP_AS_E(
freeisle::json::loader::load_root_object(data, handler),
freeisle::json::loader::Error) {
EXPECT_EQ(e.path(), "");
EXPECT_EQ(e.message(), "Mandatory field \"Enum1\" is missing");
EXPECT_EQ(e.line(), 1);
EXPECT_EQ(e.col(), 9);
}
EXPECT_EQ(test.map[TestEnum::Enum1], 0);
EXPECT_EQ(test.map[TestEnum::Enum2], 0);
EXPECT_EQ(test.map[TestEnum::Enum3], 0);
}
TEST(EnumMapLoader, AllPresent) {
TestStruct test;
TestHandler handler{test};
const std::string text =
"{\"map\": {\"Enum1\": 10, \"Enum2\": 20, \"Enum3\": 54}}";
std::vector<uint8_t> data(text.begin(), text.end());
freeisle::json::loader::load_root_object(data, handler);
EXPECT_EQ(test.map[TestEnum::Enum1], 10);
EXPECT_EQ(test.map[TestEnum::Enum2], 20);
EXPECT_EQ(test.map[TestEnum::Enum3], 54);
}
| 26.494624 | 78 | 0.662744 | aburgm |
86f0d8ec95ee742ecac5506bdedfed5bb6db6d64 | 611 | cpp | C++ | Adim1_Ornekler/18_Switch_Case/src/main.cpp | KMACEL/TR-Cpp | dac7bebd1d5fd2d69a76be5a9809417333f01817 | [
"Apache-2.0"
] | 1 | 2021-05-25T22:11:13.000Z | 2021-05-25T22:11:13.000Z | Adim1_Ornekler/18_Switch_Case/src/main.cpp | KMACEL/TR-Cpp | dac7bebd1d5fd2d69a76be5a9809417333f01817 | [
"Apache-2.0"
] | null | null | null | Adim1_Ornekler/18_Switch_Case/src/main.cpp | KMACEL/TR-Cpp | dac7bebd1d5fd2d69a76be5a9809417333f01817 | [
"Apache-2.0"
] | null | null | null | //============================================================================
// İsim : 18_Switch_Case
// Yazan : Mert AceL
// Version : 1.0
// Copyright : AceL
// Açıklama : Switch Case
//============================================================================
#include<iostream>
using namespace std;
int main ()
{
int a = 10;
switch (a)
{
case 0:
cout << "a : " << 0 << endl;
break;
case 10:
cout << "a : " << 10 << endl;
break;
default:
cout << " a '0' ve '10' değil" << endl ;
break;
}
return 0;
}
| 21.068966 | 78 | 0.332242 | KMACEL |
86f5ad4eb2ce4ea6d1bcb85d08e85de2048dace3 | 2,193 | cpp | C++ | 2018/day12/main.cpp | batduck27/Advent_of_code | 6b2dadf28bebd2301464c864f5112dccede9762b | [
"MIT"
] | null | null | null | 2018/day12/main.cpp | batduck27/Advent_of_code | 6b2dadf28bebd2301464c864f5112dccede9762b | [
"MIT"
] | null | null | null | 2018/day12/main.cpp | batduck27/Advent_of_code | 6b2dadf28bebd2301464c864f5112dccede9762b | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <map>
const std::string INIT = "initial state: ";
const std::string SEP = " => ";
const int WSIZE = 5;
const int PART1 = 20;
const long long PART2 = 50000000000;
std::map <std::string, char> M;
std::map <std::string, int> seen;
int potSum(std::string str, int firstPot) {
int s = 0;
for (size_t i = 0; i < str.size(); ++ i) {
if (str[i] == '#') {
s += (int)i + firstPot;
}
}
return s;
}
int main() {
std::ifstream fin("data.in");
std::string state, tmpState;
int firstPot = 0;
std::getline(fin, state);
fin.ignore(1, '\n');
for (std::string str; std::getline(fin, str);) {
int pos = str.find(SEP);
M[str.substr(0, pos)] = str[pos + SEP.size()];
}
state = state.substr(INIT.size());
int gen;
for (gen = 1; ; ++ gen) {
// add empty pots
{
int firstPlant = state.find('#');
int lastPlant = state.find_last_of('#');
state = std::string(WSIZE - firstPlant + 1, '.') +
state +
std::string(WSIZE - state.size() + lastPlant, '.');
firstPot -= WSIZE - firstPlant + 1;
}
tmpState = state;
for (size_t i = 0; i < state.size() - WSIZE; ++ i) {
std::string window = state.substr(i, WSIZE);
tmpState[i + WSIZE / 2] = (M.find(window) != M.end()) ? M[window] : '.';
}
// delete those empty pots
{
int firstPlant = tmpState.find('#');
int lastPlant = tmpState.find_last_of('#');
state = tmpState.substr(firstPlant, lastPlant - firstPlant + 1);
firstPot += firstPlant;
}
int ps = potSum(state, firstPot);
if (gen == PART1) {
std::cout << "The answer for part1 is: " << ps << "\n";
}
if (seen.find(state) != seen.end()) {
std::cout << "The answer for part2 is: " << seen[state] + (PART2 - (gen - 1)) * (ps - seen[state]) << "\n";
break;
} else {
seen[state] = ps;
}
}
fin.close();
return 0;
} | 25.206897 | 119 | 0.481532 | batduck27 |
86fe02cf2bca1e0ba3340f5be92d9e9a13733bd8 | 1,075 | cpp | C++ | code/970.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 23 | 2020-03-30T05:44:56.000Z | 2021-09-04T16:00:57.000Z | code/970.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 1 | 2020-05-10T15:04:05.000Z | 2020-06-14T01:21:44.000Z | code/970.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 6 | 2020-03-30T05:45:04.000Z | 2020-08-13T10:01:39.000Z | #include <bits/stdc++.h>
#define INF 2000000000
using namespace std;
typedef long long ll;
int read(){
int f = 1, x = 0;
char c = getchar();
while(c < '0' || c > '9'){if(c == '-') f = -f; c = getchar();}
while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar();
return f * x;
}
class Solution {
public:
vector<int> powerfulIntegers(int x, int y, int bound) {
vector<int> ans;
if(x > y) swap(x, y);
if(x == 1){
if(y == 1 && bound >= 2) ans.push_back(2);
else {
for (int j = 1; j + 1 <= bound; j *= y)
ans.push_back(j + 1);
}
return ans;
}
for (int i = 1; i < bound; i *= x)
for (int j = 1; i + j <= bound; j *= y)
ans.push_back(i + j);
sort(ans.begin(), ans.end());
auto newend = unique(ans.begin(), ans.end());
ans.erase(newend, ans.end());
return ans;
}
};
Solution sol;
void init(){
}
void solve(){
// sol.convert();
}
int main(){
init();
solve();
return 0;
}
| 23.369565 | 64 | 0.452093 | Nightwish-cn |
86fe1ebedf55725c4731b2ee88f421843c65a244 | 4,626 | cpp | C++ | effectNodes-for-cocos2dx-3x/code/splash/layer_splash.cpp | songxiaopeng/EffectNodes-for-cocos2dx | 905694e6a0c3063f62f2424e22e0e8c1e8b5586c | [
"MIT"
] | 2 | 2016-08-07T01:38:56.000Z | 2016-11-03T04:27:21.000Z | effectNodes-for-cocos2dx-3x/code/splash/layer_splash.cpp | songxiaopeng/EffectNodes-for-cocos2dx | 905694e6a0c3063f62f2424e22e0e8c1e8b5586c | [
"MIT"
] | null | null | null | effectNodes-for-cocos2dx-3x/code/splash/layer_splash.cpp | songxiaopeng/EffectNodes-for-cocos2dx | 905694e6a0c3063f62f2424e22e0e8c1e8b5586c | [
"MIT"
] | 4 | 2016-05-04T05:47:55.000Z | 2020-05-27T07:40:38.000Z | //
// layer_splash.cpp
// HelloWorld
//
// Created by yang chao (wantnon) on 14/12/15.
//
//
#include "layer_splash.h"
#include "chooseScene.h"
void Clayer_splash::controlButtonEvent_back(Ref *senderz, Control::EventType controlEvent){
CchooseScene*scene=new CchooseScene();
scene->autorelease();
scene->init();
CCDirector::sharedDirector()->replaceScene(scene);
}
bool Clayer_splash::init(){
this->CCLayer::init();
CCSize winSize=CCDirector::sharedDirector()->getWinSize();//winSize equals to designResolutionSize
CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
this->setTouchEnabled(true);
CCSprite* backGround=CCSprite::create("demoRes/roughPaper.png");
backGround->setPosition(ccp(winSize.width/2,winSize.height/2));
this->addChild(backGround,-1);
m_splashLayer=new CensSplashLayer();
m_splashLayer->autorelease();
m_splashLayer->init();
this->addChild(m_splashLayer);
m_splashLayer->onStart(ccp(winSize.width/2,winSize.height/2));
//back button
{
Scale9Sprite* btnUp=Scale9Sprite::create("uiRes/button.png");
Scale9Sprite* btnDn=Scale9Sprite::create("uiRes/button_dn.png");
CCLabelTTF*title=CCLabelTTF::create("back", "Helvetica", 30);
ControlButton* controlButton=ControlButton::create(title, btnUp);
controlButton->setBackgroundSpriteForState(btnDn,Control::State::HIGH_LIGHTED);
controlButton->setPreferredSize(CCSize(100,50));
controlButton->setPosition(ccp(origin.x+visibleSize.width-controlButton->getContentSize().width/2,origin.y+controlButton->getContentSize().height/2));
controlButton->addTargetWithActionForControlEvents(this, cccontrol_selector(Clayer_splash::controlButtonEvent_back), Control::EventType::TOUCH_UP_INSIDE);
this->addChild(controlButton);
m_controlButton_back=controlButton;
}
//title
{
{
CCLabelTTF* pLabel = CCLabelTTF::create("Splash", "Arial", 45);
// position the label on the center of the screen
pLabel->setPosition(ccp(origin.x + visibleSize.width/2,
origin.y + visibleSize.height - pLabel->getContentSize().height));
// add the label as a child to this layer
this->addChild(pLabel, 1);
}
{
CCLabelTTF* pLabel = CCLabelTTF::create("2015-3-2", "Arial", 30);
pLabel->setPosition(ccp(origin.x + visibleSize.width/2,
origin.y + visibleSize.height - pLabel->getContentSize().height-60));
this->addChild(pLabel, 1);
}
}
return true;
}
void Clayer_splash::onTouchesBegan(const std::vector<Touch*>& touches, Event *unused_event)
{
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
CCTouch* touch;
for(auto it = touches.begin(); it != touches.end(); it++)
{
touch = (CCTouch*)(*it);
if(!touch)
break;
CCPoint loc_winSpace = touch->getLocationInView();
CCPoint loc_GLSpace = CCDirector::sharedDirector()->convertToGL(loc_winSpace);
break;
}
}
void Clayer_splash::onTouchesMoved(const std::vector<Touch*>& touches, Event *unused_event)
{
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
CCTouch* touch;
for(auto it = touches.begin(); it != touches.end(); it++)
{
touch = (CCTouch*)(*it);
if(!touch)
break;
CCPoint loc_winSpace = touch->getLocationInView();
CCPoint loc_GLSpace = CCDirector::sharedDirector()->convertToGL(loc_winSpace);
break;
}
}
void Clayer_splash::onTouchesEnded(const std::vector<Touch*>& touches, Event *unused_event)
{
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
CCTouch* touch;
for( auto it = touches.begin(); it != touches.end(); it++)
{
touch = (CCTouch*)(*it);
if(!touch)
break;
CCPoint loc_winSpace = touch->getLocationInView();
CCPoint loc_GLSpace = CCDirector::sharedDirector()->convertToGL(loc_winSpace);
m_splashLayer->onStart(loc_GLSpace);
break;
}
} | 29.464968 | 162 | 0.601167 | songxiaopeng |
8102ee3d833dbb863456b2a29b78b8785802ff8d | 2,983 | hpp | C++ | inst/include/geometries/utils/rleid/rleid.hpp | dcooley/geometries | 2ffd841a5b4204d2460c278fe1430ac8f309fa01 | [
"MIT"
] | 27 | 2020-04-27T12:31:55.000Z | 2021-07-16T18:14:37.000Z | inst/include/geometries/utils/rleid/rleid.hpp | dcooley/geometries | 2ffd841a5b4204d2460c278fe1430ac8f309fa01 | [
"MIT"
] | 16 | 2020-04-27T14:17:02.000Z | 2021-05-04T22:42:46.000Z | inst/include/geometries/utils/rleid/rleid.hpp | dcooley/geometries | 2ffd841a5b4204d2460c278fe1430ac8f309fa01 | [
"MIT"
] | 1 | 2020-04-27T12:32:55.000Z | 2020-04-27T12:32:55.000Z | #ifndef R_GEOMETRIES_UTILS_RLEID_H
#define R_GEOMETRIES_UTILS_RLEID_H
namespace geometries {
namespace utils {
// from data.table
// https://github.com/Rdatatable/data.table/blob/8b93bb22715b45d38acf185f40d573bda8748cb4/src/uniqlist.c#L164
inline Rcpp::IntegerVector rleid( Rcpp::DataFrame& df, Rcpp::IntegerVector& ids ) {
R_xlen_t i;
R_xlen_t n_rows = df.nrow();
//R_xlen_t n_cols = Rf_length( l );
R_xlen_t n_id_cols = Rf_length( ids );
Rcpp::IntegerVector ians( n_rows );
int grp = 1;
ians[0] = grp;
for( i = 1; i < n_rows; ++i ) {
bool same = true;
int j = n_id_cols;
while( --j >= 0 && same ) {
SEXP jcol = VECTOR_ELT( df, ids[ j ] );
switch( TYPEOF( jcol ) ) {
case LGLSXP: {}
case INTSXP: {
same = INTEGER( jcol )[ i ] == INTEGER( jcol )[ i - 1 ];
break;
}
case REALSXP: {
long long *ll = (long long *)REAL( jcol );
same = ll[ i ] == ll[ i - 1 ];
break;
}
case STRSXP: {
same = STRING_ELT( jcol, i ) == STRING_ELT( jcol, i - 1 );
break;
}
default: {
Rcpp::stop("geometries - unsupported id column type");
}
}
} // while end
// at this point we now have a run-length-encoded vector
ians[ i ] = ( grp += !same );
}
return ians;
}
// template < int RTYPE >
// inline Rcpp::IntegerVector rleid_indices( Rcpp::Vector< RTYPE >& x ) {
//
// }
inline Rcpp::IntegerVector rleid_indices( SEXP& x ) {
//typedef typename Rcpp::traits::storage_type< RTYPE >::type T;
R_xlen_t i;
R_xlen_t len = Rf_length( x );
R_xlen_t counter = 0;
Rcpp::IntegerVector ians( len );
//int grp = 1;
ians[ 0 ] = 0;
counter++;
switch( TYPEOF( x ) ) {
case INTSXP: case LGLSXP: {
int *icol = INTEGER( x );
for( i = 1; i < len; ++i ) {
if( icol[i] != icol[i-1] ) {
ians[ counter ] = i;
counter++;
}
}
} break;
case REALSXP: {
long long *lljcol = (long long *)REAL(x);
for( i = 1; i < len; ++i ) {
if( lljcol[i] != lljcol[i-1] ) {
ians[ counter ] = i;
counter++;
}
}
} break;
case STRSXP: {
const SEXP *jd = STRING_PTR( x );
for (i = 1; i < len; ++i ) {
if( jd[i] != jd[i-1] ) {
ians[ counter ] = i;
counter++;
}
}
} break;
default: {
Rcpp::stop("geometries - unsupported vector type");
}
}
Rcpp::Range rng(0, counter - 1);
return ians[ rng ];
}
// inline Rcpp::IntegerVector rleid_indices( SEXP& x ) {
//
// }
inline Rcpp::IntegerVector rleid_indices( Rcpp::List& l, Rcpp::IntegerVector& col ) {
SEXP jcol = VECTOR_ELT( l, col[0] );
return rleid_indices( jcol );
}
} // utils
} // geometries
#endif
| 25.495726 | 111 | 0.507543 | dcooley |
8104741d655e13d449fb5320366c002ab5eba050 | 20,556 | cpp | C++ | tools/CodePolygons/src/Utils/GManager.cpp | wallarelvo/CRoPS | 12ecd0afefa6528fc8b2c7d2667ed3b73301d5ec | [
"Apache-2.0"
] | null | null | null | tools/CodePolygons/src/Utils/GManager.cpp | wallarelvo/CRoPS | 12ecd0afefa6528fc8b2c7d2667ed3b73301d5ec | [
"Apache-2.0"
] | null | null | null | tools/CodePolygons/src/Utils/GManager.cpp | wallarelvo/CRoPS | 12ecd0afefa6528fc8b2c7d2667ed3b73301d5ec | [
"Apache-2.0"
] | null | null | null | #include "Utils/GManager.hpp"
#include "Utils/GDraw.hpp"
#include "Utils/PrintMsg.hpp"
#include "Utils/Constants.hpp"
#include "Utils/PseudoRandom.hpp"
#include <cstdlib>
#include <cmath>
namespace Abetare
{
GManager *m_gManager = NULL;
void GManager::CallbackEventOnActiveMouseMove(int x, int y)
{
if(m_gManager)
{
if(m_gManager->HandleEventOnActiveMouseMove(x, y))
glutPostRedisplay();
m_gManager->m_mousePrevX = x;
m_gManager->m_mousePrevY = y;
}
}
void GManager::CallbackEventOnPassiveMouseMove(int x, int y)
{
if(m_gManager)
{
if(m_gManager->HandleEventOnPassiveMouseMove(x, y))
glutPostRedisplay();
m_gManager->m_mousePrevX = x;
m_gManager->m_mousePrevY = y;
}
}
void GManager::CallbackEventOnMouse(int button, int state, int x, int y)
{
if(m_gManager)
{
if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN &&
m_gManager->HandleEventOnMouseLeftBtnDown(x, y))
glutPostRedisplay();
m_gManager->m_mousePrevX = x;
m_gManager->m_mousePrevY = y;
}
}
void GManager::CallbackEventOnTimer(int id)
{
if(m_gManager)
{
m_gManager->HandleEventOnTimer();
glutTimerFunc(m_gManager->m_timer, CallbackEventOnTimer, id);
glutPostRedisplay();
}
}
void GManager::CallbackEventOnIdle(void)
{
if(m_gManager)
{
if(m_gManager->HandleEventOnIdle())
glutPostRedisplay();
}
}
void GManager::CallbackEventOnMenu(int item)
{
if(m_gManager && m_gManager->HandleEventOnMenu(item))
glutPostRedisplay();
}
void GManager::CallbackEventOnSpecialKeyPress(int key, int x, int y)
{
if(m_gManager &&
m_gManager->HandleEventOnSpecialKeyPress(key))
glutPostRedisplay();
}
void GManager::CallbackEventOnNormalKeyPress(unsigned char key, int x, int y)
{
if(m_gManager && m_gManager->HandleEventOnNormalKeyPress(key))
glutPostRedisplay();
}
void GManager::CallbackEventOnDisplay(void)
{
if(m_gManager)
{
glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
glClearDepth(1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glShadeModel(GL_SMOOTH);
glViewport(0, 0, glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT));
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(m_gManager->m_gCameraAction & ACTION_CAMERA_PROJECTION)
gluPerspective(GDrawGetParam(GDRAW_PERSPECTIVE3D_ANGLE),
(double) glutGet(GLUT_WINDOW_WIDTH) / glutGet(GLUT_WINDOW_HEIGHT),
GDrawGetParam(GDRAW_PERSPECTIVE3D_NEAR_PLANE),
GDrawGetParam(GDRAW_PERSPECTIVE3D_FAR_PLANE));
else
glOrtho(m_gManager->m_viewZoom * GDrawGetParam(GDRAW_MINX),
m_gManager->m_viewZoom * GDrawGetParam(GDRAW_MAXX),
m_gManager->m_viewZoom * GDrawGetParam(GDRAW_MINY),
m_gManager->m_viewZoom * GDrawGetParam(GDRAW_MAXY),
GDrawGetParam(GDRAW_PERSPECTIVE3D_NEAR_PLANE),
GDrawGetParam(GDRAW_PERSPECTIVE3D_FAR_PLANE));
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
double m[16];
m_gManager->m_gCamera.GetModelViewMatrixOpenGL(m);
glMultMatrixd(m);
if(m_gManager->m_gDrawAction & ACTION_DRAW_TEXTURES)
glEnable(GL_TEXTURE_2D);
else
glDisable(GL_TEXTURE_2D);
if(m_gManager->m_gDrawAction & ACTION_DRAW_LIGHTING)
{
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_SMOOTH);
glEnable(GL_LIGHTING);
GDrawIllumination();
}
else
glDisable(GL_LIGHTING);
GDrawWireframe((m_gManager->m_gDrawAction & ACTION_DRAW_WIREFRAME) != 0);
// GDrawShaderSceneRender();
m_gManager->HandleEventOnDisplay();
if(m_gManager->m_gDrawAction & ACTION_DRAW_EXPORT_FRAMES)
ExportFrameAsImage();
// glUseProgram(0);
glutSwapBuffers();
}
}
GManager::GManager(void)
{
m_idWindow = -1;
m_timer = 2;
m_gCameraAction = ACTION_CAMERA_ROTATE_CENTER |
ACTION_CAMERA_ROTATE_GLOBAL_AXIS |
ACTION_CAMERA_ROTATE_X |
// ACTION_CAMERA_ROTATE_Y |
ACTION_CAMERA_ROTATE_Z |
ACTION_CAMERA_MOVE_X |
ACTION_CAMERA_MOVE_Y |
ACTION_CAMERA_MOVE_Z |
ACTION_CAMERA_PROJECTION;
m_gCameraMove = 2.25;
m_gDrawAction = ACTION_DRAW_TEXTURES | ACTION_DRAW_LIGHTING;
m_mousePrevX = 0;
m_mousePrevY = 0;
m_viewZoom = 1;
m_frames = 0;
m_nrMenuItems = 0;
MENU_CAMERA_ROTATE_CENTER = ++m_nrMenuItems;
MENU_CAMERA_ROTATE_GLOBAL_AXIS = ++m_nrMenuItems;
MENU_CAMERA_ROTATE_X = ++m_nrMenuItems;
MENU_CAMERA_ROTATE_Y = ++m_nrMenuItems;
MENU_CAMERA_ROTATE_Z = ++m_nrMenuItems;
MENU_CAMERA_MOVE_X = ++m_nrMenuItems;
MENU_CAMERA_MOVE_Y = ++m_nrMenuItems;
MENU_CAMERA_MOVE_Z = ++m_nrMenuItems;
MENU_CAMERA_PROJECTION = ++m_nrMenuItems;
MENU_CAMERA_STANDARD = ++m_nrMenuItems;
MENU_DRAW_TEXTURE = ++m_nrMenuItems;
MENU_DRAW_LIGHTING = ++m_nrMenuItems;
MENU_DRAW_WIREFRAME = ++m_nrMenuItems;
MENU_DRAW_EXPORT_FRAMES = ++m_nrMenuItems;
MENU_DRAW_XY_BBOX = ++m_nrMenuItems;
// m_gCamera.RotateAroundAxisAtPoint(0.5 * M_PI, 0, 1, 0, 0, 0, 0);
}
GManager::~GManager(void)
{
if(m_idWindow >= 0)
glutDestroyWindow(m_idWindow);
}
void GManager::MainLoop(const char * const title, const int width, const int height)
{
m_gManager = this;
static int argc = 1;
static char *args = (char*)"args";
glutInit(&argc, &args);
glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
glutInitWindowSize(width, height);
glutInitWindowPosition(0, 0);
m_idWindow = glutCreateWindow(title);
glutDisplayFunc(CallbackEventOnDisplay);
glutMouseFunc(CallbackEventOnMouse);
glutMotionFunc(CallbackEventOnActiveMouseMove);
glutPassiveMotionFunc(CallbackEventOnPassiveMouseMove);
glutIdleFunc(CallbackEventOnIdle);
glutTimerFunc(0, CallbackEventOnTimer, 0);
glutKeyboardFunc(CallbackEventOnNormalKeyPress);
glutSpecialFunc(CallbackEventOnSpecialKeyPress);
MenuOptions();
//RandomSeed();
// GDrawShaderSceneInit();
glutMainLoop();
}
void GManager::MenuOptions(void)
{
m_idMenuCamera = CreateMenu();
AddMenuEntry("Rotate at center[on]/eye[off]", MENU_CAMERA_ROTATE_CENTER);
AddMenuEntry("Rotate axis global[on]/camera[off]", MENU_CAMERA_ROTATE_GLOBAL_AXIS);
AddMenuEntry("Rotation around x-axis [on]", MENU_CAMERA_ROTATE_X);
AddMenuEntry("Rotation around y-axis [off]", MENU_CAMERA_ROTATE_Y);
AddMenuEntry("Rotation around z-axis [on]", MENU_CAMERA_ROTATE_Z);
AddMenuEntry("Moving along x-axis [on]", MENU_CAMERA_MOVE_X);
AddMenuEntry("Moving along y-axis [on]", MENU_CAMERA_MOVE_Y);
AddMenuEntry("Moving along z-axis [on]", MENU_CAMERA_MOVE_Z);
AddMenuEntry("Perspective[on]/orthogonal[off]", MENU_CAMERA_PROJECTION);
AddMenuEntry("Look at standard position", MENU_CAMERA_STANDARD);
m_idMenuDraw = CreateMenu();
AddMenuEntry("Textures [on]", MENU_DRAW_TEXTURE);
AddMenuEntry("Lighting [on]", MENU_DRAW_LIGHTING);
AddMenuEntry("Wireframe [off]", MENU_DRAW_WIREFRAME);
AddMenuEntry("Export frames [off]", MENU_DRAW_EXPORT_FRAMES);
AddMenuEntry("Set xy bounding box", MENU_DRAW_XY_BBOX);
m_idMenuMain = CreateMenu();
AddSubMenu("Camera", m_idMenuCamera);
AddSubMenu("Draw", m_idMenuDraw);
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
bool GManager::HandleEventOnMenu(const int item)
{
if(item == MENU_CAMERA_STANDARD)
{
m_gCamera.SetLookAtStandardPosition();
return true;
}
else if(item >= MENU_CAMERA_ROTATE_CENTER && item <= MENU_CAMERA_PROJECTION)
{
const int offset = item - MENU_CAMERA_ROTATE_CENTER;
const int val = 1 << offset;
char msg[50];
SetMenu(m_idMenuCamera);
if(m_gCameraAction & val)
{
m_gCameraAction &= ~val;
if(item == MENU_CAMERA_ROTATE_CENTER)
sprintf(msg, "Rotate at center[off]/eye[on]");
else if(item == MENU_CAMERA_ROTATE_GLOBAL_AXIS)
sprintf(msg, "Rotate axis global[off]/camera[on]");
else if(item >= MENU_CAMERA_ROTATE_X && item <= MENU_CAMERA_ROTATE_Z)
sprintf(msg, "Rotation around %c-axis [off]", "xyz"[offset - 2]);
else if(item >= MENU_CAMERA_MOVE_X && item <= MENU_CAMERA_MOVE_Z)
sprintf(msg, "Moving along %c-axis [off]", "xyz"[offset - 5]);
else if(item == MENU_CAMERA_PROJECTION)
sprintf(msg, "Perspective[off]/orthogonal[on]");
}
else
{
m_gCameraAction |= val;
if(item == MENU_CAMERA_ROTATE_CENTER)
sprintf(msg, "Rotate at center[on]/eye[off]");
else if(item == MENU_CAMERA_ROTATE_GLOBAL_AXIS)
sprintf(msg, "Rotate axis global[on]/camera[off]");
else if(item >= MENU_CAMERA_ROTATE_X && item <= MENU_CAMERA_ROTATE_Z)
sprintf(msg, "Rotation around %c-axis [on]", "xyz"[offset - 2]);
else if(item >= MENU_CAMERA_MOVE_X && item <= MENU_CAMERA_MOVE_Z)
sprintf(msg, "Moving along %c-axis [on]", "xyz"[offset - 5]);
else if(item == MENU_CAMERA_PROJECTION)
sprintf(msg, "Perspective[on]/orthogonal[off]");
}
ChangeToMenuEntry(offset + 1, msg, item);
SetMenu(m_idMenuMain);
return true;
}
else if(item >= MENU_DRAW_TEXTURE && item <= MENU_DRAW_EXPORT_FRAMES)
{
const int offset = item - MENU_DRAW_TEXTURE;
const int val = 1 << offset;
char msg[50];
SetMenu(m_idMenuDraw);
if(m_gDrawAction & val)
{
m_gDrawAction &=~val;
if(item == MENU_DRAW_TEXTURE)
sprintf(msg, "Textures [off]");
else if(item == MENU_DRAW_LIGHTING)
sprintf(msg, "Lighting [off]");
else if(item == MENU_DRAW_WIREFRAME)
sprintf(msg, "Wireframe [off]");
else if(item == MENU_DRAW_EXPORT_FRAMES)
sprintf(msg, "Export frames [off]");
}
else
{
m_gDrawAction |= val;
if(item == MENU_DRAW_TEXTURE)
sprintf(msg, "Textures [on]");
else if(item == MENU_DRAW_LIGHTING)
sprintf(msg, "Lighting [on]");
else if(item == MENU_DRAW_WIREFRAME)
sprintf(msg, "Wireframe [on]");
else if(item == MENU_DRAW_EXPORT_FRAMES)
sprintf(msg, "Export frames [on]");
}
ChangeToMenuEntry(offset + 1, msg, item);
SetMenu(m_idMenuMain);
return true;
}
else if(item == MENU_DRAW_XY_BBOX)
{
double xmin, ymin, xmax, ymax;
printf("Current xy bbox: %f %f %f %f\n",
GDrawGetParam(GDRAW_MINX),
GDrawGetParam(GDRAW_MINY),
GDrawGetParam(GDRAW_MAXX),
GDrawGetParam(GDRAW_MAXY));
printf("Enter new values:");
scanf("%lf %lf %lf %lf", &xmin, &ymin, &xmax, &ymax);
GDrawSetParam(GDRAW_MINX, xmin);
GDrawSetParam(GDRAW_MINY, ymin);
GDrawSetParam(GDRAW_MAXX, xmax);
GDrawSetParam(GDRAW_MAXY, ymax);
return true;
}
return false;
}
bool GManager::HandleEventOnNormalKeyPress(const int key)
{
if(key == 27) //escape key
{
exit(0);
return true;
}
else if(glutGetModifiers() & GLUT_ACTIVE_ALT)
{
if(key == '1')
return HandleEventOnMenu(MENU_CAMERA_ROTATE_X);
else if(key == '2')
return HandleEventOnMenu(MENU_CAMERA_ROTATE_Y);
else if(key == '3')
return HandleEventOnMenu(MENU_CAMERA_ROTATE_Z);
else if(key == 'c')
return HandleEventOnMenu(MENU_CAMERA_ROTATE_CENTER);
else if(key == 'g')
return HandleEventOnMenu(MENU_CAMERA_ROTATE_GLOBAL_AXIS);
else if(key == 'p')
return HandleEventOnMenu(MENU_CAMERA_PROJECTION);
else if(key == 't')
return HandleEventOnMenu(MENU_DRAW_TEXTURE);
else if(key == 'l')
return HandleEventOnMenu(MENU_DRAW_LIGHTING);
else if(key == 'w')
return HandleEventOnMenu(MENU_DRAW_WIREFRAME);
else if(key == 'f')
{
ExportFrameAsImage();
//return HandleEventOnMenu(MENU_DRAW_EXPORT_FRAMES);
}
else if(key == 'q')
{
return HandleEventOnMenu(MENU_DRAW_EXPORT_FRAMES);
}
else if(key == 'x' || key == 'X' || key == 'y' || key == 'Y' || key == 'z' || key == 'Z')
{
const double *p =
m_gCameraAction & ACTION_CAMERA_ROTATE_CENTER ?
m_gCamera.GetCenter() : m_gCamera.GetEye();
const double theta = (key == 'x' || key == 'y' || key == 'z') ?
Constants::DEG2RAD :
-Constants::DEG2RAD;
if(key == 'x' || key == 'X')
{
if(m_gCameraAction & ACTION_CAMERA_ROTATE_GLOBAL_AXIS)
m_gCamera.RotateAroundAxisAtPoint(theta, 1, 0, 0, p[0], p[1], p[2]);
else
m_gCamera.RotateAroundRightAxisAtPoint(theta, p[0], p[1], p[2]);
}
else if(key == 'y' || key == 'Y')
{
if(m_gCameraAction & ACTION_CAMERA_ROTATE_GLOBAL_AXIS)
m_gCamera.RotateAroundAxisAtPoint(theta, 0, 1, 0, p[0], p[1], p[2]);
else
m_gCamera.RotateAroundUpAxisAtPoint(theta, p[0], p[1], p[2]);
}
else if(key == 'z' || key == 'Z')
{
if(m_gCameraAction & ACTION_CAMERA_ROTATE_GLOBAL_AXIS)
m_gCamera.RotateAroundAxisAtPoint(theta, 0, 0, 1, p[0], p[1], p[2]);
else
m_gCamera.RotateAroundForwardAxisAtPoint(theta, p[0], p[1], p[2]);
}
}
}
return false;
}
void GManager::Help(void)
{
BeginPrint(PRINT_INFO);
printf("Help -- Menu options\n");
printf(" right click to see menu\n\n");
printf("Help -- Keyboard controls\n");
printf(" F1 => help\n");
printf(" Esc => exit\n\n");
printf(" ArrowUp => move camera forward\n");
printf(" ArrowDown => move camera backward\n");
printf(" ArrowLeft => move camera left\n");
printf(" ArrowRight => move camera right\n");
printf(" PageUp => move camera up\n");
printf(" PageDown => move camera down\n\n");
printf(" Alt+x => toggle rotate camera around x-axis [current = %s]\n",
(m_gCameraAction & ACTION_CAMERA_ROTATE_X) ? "on":"off");
printf(" Alt+y => toggle rotate camera around y-axis [current = %s]\n",
(m_gCameraAction & ACTION_CAMERA_ROTATE_Y) ? "on":"off");
printf(" Alt+z => toggle rotate camera around z-axis [current = %s]\n\n",
(m_gCameraAction & ACTION_CAMERA_ROTATE_Z) ? "on":"off");
printf(" Alt+c => toggle rotate camera about center/eye [current = %s]\n",
(m_gCameraAction & ACTION_CAMERA_ROTATE_CENTER) ? "center":"eye");
printf(" Alt+g => toggle rotate camera use global/own frame [current = %s]\n",
(m_gCameraAction & ACTION_CAMERA_ROTATE_GLOBAL_AXIS) ? "global":"own frame");
printf(" Alt+p => toggle perspective/orthogonal projection [current = %s]\n\n",
(m_gCameraAction & ACTION_CAMERA_PROJECTION) ? "perspective":"orthogonal");
printf(" Alt+t => toggle textures on/off [current = %s]\n",
(m_gDrawAction & ACTION_DRAW_TEXTURES) ? "on":"off");
printf(" Alt+l => toggle lightining on/off [current = %s]\n",
(m_gDrawAction & ACTION_DRAW_LIGHTING) ? "on":"off");
printf(" Alt+w => toggle wireframe on/off [current = %s]\n",
(m_gDrawAction & ACTION_DRAW_WIREFRAME) ? "on":"off");
printf(" Alt+f => toggle export frames on/off [current = %s]\n",
(m_gDrawAction & ACTION_DRAW_EXPORT_FRAMES) ? "on":"off");
EndPrint();
}
bool GManager::HandleEventOnSpecialKeyPress(const int key)
{
switch(key)
{
case GLUT_KEY_F1:
Help();
return true;
case GLUT_KEY_UP:
if(m_gCameraAction & ACTION_CAMERA_MOVE_Y)
{
if(m_gCameraAction & ACTION_CAMERA_PROJECTION)
m_gCamera.MoveForward(m_gCameraMove);
else
m_viewZoom -= m_gCameraMove;
return true;
}
break;
case GLUT_KEY_DOWN:
if(m_gCameraAction & ACTION_CAMERA_MOVE_Y)
{
if(m_gCameraAction & ACTION_CAMERA_PROJECTION)
m_gCamera.MoveForward(-m_gCameraMove);
else
m_viewZoom += m_gCameraMove;
return true;
}
break;
case GLUT_KEY_RIGHT:
if(m_gCameraAction & ACTION_CAMERA_MOVE_X)
{
m_gCamera.MoveRight(m_gCameraMove);
return true;
}
break;
case GLUT_KEY_LEFT:
if(m_gCameraAction & ACTION_CAMERA_MOVE_X)
{
m_gCamera.MoveRight(-m_gCameraMove);
return true;
}
break;
case GLUT_KEY_PAGE_DOWN:
if(m_gCameraAction & ACTION_CAMERA_MOVE_Z)
{
m_gCamera.MoveUp(m_gCameraMove);
return true;
}
break;
case GLUT_KEY_PAGE_UP:
if(m_gCameraAction & ACTION_CAMERA_MOVE_Z)
{
m_gCamera.MoveUp(-m_gCameraMove);
return true;
}
break;
}
return false;
}
bool GManager::HandleEventOnMouseLeftBtnDown(const int x, const int y)
{
return false;
}
bool GManager::HandleEventOnActiveMouseMove(const int x, const int y)
{
const double thetax = 2 * M_PI * (y - m_mousePrevY) / glutGet(GLUT_WINDOW_HEIGHT);
const double thetay = 2 * M_PI * (x - m_mousePrevX) / glutGet(GLUT_WINDOW_WIDTH);
const double thetaz = thetay;
bool event = false;
const double *p =
m_gCameraAction & ACTION_CAMERA_ROTATE_CENTER ?
m_gCamera.GetCenter() : m_gCamera.GetEye();
if(m_gCameraAction & ACTION_CAMERA_ROTATE_X)
{
if(m_gCameraAction & ACTION_CAMERA_ROTATE_GLOBAL_AXIS)
m_gCamera.RotateAroundAxisAtPoint(thetax, 1, 0, 0, p[0], p[1], p[2]);
else
m_gCamera.RotateAroundRightAxisAtPoint(thetax, p[0], p[1], p[2]);
event = true;
}
if(m_gCameraAction & ACTION_CAMERA_ROTATE_Y)
{
if(m_gCameraAction & ACTION_CAMERA_ROTATE_GLOBAL_AXIS)
m_gCamera.RotateAroundAxisAtPoint(thetay, 0, 1, 0, p[0], p[1], p[2]);
else
m_gCamera.RotateAroundUpAxisAtPoint(thetay, p[0], p[1], p[2]);
event = true;
}
if(m_gCameraAction & ACTION_CAMERA_ROTATE_Z)
{
if(m_gCameraAction & ACTION_CAMERA_ROTATE_GLOBAL_AXIS)
m_gCamera.RotateAroundAxisAtPoint(thetaz, 0, 0, 1, p[0], p[1], p[2]);
else
m_gCamera.RotateAroundForwardAxisAtPoint(thetaz, p[0], p[1], p[2]);
event = true;
}
return event;
}
bool GManager::HandleEventOnPassiveMouseMove(const int x, const int y)
{
return false;
}
bool GManager::HandleEventOnIdle(void)
{
return false;
}
void GManager::MousePosFromScreenToWorld(const int x, const int y,
double * const wx,
double * const wy,
double * const wz)
{
GLint viewport[4];
GLdouble modelview[16];
GLdouble projection[16];
GLfloat winX, winY, winZ;
double px = 0, py = 0, pz = 0;
glGetDoublev( GL_MODELVIEW_MATRIX, modelview );
glGetDoublev( GL_PROJECTION_MATRIX, projection );
glGetIntegerv( GL_VIEWPORT, viewport );
winX = (float)x;
winY = (float)viewport[3] - (float)y;
glReadPixels( x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ );
gluUnProject(winX, winY, winZ, modelview, projection, viewport, &px, &py, &pz);
if(wx)
*wx = px;
if(wy)
*wy = py;
if(wz)
*wz = pz;
}
void GManager::ExportFrameAsImage(void)
{
char fname[50];
sprintf(fname, "frames_%05d.ppm", (m_gManager->m_frames)++);
ExportFrameAsImage(fname);
}
void GManager::ExportFrameAsImage(const char fname[])
{
const int width = glutGet(GLUT_WINDOW_WIDTH);
const int height= glutGet(GLUT_WINDOW_HEIGHT);
char *temp = new char[3 * width * height];
char *image = new char[3 * width * height];
FILE *fp = fopen(fname, "w");
printf("Writing %s\n", fname);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, temp);
int a, b, row_sz = 3*width;
// Reverse rows
for(int i=0; i < height; i+=1)
{
for(int j=0; j < width; j+=1)
{
a = i*row_sz+3*j;
b = (height-i-1)*row_sz+3*j;
image[a] = temp[b];
image[a+1] = temp[b+1];
image[a+2] = temp[b+2];
}
}
fprintf(fp, "P6\n");
fprintf(fp, "%i %i\n 255\n", width, height);
fwrite(image, sizeof(char), 3 * width * height, fp);
fclose(fp);
delete[] temp;
delete[] image;
}
int GManager::CreateMenu(void)
{
return glutCreateMenu(CallbackEventOnMenu);
}
void GManager::SetMenu(const int menu)
{
glutSetMenu(menu);
}
void GManager::AddSubMenu(const char name[], const int menu)
{
glutAddSubMenu(name, menu);
}
void GManager::AddMenuEntry(const char name[], const int item)
{
glutAddMenuEntry(name, item);
}
void GManager::ChangeToMenuEntry(const int pos, const char name[], const int item)
{
glutChangeToMenuEntry(pos, name, item);
}
}
| 28.870787 | 94 | 0.652121 | wallarelvo |
8109953b83c24dc2568bc0fa2944ed4e50e32288 | 5,875 | cxx | C++ | resip/dum/DumTimeout.cxx | dulton/reSipServer | ac4241df81c1e3eef2e678271ffef4dda1fc6747 | [
"Apache-2.0"
] | 1 | 2019-04-15T14:10:58.000Z | 2019-04-15T14:10:58.000Z | resip/dum/DumTimeout.cxx | dulton/reSipServer | ac4241df81c1e3eef2e678271ffef4dda1fc6747 | [
"Apache-2.0"
] | null | null | null | resip/dum/DumTimeout.cxx | dulton/reSipServer | ac4241df81c1e3eef2e678271ffef4dda1fc6747 | [
"Apache-2.0"
] | 2 | 2019-10-31T09:11:09.000Z | 2021-09-17T01:00:49.000Z | #include <cassert>
#include "DumTimeout.hxx"
#include "rutil/WinLeakCheck.hxx"
#include "resip/dum/BaseUsage.hxx"
using namespace resip;
DumTimeout::DumTimeout(Type type,
unsigned long duration,
BaseUsageHandle targetBu,
unsigned int seq,
unsigned int altSeq,
const Data &transactionId)
: mType(type),
mDuration(duration),
mUsageHandle(targetBu),
mSeq(seq),
mSecondarySeq(altSeq),
mTransactionId(transactionId)
{}
DumTimeout::DumTimeout(const DumTimeout& source)
: mType(source.mType),
mDuration(source.mDuration),
mUsageHandle(source.mUsageHandle),
mSeq(source.mSeq),
mSecondarySeq(source.mSecondarySeq),
mTransactionId(source.mTransactionId)
{}
DumTimeout::~DumTimeout()
{}
Message*
DumTimeout::clone() const
{
return new DumTimeout(*this);
}
DumTimeout::Type
DumTimeout::type() const
{
return mType;
}
unsigned int
DumTimeout::seq() const
{
return mSeq;
}
unsigned int
DumTimeout::secondarySeq() const
{
return mSecondarySeq;
}
const Data & DumTimeout::transactionId() const
{
return mTransactionId;
}
bool
DumTimeout::isClientTransaction() const
{
assert(0);
return false;
}
EncodeStream&
DumTimeout::encodeBrief(EncodeStream& strm) const
{
return encode(strm);
}
EncodeStream&
DumTimeout::encode(EncodeStream& strm) const
{
strm << "DumTimeout::";
switch (mType)
{
case SessionExpiration:
strm <<"SessionExpiration";
break;
case SessionRefresh:
strm <<"SessionRefresh";
break;
case Registration:
strm <<"Registration";
break;
case RegistrationRetry:
strm <<"RegistrationRetry";
break;
case Publication:
strm <<"Publication";
break;
case Retransmit200:
strm <<"Retransmit200";
break;
case Retransmit1xx:
strm <<"Retransmit1xx";
break;
case Retransmit1xxRel:
strm <<"Retransmit1xxRel";
break;
case Resubmit1xxRel:
strm <<"Resubmit1xxRel";
break;
case WaitForAck:
strm <<"WaitForAck";
break;
case CanDiscardAck:
strm <<"CanDiscardAck";
break;
case StaleCall:
strm <<"StaleCall";
break;
case Subscription:
strm <<"Subscription";
break;
case SubscriptionRetry:
strm <<"SubscriptionRetry";
break;
case WaitForNotify:
strm <<"WaitForNotify";
break;
case StaleReInvite:
strm <<"StaleReInvite";
break;
case Glare:
strm <<"Glare";
break;
case Cancelled:
strm <<"Cancelled";
break;
case WaitingForForked2xx:
strm <<"WaitingForForked2xx";
break;
case SendNextNotify:
strm <<"SendNextNotify";
break;
}
// Accessing mUsageHandle is not threadsafe, and this encode method is used outside
// the dum thread, in the stack thread via the TuSelector::add method for logging.
//if (mUsageHandle.isValid())
//{
// strm << " " << *mUsageHandle;
//}
//else
//{
// strm << " defunct";
//}
strm << ": duration=" << mDuration << " seq=" << mSeq;
return strm;
}
BaseUsageHandle
DumTimeout::getBaseUsage() const
{
return mUsageHandle;
}
/* ====================================================================
* The Vovida Software License, Version 1.0
*
* Copyright (c) 2000 Vovida Networks, 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:
*
* 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. The names "VOCAL", "Vovida Open Communication Application Library",
* and "Vovida Open Communication Application Library (VOCAL)" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact vocal@vovida.org.
*
* 4. Products derived from this software may not be called "VOCAL", nor
* may "VOCAL" appear in their name, without prior written
* permission of Vovida Networks, Inc.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
* NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL VOVIDA
* NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES
* IN EXCESS OF $1,000, NOR FOR ANY 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.
*
* ====================================================================
*
* This software consists of voluntary contributions made by Vovida
* Networks, Inc. and many individuals on behalf of Vovida Networks,
* Inc. For more information on Vovida Networks, Inc., please see
* <http://www.vovida.org/>.
*
*/
| 27.453271 | 86 | 0.630638 | dulton |
810df11717669e7c77c48499a802e6b3013e6518 | 2,552 | hpp | C++ | include/eagine/sslplus/api/result.hpp | matus-chochlik/eagine-sslplus | c136220a5f2dafdcecf847e517728f8fa8e43959 | [
"BSL-1.0"
] | null | null | null | include/eagine/sslplus/api/result.hpp | matus-chochlik/eagine-sslplus | c136220a5f2dafdcecf847e517728f8fa8e43959 | [
"BSL-1.0"
] | null | null | null | include/eagine/sslplus/api/result.hpp | matus-chochlik/eagine-sslplus | c136220a5f2dafdcecf847e517728f8fa8e43959 | [
"BSL-1.0"
] | null | null | null | /// @file
///
/// Copyright Matus Chochlik.
/// Distributed under the Boost Software License, Version 1.0.
/// See accompanying file LICENSE_1_0.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt
///
#ifndef EAGINE_SSLPLUS_API_RESULT_HPP
#define EAGINE_SSLPLUS_API_RESULT_HPP
#include "config.hpp"
#include <eagine/anything.hpp>
#include <eagine/c_api_wrap.hpp>
#include <eagine/string_span.hpp>
namespace eagine::sslplus {
//------------------------------------------------------------------------------
class ssl_no_result_info {
public:
constexpr auto error_code(const anything) noexcept -> auto& {
return *this;
}
constexpr auto message() const noexcept -> string_view {
return {"OpenSSL function not available"};
}
constexpr auto set_unknown_error() noexcept -> auto& {
return *this;
}
};
//------------------------------------------------------------------------------
class ssl_result_info {
public:
explicit constexpr operator bool() const noexcept {
return _error_code == 0;
}
constexpr auto error_code(const unsigned long ec) noexcept -> auto& {
_error_code = ec;
return *this;
}
constexpr auto set_unknown_error() noexcept -> auto& {
if(!_error_code) {
_error_code = ~0UL;
}
return *this;
}
auto message() const noexcept -> string_view {
// TODO: get error string from OpenSSL
return {"unknown ssl error"};
}
private:
unsigned long _error_code{0UL};
};
//------------------------------------------------------------------------------
template <typename Result>
using ssl_no_result = api_no_result<Result, ssl_no_result_info>;
//------------------------------------------------------------------------------
template <typename Result>
using ssl_result = api_result<Result, ssl_result_info>;
//------------------------------------------------------------------------------
template <typename Result>
using ssl_opt_result = api_opt_result<Result, ssl_result_info>;
//------------------------------------------------------------------------------
template <typename Result, api_result_validity Validity>
inline auto collapse_bool(
api_result<Result, ssl_result_info, Validity>&& r) noexcept {
return r.collapsed(
[](int value) { return value == 1; },
[](auto& info) { info.set_unknown_error(); });
}
//------------------------------------------------------------------------------
} // namespace eagine::sslplus
#endif // EAGINE_SSLPLUS_API_RESULT_HPP
| 31.9 | 80 | 0.535658 | matus-chochlik |
8110fe1adfcaf3ed9036cf16f4d9f8c9994b1ffc | 11,154 | inl | C++ | include/LinearAlgebra/tmlVector4.inl | mbatc/Template-Math-Library | 66aa61edbe8c16e636b28a355be0fe5e9989742f | [
"MIT"
] | null | null | null | include/LinearAlgebra/tmlVector4.inl | mbatc/Template-Math-Library | 66aa61edbe8c16e636b28a355be0fe5e9989742f | [
"MIT"
] | null | null | null | include/LinearAlgebra/tmlVector4.inl | mbatc/Template-Math-Library | 66aa61edbe8c16e636b28a355be0fe5e9989742f | [
"MIT"
] | null | null | null |
template<typename T>
inline tmlVector4<T>::tmlVector4()
: x(0)
, y(0)
, z(0)
, w(0)
{}
template<typename T>
inline tmlVector4<T>::tmlVector4(T val)
: x(val)
, y(val)
, z(val)
, w(val)
{}
template<typename T>
inline tmlVector4<T>::tmlVector4(T _x, T _y, T _z, T _w)
: x(_x)
, y(_y)
, z(_z)
, w(_w)
{}
template<typename T>
inline tmlVector4<T>::tmlVector4(const tmlVector3<T> &xyz, T _w)
: x(xyz.x)
, y(xyz.y)
, z(xyz.z)
, w(_w)
{}
template<typename T>
inline tmlVector4<T>::tmlVector4(T _x, const tmlVector3<T> &yzw)
: x(_x)
, y(yzw.x)
, z(yzw.y)
, w(yzw.z)
{}
template<typename T>
inline tmlVector4<T>::tmlVector4(T _x, T _y, const tmlVector2<T> &zw)
: x(_x)
, y(_y)
, z(zw.x)
, w(zw.y)
{}
template<typename T>
inline tmlVector4<T>::tmlVector4(T _x, const tmlVector2<T> &yz, T _w)
: x(_x)
, y(yz.x)
, z(yz.y)
, w(_w)
{}
template<typename T>
inline tmlVector4<T>::tmlVector4(const tmlVector2<T> &xy, T _z, T _w)
: x(xy.x)
, y(xy.y)
, z(_z)
, w(_w)
{}
template<typename T>
template<typename T2>
inline tmlVector4<T>::tmlVector4(T2 val)
: x((T)val)
, y((T)val)
, z((T)val)
, w((T)val)
{}
template<typename T>
template<typename T2>
inline tmlVector4<T>::tmlVector4(T2 _x, T2 _y, T2 _z, T2 _w)
: x((T)_x)
, y((T)_y)
, z((T)_z)
, w((T)_w)
{}
template<typename T>
template<typename T2>
inline tmlVector4<T>::tmlVector4(const tmlVector3<T2> &xyz, T2 _w)
: x((T)xyz.x)
, y((T)xyz.y)
, z((T)xyz.z)
, w((T)_w)
{}
template<typename T>
template<typename T2>
inline tmlVector4<T>::tmlVector4(T2 _x, const tmlVector3<T2> &yzw)
: x((T)_x)
, y((T)yzw.x)
, z((T)yzw.y)
, w((T)yzw.z)
{}
template<typename T>
template<typename T2>
inline tmlVector4<T>::tmlVector4(T2 _x, T2 _y, const tmlVector2<T2> &zw)
: x((T)_x)
, y((T)_y)
, z((T)zw.x)
, w((T)zw.y)
{}
template<typename T>
template<typename T2>
inline tmlVector4<T>::tmlVector4(T2 _x, const tmlVector2<T2> &yz, T2 _w)
: x((T)_x)
, y((T)yz.x)
, z((T)yz.y)
, w((T)_w)
{}
template<typename T>
template<typename T2>
inline tmlVector4<T>::tmlVector4(const tmlVector2<T2> &xy, T2 _z, T2 _w)
: x((T)xy.x)
, y((T)xy.y)
, z((T)_z)
, w((T)_w)
{}
template<typename T>
template<typename T2>
inline tmlVector4<T>::tmlVector4(tmlVector4<T2> copy)
: x((T)copy.x)
, y((T)copy.y)
, z((T)copy.z)
, w((T)copy.w)
{}
template<typename T>
inline tmlVector4<T>::tmlVector4(const tmlVector2<T> &xy, const tmlVector2<T> &yw)
: x(xy.x)
, y(xy.y)
, z(yw.x)
, w(yw.y)
{}
template<typename T>
inline tmlVector4<T>::tmlVector4(const tmlVector4<T> ©)
: x(copy.x)
, y(copy.y)
, z(copy.z)
, w(copy.w)
{}
template<typename T>
inline tmlVector4<T>::tmlVector4(tmlVector4<T> &&move)
: x(move.x)
, y(move.y)
, z(move.z)
, w(move.w)
{}
template<typename T>
inline const tmlVector4<T>& tmlVector4<T>::assign(T _x, T _y, T _z, T _w)
{
x = _x;
y = _y;
z = _z;
w = _w;
return *this;
}
template<typename T>
template<typename T2>
inline const tmlVector4<T>& tmlVector4<T>::assign(T2 _x, T2 _y, T2 _z, T2 _w)
{
x = (T)_x;
y = (T)_y;
z = (T)_z;
w = (T)_w;
return *this;
}
template<typename T>
template<typename T2>
inline const tmlVector4<T>& tmlVector4<T>::assign(const tmlVector4<T2> &rhs)
{
x = (T)rhs.x;
y = (T)rhs.y;
z = (T)rhs.z;
w = (T)rhs.w;
return *this;
}
template<typename T>
inline const tmlVector4<T>& tmlVector4<T>::assign(const tmlVector4<T> &rhs)
{
x = (T)rhs.x;
y = (T)rhs.y;
z = (T)rhs.z;
w = (T)rhs.w;
return *this;
}
template<typename T>
inline T tmlVector4<T>::Dot(const tmlVector4<T> &lhs, const tmlVector4<T> &rhs)
{
return lhs.x * rhs.x +
lhs.y * rhs.y +
lhs.z * rhs.z +
lhs.w * rhs.w;
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::Max(const tmlVector4<T> &a, const tmlVector4<T> &b)
{
return tmlVector4<T>(atMax(a.x, b.x), tmlMax(a.y, b.y), tmlMax(a.z, b.z), tmlMax(a.w, b.w));
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::Min(const tmlVector4<T> &a, const tmlVector4<T> &b)
{
return tmlVector4<T>(atMin(a.x, b.x), tmlMin(a.y, b.y), tmlMin(a.z, b.z), tmlMin(a.w, b.w));
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::Clamp(const tmlVector4<T> &vec, const tmlVector4<T> &min, const tmlVector4<T> &max)
{
return Max(min, Min(vec, max));
}
template<typename T>
inline tmlVector2<T> tmlVector4<T>::xy() const
{
return tmlVector2<T>(x, y);
}
template<typename T>
inline tmlVector2<T> tmlVector4<T>::xz() const
{
return tmlVector2<T>(x, z);
}
template<typename T>
inline tmlVector2<T> tmlVector4<T>::xw() const
{
return tmlVector2<T>(x, w);
}
template<typename T>
inline tmlVector2<T> tmlVector4<T>::yz() const
{
return tmlVector2<T>(y, z);
}
template<typename T>
inline tmlVector2<T> tmlVector4<T>::yw() const
{
return tmlVector2<T>(y, w);
}
template<typename T>
inline tmlVector2<T> tmlVector4<T>::zw() const
{
return tmlVector2<T>(z, w);
}
template<typename T>
inline tmlVector3<T> tmlVector4<T>::xyz() const
{
return tmlVector3<T>(x, y, z);
}
template<typename T>
inline tmlVector3<T> tmlVector4<T>::xzw() const
{
return tmlVector3<T>(x, z, w);
}
template<typename T>
inline tmlVector3<T> tmlVector4<T>::xyw() const
{
return tmlVector3<T>(x, y, w);
}
template<typename T>
inline tmlVector3<T> tmlVector4<T>::yzw() const
{
return tmlVector3<T>(y, z, w);
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::Add(const tmlVector4<T> &rhs) const
{
return *this + rhs;
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::Sub(const tmlVector4<T> &rhs) const
{
return *this - rhs;
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::Mul(const tmlVector4<T> &rhs) const
{
return *this * rhs;
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::Div(const tmlVector4<T> &rhs) const
{
return *this / rhs;
}
template<typename T>
inline T tmlVector4<T>::Mag() const
{
return Mag(*this);
}
template<typename T>
inline T tmlVector4<T>::Length() const
{
return Length(*this);
}
template<typename T>
inline T tmlVector4<T>::Dot(const tmlVector4<T> &rhs) const
{
return Dot(*this, rhs);
}
template<typename T>
inline T tmlVector4<T>::Angle(const tmlVector4<T> &rhs) const
{
return Angle(*this, rhs);
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::Normalize() const
{
return Normalize(*this);
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::Reflect(const tmlVector4<T> &norm) const
{
return Reflect(*this, norm);
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::Project(const tmlVector4<T> &to) const
{
return Project(*this, to);
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::Max(const tmlVector4<T> &b) const
{
return Max(*this, b);
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::Min(const tmlVector4<T> &b) const
{
return Min(*this, b);
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::Clamp(const tmlVector4<T> &min, const tmlVector4<T> &max) const
{
return Clamp(*this, min, max);
}
template<typename T>
inline T tmlVector4<T>::Mag(const tmlVector4<T> &rhs)
{
return tmlSqrt(Length(rhs));
}
template<typename T>
inline T tmlVector4<T>::Length(const tmlVector4<T> &rhs)
{
return Dot(rhs, rhs);
}
template<typename T>
inline T tmlVector4<T>::Angle(const tmlVector4<T> &lhs, const tmlVector4<T> &rhs)
{
return tmlACos(Dot(lhs, rhs) / (Mag(lhs) * Mag(rhs)));
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::Reflect(const tmlVector4<T> &dir, const tmlVector4<T> &norm)
{
return dir - norm * Dot(dir, norm) * 2;
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::Normalize(const tmlVector4<T> &rhs)
{
return rhs / Mag(rhs);
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::Project(const tmlVector4<T> &vec, const tmlVector4<T> &to)
{
return vec * to.Normalize();
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::zero()
{
return tmlVector4<T>((T)0);
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::one()
{
return tmlVector4<T>((T)1);
}
template<typename T>
inline T& tmlVector4<T>::operator[](int64_t index)
{
return m[index];
}
template<typename T>
inline const T& tmlVector4<T>::operator[](int64_t index) const
{
return m[index];
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::operator-() const
{
return tmlVector4<T>(-x, -y, -z, -w);
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::operator+(const tmlVector4<T> &rhs) const
{
return tmlVector4<T>(x + rhs.x, y + rhs.y, z + rhs.z, w + rhs.w);
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::operator-(const tmlVector4<T> &rhs) const
{
return tmlVector4<T>(x - rhs.x, y - rhs.y, z - rhs.z, w - rhs.w);
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::operator*(const tmlVector4<T> &rhs) const
{
return tmlVector4<T>(x * rhs.x, y * rhs.y, z * rhs.z, w * rhs.w);
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::operator/(const tmlVector4<T> &rhs) const
{
return tmlVector4<T>(x / rhs.x, y / rhs.y, z / rhs.z, w / rhs.w);
}
template<typename T>
inline tmlVector4<T> tmlVector4<T>::operator%(const tmlVector4<T> &rhs) const
{
return tmlVector4<T>(x % rhs.x, y % rhs.y, z % rhs.z, w % rhs.w);
}
template<typename T>
inline const tmlVector4<T>& tmlVector4<T>::operator+=(const tmlVector4<T> &rhs)
{
return assign(*this + rhs);
}
template<typename T>
inline const tmlVector4<T>& tmlVector4<T>::operator-=(const tmlVector4<T> &rhs)
{
return assign(*this - rhs);
}
template<typename T>
inline const tmlVector4<T>& tmlVector4<T>::operator*=(const tmlVector4<T> &rhs)
{
return assign(*this * rhs);
}
template<typename T>
inline const tmlVector4<T>& tmlVector4<T>::operator/=(const tmlVector4<T> &rhs)
{
return assign(*this / rhs);
}
template<typename T>
inline const tmlVector4<T>& tmlVector4<T>::operator%=(const tmlVector4<T> &rhs)
{
return assign(atMod(x, rhs.x), tmlMod(y, rhs.y), tmlMod(z, rhs.z), tmlMod(w, rhs.w));
}
template<typename T>
inline const tmlVector4<T>& tmlVector4<T>::operator=(const tmlVector4<T> &rhs)
{
return assign(rhs);
}
template<typename T>
inline bool tmlVector4<T>::operator==(const tmlVector4<T> &rhs) const
{
return x == rhs.x && y == rhs.y && z == rhs.z && w == rhs.w;
}
template<typename T>
inline bool tmlVector4<T>::operator!=(const tmlVector4<T> &rhs) const
{
return !(*this == rhs);
}
template<typename T>
inline const T* tmlVector4<T>::end() const
{
return m + ElementCount;
}
template<typename T>
inline const T* tmlVector4<T>::begin() const
{
return m;
}
template<typename T>
inline const T* tmlVector4<T>::data() const
{
return m;
}
template<typename T>
inline T* tmlVector4<T>::end()
{
return m + ElementCount;
}
template<typename T>
inline T* tmlVector4<T>::begin()
{
return m;
}
template<typename T>
inline T* tmlVector4<T>::data()
{
return m;
}
template<typename T>
inline tmlVector4<T> operator*(const T &lhs, const tmlVector4<T> &rhs)
{
return rhs * lhs;
}
template<typename T>
inline tmlVector4<T> operator/(const T &lhs, const tmlVector4<T> &rhs)
{
return tmlVector4<T>(lhs / rhs.x, lhs / rhs.y, lhs / rhs.z, lhs / rhs.w);
}
| 19.671958 | 119 | 0.659674 | mbatc |
8113150dfb348382492944415f1bc06d7286c299 | 4,363 | cpp | C++ | src/tests/containerizer/composing_containerizer_tests.cpp | NinthDecimal/mesos | 601c3cd3dfaa8e353a1f404676bf779bd2989843 | [
"Apache-2.0"
] | null | null | null | src/tests/containerizer/composing_containerizer_tests.cpp | NinthDecimal/mesos | 601c3cd3dfaa8e353a1f404676bf779bd2989843 | [
"Apache-2.0"
] | null | null | null | src/tests/containerizer/composing_containerizer_tests.cpp | NinthDecimal/mesos | 601c3cd3dfaa8e353a1f404676bf779bd2989843 | [
"Apache-2.0"
] | null | null | null | /**
* 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.
*/
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <process/future.hpp>
#include <process/gmock.hpp>
#include <stout/option.hpp>
#include "messages/messages.hpp"
#include "slave/containerizer/containerizer.hpp"
#include "slave/containerizer/composing.hpp"
#include "tests/mesos.hpp"
using namespace mesos::internal::slave;
using namespace process;
using std::vector;
using testing::_;
using testing::Return;
namespace mesos {
namespace internal {
namespace tests {
class ComposingContainerizerTest : public MesosTest {};
class MockContainerizer : public slave::Containerizer
{
public:
MOCK_METHOD1(
recover,
process::Future<Nothing>(
const Option<slave::state::SlaveState>&));
MOCK_METHOD7(
launch,
process::Future<bool>(
const ContainerID&,
const ExecutorInfo&,
const std::string&,
const Option<std::string>&,
const SlaveID&,
const process::PID<Slave>&,
bool));
MOCK_METHOD8(
launch,
process::Future<bool>(
const ContainerID&,
const TaskInfo&,
const ExecutorInfo&,
const std::string&,
const Option<std::string>&,
const SlaveID&,
const process::PID<Slave>&,
bool));
MOCK_METHOD2(
update,
process::Future<Nothing>(
const ContainerID&,
const Resources&));
MOCK_METHOD1(
usage,
process::Future<ResourceStatistics>(
const ContainerID&));
MOCK_METHOD1(
wait,
process::Future<containerizer::Termination>(
const ContainerID&));
MOCK_METHOD1(
destroy,
void(const ContainerID&));
MOCK_METHOD0(
containers,
process::Future<hashset<ContainerID> >());
};
// This test checks if destroy is called while container is being
// launched, the composing containerizer still calls the underlying
// containerizer's destroy and skip calling the rest of the
// containerizers.
TEST_F(ComposingContainerizerTest, DestroyWhileLaunching)
{
vector<Containerizer*> containerizers;
MockContainerizer* mockContainerizer = new MockContainerizer();
MockContainerizer* mockContainerizer2 = new MockContainerizer();
containerizers.push_back(mockContainerizer);
containerizers.push_back(mockContainerizer2);
ComposingContainerizer containerizer(containerizers);
ContainerID containerId;
containerId.set_value("container");
TaskInfo taskInfo;
ExecutorInfo executorInfo;
SlaveID slaveId;
PID<Slave> slavePid;
Promise<bool> launchPromise;
EXPECT_CALL(*mockContainerizer, launch(_, _, _, _, _, _, _, _))
.WillOnce(Return(launchPromise.future()));
Future<Nothing> destroy;
EXPECT_CALL(*mockContainerizer, destroy(_))
.WillOnce(FutureSatisfy(&destroy));
Future<bool> launch = containerizer.launch(
containerId,
taskInfo,
executorInfo,
"dir",
"user",
slaveId,
slavePid,
false);
Resources resources = Resources::parse("cpus:1;mem:256").get();
EXPECT_TRUE(launch.isPending());
containerizer.destroy(containerId);
EXPECT_CALL(*mockContainerizer2, launch(_, _, _, _, _, _, _, _))
.Times(0);
// We make sure the destroy is being called on the first containerizer.
// The second containerizer shouldn't be called as well since the
// container is already destroyed.
AWAIT_READY(destroy);
launchPromise.set(false);
AWAIT_FAILED(launch);
}
} // namespace tests {
} // namespace internal {
} // namespace mesos {
| 25.219653 | 75 | 0.691955 | NinthDecimal |
8115d66462ee123dc86f5ff58d206fb39b2c7f99 | 1,094 | cpp | C++ | 239. Sliding Window Maximum/main.cpp | shenzheyu/LeetCode | 08478996f9c41a526ea8560233b4e91ed04c9682 | [
"MIT"
] | 6 | 2018-04-20T14:43:06.000Z | 2021-01-17T21:51:22.000Z | 239. Sliding Window Maximum/main.cpp | shenzheyu/LeetCode | 08478996f9c41a526ea8560233b4e91ed04c9682 | [
"MIT"
] | 1 | 2018-04-29T13:10:02.000Z | 2018-04-29T14:47:44.000Z | 239. Sliding Window Maximum/main.cpp | shenzheyu/LeetCode | 08478996f9c41a526ea8560233b4e91ed04c9682 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <deque>
using namespace std;
class MonotonicQueue {
public:
// push element n at back
void push(int n) {
while (!data.empty() && data.back() < n) {
data.pop_back();
}
data.push_back(n);
}
// return the max value in queue
int max() {
return data.front();
}
// if front is n, pop it
void pop(int n) {
if (!data.empty() && data.front() == n) {
data.pop_front();
}
}
private:
deque<int> data;
};
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
MonotonicQueue window;
vector<int> res;
for (int i = 0; i < nums.size(); i++) {
if (i < k - 1) {
window.push(nums[i]);
} else {
window.push(nums[i]);
res.push_back(window.max());
window.pop(nums[i - k + 1]);
}
}
return res;
}
};
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
| 19.535714 | 60 | 0.474406 | shenzheyu |
8117495cdf7132a902636fce0b5868cf605663bb | 2,195 | cpp | C++ | src/library/tactic/check_expr_tactic.cpp | javra/lean | cc70845332e63a1f1be21dc1f96d17269fc85909 | [
"Apache-2.0"
] | 130 | 2016-12-02T22:46:10.000Z | 2022-03-22T01:09:48.000Z | src/library/tactic/check_expr_tactic.cpp | soonhokong/lean | 38607e3eb57f57f77c0ac114ad169e9e4262e24f | [
"Apache-2.0"
] | 8 | 2017-05-03T01:21:08.000Z | 2020-02-25T11:38:05.000Z | src/library/tactic/check_expr_tactic.cpp | soonhokong/lean | 38607e3eb57f57f77c0ac114ad169e9e4262e24f | [
"Apache-2.0"
] | 28 | 2016-12-02T22:46:20.000Z | 2022-03-18T21:28:20.000Z | /*
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <string>
#include "util/fresh_name.h"
#include "library/constants.h"
#include "library/reducible.h"
#include "library/flycheck.h"
#include "library/tactic/expr_to_tactic.h"
namespace lean {
tactic check_expr_tactic(elaborate_fn const & elab, expr const & e,
std::string const & fname, pair<unsigned, unsigned> const & pos) {
return tactic01([=](environment const & env, io_state const & ios, proof_state const & s) {
goals const & gs = s.get_goals();
if (empty(gs)) {
throw_no_goal_if_enabled(s);
return none_proof_state();
}
goal const & g = head(gs);
expr new_e = std::get<0>(elab(g, ios.get_options(), e, none_expr(), s.get_subst(), false));
auto tc = mk_type_checker(env);
expr new_t = tc->infer(new_e).first;
auto out = regular(env, ios, tc->get_type_context());
flycheck_information info(out.get_stream(), out.get_options());
if (info.enabled()) {
out << fname << ":" << pos.first << ":" << pos.second << ": information: ";
out << "check result:\n";
}
out << new_e << " : " << new_t << endl;
return some_proof_state(s);
});
}
void initialize_check_expr_tactic() {
register_tac(get_tactic_check_expr_name(),
[](type_checker &, elaborate_fn const & fn, expr const & e, pos_info_provider const * p) {
check_tactic_expr(app_arg(e), "invalid 'check_expr' tactic, invalid argument");
expr arg = get_tactic_expr_expr(app_arg(e));
if (p) {
if (auto it = p->get_pos_info(e))
return check_expr_tactic(fn, arg, std::string(p->get_file_name()), *it);
}
return check_expr_tactic(fn, arg, "<unknown file>", mk_pair(0, 0));
});
}
void finalize_check_expr_tactic() {
}
}
| 41.415094 | 107 | 0.561731 | javra |
8118a3bbdbc29795c14623c592d641eb8f0fc21e | 3,328 | cpp | C++ | Source/ProjectX/Character/AI/EnemyAI/EnemyAIController.cpp | pz64/project-x-college | fb269fb343db2d532cb205b691ee143207d75bdb | [
"Apache-2.0"
] | 1 | 2019-04-16T17:40:51.000Z | 2019-04-16T17:40:51.000Z | Source/ProjectX/Character/AI/EnemyAI/EnemyAIController.cpp | pz64/project-x-college | fb269fb343db2d532cb205b691ee143207d75bdb | [
"Apache-2.0"
] | null | null | null | Source/ProjectX/Character/AI/EnemyAI/EnemyAIController.cpp | pz64/project-x-college | fb269fb343db2d532cb205b691ee143207d75bdb | [
"Apache-2.0"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "EnemyAIController.h"
#include "BehaviorTree/BehaviorTreeComponent.h"
#include "BehaviorTree/BlackboardComponent.h"
#include "BehaviorTree/Blackboard/BlackboardKeyAllTypes.h"
#include "BehaviorTree/BehaviorTree.h"
#include "Perception/AIPerceptionComponent.h"
#include "Perception/AISenseConfig_Sight.h"
#include "enemyAICharacter.h"
#include "Character/ProjectXPlayerCharacter.h"
#include "EngineUtils.h"
#include "Character/AI/SupportAI/SupportAICharacter.h"
#include "Character/AI/CombatBehavior.h"
AEnemyAIController::AEnemyAIController()
{
BlackboardComp = CreateDefaultSubobject<UBlackboardComponent>(TEXT("BlackboardComp"));
BehaviourTreeComp = CreateDefaultSubobject<UBehaviorTreeComponent>(TEXT("BehaviourTreeComp"));
PerceptionComp = CreateDefaultSubobject<UAIPerceptionComponent>(TEXT("PerceptionComp"));
Sight = CreateDefaultSubobject<UAISenseConfig_Sight>(TEXT("Sight"));
Sight->SightRadius = 4000.f;
Sight->LoseSightRadius = 4500.f;
Sight->PeripheralVisionAngleDegrees = 170.f;
//Tell the sight sense to detect everything
Sight->DetectionByAffiliation.bDetectEnemies = true;
Sight->DetectionByAffiliation.bDetectFriendlies = true;
Sight->DetectionByAffiliation.bDetectNeutrals = true;
SetPerceptionComponent(*PerceptionComponent);
PerceptionComp->ConfigureSense(*Sight);
}
void AEnemyAIController::Possess(APawn * InPawn)
{
Super::Possess(InPawn);
AEnemyAICharacter *AIChar = Cast<AEnemyAICharacter>(InPawn);
if (AIChar && AIChar->AIBehaviour)
{
BlackboardComp->InitializeBlackboard(*AIChar->AIBehaviour->BlackboardAsset);
SelfKeyID = BlackboardComp->GetKeyID("SelfActor");
PlayerKeyID = BlackboardComp->GetKeyID("Player");
BlackboardComp->SetValue<UBlackboardKeyType_Object>(SelfKeyID, AIChar);
BehaviourTreeComp->StartTree(*AIChar->AIBehaviour);
}
GetPerceptionComponent()->OnPerceptionUpdated.AddDynamic(this, &AEnemyAIController::OnPerceptionUpdated);
}
bool AEnemyAIController::isPlayerNearby()
{
return BlackboardComp->GetValue<UBlackboardKeyType_Object>(PlayerKeyID) ? true : false;
}
void AEnemyAIController::OnPerceptionUpdated(TArray<AActor*> UpdatedActors)
{
TArray<ACombatBehavior*> CombatBehavior;
FindAllActors<ACombatBehavior>(GetWorld(), CombatBehavior);
bool EnemyDetected = false;
for (AActor* Player : UpdatedActors)
{
if (
CombatBehavior.Num() &&
Player->IsA<ASupportAICharacter>() &&
Cast<ASupportAICharacter>(Player) == CombatBehavior[0]->GetSupportAIOf(Cast<AEnemyAICharacter>(GetPawn()))
)
{
EnemyDetected = true;
BlackboardComp->SetValueAsObject("Enemy", Player);
break;
}
}
for (AActor* Player : UpdatedActors)
if (Player->IsA<AProjectXPlayerCharacter>() && !isPlayerNearby())
{
BlackboardComp->SetValueAsObject(BlackboardPlayerKey, Player);
return;
}
if (!isPlayerNearby())
BlackboardComp->SetValueAsObject(BlackboardPlayerKey, nullptr);
}
template<typename T>
void FindAllActors(UWorld* World, TArray<T*>& Out)
{
for (TActorIterator<AActor> It(World, T::StaticClass()); It; ++It)
{
T* Actor = Cast<T>(*It);
if (Actor && !Actor->IsPendingKill())
{
Out.Add(Actor);
}
}
}
| 29.714286 | 110 | 0.746695 | pz64 |
811c3c9d52df9cab749f26292de6aadaa7357c49 | 80 | cpp | C++ | test/llvm_test_code/constness/basic/basic_03.cpp | flix-/phasar | 85b30c329be1766136c8cbc6f925cb4fd1bafd27 | [
"BSL-1.0"
] | 581 | 2018-06-10T10:37:55.000Z | 2022-03-30T14:56:53.000Z | test/llvm_test_code/constness/basic/basic_03.cpp | flix-/phasar | 85b30c329be1766136c8cbc6f925cb4fd1bafd27 | [
"BSL-1.0"
] | 172 | 2018-06-13T12:33:26.000Z | 2022-03-26T07:21:41.000Z | test/llvm_test_code/constness/basic/basic_03.cpp | flix-/phasar | 85b30c329be1766136c8cbc6f925cb4fd1bafd27 | [
"BSL-1.0"
] | 137 | 2018-06-10T10:31:14.000Z | 2022-03-06T11:53:56.000Z | /* i | %2 (ID: 1) */
int main() {
int i = 10;
int j = 14;
i = j;
return 0;
} | 11.428571 | 20 | 0.4125 | flix- |
812221fc845508a99f8b91e2a2f8091e63516a26 | 19,580 | hpp | C++ | source/backend/cpu/x86_x64/avx512/Gemm48_8.hpp | JujuDel/MNN | 8a82f5c5a7ae37192784c2dbd6dfc8ca8833565a | [
"Apache-2.0"
] | 1 | 2021-09-17T03:22:16.000Z | 2021-09-17T03:22:16.000Z | source/backend/cpu/x86_x64/avx512/Gemm48_8.hpp | JujuDel/MNN | 8a82f5c5a7ae37192784c2dbd6dfc8ca8833565a | [
"Apache-2.0"
] | null | null | null | source/backend/cpu/x86_x64/avx512/Gemm48_8.hpp | JujuDel/MNN | 8a82f5c5a7ae37192784c2dbd6dfc8ca8833565a | [
"Apache-2.0"
] | null | null | null | #ifndef __AVX512_GEMM48_8_HPP__
#define __AVX512_GEMM48_8_HPP__
#define MNNAVXFMA _mm256_fmadd_ps
#define MNNAVX512FMA _mm512_fmadd_ps
#define INIT_MAIN_4_8 \
auto s0 = _mm256_loadu_ps(weight + 0 * 8); \
auto w0 = _mm256_broadcast_ss(A + 0 * aStride + 0); \
auto w1 = _mm256_broadcast_ss(A + 0 * aStride + 1); \
auto w2 = _mm256_broadcast_ss(A + 0 * aStride + 2); \
auto w3 = _mm256_broadcast_ss(A + 0 * aStride + 3); \
auto z0 = _mm256_mul_ps(s0, w0); \
auto z1 = _mm256_mul_ps(s0, w1); \
auto z2 = _mm256_mul_ps(s0, w2); \
auto z3 = _mm256_mul_ps(s0, w3); \
#define COMPUTE_4_8 \
s0 = _mm256_loadu_ps(weight + sy * 8); \
w0 = _mm256_broadcast_ss(A + sy * aStride + 0); \
w1 = _mm256_broadcast_ss(A + sy * aStride + 1); \
w2 = _mm256_broadcast_ss(A + sy * aStride + 2); \
w3 = _mm256_broadcast_ss(A + sy * aStride + 3); \
z0 = MNNAVXFMA(s0, w0, z0); \
z1 = MNNAVXFMA(s0, w1, z1); \
z2 = MNNAVXFMA(s0, w2, z2); \
z3 = MNNAVXFMA(s0, w3, z3); \
#define INIT_MAIN_5_8 \
auto s0 = _mm256_loadu_ps(weight + 0 * 8); \
auto w0 = _mm256_broadcast_ss(A + 0 * aStride + 0); \
auto w1 = _mm256_broadcast_ss(A + 0 * aStride + 1); \
auto w2 = _mm256_broadcast_ss(A + 0 * aStride + 2); \
auto w3 = _mm256_broadcast_ss(A + 0 * aStride + 3); \
auto w4 = _mm256_broadcast_ss(A + 0 * aStride + 4); \
auto z0 = _mm256_mul_ps(s0, w0); \
auto z1 = _mm256_mul_ps(s0, w1); \
auto z2 = _mm256_mul_ps(s0, w2); \
auto z3 = _mm256_mul_ps(s0, w3); \
auto z4 = _mm256_mul_ps(s0, w4); \
#define COMPUTE_5_8 \
s0 = _mm256_loadu_ps(weight + sy * 8); \
w0 = _mm256_broadcast_ss(A + sy * aStride + 0); \
w1 = _mm256_broadcast_ss(A + sy * aStride + 1); \
w2 = _mm256_broadcast_ss(A + sy * aStride + 2); \
w3 = _mm256_broadcast_ss(A + sy * aStride + 3); \
w4 = _mm256_broadcast_ss(A + sy * aStride + 4); \
z0 = MNNAVXFMA(s0, w0, z0); \
z1 = MNNAVXFMA(s0, w1, z1); \
z2 = MNNAVXFMA(s0, w2, z2); \
z3 = MNNAVXFMA(s0, w3, z3); \
z4 = MNNAVXFMA(s0, w4, z4); \
#define INIT_MAIN_8_8 \
auto s0 = _mm256_loadu_ps(A + 0 * aStride); \
auto w0 = _mm256_broadcast_ss(weight + 0 * 8 + 0); \
auto w1 = _mm256_broadcast_ss(weight + 0 * 8 + 1); \
auto w2 = _mm256_broadcast_ss(weight + 0 * 8 + 2); \
auto w3 = _mm256_broadcast_ss(weight + 0 * 8 + 3); \
auto w4 = _mm256_broadcast_ss(weight + 0 * 8 + 4); \
auto w5 = _mm256_broadcast_ss(weight + 0 * 8 + 5); \
auto w6 = _mm256_broadcast_ss(weight + 0 * 8 + 6); \
auto w7 = _mm256_broadcast_ss(weight + 0 * 8 + 7); \
auto z0 = _mm256_mul_ps(s0, w0); \
auto z1 = _mm256_mul_ps(s0, w1); \
auto z2 = _mm256_mul_ps(s0, w2); \
auto z3 = _mm256_mul_ps(s0, w3); \
auto z4 = _mm256_mul_ps(s0, w4); \
auto z5 = _mm256_mul_ps(s0, w5); \
auto z6 = _mm256_mul_ps(s0, w6); \
auto z7 = _mm256_mul_ps(s0, w7);
#define COMPUTE_8_8 \
s0 = _mm256_loadu_ps(A + sy * aStride); \
w0 = _mm256_broadcast_ss(weight + sy * 8 + 0); \
w1 = _mm256_broadcast_ss(weight + sy * 8 + 1); \
w2 = _mm256_broadcast_ss(weight + sy * 8 + 2); \
w3 = _mm256_broadcast_ss(weight + sy * 8 + 3); \
w4 = _mm256_broadcast_ss(weight + sy * 8 + 4); \
w5 = _mm256_broadcast_ss(weight + sy * 8 + 5); \
w6 = _mm256_broadcast_ss(weight + sy * 8 + 6); \
w7 = _mm256_broadcast_ss(weight + sy * 8 + 7); \
z0 = MNNAVXFMA(s0, w0, z0); \
z1 = MNNAVXFMA(s0, w1, z1); \
z2 = MNNAVXFMA(s0, w2, z2); \
z3 = MNNAVXFMA(s0, w3, z3); \
z4 = MNNAVXFMA(s0, w4, z4); \
z5 = MNNAVXFMA(s0, w5, z5); \
z6 = MNNAVXFMA(s0, w6, z6); \
z7 = MNNAVXFMA(s0, w7, z7);
#define INIT_MAIN_16_8 \
auto s0 = _mm512_loadu_ps(A + 0 * aStride); \
auto wt = _mm_load_ss(weight + 0 * 8 + 0); \
auto w0 = _mm512_broadcastss_ps(wt); \
auto z0 = _mm512_mul_ps(s0, w0); \
wt = _mm_load_ss(weight + 0 * 8 + 1); \
auto w1 = _mm512_broadcastss_ps(wt); \
auto z1 = _mm512_mul_ps(s0, w1); \
wt = _mm_load_ss(weight + 0 * 8 + 2); \
auto w2 = _mm512_broadcastss_ps(wt); \
auto z2 = _mm512_mul_ps(s0, w2); \
wt = _mm_load_ss(weight + 0 * 8 + 3); \
auto w3 = _mm512_broadcastss_ps(wt); \
auto z3 = _mm512_mul_ps(s0, w3); \
wt = _mm_load_ss(weight + 0 * 8 + 4); \
auto w4 = _mm512_broadcastss_ps(wt); \
auto z4 = _mm512_mul_ps(s0, w4); \
wt = _mm_load_ss(weight + 0 * 8 + 5); \
auto w5 = _mm512_broadcastss_ps(wt); \
auto z5 = _mm512_mul_ps(s0, w5); \
wt = _mm_load_ss(weight + 0 * 8 + 6); \
auto w6 = _mm512_broadcastss_ps(wt); \
auto z6 = _mm512_mul_ps(s0, w6); \
wt = _mm_load_ss(weight + 0 * 8 + 7); \
auto w7 = _mm512_broadcastss_ps(wt); \
auto z7 = _mm512_mul_ps(s0, w7);
#define COMPUTE_16_8 \
s0 = _mm512_loadu_ps(A + sy * aStride); \
wt = _mm_load_ss(weight + sy * 8 + 0); \
w0 = _mm512_broadcastss_ps(wt); \
z0 = MNNAVX512FMA(s0, w0, z0); \
wt = _mm_load_ss(weight + sy * 8 + 1); \
w1 = _mm512_broadcastss_ps(wt); \
z1 = MNNAVX512FMA(s0, w1, z1); \
wt = _mm_load_ss(weight + sy * 8 + 2); \
w2 = _mm512_broadcastss_ps(wt); \
z2 = MNNAVX512FMA(s0, w2, z2); \
wt = _mm_load_ss(weight + sy * 8 + 3); \
w3 = _mm512_broadcastss_ps(wt); \
z3 = MNNAVX512FMA(s0, w3, z3); \
wt = _mm_load_ss(weight + sy * 8 + 4); \
w4 = _mm512_broadcastss_ps(wt); \
z4 = MNNAVX512FMA(s0, w4, z4); \
wt = _mm_load_ss(weight + sy * 8 + 5); \
w5 = _mm512_broadcastss_ps(wt); \
z5 = MNNAVX512FMA(s0, w5, z5); \
wt = _mm_load_ss(weight + sy * 8 + 6); \
w6 = _mm512_broadcastss_ps(wt); \
z6 = MNNAVX512FMA(s0, w6, z6); \
wt = _mm_load_ss(weight + sy * 8 + 7); \
w7 = _mm512_broadcastss_ps(wt); \
z7 = MNNAVX512FMA(s0, w7, z7);
#define INIT_MAIN_48_8 \
auto s0 = _mm512_loadu_ps(A + 0 * 48); \
auto s1 = _mm512_loadu_ps(A + 0 * 48 + 16); \
auto s2 = _mm512_loadu_ps(A + 0 * 48 + 32); \
auto wt = _mm_load_ss(weight + 0 * 8 + 0); \
auto w0 = _mm512_broadcastss_ps(wt); \
auto z0 = _mm512_mul_ps(s0, w0); \
auto z1 = _mm512_mul_ps(s1, w0); \
auto z2 = _mm512_mul_ps(s2, w0); \
wt = _mm_load_ss(weight + 0 * 8 + 1); \
auto w1 = _mm512_broadcastss_ps(wt); \
auto z3 = _mm512_mul_ps(s0, w1); \
auto z4 = _mm512_mul_ps(s1, w1); \
auto z5 = _mm512_mul_ps(s2, w1); \
wt = _mm_load_ss(weight + 0 * 8 + 2); \
auto w2 = _mm512_broadcastss_ps(wt); \
auto z6 = _mm512_mul_ps(s0, w2); \
auto z7 = _mm512_mul_ps(s1, w2); \
auto z8 = _mm512_mul_ps(s2, w2); \
wt = _mm_load_ss(weight + 0 * 8 + 3); \
auto w3 = _mm512_broadcastss_ps(wt); \
auto z9 = _mm512_mul_ps(s0, w3); \
auto z10 = _mm512_mul_ps(s1, w3); \
auto z11 = _mm512_mul_ps(s2, w3); \
wt = _mm_load_ss(weight + 0 * 8 + 4); \
auto w4 = _mm512_broadcastss_ps(wt); \
auto z12 = _mm512_mul_ps(s0, w4); \
auto z13 = _mm512_mul_ps(s1, w4); \
auto z14 = _mm512_mul_ps(s2, w4); \
wt = _mm_load_ss(weight + 0 * 8 + 5); \
auto w5 = _mm512_broadcastss_ps(wt); \
auto z15 = _mm512_mul_ps(s0, w5); \
auto z16 = _mm512_mul_ps(s1, w5); \
auto z17 = _mm512_mul_ps(s2, w5); \
wt = _mm_load_ss(weight + 0 * 8 + 6); \
auto w6 = _mm512_broadcastss_ps(wt); \
auto z18 = _mm512_mul_ps(s0, w6); \
auto z19 = _mm512_mul_ps(s1, w6); \
auto z20 = _mm512_mul_ps(s2, w6); \
wt = _mm_load_ss(weight + 0 * 8 + 7); \
auto w7 = _mm512_broadcastss_ps(wt); \
auto z21 = _mm512_mul_ps(s0, w7); \
auto z22 = _mm512_mul_ps(s1, w7); \
auto z23 = _mm512_mul_ps(s2, w7);
#define COMPUTE_48_8 \
s0 = _mm512_loadu_ps(A + sy * 48); \
s1 = _mm512_loadu_ps(A + sy * 48 + 16); \
s2 = _mm512_loadu_ps(A + sy * 48 + 32); \
wt = _mm_load_ss(weight + sy * 8 + 0); \
w0 = _mm512_broadcastss_ps(wt); \
z0 = MNNAVX512FMA(s0, w0, z0); \
z1 = MNNAVX512FMA(s1, w0, z1); \
z2 = MNNAVX512FMA(s2, w0, z2); \
wt = _mm_load_ss(weight + sy * 8 + 1); \
w1 = _mm512_broadcastss_ps(wt); \
z3 = MNNAVX512FMA(s0, w1, z3); \
z4 = MNNAVX512FMA(s1, w1, z4); \
z5 = MNNAVX512FMA(s2, w1, z5); \
wt = _mm_load_ss(weight + sy * 8 + 2); \
w2 = _mm512_broadcastss_ps(wt); \
z6 = MNNAVX512FMA(s0, w2, z6); \
z7 = MNNAVX512FMA(s1, w2, z7); \
z8 = MNNAVX512FMA(s2, w2, z8); \
wt = _mm_load_ss(weight + sy * 8 + 3); \
w3 = _mm512_broadcastss_ps(wt); \
z9 = MNNAVX512FMA(s0, w3, z9); \
z10 = MNNAVX512FMA(s1, w3, z10); \
z11 = MNNAVX512FMA(s2, w3, z11); \
wt = _mm_load_ss(weight + sy * 8 + 4); \
w4 = _mm512_broadcastss_ps(wt); \
z12 = MNNAVX512FMA(s0, w4, z12); \
z13 = MNNAVX512FMA(s1, w4, z13); \
z14 = MNNAVX512FMA(s2, w4, z14); \
wt = _mm_load_ss(weight + sy * 8 + 5); \
w5 = _mm512_broadcastss_ps(wt); \
z15 = MNNAVX512FMA(s0, w5, z15); \
z16 = MNNAVX512FMA(s1, w5, z16); \
z17 = MNNAVX512FMA(s2, w5, z17); \
wt = _mm_load_ss(weight + sy * 8 + 6); \
w6 = _mm512_broadcastss_ps(wt); \
z18 = MNNAVX512FMA(s0, w6, z18); \
z19 = MNNAVX512FMA(s1, w6, z19); \
z20 = MNNAVX512FMA(s2, w6, z20); \
wt = _mm_load_ss(weight + sy * 8 + 7); \
w7 = _mm512_broadcastss_ps(wt); \
z21 = MNNAVX512FMA(s0, w7, z21); \
z22 = MNNAVX512FMA(s1, w7, z22); \
z23 = MNNAVX512FMA(s2, w7, z23);
#define AVX512_TRANSPOSE_SAVE(u, v, z0, z3, z6, z9, z12, z15, z18, z21) \
{ \
auto m0 = _mm512_extractf32x4_ps(z0, u); \
auto m1 = _mm512_extractf32x4_ps(z3, u); \
auto m2 = _mm512_extractf32x4_ps(z6, u); \
auto m3 = _mm512_extractf32x4_ps(z9, u); \
auto m4 = _mm512_extractf32x4_ps(z12, u); \
auto m5 = _mm512_extractf32x4_ps(z15, u); \
auto m6 = _mm512_extractf32x4_ps(z18, u); \
auto m7 = _mm512_extractf32x4_ps(z21, u); \
_MM_TRANSPOSE4_PS(m0, m1, m2, m3); \
_MM_TRANSPOSE4_PS(m4, m5, m6, m7); \
auto tmp0 = _mm256_castps128_ps256(m0); \
auto tmp4 = _mm256_castps128_ps256(m4); \
auto s0 = _mm256_permute2f128_ps(tmp0, tmp4, 0x20); \
auto tmp1 = _mm256_castps128_ps256(m1); \
auto tmp5 = _mm256_castps128_ps256(m5); \
auto s1 = _mm256_permute2f128_ps(tmp1, tmp5, 0x20); \
auto tmp2 = _mm256_castps128_ps256(m2); \
auto tmp6 = _mm256_castps128_ps256(m6); \
auto s2 = _mm256_permute2f128_ps(tmp2, tmp6, 0x20); \
auto tmp3 = _mm256_castps128_ps256(m3); \
auto tmp7 = _mm256_castps128_ps256(m7); \
auto s3 = _mm256_permute2f128_ps(tmp3, tmp7, 0x20); \
_mm256_storeu_ps(dst + 128 * v + 32 * u, s0); \
_mm256_storeu_ps(dst + 128 * v + 32 * u + 8, s1); \
_mm256_storeu_ps(dst + 128 * v + 32 * u + 16, s2); \
_mm256_storeu_ps(dst + 128 * v + 32 * u + 24, s3); \
}
#define AVX512_TRANSPOSE_SAVE_HALF(u, v, z0, z3, z6, z9, z12, z15, z18, z21) \
{ \
auto m0 = _mm512_extractf32x4_ps(z0, u); \
auto m1 = _mm512_extractf32x4_ps(z3, u); \
auto m2 = _mm512_extractf32x4_ps(z6, u); \
auto m3 = _mm512_extractf32x4_ps(z9, u); \
_MM_TRANSPOSE4_PS(m0, m1, m2, m3); \
auto tmp0 = _mm256_castps128_ps256(m0); \
auto tmp1 = _mm256_castps128_ps256(m1); \
auto s0 = _mm256_permute2f128_ps(tmp0, tmp1, 0x20); \
auto tmp2 = _mm256_castps128_ps256(m2); \
auto tmp3 = _mm256_castps128_ps256(m3); \
auto s1 = _mm256_permute2f128_ps(tmp2, tmp3, 0x20); \
_mm256_storeu_ps((dst + 128 * v + 32 * u), s0); \
_mm256_storeu_ps((dst + 128 * v + 32 * u + 8), s1); \
}
#define AVX2_TRANSPOSE_SAVE(u, z0, z3, z6, z9, z12, z15, z18, z21) \
{ \
auto m0 = _mm256_extractf128_ps(z0, u); \
auto m1 = _mm256_extractf128_ps(z3, u); \
auto m2 = _mm256_extractf128_ps(z6, u); \
auto m3 = _mm256_extractf128_ps(z9, u); \
auto m4 = _mm256_extractf128_ps(z12, u); \
auto m5 = _mm256_extractf128_ps(z15, u); \
auto m6 = _mm256_extractf128_ps(z18, u); \
auto m7 = _mm256_extractf128_ps(z21, u); \
_MM_TRANSPOSE4_PS(m0, m1, m2, m3); \
_MM_TRANSPOSE4_PS(m4, m5, m6, m7); \
auto tmp0 = _mm256_castps128_ps256(m0); \
auto tmp4 = _mm256_castps128_ps256(m4); \
auto s0 = _mm256_permute2f128_ps(tmp0, tmp4, 0x20); \
auto tmp1 = _mm256_castps128_ps256(m1); \
auto tmp5 = _mm256_castps128_ps256(m5); \
auto s1 = _mm256_permute2f128_ps(tmp1, tmp5, 0x20); \
auto tmp2 = _mm256_castps128_ps256(m2); \
auto tmp6 = _mm256_castps128_ps256(m6); \
auto s2 = _mm256_permute2f128_ps(tmp2, tmp6, 0x20); \
auto tmp3 = _mm256_castps128_ps256(m3); \
auto tmp7 = _mm256_castps128_ps256(m7); \
auto s3 = _mm256_permute2f128_ps(tmp3, tmp7, 0x20); \
_mm256_storeu_ps(dst + 32 * u, s0); \
_mm256_storeu_ps(dst + 32 * u + 8, s1); \
_mm256_storeu_ps(dst + 32 * u + 16, s2); \
_mm256_storeu_ps(dst + 32 * u + 24, s3); \
}
#define AVX2_TRANSPOSE_SAVE_HALF(u, z0, z3, z6, z9, z12, z15, z18, z21) \
{ \
auto m0 = _mm256_extractf128_ps(z0, u); \
auto m1 = _mm256_extractf128_ps(z3, u); \
auto m2 = _mm256_extractf128_ps(z6, u); \
auto m3 = _mm256_extractf128_ps(z9, u); \
_MM_TRANSPOSE4_PS(m0, m1, m2, m3); \
auto tmp0 = _mm256_castps128_ps256(m0); \
auto tmp1 = _mm256_castps128_ps256(m1); \
auto s0 = _mm256_permute2f128_ps(tmp0, tmp1, 0x20); \
auto tmp2 = _mm256_castps128_ps256(m2); \
auto tmp3 = _mm256_castps128_ps256(m3); \
auto s1 = _mm256_permute2f128_ps(tmp2, tmp3, 0x20); \
_mm256_storeu_ps(dst + 8 * (0 + 4 * u), s0); \
_mm256_storeu_ps(dst + 8 * (1 + 4 * u), s1); \
}
#endif
| 58.975904 | 78 | 0.416701 | JujuDel |
8126b2edf7e4822264b46a28debcf5b97c40d736 | 5,299 | hpp | C++ | src/model/CoilCoolingDXVariableRefrigerantFlow.hpp | muehleisen/OpenStudio | 3bfe89f6c441d1e61e50b8e94e92e7218b4555a0 | [
"blessing"
] | 354 | 2015-01-10T17:46:11.000Z | 2022-03-29T10:00:00.000Z | src/model/CoilCoolingDXVariableRefrigerantFlow.hpp | muehleisen/OpenStudio | 3bfe89f6c441d1e61e50b8e94e92e7218b4555a0 | [
"blessing"
] | 3,243 | 2015-01-02T04:54:45.000Z | 2022-03-31T17:22:22.000Z | src/model/CoilCoolingDXVariableRefrigerantFlow.hpp | jmarrec/OpenStudio | 5276feff0d8dbd6c8ef4e87eed626bc270a19b14 | [
"blessing"
] | 157 | 2015-01-07T15:59:55.000Z | 2022-03-30T07:46:09.000Z | /***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. 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 any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 MODEL_COILCOOLINGDXVARIABLEREFRIGERANTFLOW_HPP
#define MODEL_COILCOOLINGDXVARIABLEREFRIGERANTFLOW_HPP
#include "ModelAPI.hpp"
#include "HVACComponent.hpp"
namespace openstudio {
namespace model {
class Schedule;
class Curve;
namespace detail {
class CoilCoolingDXVariableRefrigerantFlow_Impl;
} // namespace detail
/** CoilCoolingDXVariableRefrigerantFlow is a HVACComponent that wraps the OpenStudio IDD object 'OS:Coil:Cooling:DX:VariableRefrigerantFlow'. */
class MODEL_API CoilCoolingDXVariableRefrigerantFlow : public HVACComponent
{
public:
explicit CoilCoolingDXVariableRefrigerantFlow(const Model& model);
virtual ~CoilCoolingDXVariableRefrigerantFlow() {}
static IddObjectType iddObjectType();
Schedule availabilitySchedule() const;
bool setAvailabilitySchedule(Schedule& schedule);
boost::optional<double> ratedTotalCoolingCapacity() const;
bool isRatedTotalCoolingCapacityAutosized() const;
bool setRatedTotalCoolingCapacity(double ratedTotalCoolingCapacity);
void autosizeRatedTotalCoolingCapacity();
boost::optional<double> ratedSensibleHeatRatio() const;
bool isRatedSensibleHeatRatioAutosized() const;
bool setRatedSensibleHeatRatio(double ratedSensibleHeatRatio);
void autosizeRatedSensibleHeatRatio();
boost::optional<double> ratedAirFlowRate() const;
bool isRatedAirFlowRateAutosized() const;
bool setRatedAirFlowRate(double ratedAirFlowRate);
void autosizeRatedAirFlowRate();
Curve coolingCapacityRatioModifierFunctionofTemperatureCurve() const;
bool setCoolingCapacityRatioModifierFunctionofTemperatureCurve(const Curve& lcurve);
Curve coolingCapacityModifierCurveFunctionofFlowFraction() const;
bool setCoolingCapacityModifierCurveFunctionofFlowFraction(const Curve& lcurve);
boost::optional<double> autosizedRatedTotalCoolingCapacity() const;
boost::optional<double> autosizedRatedSensibleHeatRatio() const;
boost::optional<double> autosizedRatedAirFlowRate() const;
protected:
/// @cond
typedef detail::CoilCoolingDXVariableRefrigerantFlow_Impl ImplType;
explicit CoilCoolingDXVariableRefrigerantFlow(std::shared_ptr<detail::CoilCoolingDXVariableRefrigerantFlow_Impl> impl);
friend class detail::CoilCoolingDXVariableRefrigerantFlow_Impl;
friend class Model;
friend class IdfObject;
friend class openstudio::detail::IdfObject_Impl;
/// @endcond
private:
REGISTER_LOGGER("openstudio.model.CoilCoolingDXVariableRefrigerantFlow");
};
/** \relates CoilCoolingDXVariableRefrigerantFlow*/
typedef boost::optional<CoilCoolingDXVariableRefrigerantFlow> OptionalCoilCoolingDXVariableRefrigerantFlow;
/** \relates CoilCoolingDXVariableRefrigerantFlow*/
typedef std::vector<CoilCoolingDXVariableRefrigerantFlow> CoilCoolingDXVariableRefrigerantFlowVector;
} // namespace model
} // namespace openstudio
#endif // MODEL_COILCOOLINGDXVARIABLEREFRIGERANTFLOW_HPP
| 41.398438 | 147 | 0.758256 | muehleisen |
812874564e4064e32a54583b67e77fbb410fcfe6 | 303 | cpp | C++ | C++/Programming_Principles_and_Practice_Using_C++/Chapter3/input_type.cpp | MaRauder111/Cplusplus | 9b18f95b5aee67f67c6e579ba7f3e80d3a3c68a5 | [
"MIT"
] | null | null | null | C++/Programming_Principles_and_Practice_Using_C++/Chapter3/input_type.cpp | MaRauder111/Cplusplus | 9b18f95b5aee67f67c6e579ba7f3e80d3a3c68a5 | [
"MIT"
] | null | null | null | C++/Programming_Principles_and_Practice_Using_C++/Chapter3/input_type.cpp | MaRauder111/Cplusplus | 9b18f95b5aee67f67c6e579ba7f3e80d3a3c68a5 | [
"MIT"
] | null | null | null | #include <iostream>
int main()
{
std::cout << "Enter you name and age : ";
std::string first_name;
std::cin >> first_name;
double age = 0;
std::cin >> age;
int months = age * 12;
std::cout << "First name " << first_name << " age is " << months << std::endl;
return 0;
} | 21.642857 | 82 | 0.547855 | MaRauder111 |
8128b3efd57e9e20211f08cbc63a7e9e3367762d | 2,916 | cpp | C++ | src/rx/render/frontend/timer.cpp | DethRaid/rex | 21ba92d38398240faa45a402583c11f8c72e6e41 | [
"MIT"
] | 2 | 2020-06-13T11:39:46.000Z | 2021-03-10T01:03:03.000Z | src/rx/render/frontend/timer.cpp | DethRaid/rex | 21ba92d38398240faa45a402583c11f8c72e6e41 | [
"MIT"
] | null | null | null | src/rx/render/frontend/timer.cpp | DethRaid/rex | 21ba92d38398240faa45a402583c11f8c72e6e41 | [
"MIT"
] | 1 | 2021-01-06T03:47:08.000Z | 2021-01-06T03:47:08.000Z | #include "rx/render/frontend/timer.h"
#include "rx/core/math/abs.h"
#include "rx/core/time/qpc.h"
#include "rx/core/time/delay.h"
namespace Rx::Render::Frontend {
FrameTimer::FrameTimer()
: m_frequency{Time::qpc_frequency()}
, m_resolution{1.0 / m_frequency}
, m_max_frame_ticks{0.0f}
, m_last_second_ticks{0}
, m_frame_count{0}
, m_min_ticks{0}
, m_max_ticks{0}
, m_average_ticks{0.0f}
, m_delta_time{0.0f}
, m_last_frame_ticks{Time::qpc_ticks()}
, m_current_ticks{0}
, m_target_ticks{0}
, m_frame_min{0}
, m_frame_max{0}
, m_frame_average{0.0f}
, m_frames_per_second{0}
{
}
void FrameTimer::cap_fps(Float32 _max_fps) {
static constexpr const Float32 k_dampen{0.00001f};
m_max_frame_ticks = _max_fps <= 0.0f ? -1.0f : (m_frequency / _max_fps) - k_dampen;
}
void FrameTimer::reset() {
m_last_second_ticks = Time::qpc_ticks();
m_frequency = Time::qpc_frequency();
m_resolution = 1.0 / m_frequency;
m_frame_count = 0;
m_min_ticks = m_frequency;
m_max_ticks = 0;
m_average_ticks = 0.0;
}
bool FrameTimer::update() {
m_frame_count++;
m_target_ticks = m_max_frame_ticks != -1.0f
? m_last_second_ticks + Uint64(m_frame_count * m_max_frame_ticks) : 0;
m_current_ticks = Time::qpc_ticks();
m_average_ticks += m_current_ticks - m_last_frame_ticks;
const Float64 life_time{m_current_ticks * m_resolution};
const Float64 frame_time{(life_time - (m_last_frame_ticks * m_resolution)) * 1000.0};
m_frame_times.push_back({life_time, frame_time});
// Erase old frame times. We only want a window that is |k_frame_history_seconds|
// in size.
for (Size i{0}; i < m_frame_times.size(); i++) {
if (m_frame_times[i].life >= life_time - k_frame_history_seconds) {
if (i != 0) {
m_frame_times.erase(0, i);
}
break;
}
}
if (m_current_ticks - m_last_frame_ticks <= m_min_ticks) {
m_min_ticks = m_current_ticks - m_last_frame_ticks;
}
if (m_current_ticks - m_last_frame_ticks >= m_max_ticks) {
m_max_ticks = m_current_ticks - m_last_frame_ticks;
}
if (m_target_ticks && m_current_ticks < m_target_ticks) {
const auto ticks_before_delay{Time::qpc_ticks()};
Time::delay(static_cast<Uint64>((m_target_ticks - m_current_ticks) * 1000) / m_frequency);
m_current_ticks = Time::qpc_ticks();
m_average_ticks += m_current_ticks - ticks_before_delay;
}
const Float64 delta{m_resolution * (m_current_ticks - m_last_frame_ticks)};
m_delta_time = delta;
m_last_frame_ticks = m_current_ticks;
if (m_current_ticks - m_last_second_ticks >= m_frequency) {
m_frames_per_second = static_cast<Uint32>(m_frame_count);
m_frame_average = static_cast<Float32>((m_resolution * m_average_ticks / m_frame_count) * 1000.0);
m_frame_min = m_min_ticks;
m_frame_max = m_max_ticks;
reset();
return true;
}
return false;
}
} // namespace rx::render::frontend
| 28.871287 | 102 | 0.705418 | DethRaid |
812933dd664995465fa398aabcb94905bebc5df9 | 1,230 | cpp | C++ | test/next_power_of_2.cpp | jgmbenoit/primecount | 1c39ff8daeb149d100108d1cb364d20f20f48009 | [
"BSD-2-Clause"
] | 259 | 2015-01-31T15:44:26.000Z | 2022-03-31T07:09:13.000Z | test/next_power_of_2.cpp | jgmbenoit/primecount | 1c39ff8daeb149d100108d1cb364d20f20f48009 | [
"BSD-2-Clause"
] | 36 | 2016-05-14T22:13:16.000Z | 2022-02-14T07:27:50.000Z | test/next_power_of_2.cpp | jgmbenoit/primecount | 1c39ff8daeb149d100108d1cb364d20f20f48009 | [
"BSD-2-Clause"
] | 44 | 2015-02-03T17:37:42.000Z | 2022-03-02T21:01:36.000Z | ///
/// @file next_power_of_2.cpp
/// @brief Round up to nearest power of 2.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <imath.hpp>
#include <stdint.h>
#include <iostream>
#include <cstdlib>
void check(bool OK)
{
std::cout << " " << (OK ? "OK" : "ERROR") << "\n";
if (!OK)
std::exit(1);
}
int main()
{
uint64_t n;
uint64_t res1;
uint64_t res2;
for (uint64_t i = 0; i < 64; i++)
{
n = 1ull << i;
res1 = next_power_of_2(n);
res2 = n;
std::cout << "next_power_of_2(" << n << ") = " << res1;
check(res1 == res2);
}
for (uint64_t i = 0; i < 63; i++)
{
n = (1ull << i) + 1;
res1 = next_power_of_2(n);
res2 = 1ull << (i + 1);
std::cout << "next_power_of_2(" << n << ") = " << res1;
check(res1 == res2);
}
for (uint64_t i = 2; i < 64; i++)
{
n = (1ull << i) - 1;
res1 = next_power_of_2(n);
res2 = 1ull << i;
std::cout << "next_power_of_2(" << n << ") = " << res1;
check(res1 == res2);
}
std::cout << std::endl;
std::cout << "All tests passed successfully!" << std::endl;
return 0;
}
| 19.83871 | 67 | 0.527642 | jgmbenoit |
8129afc07a2dd40d10bfdafb9163f25678886f98 | 498 | cpp | C++ | test/main_test.cpp | connectivecpp/utility-rack | 5ff69a2258726d56da15248f70be65817bed8f1e | [
"BSL-1.0"
] | 3 | 2019-04-30T02:42:21.000Z | 2020-05-14T16:35:43.000Z | test/main_test.cpp | connectivecpp/utility-rack | 5ff69a2258726d56da15248f70be65817bed8f1e | [
"BSL-1.0"
] | 10 | 2019-03-12T07:31:56.000Z | 2020-03-09T21:39:33.000Z | test/main_test.cpp | connectivecpp/utility-rack | 5ff69a2258726d56da15248f70be65817bed8f1e | [
"BSL-1.0"
] | 1 | 2019-05-21T02:12:43.000Z | 2019-05-21T02:12:43.000Z | /** @file
*
* @defgroup test_module Unit tests for the various Chops Utility Rack components.
*
* @ingroup test_module
*
* @brief Source file for combining (i.e. linking) all Chops tests together.
*
* @author Cliff Green
*
* Copyright (c) 2017-2019 by Cliff Green
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
*/
#define CATCH_CONFIG_MAIN
#include "catch2/catch.hpp"
| 22.636364 | 87 | 0.702811 | connectivecpp |
813152d1d59a570600bbae97b80e0ea3af93a9ec | 5,331 | cpp | C++ | bitcoinPoSTdisplay/libraries/ArduinoJson/extras/tests/JsonDocument/MemberProxy.cpp | adrienlacombe-ledger/bitcoinPoS | 2a4701c445c7eeec88c8abc2bd7940916899e79c | [
"MIT"
] | 81 | 2022-01-22T17:35:01.000Z | 2022-03-08T09:59:02.000Z | bitcoinPoSTdisplay/libraries/ArduinoJson/extras/tests/JsonDocument/MemberProxy.cpp | adrienlacombe-ledger/bitcoinPoS | 2a4701c445c7eeec88c8abc2bd7940916899e79c | [
"MIT"
] | 6 | 2022-01-25T20:23:08.000Z | 2022-03-07T23:50:32.000Z | bitcoinPoSTdisplay/libraries/ArduinoJson/extras/tests/JsonDocument/MemberProxy.cpp | adrienlacombe-ledger/bitcoinPoS | 2a4701c445c7eeec88c8abc2bd7940916899e79c | [
"MIT"
] | 14 | 2022-01-22T18:16:11.000Z | 2022-03-07T21:32:41.000Z | // ArduinoJson - https://arduinojson.org
// Copyright © 2014-2022, Benoit BLANCHON
// MIT License
#include <ArduinoJson.h>
#include <catch.hpp>
using namespace ARDUINOJSON_NAMESPACE;
TEST_CASE("MemberProxy::add()") {
DynamicJsonDocument doc(4096);
MemberProxy<JsonDocument &, const char *> mp = doc["hello"];
SECTION("add(int)") {
mp.add(42);
REQUIRE(doc.as<std::string>() == "{\"hello\":[42]}");
}
SECTION("add(const char*)") {
mp.add("world");
REQUIRE(doc.as<std::string>() == "{\"hello\":[\"world\"]}");
}
}
TEST_CASE("MemberProxy::clear()") {
DynamicJsonDocument doc(4096);
MemberProxy<JsonDocument &, const char *> mp = doc["hello"];
SECTION("size goes back to zero") {
mp.add(42);
mp.clear();
REQUIRE(mp.size() == 0);
}
SECTION("isNull() return true") {
mp.add("hello");
mp.clear();
REQUIRE(mp.isNull() == true);
}
}
TEST_CASE("MemberProxy::operator==()") {
DynamicJsonDocument doc(4096);
SECTION("1 vs 1") {
doc["a"] = 1;
doc["b"] = 1;
REQUIRE(doc["a"] <= doc["b"]);
REQUIRE(doc["a"] == doc["b"]);
REQUIRE(doc["a"] >= doc["b"]);
REQUIRE_FALSE(doc["a"] != doc["b"]);
REQUIRE_FALSE(doc["a"] < doc["b"]);
REQUIRE_FALSE(doc["a"] > doc["b"]);
}
SECTION("1 vs 2") {
doc["a"] = 1;
doc["b"] = 2;
REQUIRE(doc["a"] != doc["b"]);
REQUIRE(doc["a"] < doc["b"]);
REQUIRE(doc["a"] <= doc["b"]);
REQUIRE_FALSE(doc["a"] == doc["b"]);
REQUIRE_FALSE(doc["a"] > doc["b"]);
REQUIRE_FALSE(doc["a"] >= doc["b"]);
}
SECTION("'abc' vs 'bcd'") {
doc["a"] = "abc";
doc["b"] = "bcd";
REQUIRE(doc["a"] != doc["b"]);
REQUIRE(doc["a"] < doc["b"]);
REQUIRE(doc["a"] <= doc["b"]);
REQUIRE_FALSE(doc["a"] == doc["b"]);
REQUIRE_FALSE(doc["a"] > doc["b"]);
REQUIRE_FALSE(doc["a"] >= doc["b"]);
}
}
TEST_CASE("MemberProxy::containsKey()") {
DynamicJsonDocument doc(4096);
MemberProxy<JsonDocument &, const char *> mp = doc["hello"];
SECTION("containsKey(const char*)") {
mp["key"] = "value";
REQUIRE(mp.containsKey("key") == true);
REQUIRE(mp.containsKey("key") == true);
}
SECTION("containsKey(std::string)") {
mp["key"] = "value";
REQUIRE(mp.containsKey(std::string("key")) == true);
REQUIRE(mp.containsKey(std::string("key")) == true);
}
}
TEST_CASE("MemberProxy::operator|()") {
DynamicJsonDocument doc(4096);
SECTION("const char*") {
doc["a"] = "hello";
REQUIRE((doc["a"] | "world") == std::string("hello"));
REQUIRE((doc["b"] | "world") == std::string("world"));
}
SECTION("Issue #1411") {
doc["sensor"] = "gps";
const char *test = "test"; // <- the literal must be captured in a variable
// to trigger the bug
const char *sensor = doc["sensor"] | test; // "gps"
REQUIRE(sensor == std::string("gps"));
}
SECTION("Issue #1415") {
JsonObject object = doc.to<JsonObject>();
object["hello"] = "world";
StaticJsonDocument<0> emptyDoc;
JsonObject anotherObject = object["hello"] | emptyDoc.to<JsonObject>();
REQUIRE(anotherObject.isNull() == false);
REQUIRE(anotherObject.size() == 0);
}
}
TEST_CASE("MemberProxy::remove()") {
DynamicJsonDocument doc(4096);
MemberProxy<JsonDocument &, const char *> mp = doc["hello"];
SECTION("remove(int)") {
mp.add(1);
mp.add(2);
mp.add(3);
mp.remove(1);
REQUIRE(mp.as<std::string>() == "[1,3]");
}
SECTION("remove(const char *)") {
mp["a"] = 1;
mp["b"] = 2;
mp.remove("a");
REQUIRE(mp.as<std::string>() == "{\"b\":2}");
}
SECTION("remove(std::string)") {
mp["a"] = 1;
mp["b"] = 2;
mp.remove(std::string("b"));
REQUIRE(mp.as<std::string>() == "{\"a\":1}");
}
#ifdef HAS_VARIABLE_LENGTH_ARRAY
SECTION("remove(vla)") {
mp["a"] = 1;
mp["b"] = 2;
int i = 4;
char vla[i];
strcpy(vla, "b");
mp.remove(vla);
REQUIRE(mp.as<std::string>() == "{\"a\":1}");
}
#endif
}
TEST_CASE("MemberProxy::set()") {
DynamicJsonDocument doc(4096);
MemberProxy<JsonDocument &, const char *> mp = doc["hello"];
SECTION("set(int)") {
mp.set(42);
REQUIRE(doc.as<std::string>() == "{\"hello\":42}");
}
SECTION("set(const char*)") {
mp.set("world");
REQUIRE(doc.as<std::string>() == "{\"hello\":\"world\"}");
}
SECTION("set(char[])") { // issue #1191
char s[] = "world";
mp.set(s);
strcpy(s, "!!!!!");
REQUIRE(doc.as<std::string>() == "{\"hello\":\"world\"}");
}
}
TEST_CASE("MemberProxy::size()") {
DynamicJsonDocument doc(4096);
MemberProxy<JsonDocument &, const char *> mp = doc["hello"];
SECTION("returns 0") {
REQUIRE(mp.size() == 0);
}
SECTION("as an array, return 2") {
mp.add(1);
mp.add(2);
REQUIRE(mp.size() == 2);
}
SECTION("as an object, return 2") {
mp["a"] = 1;
mp["b"] = 2;
REQUIRE(mp.size() == 2);
}
}
TEST_CASE("MemberProxy::operator[]") {
DynamicJsonDocument doc(4096);
MemberProxy<JsonDocument &, const char *> mp = doc["hello"];
SECTION("set member") {
mp["world"] = 42;
REQUIRE(doc.as<std::string>() == "{\"hello\":{\"world\":42}}");
}
SECTION("set element") {
mp[2] = 42;
REQUIRE(doc.as<std::string>() == "{\"hello\":[null,null,42]}");
}
}
| 21.495968 | 80 | 0.5423 | adrienlacombe-ledger |
813559f2544ebe9ca6c74895f0b942a5c71e3155 | 946 | cpp | C++ | test/test-base/FakeLauncher.cpp | azubieta/appimage-appsdir | 76da0cac1542fe8159a63615b4614de2a1486b8c | [
"MIT"
] | 1 | 2019-08-19T16:52:41.000Z | 2019-08-19T16:52:41.000Z | test/test-base/FakeLauncher.cpp | azubieta/appimage-appsfolder | 76da0cac1542fe8159a63615b4614de2a1486b8c | [
"MIT"
] | 1 | 2019-08-21T07:31:46.000Z | 2019-08-21T07:31:46.000Z | test/test-base/FakeLauncher.cpp | azubieta/appimage-appsfolder | 76da0cac1542fe8159a63615b4614de2a1486b8c | [
"MIT"
] | null | null | null | #include "FakeLauncher.h"
void FakeLauncher::launch(const QString& command, const QStringList& args) {
launchCalled = true;
}
bool FakeLauncher::wasLaunchCalled() const {
return launchCalled;
}
bool FakeLauncher::registerApp(const QString& appImagePath) {
registerAppCalled = true;
return true;
}
bool FakeLauncher::unregisterApp(const QString& appImagePath) {
unregisterAppCalled = true;
return true;
}
bool FakeLauncher::isRegistered(const QString& appImagePath) {
isRegisteredCalled = true;
return registered;
}
FakeLauncher::FakeLauncher() {
reset();
}
void FakeLauncher::reset() {
registered = false;
launchCalled = false;
registerAppCalled = false;
unregisterAppCalled = false;
isRegisteredCalled = false;
}
bool FakeLauncher::isRegisterAppCalled() const {
return registerAppCalled;
}
bool FakeLauncher::isUnregisterAppCalled() const {
return unregisterAppCalled;
}
| 20.565217 | 76 | 0.729387 | azubieta |
81357d128906824f6fb6f52e722c5fb7168774d3 | 1,339 | cc | C++ | average-pv.cc | lemrobotry/thesis | 14ad489e8f04cb957707b89c454ee7d81ec672ad | [
"MIT"
] | null | null | null | average-pv.cc | lemrobotry/thesis | 14ad489e8f04cb957707b89c454ee7d81ec672ad | [
"MIT"
] | null | null | null | average-pv.cc | lemrobotry/thesis | 14ad489e8f04cb957707b89c454ee7d81ec672ad | [
"MIT"
] | null | null | null | #include "Application.hh"
#include "PV.hh"
APPLICATION
using namespace Permute;
// Accepts many model files on the command line and outputs the model with the
// average feature weight.
class AveragePV : public Application {
public:
AveragePV () :
Application ("average-pv")
{}
int main (const std::vector <std::string> & args) {
this -> getParameters ();
PV pv;
int count = 0;
std::vector <std::string>::const_iterator it = args.begin ();
if (it == args.end ()) {
return EXIT_SUCCESS;
}
if (! readFile (pv, * it)) {
std::cerr << "Could not read LOP parameter file: " << * it << std::endl;
return EXIT_FAILURE;
} else {
count = 1;
}
// Successfully read the first parameter file. Now reads additional
// parameter files, aggregating their parameters into the existing PV.
for (++ it; it != args.end (); ++ it) {
if (! aggregateFile (pv, * it)) {
std::cerr << "Could not read LOP parameter file: " << * it << std::endl;
return EXIT_FAILURE;
} else {
++ count;
}
}
// Normalizes the parameter totals by count.
for (PV::iterator pv_it = pv.begin (); pv_it != pv.end (); ++ pv_it) {
pv_it -> second /= count;
}
// Writes out the average PV.
this -> writePV (pv);
return EXIT_SUCCESS;
}
} app;
| 24.345455 | 78 | 0.59522 | lemrobotry |
8138b1367fe48b9431a737f88da8d5009ed23dec | 18,605 | hh | C++ | extra/witre.old/WitreGraph.hh | miatauro/trex2-agent | d896f8335f3194237a8bba49949e86f5488feddb | [
"BSD-3-Clause"
] | null | null | null | extra/witre.old/WitreGraph.hh | miatauro/trex2-agent | d896f8335f3194237a8bba49949e86f5488feddb | [
"BSD-3-Clause"
] | null | null | null | extra/witre.old/WitreGraph.hh | miatauro/trex2-agent | d896f8335f3194237a8bba49949e86f5488feddb | [
"BSD-3-Clause"
] | null | null | null | #ifndef WITREGRAPH
#define WITREGRAPH
#include<Wt/WPaintedWidget>
#include<Wt/WPainter>
#include<Wt/WPaintDevice>
#include<Wt/WPointF>
#include <Wt/WRectArea>
#include "WitreServer.hh"
#include <trex/transaction/TeleoReactor.hh>
# if defined(__clang__)
// clang annoys me by putting plenty of warnings on unused variables from boost
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wunused-variable"
# pragma clang diagnostic ignored "-Wunneeded-internal-declaration"
# endif
# include <boost/graph/depth_first_search.hpp>
# if defined(__clang__)
# pragma clang diagnostic pop
# endif
#include <map>
#include <string>
#include <cmath>
#include <limits>
using namespace std;
using namespace TREX::transaction;
namespace TREX {
namespace witre {
class WitreGraph :public boost::dfs_visitor<> {
public:
WitreGraph(std::map<utils::Symbol, int> &rel)
:relation(rel) {};
virtual ~WitreGraph() {};
void initialize_vertex(graph::reactor_id r, graph const &g)
{
vertex[r] = 0;
}
void examine_edge(graph::relation_type const & rel, graph const &g)
{
if(rel->active())
{
graph::reactor_id source = boost::source(rel,g);
graph::reactor_id target = boost::target(rel, g);
vertex[target] = vertex[source]+1;
relation.insert( std::pair<utils::Symbol, int>(rel->name(), vertex[source]));
}
};
protected:
bool is_valid(graph::reactor_id r) const
{
return graph::null_reactor()!=r;
};
private:
std::map<graph::reactor_id, int> vertex;
std::map<utils::Symbol, int>& relation;
};
class WitrePaintSearch :public boost::dfs_visitor<> {
public:
class nodeObject
{
public:
utils::Symbol name;
std::list<utils::Symbol> connections;
int level;
nodeObject(utils::Symbol name, int level)
{
this->name = name;
this->level = level;
}
void addConnection(utils::Symbol name)
{
connections.push_back(name);
}
};
typedef std::map<utils::Symbol, nodeObject> GraphMap;
WitrePaintSearch(GraphMap& temp)
:graphMap(temp), level(0), highestLevel(0) {};
virtual ~WitrePaintSearch() {};
void discover_vertex(graph::reactor_id r, graph const &g)
{
if(is_valid(r))
{
std::pair<TREX::transaction::TeleoReactor::internal_iterator,
TREX::transaction::TeleoReactor::internal_iterator> internal;
internal = boost::in_edges(r,g);
TREX::transaction::TeleoReactor::internal_iterator it;
for(it = internal.first; it!=internal.second; ++it)
{
utils::Symbol name = it->name();
if(graphMap.find(name)==graphMap.end())
{
nodeObject node(name,0);
graphMap.insert(std::pair<utils::Symbol,nodeObject>(name, node));
}
for(TeleoReactor::external_iterator temp = r->ext_begin(); temp!=r->ext_end(); ++temp)
{
if(temp->active())
{
utils::Symbol externalName = temp->name();
if(!findName(graphMap.find(name)->second.connections,externalName))
{
graphMap.find(name)->second.addConnection(externalName);
}
if(graphMap.find(externalName)==graphMap.end())
{
nodeObject node(externalName, graphMap.find(name)->second.level+1);
graphMap.insert(std::pair<utils::Symbol,nodeObject>(externalName, node));
}
else
{
int oldLevel = graphMap.find(externalName)->second.level;
int newLevel = graphMap.find(name)->second.level+1;
if(newLevel>oldLevel)
{
int difference = newLevel-oldLevel;
upLevel(externalName, difference);
}
}
}
}
}
level++;
highestLevel = (level>highestLevel)?level:highestLevel;
}
}
void upLevel(utils::Symbol name, int difference)
{
std::list<utils::Symbol> called;
graphMap.find(name)->second.level += difference;
nodeObject* temp = &graphMap.find(name)->second;
std::list<utils::Symbol>::iterator it;
for(it = temp->connections.begin(); it!= temp->connections.end(); it++)
{
if(!findName(called,*it))
{
upLevel(*it,difference);
called.push_back(*it);
}
}
}
bool findName(std::list<utils::Symbol> list, utils::Symbol name)
{
std::list<utils::Symbol>::iterator it;
for(it = list.begin(); it!=list.end(); it++)
{
if(*it==name)
{
return true;
}
}
return false;
}
void finish_vertex(graph::reactor_id r, graph const &g)
{
level--;
}
int getMaxLevel()
{
return highestLevel;
}
private:
GraphMap& graphMap;
int level;
int highestLevel;
bool is_valid(graph::reactor_id r) const
{
return graph::null_reactor()!=r;
}
};
class PaintedGraph : public Wt::WPaintedWidget
{
private:
const graph& pGraph;
std::map<utils::Symbol, Wt::WRectF> placement;
// Wt::WPainter* paint;
protected:
void paintEvent(Wt::WPaintDevice* temp)
{
Wt::WPainter painter(temp);
//Getting the graph information to build the image
WitrePaintSearch::GraphMap graphMap;
WitrePaintSearch vis(graphMap);
boost::depth_first_search(pGraph, boost::visitor(vis));
std::map<int,int> num;
WitrePaintSearch::GraphMap::iterator it;
//Drawing the circles and their names
for(it = graphMap.begin(); it!=graphMap.end(); it++)
{
int level = (*it).second.level;
if(num.find(level)==num.end())
num[level]=0;
//Building rectangle and storing it
Wt::WRectF box(num[level]*130,level*130,70,70);
placement[(*it).second.name] = box;
//Drawing circle with name
painter.drawEllipse(box);
std::string name = ((*it).second.name.str().size()<8)?(*it).second.name.str():(*it).second.name.str().substr(0,8);
painter.drawText(box, Wt::AlignCenter | Wt::AlignMiddle, name);
//Increaing number of nodes in level
num[level]++;
}
//Drawing the lines and the arrows
for(it = graphMap.begin(); it!=graphMap.end(); it++)
{
std::list<utils::Symbol>& connections = (*it).second.connections;
std::list<utils::Symbol>::iterator connect;
for(connect = connections.begin(); connect!=connections.end(); connect++)
{
Wt::WPointF tCenter = placement[(*it).first].center();
Wt::WPointF bCenter = placement[(*connect)].center();
double slope = getSlope(tCenter, bCenter);
Wt::WPainterPath line = drawLine(tCenter,bCenter,slope);
painter.drawPath(line);
drawArrow(painter,bCenter,slope);
}
}
//Adds interactive areas to the graph picture
addInteractiveAreas();
}
double getSlope(Wt::WPointF& top, Wt::WPointF& bottom)
{
return (bottom.y()-top.y())/(bottom.x()-top.x());
}
double shortestPoint(Wt::WPointF& center, const Wt::WPointF& outside)
{
if(center.x()==outside.x())
{
if(center.y()>outside.y())
{
center.setY(center.y()-35);
}
else
{
center.setY(center.y()+35);
}
return numeric_limits<double>::infinity();
}
else if(center.y()==outside.y())
{
if(center.x()<outside.x())
{
center.setX(center.x()-35);
}
else
{
center.setX(center.x()+35);
}
return 0;
}
else
{
double slope = (outside.y()-center.y())/(outside.x()-center.x());
if(slope>0)
{
if(center.y()>outside.y())
{
center.setX(center.x()-(center.x()+35*cos(atan(slope))-center.x()));
center.setY(center.y()-(center.y()+35*sin(atan(slope))-center.y()));
}
else
{
center.setX(center.x()+35*cos(atan(slope)));
center.setY(center.y()+35*sin(atan(slope)));
}
}
else
{
if(center.y()>outside.y())
{
center.setX(center.x()+35*cos(atan(slope)));
center.setY(center.y()+35*sin(atan(slope)));
}
else
{
center.setX(center.x()-(center.x()+35*cos(atan(slope))-center.x()));
center.setY(center.y()-(center.y()+35*sin(atan(slope))-center.y()));
}
}
return slope;
}
}
Wt::WPainterPath drawLine(Wt::WPointF& tCenter, Wt::WPointF& bCenter, double& slope)
{
Wt::WPointF nullPoint;
Wt::WPointF topPoint;
Wt::WPointF bottomPoint;
std::map<utils::Symbol, Wt::WRectF>::iterator it;
for(it=placement.begin(); it!=placement.end(); it++)
{
//True if the rect does not contain the two points and any points in slope
if((!(*it).second.contains(tCenter) && !(*it).second.contains(bCenter))
&& intersectRect(tCenter,bCenter,slope,(*it).second))
{
Wt::WPointF tpoint = (*it).second.topRight();
tpoint.setX(tpoint.x()+(*it).second.width()/1.5);
Wt::WPointF bpoint = (*it).second.bottomRight();
bpoint.setX(bpoint.x()+(*it).second.width()/1.5);
if(topPoint==nullPoint || tpoint.y()<topPoint.y())
{
topPoint = tpoint;
}
if(bottomPoint==nullPoint || bpoint.y()>bottomPoint.y())
{
bottomPoint = bpoint;
}
}
}
if(topPoint!=nullPoint && bottomPoint!=nullPoint)
{
shortestPoint(tCenter,topPoint);
shortestPoint(bCenter,bottomPoint);
slope = getSlope(bCenter, bottomPoint);
Wt::WPainterPath* line = new Wt::WPainterPath(tCenter);
line->cubicTo(topPoint,bottomPoint,bCenter);
return *line;
}
else
{
shortestPoint(tCenter,bCenter);
shortestPoint(bCenter,tCenter);
Wt::WPainterPath* line = new Wt::WPainterPath(tCenter);
line->lineTo(bCenter);
return *line;
}
}
bool intersectRect(Wt::WPointF& tCenter, Wt::WPointF& bCenter, double& slope, Wt::WRectF& rect)
{
if(slope!=numeric_limits<double>::infinity())
{
bool test = false;
if(slope>0)
{
if(rect.x()>=tCenter.x() && rect.x()+rect.width()<=bCenter.x())
{
test = true;
}
}
else
{
if(rect.x()>=bCenter.x() && rect.x()+rect.width()<=tCenter.x())
{
test = true;
}
}
if(test)
{
double b = tCenter.y() - tCenter.x()*slope;
for(int i=rect.x(); i!=rect.x()+rect.width(); i++)
{
int y = slope*i+b;
if(rect.contains(i,y))
{
return true;
}
}
}
return false;
}
else
{
if(rect.x()<=tCenter.x()&&rect.x()+rect.width()>=bCenter.x())
{
if(rect.y()>tCenter.y()&&rect.y()+rect.height()<bCenter.y())
{
return true;
}
return false;
}
}
return false; // fpy : I added this return at the end ...
// I gueess it should return false if all the above ifs failed
}
void drawArrow(Wt::WPainter& painter, Wt::WPointF& center, const double& slope)
{
const double cosVar = 0.866;
const double sinVar = 0.500;
Wt::WPointF tail;
if(slope == numeric_limits<double>::infinity())
{
tail.setX(center.x());
tail.setY(center.y()+10);
}
else if(slope>=0)
{
tail.setX(center.x()+10*cos(atan(slope)));
tail.setY(center.y()+10*sin(atan(slope)));
}
else
{
tail.setX(center.x()-(center.x()+10*cos(atan(slope))-center.x()));
tail.setY(center.y()-(center.y()+10*sin(atan(slope))-center.y()));
}
double dx = center.x()-tail.x();
double dy = center.y()-tail.y();
Wt::WPointF line1;
line1.setX(center.x()+(dx*cosVar+dy*-sinVar));
line1.setY(center.y()+(dx*sinVar+dy*cosVar));
Wt::WPointF line2;
line2.setX(center.x()+(dx*cosVar+dy*sinVar));
line2.setY(center.y()+(dx*-sinVar+dy*cosVar));
painter.drawLine(center,line1);
painter.drawLine(center,line2);
}
void addInteractiveAreas()
{
std::map<utils::Symbol, Wt::WRectF>::iterator it;
for(it=placement.begin(); it!=placement.end(); it++)
{
Wt::WRectArea* area = new Wt::WRectArea((*it).second);
area->setToolTip((*it).first.str());
this->addArea(area);
}
}
public:
PaintedGraph(const graph& temp)
:pGraph(temp)
{
resize(1000,1000);
}
};
class WitreGraphContainer : public Wt::WContainerWidget
{
public:
WitreGraphContainer(Wt::WContainerWidget* parent, const graph& temp)
: Wt::WContainerWidget(parent), paintedGraph(new PaintedGraph(temp))
{
this->addWidget(paintedGraph);
}
Wt::WContainerWidget* getWidget()
{
return this;
}
private:
PaintedGraph * const paintedGraph;
};
}
}
#endif
| 37.969388 | 134 | 0.40172 | miatauro |
8138e46fcfb2ab5ad3e428a8d389b9e3c2a99aa2 | 179 | cpp | C++ | projects/PathosEngine/src/pathos/named_object.cpp | codeonwort/pathosengine | ea568afeac9af3ebe3f2e53cc5abeecb40714466 | [
"MIT"
] | 11 | 2016-08-30T12:01:35.000Z | 2021-12-29T15:34:03.000Z | projects/PathosEngine/src/pathos/named_object.cpp | codeonwort/pathosengine | ea568afeac9af3ebe3f2e53cc5abeecb40714466 | [
"MIT"
] | 9 | 2016-05-19T03:14:22.000Z | 2021-01-17T05:45:52.000Z | projects/PathosEngine/src/pathos/named_object.cpp | codeonwort/pathosengine | ea568afeac9af3ebe3f2e53cc5abeecb40714466 | [
"MIT"
] | null | null | null | #include "named_object.h"
namespace pathos {
const std::string& NamedObject::getName() const { return name; }
void NamedObject::setName(const std::string& n) { name = n; }
}
| 19.888889 | 65 | 0.692737 | codeonwort |
81417438e047999b33f80bf24cd746d7630711bd | 17,049 | cpp | C++ | gui/main_window/settings/SettingsTab.cpp | Vavilon3000/icq | 9fe7a3c42c07eb665d2e3b0ec50052de382fd89c | [
"Apache-2.0"
] | 1 | 2021-03-18T20:00:07.000Z | 2021-03-18T20:00:07.000Z | gui/main_window/settings/SettingsTab.cpp | Vavilon3000/icq | 9fe7a3c42c07eb665d2e3b0ec50052de382fd89c | [
"Apache-2.0"
] | null | null | null | gui/main_window/settings/SettingsTab.cpp | Vavilon3000/icq | 9fe7a3c42c07eb665d2e3b0ec50052de382fd89c | [
"Apache-2.0"
] | null | null | null | #include "stdafx.h"
#include "SettingsTab.h"
#include "../contact_list/Common.h"
#include "../../core_dispatcher.h"
#include "../../gui_settings.h"
#include "../../utils/utils.h"
#include "../../utils/InterConnector.h"
#include "../../utils/gui_coll_helper.h"
#include "../../controls/CustomButton.h"
#include "../../controls/GeneralDialog.h"
#include "../../controls/LabelEx.h"
#include "../../controls/TransparentScrollBar.h"
#include "../../utils/log/log.h"
namespace
{
const int LEFT_OFFSET = 16;
const int BUTTON_WIDTH = 28;
const int BACK_WIDTH = 52;
const int BACK_HEIGHT = 48;
}
namespace Ui
{
class SettingsTab::UI
{
private:
QWidget *settingsView;
LabelEx *topicLabel;
QWidget* topWidget_;
CustomButton *myProfileButton;
CustomButton *generalButton;
CustomButton *voipButton;
CustomButton *notificationsButton;
CustomButton *themesButton;
friend class SettingsTab;
public:
void init(QWidget* _p, QLayout* _pl)
{
auto back = new CustomButton(_p, qsl(":/controls/arrow_left_100"));
back->setFixedSize(QSize(Utils::scale_value(BACK_WIDTH), Utils::scale_value(BACK_HEIGHT)));
back->setStyleSheet(qsl("background: transparent; border-style: none;"));
back->setOffsets(Utils::scale_value(LEFT_OFFSET), 0);
back->setAlign(Qt::AlignLeft);
topWidget_ = new QWidget(_p);
auto hLayout = Utils::emptyHLayout(topWidget_);
hLayout->setContentsMargins(0, 0, Utils::scale_value(LEFT_OFFSET + BACK_WIDTH), 0);
hLayout->addWidget(back);
topicLabel = new LabelEx(_p);
topicLabel->setColor(CommonStyle::getColor(CommonStyle::Color::TEXT_LIGHT));
topicLabel->setFont(Fonts::appFontScaled(16, Fonts::FontWeight::Medium));
Utils::grabTouchWidget(topicLabel);
topicLabel->setAlignment(Qt::AlignCenter);
topicLabel->setFixedHeight(Utils::scale_value(48));
topicLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
hLayout->addWidget(topicLabel);
_pl->addWidget(topWidget_);
back->setCursor(QCursor(Qt::PointingHandCursor));
connect(back, &QAbstractButton::clicked,[] ()
{
emit Utils::InterConnector::instance().myProfileBack();
});
const auto flatted = true;
const auto checkable = true;
myProfileButton = new CustomButton(settingsView, qsl(":/resources/settings/settings_profile_100.png"));
myProfileButton->setActiveImage(qsl(":/resources/settings/settings_profile_100_active.png"));
Testing::setAccessibleName(myProfileButton, qsl("settings_my_profile_button"));
Utils::grabTouchWidget(myProfileButton);
myProfileButton->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Preferred));
myProfileButton->setMouseTracking(true);
myProfileButton->setFlat(flatted);
myProfileButton->setCheckable(checkable);
myProfileButton->setAlign(Qt::AlignLeft);
myProfileButton->setOffsets(Utils::scale_value(LEFT_OFFSET), 0);
myProfileButton->setFocusPolicy(Qt::NoFocus);
myProfileButton->setCursor(QCursor(Qt::PointingHandCursor));
_pl->addWidget(myProfileButton);
generalButton = new CustomButton(settingsView, qsl(":/resources/settings/settings_general_100.png"));
generalButton->setActiveImage(qsl(":/resources/settings/settings_general_100_active.png"));
Utils::grabTouchWidget(generalButton);
generalButton->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Preferred));
generalButton->setMouseTracking(true);
generalButton->setFlat(flatted);
generalButton->setCheckable(checkable);
generalButton->setAlign(Qt::AlignLeft);
generalButton->setOffsets(Utils::scale_value(LEFT_OFFSET), 0);
generalButton->setFocusPolicy(Qt::NoFocus);
generalButton->setCursor(QCursor(Qt::PointingHandCursor));
_pl->addWidget(generalButton);
themesButton = new CustomButton(settingsView, qsl(":/resources/settings/settings_themes_100.png"));
themesButton->setActiveImage(qsl(":/resources/settings/settings_themes_100_active.png"));
themesButton->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Preferred));
themesButton->setMouseTracking(true);
themesButton->setFlat(flatted);
themesButton->setCheckable(checkable);
themesButton->setAlign(Qt::AlignLeft);
themesButton->setOffsets(Utils::scale_value(LEFT_OFFSET), 0);
themesButton->setFocusPolicy(Qt::NoFocus);
themesButton->setCursor(QCursor(Qt::PointingHandCursor));
_pl->addWidget(themesButton);
notificationsButton = new CustomButton(settingsView, qsl(":/resources/settings/settings_notify_100.png"));
notificationsButton->setActiveImage(qsl(":/resources/settings/settings_notify_100_active.png"));
Utils::grabTouchWidget(notificationsButton);
notificationsButton->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Preferred));
notificationsButton->setMouseTracking(true);
notificationsButton->setFlat(flatted);
notificationsButton->setCheckable(checkable);
notificationsButton->setAlign(Qt::AlignLeft);
notificationsButton->setOffsets(Utils::scale_value(LEFT_OFFSET), 0);
notificationsButton->setFocusPolicy(Qt::NoFocus);
notificationsButton->setCursor(QCursor(Qt::PointingHandCursor));
_pl->addWidget(notificationsButton);
voipButton = new CustomButton(settingsView, qsl(":/resources/settings/settings_video_100.png"));
voipButton->setActiveImage(qsl(":/resources/settings/settings_video_100_active.png"));
Utils::grabTouchWidget(voipButton);
voipButton->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Preferred));
voipButton->setMouseTracking(true);
voipButton->setFlat(flatted);
voipButton->setCheckable(checkable);
voipButton->setAlign(Qt::AlignLeft);
voipButton->setOffsets(Utils::scale_value(LEFT_OFFSET), 0);
voipButton->setFocusPolicy(Qt::NoFocus);
voipButton->setCursor(QCursor(Qt::PointingHandCursor));
_pl->addWidget(voipButton);
topicLabel->setText(QT_TRANSLATE_NOOP("settings_pages","Settings"));
myProfileButton->setText(QT_TRANSLATE_NOOP("settings_pages", "My Profile"));
generalButton->setText(QT_TRANSLATE_NOOP("settings_pages", "General"));
themesButton->setText(QT_TRANSLATE_NOOP("settings_pages", "Wallpaper"));
voipButton->setText(QT_TRANSLATE_NOOP("settings_pages", "Voice and video"));
notificationsButton->setText(QT_TRANSLATE_NOOP("settings_pages", "Notifications"));
}
};
SettingsTab::SettingsTab(QWidget* _parent):
QWidget(_parent),
ui_(new UI()),
currentSettingsItem_(Utils::CommonSettingsType::CommonSettingsType_None),
isCompact_(false)
{
setStyleSheet(Utils::LoadStyle(qsl(":/qss/settings_tab")));
auto scrollArea = CreateScrollAreaAndSetTrScrollBarV(this);
scrollArea->setObjectName(qsl("scroll_area"));
scrollArea->setWidgetResizable(true);
scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
Utils::grabTouchWidget(scrollArea->viewport(), true);
auto scrollAreaContent = new QWidget(scrollArea);
scrollAreaContent->setObjectName(qsl("settings_view"));
Utils::grabTouchWidget(scrollAreaContent);
auto scrollAreaContentLayout = Utils::emptyVLayout(scrollAreaContent);
scrollAreaContentLayout->setAlignment(Qt::AlignTop);
scrollArea->setWidget(scrollAreaContent);
auto layout = Utils::emptyVLayout(this);
layout->addWidget(scrollArea);
ui_->init(scrollAreaContent, scrollAreaContentLayout);
connect(ui_->myProfileButton, &Ui::CustomButton::toggled, this, &SettingsTab::settingsProfileClicked, Qt::QueuedConnection);
connect(ui_->generalButton, &Ui::CustomButton::toggled, this, &SettingsTab::settingsGeneralClicked, Qt::QueuedConnection);
connect(ui_->voipButton, &Ui::CustomButton::toggled, this, &SettingsTab::settingsVoiceVideoClicked, Qt::QueuedConnection);
connect(ui_->notificationsButton, &Ui::CustomButton::toggled, this, &SettingsTab::settingsNotificationsClicked, Qt::QueuedConnection);
connect(ui_->themesButton, &Ui::CustomButton::toggled, this, &SettingsTab::settingsThemesClicked, Qt::QueuedConnection);
connect(&Utils::InterConnector::instance(), &Utils::InterConnector::compactModeChanged, this, &SettingsTab::compactModeChanged, Qt::QueuedConnection);
#ifdef STRIP_VOIP
ui_->voipButton->hide();
#endif //STRIP_VOIP
}
SettingsTab::~SettingsTab() throw()
{
//
}
void SettingsTab::cleanSelection()
{
emit Utils::InterConnector::instance().popPagesToRoot();
currentSettingsItem_ = Utils::CommonSettingsType::CommonSettingsType_None;
updateSettingsState();
}
void SettingsTab::setCompactMode(bool isCompact, bool force)
{
if (isCompact == isCompact_ && !force)
return;
isCompact_ = isCompact;
int compact_offset =
(ContactList::ItemWidth(false, false, true) - Utils::scale_value(BUTTON_WIDTH)) / 2;
ui_->topWidget_->setVisible(!isCompact_);
ui_->myProfileButton->setText(isCompact_ ? QString() : QT_TRANSLATE_NOOP("settings_pages", "My Profile"));
ui_->myProfileButton->setOffsets(isCompact_ ? compact_offset : Utils::scale_value(LEFT_OFFSET), 0);
ui_->generalButton->setText(isCompact_ ? QString() : QT_TRANSLATE_NOOP("settings_pages", "General"));
ui_->generalButton->setOffsets(isCompact_ ? compact_offset : Utils::scale_value(LEFT_OFFSET), 0);
ui_->themesButton->setText(isCompact_ ? QString() : QT_TRANSLATE_NOOP("settings_pages", "Wallpaper"));
ui_->themesButton->setOffsets(isCompact_ ? compact_offset : Utils::scale_value(LEFT_OFFSET), 0);
ui_->voipButton->setText(isCompact_ ? QString() : QT_TRANSLATE_NOOP("settings_pages", "Voice and video"));
ui_->voipButton->setOffsets(isCompact_ ? compact_offset : Utils::scale_value(LEFT_OFFSET), 0);
ui_->notificationsButton->setText(isCompact_ ? QString() : QT_TRANSLATE_NOOP("settings_pages", "Notifications"));
ui_->notificationsButton->setOffsets(isCompact_ ? compact_offset : Utils::scale_value(LEFT_OFFSET), 0);
}
void SettingsTab::settingsProfileClicked()
{
if (currentSettingsItem_ != Utils::CommonSettingsType::CommonSettingsType_Profile
&& currentSettingsItem_ != Utils::CommonSettingsType::CommonSettingsType_None)
emit Utils::InterConnector::instance().generalSettingsBack();
currentSettingsItem_ = Utils::CommonSettingsType::CommonSettingsType_Profile;
updateSettingsState();
emit Utils::InterConnector::instance().profileSettingsShow(QString());
emit Utils::InterConnector::instance().showHeader(QT_TRANSLATE_NOOP("main_page", "My profile"));
GetDispatcher()->post_stats_to_core(core::stats::stats_event_names::myprofile_open);
}
void SettingsTab::settingsGeneralClicked()
{
if (currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_Profile)
emit Utils::InterConnector::instance().profileSettingsBack();
currentSettingsItem_ = Utils::CommonSettingsType::CommonSettingsType_General;
updateSettingsState();
emit Utils::InterConnector::instance().showHeader(QT_TRANSLATE_NOOP("main_page", "General settings"));
emit Utils::InterConnector::instance().generalSettingsShow((int)Utils::CommonSettingsType::CommonSettingsType_General);
}
void SettingsTab::settingsVoiceVideoClicked()
{
if (currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_Profile)
emit Utils::InterConnector::instance().profileSettingsBack();
currentSettingsItem_ = Utils::CommonSettingsType::CommonSettingsType_VoiceVideo;
updateSettingsState();
emit Utils::InterConnector::instance().showHeader(QT_TRANSLATE_NOOP("main_page", "Voice and video"));
emit Utils::InterConnector::instance().generalSettingsShow((int)Utils::CommonSettingsType::CommonSettingsType_VoiceVideo);
}
void SettingsTab::settingsNotificationsClicked()
{
if (currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_Profile)
emit Utils::InterConnector::instance().profileSettingsBack();
currentSettingsItem_ = Utils::CommonSettingsType::CommonSettingsType_Notifications;
updateSettingsState();
emit Utils::InterConnector::instance().showHeader(QT_TRANSLATE_NOOP("main_page", "Notifications"));
emit Utils::InterConnector::instance().generalSettingsShow((int)Utils::CommonSettingsType::CommonSettingsType_Notifications);
}
void SettingsTab::settingsThemesClicked()
{
if (currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_Profile)
emit Utils::InterConnector::instance().profileSettingsBack();
currentSettingsItem_ = Utils::CommonSettingsType::CommonSettingsType_Themes;
updateSettingsState();
emit Utils::InterConnector::instance().showHeader(QT_TRANSLATE_NOOP("main_page", "Wallpaper"));
emit Utils::InterConnector::instance().themesSettingsShow(false, QString());
}
void SettingsTab::updateSettingsState()
{
QSignalBlocker sbMyProfile(ui_->myProfileButton);
QSignalBlocker sbGeneral(ui_->generalButton);
QSignalBlocker sbVoip(ui_->voipButton);
QSignalBlocker sbNotif(ui_->notificationsButton);
QSignalBlocker sbThemes(ui_->themesButton);
ui_->myProfileButton->setChecked(currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_Profile);
ui_->myProfileButton->setDisabled(currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_Profile);
ui_->myProfileButton->setActive(currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_Profile);
ui_->myProfileButton->setTextColor(currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_Profile ? qsl("#ffffff") : qsl("#454545"));
ui_->generalButton->setChecked(currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_General);
ui_->generalButton->setDisabled(currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_General);
ui_->generalButton->setActive(currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_General);
ui_->generalButton->setTextColor(currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_General ? qsl("#ffffff") : qsl("#454545"));
ui_->voipButton->setChecked(currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_VoiceVideo);
ui_->voipButton->setDisabled(currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_VoiceVideo);
ui_->voipButton->setActive(currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_VoiceVideo);
ui_->voipButton->setTextColor(currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_VoiceVideo ? qsl("#ffffff") : qsl("#454545"));
ui_->notificationsButton->setChecked(currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_Notifications);
ui_->notificationsButton->setDisabled(currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_Notifications);
ui_->notificationsButton->setActive(currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_Notifications);
ui_->notificationsButton->setTextColor(currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_Notifications ? qsl("#ffffff") : qsl("#454545"));
ui_->themesButton->setChecked(currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_Themes);
ui_->themesButton->setDisabled(currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_Themes);
ui_->themesButton->setActive(currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_Themes);
ui_->themesButton->setTextColor(currentSettingsItem_ == Utils::CommonSettingsType::CommonSettingsType_Themes ? qsl("#ffffff") : qsl("#454545"));
}
void SettingsTab::compactModeChanged()
{
setCompactMode(isCompact_, true);
}
}
| 52.783282 | 166 | 0.704206 | Vavilon3000 |
814bcac929e8933dd5252a86359de0e02343b476 | 2,303 | cpp | C++ | src/d3d12/ResourceHeapAllocatorD3D12.cpp | bbernhar/GPGMM | 82618e725c33ddd49680684a9ed90040dda55e0e | [
"Apache-2.0"
] | null | null | null | src/d3d12/ResourceHeapAllocatorD3D12.cpp | bbernhar/GPGMM | 82618e725c33ddd49680684a9ed90040dda55e0e | [
"Apache-2.0"
] | null | null | null | src/d3d12/ResourceHeapAllocatorD3D12.cpp | bbernhar/GPGMM | 82618e725c33ddd49680684a9ed90040dda55e0e | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 The Dawn Authors
// Copyright 2021 The GPGMM Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "src/d3d12/ResourceHeapAllocatorD3D12.h"
#include "src/common/IntegerTypes.h"
#include "src/d3d12/HeapD3D12.h"
#include "src/d3d12/ResourceAllocatorD3D12.h"
namespace gpgmm { namespace d3d12 {
ResourceHeapAllocator::ResourceHeapAllocator(ResourceAllocator* resourceAllocator,
D3D12_HEAP_TYPE heapType,
D3D12_HEAP_FLAGS heapFlags,
DXGI_MEMORY_SEGMENT_GROUP memorySegment,
uint64_t heapSize)
: mResourceAllocator(resourceAllocator),
mHeapType(heapType),
mHeapFlags(heapFlags),
mMemorySegment(memorySegment) {
}
std::unique_ptr<MemoryAllocation> ResourceHeapAllocator::AllocateMemory(uint64_t size,
uint64_t alignment) {
Heap* heap = nullptr;
if (FAILED(mResourceAllocator->CreateResourceHeap(size, mHeapType, mHeapFlags,
mMemorySegment, alignment, &heap))) {
return nullptr;
}
AllocationInfo info = {};
info.mMethod = AllocationMethod::kStandalone;
return std::make_unique<MemoryAllocation>(/*allocator*/ this, info, kInvalidOffset, heap);
}
void ResourceHeapAllocator::DeallocateMemory(MemoryAllocation* allocation) {
ASSERT(allocation != nullptr);
Heap* heap = static_cast<Heap*>(allocation->GetMemory());
mResourceAllocator->FreeResourceHeap(heap);
}
}} // namespace gpgmm::d3d12
| 42.648148 | 98 | 0.625271 | bbernhar |
814f894e431b2d108e977d40ce9f0ec1cd13640e | 9,039 | cpp | C++ | Gamepad.cpp | Raattis/SFML_GamepadSupport | 73e35a315037fbba0d8789b6652065e187fda71b | [
"MIT"
] | null | null | null | Gamepad.cpp | Raattis/SFML_GamepadSupport | 73e35a315037fbba0d8789b6652065e187fda71b | [
"MIT"
] | null | null | null | Gamepad.cpp | Raattis/SFML_GamepadSupport | 73e35a315037fbba0d8789b6652065e187fda71b | [
"MIT"
] | null | null | null | #include "Gamepad.h"
#include <SFML/Graphics.hpp>
#include <string>
#include <fstream>
#include <iostream>
/// XInput
#include "Windows.h"
#include "Xinput.h"
#pragma comment(lib,"XInput.lib") // include libraries
#pragma comment(lib,"Xinput9_1_0.lib") // include libraries
Gamepad::Gamepad(int number, bool XInput) : gamepadNumber(number)
{
/// XINPUT
isXInput = XInput;
if (isXInput) {
std::cout << "XInput device found.";
return;
}
/// SDL DATABASE
sf::Joystick::Identification data = sf::Joystick::getIdentification(gamepadNumber);
// open db
std::ifstream gamepads("resources/gamecontrollerdb.txt");
if (!gamepads.is_open()) {
std::cout << "Gamepad database not found!";
return;
}
// Windows section
std::string line = "";
while (line != "# Windows") std::getline(gamepads, line);
// Get vendorID and productID from GUID
/* EXAMPLE:
030000005e040000d102000000000000
\__/ \__/
vendor product
vendor: 5e04 -> 0x045e Hex -> 1118 decimal (Microsoft)
product: d102 -> 0x02d1 Hex -> 721 decimal (Xbox One Controller)
*/
unsigned int vID = 0;
unsigned int pID = 0;
while (!(vID == data.vendorId && pID == data.productId) || gamepads.eof()) {
std::getline(gamepads, line); // entire line
vID = std::stoul(line.substr(10, 2) + line.substr(8, 2), nullptr, 16); // hex string to unsigned int
pID = std::stoul(line.substr(18, 2) + line.substr(16, 2), nullptr, 16);
}
if (!gamepads.eof()) {
std::cout << data.name.toAnsiString() << " found.";
LoadData(line);
}
else std::cout << "Gamepad not found!"; // TO DO: Manually enter gamepad values
// close db
gamepads.close();
}
bool Gamepad::isButtonPressed(GAMEPAD_BUTTON btn)
{
if (isXInput) {
XINPUT_STATE state;
ZeroMemory(&state, sizeof(XINPUT_STATE));
XInputGetState(gamepadNumber, &state);
if (state.Gamepad.wButtons & getButtonNumber(btn)) return true;
}
return (sf::Joystick::isButtonPressed(gamepadNumber, getButtonNumber(btn)));
}
float Gamepad::getAxisPosition(GAMEPAD_AXIS axis)
{
XINPUT_STATE state;
if (isXInput) {
ZeroMemory(&state, sizeof(XINPUT_STATE));
XInputGetState(gamepadNumber, &state);
}
GamePadAxis ax;
switch (axis)
{
case GAMEPAD_AXIS::leftStick_X: {
if (isXInput) return shrinkValue(state.Gamepad.sThumbLX, false);
else ax = LSTICK_X;
} break;
case GAMEPAD_AXIS::leftStick_Y: {
if (isXInput) return shrinkValue(-state.Gamepad.sThumbLY, false);
else ax = LSTICK_Y;
} break;
case GAMEPAD_AXIS::rightStick_X: {
if (isXInput) return shrinkValue(state.Gamepad.sThumbRX, false);
else ax = RSTICK_X;
} break;
case GAMEPAD_AXIS::rightStick_Y: {
if (isXInput) return shrinkValue(-state.Gamepad.sThumbRY, false);
else ax = RSTICK_Y;
} break;
}
float p = sf::Joystick::getAxisPosition(gamepadNumber, ax.Axis);
if (ax.inverted) p = -p;
return p;
}
float Gamepad::getTriggerValue(GAMEPAD_TRIGGER tgr)
{
if (isXInput) {
XINPUT_STATE state;
ZeroMemory(&state, sizeof(XINPUT_STATE));
XInputGetState(gamepadNumber, &state);
if (tgr == GAMEPAD_TRIGGER::leftTrigger) return shrinkValue(state.Gamepad.bLeftTrigger, true);
else return shrinkValue(state.Gamepad.bRightTrigger, true);
}
else {
if (tgr == GAMEPAD_TRIGGER::leftTrigger) {
// as axis
if (LTRIGGER.isAxis) {
float p = sf::Joystick::getAxisPosition(gamepadNumber, LTRIGGER.Axis.Axis);
if (LTRIGGER.Axis.inverted) p = -p;
return p;
}
// as button
else if (sf::Joystick::isButtonPressed(gamepadNumber, LTRIGGER.button)) return 100.f;
else return 0.f;
}
else {
// as axis
if (RTRIGGER.isAxis) {
float p = sf::Joystick::getAxisPosition(gamepadNumber, RTRIGGER.Axis.Axis);
if (RTRIGGER.Axis.inverted) p = -p;
return p;
}
// as button
if (sf::Joystick::isButtonPressed(gamepadNumber, RTRIGGER.button)) return 100.f;
else return 0.f;
}
}
}
int Gamepad::getButtonNumber(GAMEPAD_BUTTON btn)
{
switch (btn)
{
case GAMEPAD_BUTTON::btn_a: if (isXInput) return XINPUT_GAMEPAD_A; return A;
case GAMEPAD_BUTTON::btn_b: if (isXInput) return XINPUT_GAMEPAD_B; return B;
case GAMEPAD_BUTTON::btn_x: if (isXInput) return XINPUT_GAMEPAD_X; return X;
case GAMEPAD_BUTTON::btn_y: if (isXInput) return XINPUT_GAMEPAD_Y; return Y;
case GAMEPAD_BUTTON::btn_leftStick: if (isXInput) return XINPUT_GAMEPAD_LEFT_THUMB; return LSTICK;
case GAMEPAD_BUTTON::btn_rightStick: if (isXInput) return XINPUT_GAMEPAD_RIGHT_THUMB; return RSTICK;
case GAMEPAD_BUTTON::btn_back: if (isXInput) return XINPUT_GAMEPAD_BACK; return BACK;
case GAMEPAD_BUTTON::btn_start: if (isXInput) return XINPUT_GAMEPAD_START; return START;
case GAMEPAD_BUTTON::btn_lb: if (isXInput) return XINPUT_GAMEPAD_LEFT_SHOULDER; return LB;
case GAMEPAD_BUTTON::btn_rb: if (isXInput) return XINPUT_GAMEPAD_RIGHT_SHOULDER; return RB;
/*case GAMEPAD_BUTTON::dpad_up: if (isXInput) return XINPUT_GAMEPAD_DPAD_UP; return DPADUP;
case GAMEPAD_BUTTON::dpad_down: if (isXInput) return XINPUT_GAMEPAD_DPAD_DOWN; return DPADDOWN;
case GAMEPAD_BUTTON::dpad_left: if (isXInput) return XINPUT_GAMEPAD_DPAD_LEFT; return DPADLEFT;
case GAMEPAD_BUTTON::dpad_right: if (isXInput) return XINPUT_GAMEPAD_DPAD_RIGHT; return DPADRIGHT;*/
}
}
void Gamepad::LoadData(std::string line)
{
// EXAMPLE:
/* 030000005e040000d102000000000000,Xbox One Controller,
a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,
leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,
rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,
righty:a4,start:b7,x:b2,y:b3,platform:Windows,
*/
int pos = line.find(",");
line = line.substr(pos + 1); // clear GUID "Xbox One Controller,a:b0,b..."
pos = line.find(",");
line = line.substr(pos + 1); // clear name "a:b0,b:b1,back:b6,d..."
while (line.substr(0, 8) != "platform") {
// extract name and data of current button/axis
pos = line.find(":");
int endPos = line.find(",");
std::string name = line.substr(0, pos); // "a"
std::string data = line.substr(pos + 1, endPos - pos - 1); // "b0"
if (data[0] == 'b') { // button (TO DO: DPAD)
if (!assignButton(name, data)) {
std::cerr << "Button not found: \"" << name << "\" \"" << data << "\"";
}
}
else if (data[0] == 'a' || data[0] == '-' || data[0] == '+') { // axis
if (!assignAxis(name, data)) {
std::cerr << "Axis not found: \"" << name << "\" \"" << data << "\"";
}
}
// next button or axis
pos = line.find(",");
line = line.substr(pos + 1);
}
}
bool Gamepad::assignButton(std::string n, std::string d)
{
int b = std::stoi(d.substr(1, d.size() - 1)); // just number -> "b0" -> "0"
if (n == "a") A = b;
else if (n == "b") B = b;
else if (n == "x") X = b;
else if (n == "y") Y = b;
else if (n == "back") BACK = b;
else if (n == "start") START = b;
else if (n == "leftshoulder") LB = b;
else if (n == "rightshoulder") RB = b;
else if (n == "leftstick") LSTICK = b;
else if (n == "rightstick") RSTICK = b;
else if (n == "lefttrigger") {
LTRIGGER.isAxis = false;
LTRIGGER.button = b;
}
else if (n == "righttrigger") {
RTRIGGER.isAxis = false;
RTRIGGER.button = b;
}
else if (n == "guide") return true; // ignore button "guide"
else return false;
return true;
}
bool Gamepad::assignAxis(std::string n, std::string d)
{
// possible input: "a0" , "-a1", +a3"
bool inverted = (d[0] == '-');
int a;
((d[0] == '-' || d[0] == '+'))
? a = std::stoi(d.substr(2)) // "-a2" -> "2"
: a = std::stoi(d.substr(1)); // "a2" -> "2"
if (n == "leftx") {
LSTICK_X.Axis = extractAxis(a);
LSTICK_X.inverted = inverted;
}
else if (n == "lefty") {
LSTICK_Y.Axis = extractAxis(a);
LSTICK_Y.inverted = inverted;
}
else if (n == "rightx") {
RSTICK_X.Axis = extractAxis(a);
RSTICK_X.inverted = inverted;
}
else if (n == "righty") {
RSTICK_Y.Axis = extractAxis(a);
RSTICK_Y.inverted = inverted;
}
else if (n == "lefttrigger") {
LTRIGGER.isAxis = true;
LTRIGGER.Axis.Axis = extractAxis(a);
LTRIGGER.Axis.inverted = inverted;
}
else if (n == "righttrigger") {
RTRIGGER.isAxis = true;
RTRIGGER.Axis.Axis = extractAxis(a);
RTRIGGER.Axis.inverted = inverted;
}
else return false;
return true;
}
sf::Joystick::Axis Gamepad::extractAxis(int axisNumber)
{
switch (axisNumber)
{
case 0: return sf::Joystick::Axis::X;
case 1: return sf::Joystick::Axis::Y;
case 2: return sf::Joystick::Axis::Z;
case 3: return sf::Joystick::Axis::R;
case 4: return sf::Joystick::Axis::U;
case 5: return sf::Joystick::Axis::V;
case 6: return sf::Joystick::Axis::PovX;
case 7: return sf::Joystick::Axis::PovY;
}
assert(false && "Axis Number out of range");
}
float Gamepad::shrinkValue(float f, bool trigger)
{
/*
Triggers:
old: 0 to 255
new: 0 to 100
Thumbs:
old: -32768 to 32767
new: -100 to 100
*/
float oldMin = (f < 0) ? -32768 : 0;
float oldMax = (trigger) ? 255 : 32767;
float newMin = (f < 0) ? -100 : 0;
float newMax = 100;
float oldPercent = (f - oldMin) / (oldMax - oldMin);
return ((newMax - newMin) * oldPercent + newMin);
}
| 29.442997 | 102 | 0.664897 | Raattis |
8151a76754506bee9852f224111f50244b999c55 | 2,614 | cpp | C++ | gym/100518/E.cpp | albexl/codeforces-gym-submissions | 2a51905c50fcf5d7f417af81c4c49ca5217d0753 | [
"MIT"
] | 1 | 2021-07-16T19:59:39.000Z | 2021-07-16T19:59:39.000Z | gym/100518/E.cpp | albexl/codeforces-gym-submissions | 2a51905c50fcf5d7f417af81c4c49ca5217d0753 | [
"MIT"
] | null | null | null | gym/100518/E.cpp | albexl/codeforces-gym-submissions | 2a51905c50fcf5d7f417af81c4c49ca5217d0753 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define endl '\n'
typedef long long ll;
typedef pair<ll, ll> pii;
const int maxn = 300 + 5;
int n;
vector<int> g[maxn];
bool visited[maxn];
int cnt = 0;
bool ok = false;
vector<int> path, comb;
void print(){
for(int i = 0; i < (int)path.size(); i++)
cout << path[i] + 1 << " ";
for(int i = 0; i < (int)comb.size(); i++)
cout << comb[i] + 1 << " \n"[i + 1 == (int)comb.size()];
}
void dfs(int u, int lvl){
// cout << u << " " << lvl << endl;
path.push_back(u);
visited[u] = true;
cnt++;
if(cnt == n){
ok = true;
print();
return;
}
if(lvl){
for(auto &v : g[u]){
for(auto &y : g[u]){
if(v != y && !visited[v] && !visited[y]){
visited[y] = true;
cnt++;
comb.push_back(y);
dfs(v, lvl + 1);
comb.pop_back();
visited[y] = false;
cnt--;
if(ok)
return;
}
}
}
}
else{
for(auto &v : g[u]){
if(!visited[v])
dfs(v, lvl + 1);
if(ok)
return;
}
}
cnt--;
visited[u] = false;
path.pop_back();
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
freopen("embedding.in", "r", stdin);
freopen("embedding.out", "w", stdout);
while(cin >> n && n){
path.clear();
comb.clear();
cnt = 0;
for(int i = 0; i < maxn; i++){
g[i].clear();
visited[i] = false;
}
ok = false;
set<pii> bad;
n *= 2;
for(int i = 0; i < n / 2; i++){
bad.insert({i, (i + 1) % n});
bad.insert({(i + 1) % n, i});
path.push_back(i);
}
path.push_back(n / 2);
for(int i = 1; i < n / 2; i++){
bad.insert({i, n - i});
bad.insert({n - i, i});
comb.push_back(n - i);
}
print();
path.clear();
comb.clear();
for(int i = n / 2; i < n; i++){
bad.insert({i, (i + 1) % n});
bad.insert({(i + 1) % n, i});
path.push_back(i);
}
path.push_back(0);
reverse(path.begin(), path.end());
for(int i = n - 1; i > n / 2 + 1; i--){
bad.insert({i, n - i + 1});
bad.insert({n - i + 1, i});
comb.push_back(n - i + 1);
// cout << i << " " << n - i + 1 << endl;
}
bad.insert({n / 2 + 1, 1});
bad.insert({1, n / 2 + 1});
comb.push_back(1);
print();
path.clear();
comb.clear();
// cout << "bad" << endl;
// for(auto &e : bad)
// cout << e.first << " " << e.second << endl;
//
// cout << (bad.size() == (4 * (n - 1))) << endl;
// cout << "edges" << endl;
for(int i = 0; i < n; i++)
for(int j = i + 1; j < n; j++)
if(bad.find(pii(i, j)) == bad.end()){
g[i].push_back(j);
g[j].push_back(i);
// cout << i << " " << j << endl;
}
dfs(1, 0);
}
return 0;
} | 14.768362 | 58 | 0.466335 | albexl |
8152aee6b8f10a4e5a78477f105e4548c53f0eea | 32,524 | cpp | C++ | src/context.cpp | winsider/libsass | a3e4df0ea5bdf2728a663294b8b84a3c7574be29 | [
"MIT"
] | null | null | null | src/context.cpp | winsider/libsass | a3e4df0ea5bdf2728a663294b8b84a3c7574be29 | [
"MIT"
] | null | null | null | src/context.cpp | winsider/libsass | a3e4df0ea5bdf2728a663294b8b84a3c7574be29 | [
"MIT"
] | null | null | null | // sass.hpp must go before all system headers to get the
// __EXTENSIONS__ fix on Solaris.
#include "sass.hpp"
#include "ast.hpp"
#include "remove_placeholders.hpp"
#include "sass_functions.hpp"
#include "check_nesting.hpp"
#include "fn_selectors.hpp"
#include "fn_strings.hpp"
#include "fn_numbers.hpp"
#include "fn_colors.hpp"
#include "fn_miscs.hpp"
#include "fn_lists.hpp"
#include "fn_maps.hpp"
#include "context.hpp"
#include "expand.hpp"
#include "parser.hpp"
#include "cssize.hpp"
namespace Sass {
using namespace Constants;
using namespace File;
using namespace Sass;
inline bool sort_importers (const Sass_Importer_Entry& i, const Sass_Importer_Entry& j)
{ return sass_importer_get_priority(i) > sass_importer_get_priority(j); }
static sass::string safe_input(const char* in_path)
{
if (in_path == nullptr || in_path[0] == '\0') return "stdin";
return in_path;
}
static sass::string safe_output(const char* out_path, sass::string input_path)
{
if (out_path == nullptr || out_path[0] == '\0') {
if (input_path.empty()) return "stdout";
return input_path.substr(0, input_path.find_last_of(".")) + ".css";
}
return out_path;
}
Context::Context(struct Sass_Context& c_ctx)
: CWD(File::get_cwd()),
c_options(c_ctx),
entry_path(""),
head_imports(0),
plugins(),
emitter(c_options),
ast_gc(),
strings(),
resources(),
sheets(),
import_stack(),
callee_stack(),
traces(),
extender(Extender::NORMAL, traces),
c_compiler(NULL),
c_headers (sass::vector<Sass_Importer_Entry>()),
c_importers (sass::vector<Sass_Importer_Entry>()),
c_functions (sass::vector<Sass_Function_Entry>()),
indent (safe_str(c_options.indent, " ")),
linefeed (safe_str(c_options.linefeed, "\n")),
input_path (make_canonical_path(safe_input(c_options.input_path))),
output_path (make_canonical_path(safe_output(c_options.output_path, input_path))),
source_map_file (make_canonical_path(safe_str(c_options.source_map_file, ""))),
source_map_root (make_canonical_path(safe_str(c_options.source_map_root, "")))
{
// Sass 3.4: The current working directory will no longer be placed onto the Sass load path by default.
// If you need the current working directory to be available, set SASS_PATH=. in your shell's environment.
// include_paths.push_back(CWD);
// collect more paths from different options
collect_include_paths(c_options.include_path);
collect_include_paths(c_options.include_paths);
collect_plugin_paths(c_options.plugin_path);
collect_plugin_paths(c_options.plugin_paths);
// load plugins and register custom behaviors
for(auto plug : plugin_paths) plugins.load_plugins(plug);
for(auto fn : plugins.get_headers()) c_headers.push_back(fn);
for(auto fn : plugins.get_importers()) c_importers.push_back(fn);
for(auto fn : plugins.get_functions()) c_functions.push_back(fn);
// sort the items by priority (lowest first)
sort (c_headers.begin(), c_headers.end(), sort_importers);
sort (c_importers.begin(), c_importers.end(), sort_importers);
emitter.set_filename(abs2rel(output_path, source_map_file, CWD));
}
void Context::add_c_function(Sass_Function_Entry function)
{
c_functions.push_back(function);
}
void Context::add_c_header(Sass_Importer_Entry header)
{
c_headers.push_back(header);
// need to sort the array afterwards (no big deal)
sort (c_headers.begin(), c_headers.end(), sort_importers);
}
void Context::add_c_importer(Sass_Importer_Entry importer)
{
c_importers.push_back(importer);
// need to sort the array afterwards (no big deal)
sort (c_importers.begin(), c_importers.end(), sort_importers);
}
Context::~Context()
{
// resources were allocated by malloc
for (size_t i = 0; i < resources.size(); ++i) {
free(resources[i].contents);
free(resources[i].srcmap);
}
// free all strings we kept alive during compiler execution
for (size_t n = 0; n < strings.size(); ++n) free(strings[n]);
// everything that gets put into sources will be freed by us
// this shouldn't have anything in it anyway!?
for (size_t m = 0; m < import_stack.size(); ++m) {
sass_import_take_source(import_stack[m]);
sass_import_take_srcmap(import_stack[m]);
sass_delete_import(import_stack[m]);
}
// clear inner structures (vectors) and input source
resources.clear(); import_stack.clear();
sheets.clear();
}
Data_Context::~Data_Context()
{
// --> this will be freed by resources
// make sure we free the source even if not processed!
// if (resources.size() == 0 && source_c_str) free(source_c_str);
// if (resources.size() == 0 && srcmap_c_str) free(srcmap_c_str);
// source_c_str = 0; srcmap_c_str = 0;
}
File_Context::~File_Context()
{
}
void Context::collect_include_paths(const char* paths_str)
{
if (paths_str) {
const char* beg = paths_str;
const char* end = Prelexer::find_first<PATH_SEP>(beg);
while (end) {
sass::string path(beg, end - beg);
if (!path.empty()) {
if (*path.rbegin() != '/') path += '/';
include_paths.push_back(path);
}
beg = end + 1;
end = Prelexer::find_first<PATH_SEP>(beg);
}
sass::string path(beg);
if (!path.empty()) {
if (*path.rbegin() != '/') path += '/';
include_paths.push_back(path);
}
}
}
void Context::collect_include_paths(string_list* paths_array)
{
while (paths_array)
{
collect_include_paths(paths_array->string);
paths_array = paths_array->next;
}
}
void Context::collect_plugin_paths(const char* paths_str)
{
if (paths_str) {
const char* beg = paths_str;
const char* end = Prelexer::find_first<PATH_SEP>(beg);
while (end) {
sass::string path(beg, end - beg);
if (!path.empty()) {
if (*path.rbegin() != '/') path += '/';
plugin_paths.push_back(path);
}
beg = end + 1;
end = Prelexer::find_first<PATH_SEP>(beg);
}
sass::string path(beg);
if (!path.empty()) {
if (*path.rbegin() != '/') path += '/';
plugin_paths.push_back(path);
}
}
}
void Context::collect_plugin_paths(string_list* paths_array)
{
while (paths_array)
{
collect_plugin_paths(paths_array->string);
paths_array = paths_array->next;
}
}
// resolve the imp_path in base_path or include_paths
// looks for alternatives and returns a list from one directory
sass::vector<Include> Context::find_includes(const Importer& import)
{
// make sure we resolve against an absolute path
sass::string base_path(rel2abs(import.base_path));
// first try to resolve the load path relative to the base path
sass::vector<Include> vec(resolve_includes(base_path, import.imp_path));
// then search in every include path (but only if nothing found yet)
for (size_t i = 0, S = include_paths.size(); vec.size() == 0 && i < S; ++i)
{
// call resolve_includes and individual base path and append all results
sass::vector<Include> resolved(resolve_includes(include_paths[i], import.imp_path));
if (resolved.size()) vec.insert(vec.end(), resolved.begin(), resolved.end());
}
// return vector
return vec;
}
// register include with resolved path and its content
// memory of the resources will be freed by us on exit
void Context::register_resource(const Include& inc, const Resource& res)
{
// do not parse same resource twice
// maybe raise an error in this case
// if (sheets.count(inc.abs_path)) {
// free(res.contents); free(res.srcmap);
// throw std::runtime_error("duplicate resource registered");
// return;
// }
// get index for this resource
size_t idx = resources.size();
// tell emitter about new resource
emitter.add_source_index(idx);
// put resources under our control
// the memory will be freed later
resources.push_back(res);
// add a relative link to the working directory
included_files.push_back(inc.abs_path);
// add a relative link to the source map output file
srcmap_links.push_back(abs2rel(inc.abs_path, source_map_file, CWD));
// get pointer to the loaded content
Sass_Import_Entry import = sass_make_import(
inc.imp_path.c_str(),
inc.abs_path.c_str(),
res.contents,
res.srcmap
);
// add the entry to the stack
import_stack.push_back(import);
// get pointer to the loaded content
const char* contents = resources[idx].contents;
// keep a copy of the path around (for parserstates)
// ToDo: we clean it, but still not very elegant!?
strings.push_back(sass_copy_c_string(inc.abs_path.c_str()));
// create the initial parser state from resource
SourceSpan pstate(strings.back(), contents, idx);
// check existing import stack for possible recursion
for (size_t i = 0; i < import_stack.size() - 2; ++i) {
auto parent = import_stack[i];
if (std::strcmp(parent->abs_path, import->abs_path) == 0) {
sass::string cwd(File::get_cwd());
// make path relative to the current directory
sass::string stack("An @import loop has been found:");
for (size_t n = 1; n < i + 2; ++n) {
stack += "\n " + sass::string(File::abs2rel(import_stack[n]->abs_path, cwd, cwd)) +
" imports " + sass::string(File::abs2rel(import_stack[n+1]->abs_path, cwd, cwd));
}
// implement error throw directly until we
// decided how to handle full stack traces
throw Exception::InvalidSyntax(pstate, traces, stack);
// error(stack, prstate ? *prstate : pstate, import_stack);
}
}
// create a parser instance from the given c_str buffer
Parser p(Parser::from_c_str(contents, *this, traces, pstate));
// do not yet dispose these buffers
sass_import_take_source(import);
sass_import_take_srcmap(import);
// then parse the root block
Block_Obj root = p.parse();
// delete memory of current stack frame
sass_delete_import(import_stack.back());
// remove current stack frame
import_stack.pop_back();
// create key/value pair for ast node
std::pair<const sass::string, StyleSheet>
ast_pair(inc.abs_path, { res, root });
// register resulting resource
sheets.insert(ast_pair);
}
// register include with resolved path and its content
// memory of the resources will be freed by us on exit
void Context::register_resource(const Include& inc, const Resource& res, SourceSpan& prstate)
{
traces.push_back(Backtrace(prstate));
register_resource(inc, res);
traces.pop_back();
}
// Add a new import to the context (called from `import_url`)
Include Context::load_import(const Importer& imp, SourceSpan pstate)
{
// search for valid imports (ie. partials) on the filesystem
// this may return more than one valid result (ambiguous imp_path)
const sass::vector<Include> resolved(find_includes(imp));
// error nicely on ambiguous imp_path
if (resolved.size() > 1) {
sass::sstream msg_stream;
msg_stream << "It's not clear which file to import for ";
msg_stream << "'@import \"" << imp.imp_path << "\"'." << "\n";
msg_stream << "Candidates:" << "\n";
for (size_t i = 0, L = resolved.size(); i < L; ++i)
{ msg_stream << " " << resolved[i].imp_path << "\n"; }
msg_stream << "Please delete or rename all but one of these files." << "\n";
error(msg_stream.str(), pstate, traces);
}
// process the resolved entry
else if (resolved.size() == 1) {
bool use_cache = c_importers.size() == 0;
// use cache for the resource loading
if (use_cache && sheets.count(resolved[0].abs_path)) return resolved[0];
// try to read the content of the resolved file entry
// the memory buffer returned must be freed by us!
if (char* contents = read_file(resolved[0].abs_path)) {
// register the newly resolved file resource
register_resource(resolved[0], { contents, 0 }, pstate);
// return resolved entry
return resolved[0];
}
}
// nothing found
return { imp, "" };
}
void Context::import_url (Import* imp, sass::string load_path, const sass::string& ctx_path) {
SourceSpan pstate(imp->pstate());
sass::string imp_path(unquote(load_path));
sass::string protocol("file");
using namespace Prelexer;
if (const char* proto = sequence< identifier, exactly<':'>, exactly<'/'>, exactly<'/'> >(imp_path.c_str())) {
protocol = sass::string(imp_path.c_str(), proto - 3);
// if (protocol.compare("file") && true) { }
}
// add urls (protocol other than file) and urls without protocol to `urls` member
// ToDo: if ctx_path is already a file resource, we should not add it here?
if (imp->import_queries() || protocol != "file" || imp_path.substr(0, 2) == "//") {
imp->urls().push_back(SASS_MEMORY_NEW(String_Quoted, imp->pstate(), load_path));
}
else if (imp_path.length() > 4 && imp_path.substr(imp_path.length() - 4, 4) == ".css") {
String_Constant* loc = SASS_MEMORY_NEW(String_Constant, pstate, unquote(load_path));
Argument_Obj loc_arg = SASS_MEMORY_NEW(Argument, pstate, loc);
Arguments_Obj loc_args = SASS_MEMORY_NEW(Arguments, pstate);
loc_args->append(loc_arg);
Function_Call* new_url = SASS_MEMORY_NEW(Function_Call, pstate, sass::string("url"), loc_args);
imp->urls().push_back(new_url);
}
else {
const Importer importer(imp_path, ctx_path);
Include include(load_import(importer, pstate));
if (include.abs_path.empty()) {
error("File to import not found or unreadable: " + imp_path + ".", pstate, traces);
}
imp->incs().push_back(include);
}
}
// call custom importers on the given (unquoted) load_path and eventually parse the resulting style_sheet
bool Context::call_loader(const sass::string& load_path, const char* ctx_path, SourceSpan& pstate, Import* imp, sass::vector<Sass_Importer_Entry> importers, bool only_one)
{
// unique counter
size_t count = 0;
// need one correct import
bool has_import = false;
// process all custom importers (or custom headers)
for (Sass_Importer_Entry& importer_ent : importers) {
// int priority = sass_importer_get_priority(importer);
Sass_Importer_Fn fn = sass_importer_get_function(importer_ent);
// skip importer if it returns NULL
if (Sass_Import_List includes =
fn(load_path.c_str(), importer_ent, c_compiler)
) {
// get c pointer copy to iterate over
Sass_Import_List it_includes = includes;
while (*it_includes) { ++count;
// create unique path to use as key
sass::string uniq_path = load_path;
if (!only_one && count) {
sass::sstream path_strm;
path_strm << uniq_path << ":" << count;
uniq_path = path_strm.str();
}
// create the importer struct
Importer importer(uniq_path, ctx_path);
// query data from the current include
Sass_Import_Entry include_ent = *it_includes;
char* source = sass_import_take_source(include_ent);
char* srcmap = sass_import_take_srcmap(include_ent);
size_t line = sass_import_get_error_line(include_ent);
size_t column = sass_import_get_error_column(include_ent);
const char *abs_path = sass_import_get_abs_path(include_ent);
// handle error message passed back from custom importer
// it may (or may not) override the line and column info
if (const char* err_message = sass_import_get_error_message(include_ent)) {
if (source || srcmap) register_resource({ importer, uniq_path }, { source, srcmap }, pstate);
if (line == sass::string::npos && column == sass::string::npos) error(err_message, pstate, traces);
else error(err_message, SourceSpan(ctx_path, source, Position(line, column)), traces);
}
// content for import was set
else if (source) {
// resolved abs_path should be set by custom importer
// use the created uniq_path as fallback (maybe enforce)
sass::string path_key(abs_path ? abs_path : uniq_path);
// create the importer struct
Include include(importer, path_key);
// attach information to AST node
imp->incs().push_back(include);
// register the resource buffers
register_resource(include, { source, srcmap }, pstate);
}
// only a path was retuned
// try to load it like normal
else if(abs_path) {
// checks some urls to preserve
// `http://`, `https://` and `//`
// or dispatchs to `import_file`
// which will check for a `.css` extension
// or resolves the file on the filesystem
// added and resolved via `add_file`
// finally stores everything on `imp`
import_url(imp, abs_path, ctx_path);
}
// move to next
++it_includes;
}
// deallocate the returned memory
sass_delete_import_list(includes);
// set success flag
has_import = true;
// break out of loop
if (only_one) break;
}
}
// return result
return has_import;
}
void register_function(Context&, Signature sig, Native_Function f, Env* env);
void register_function(Context&, Signature sig, Native_Function f, size_t arity, Env* env);
void register_overload_stub(Context&, sass::string name, Env* env);
void register_built_in_functions(Context&, Env* env);
void register_c_functions(Context&, Env* env, Sass_Function_List);
void register_c_function(Context&, Env* env, Sass_Function_Entry);
char* Context::render(Block_Obj root)
{
// check for valid block
if (!root) return 0;
// start the render process
root->perform(&emitter);
// finish emitter stream
emitter.finalize();
// get the resulting buffer from stream
OutputBuffer emitted = emitter.get_buffer();
// should we append a source map url?
if (!c_options.omit_source_map_url) {
// generate an embedded source map
if (c_options.source_map_embed) {
emitted.buffer += linefeed;
emitted.buffer += format_embedded_source_map();
}
// or just link the generated one
else if (source_map_file != "") {
emitted.buffer += linefeed;
emitted.buffer += format_source_mapping_url(source_map_file);
}
}
// create a copy of the resulting buffer string
// this must be freed or taken over by implementor
return sass_copy_c_string(emitted.buffer.c_str());
}
void Context::apply_custom_headers(Block_Obj root, const char* ctx_path, SourceSpan pstate)
{
// create a custom import to resolve headers
Import_Obj imp = SASS_MEMORY_NEW(Import, pstate);
// dispatch headers which will add custom functions
// custom headers are added to the import instance
call_headers(entry_path, ctx_path, pstate, imp);
// increase head count to skip later
head_imports += resources.size() - 1;
// add the statement if we have urls
if (!imp->urls().empty()) root->append(imp);
// process all other resources (add Import_Stub nodes)
for (size_t i = 0, S = imp->incs().size(); i < S; ++i) {
root->append(SASS_MEMORY_NEW(Import_Stub, pstate, imp->incs()[i]));
}
}
Block_Obj File_Context::parse()
{
// check if entry file is given
if (input_path.empty()) return {};
// create absolute path from input filename
// ToDo: this should be resolved via custom importers
sass::string abs_path(rel2abs(input_path, CWD));
// try to load the entry file
char* contents = read_file(abs_path);
// alternatively also look inside each include path folder
// I think this differs from ruby sass (IMO too late to remove)
for (size_t i = 0, S = include_paths.size(); contents == 0 && i < S; ++i) {
// build absolute path for this include path entry
abs_path = rel2abs(input_path, include_paths[i]);
// try to load the resulting path
contents = read_file(abs_path);
}
// abort early if no content could be loaded (various reasons)
if (!contents) throw std::runtime_error("File to read not found or unreadable: " + input_path);
// store entry path
entry_path = abs_path;
// create entry only for import stack
Sass_Import_Entry import = sass_make_import(
input_path.c_str(),
entry_path.c_str(),
contents,
0
);
// add the entry to the stack
import_stack.push_back(import);
// create the source entry for file entry
register_resource({{ input_path, "." }, abs_path }, { contents, 0 });
// create root ast tree node
return compile();
}
Block_Obj Data_Context::parse()
{
// check if source string is given
if (!source_c_str) return {};
// convert indented sass syntax
if(c_options.is_indented_syntax_src) {
// call sass2scss to convert the string
char * converted = sass2scss(source_c_str,
// preserve the structure as much as possible
SASS2SCSS_PRETTIFY_1 | SASS2SCSS_KEEP_COMMENT);
// replace old source_c_str with converted
free(source_c_str); source_c_str = converted;
}
// remember entry path (defaults to stdin for string)
entry_path = input_path.empty() ? "stdin" : input_path;
// ToDo: this may be resolved via custom importers
sass::string abs_path(rel2abs(entry_path));
char* abs_path_c_str = sass_copy_c_string(abs_path.c_str());
strings.push_back(abs_path_c_str);
// create entry only for the import stack
Sass_Import_Entry import = sass_make_import(
entry_path.c_str(),
abs_path_c_str,
source_c_str,
srcmap_c_str
);
// add the entry to the stack
import_stack.push_back(import);
// register a synthetic resource (path does not really exist, skip in includes)
register_resource({{ input_path, "." }, input_path }, { source_c_str, srcmap_c_str });
// create root ast tree node
return compile();
}
// parse root block from includes
Block_Obj Context::compile()
{
// abort if there is no data
if (resources.size() == 0) return {};
// get root block from the first style sheet
Block_Obj root = sheets.at(entry_path).root;
// abort on invalid root
if (root.isNull()) return {};
Env global; // create root environment
// register built-in functions on env
register_built_in_functions(*this, &global);
// register custom functions (defined via C-API)
for (size_t i = 0, S = c_functions.size(); i < S; ++i)
{ register_c_function(*this, &global, c_functions[i]); }
// create initial backtrace entry
// create crtp visitor objects
Expand expand(*this, &global);
Cssize cssize(*this);
CheckNesting check_nesting;
// check nesting in all files
for (auto sheet : sheets) {
auto styles = sheet.second;
check_nesting(styles.root);
}
// expand and eval the tree
root = expand(root);
Extension unsatisfied;
// check that all extends were used
if (extender.checkForUnsatisfiedExtends(unsatisfied)) {
throw Exception::UnsatisfiedExtend(traces, unsatisfied);
}
// check nesting
check_nesting(root);
// merge and bubble certain rules
root = cssize(root);
// clean up by removing empty placeholders
// ToDo: maybe we can do this somewhere else?
Remove_Placeholders remove_placeholders;
root->perform(&remove_placeholders);
// return processed tree
return root;
}
// EO compile
sass::string Context::format_embedded_source_map()
{
sass::string map = emitter.render_srcmap(*this);
std::istringstream is( map );
std::ostringstream buffer;
base64::encoder E;
E.encode(is, buffer);
sass::string url = "data:application/json;base64," + buffer.str();
url.erase(url.size() - 1);
return "/*# sourceMappingURL=" + url + " */";
}
sass::string Context::format_source_mapping_url(const sass::string& file)
{
sass::string url = abs2rel(file, output_path, CWD);
return "/*# sourceMappingURL=" + url + " */";
}
char* Context::render_srcmap()
{
if (source_map_file == "") return 0;
sass::string map = emitter.render_srcmap(*this);
return sass_copy_c_string(map.c_str());
}
// for data context we want to start after "stdin"
// we probably always want to skip the header includes?
sass::vector<sass::string> Context::get_included_files(bool skip, size_t headers)
{
// create a copy of the vector for manipulations
sass::vector<sass::string> includes = included_files;
if (includes.size() == 0) return includes;
if (skip) { includes.erase( includes.begin(), includes.begin() + 1 + headers); }
else { includes.erase( includes.begin() + 1, includes.begin() + 1 + headers); }
includes.erase( std::unique( includes.begin(), includes.end() ), includes.end() );
std::sort( includes.begin() + (skip ? 0 : 1), includes.end() );
return includes;
}
void register_function(Context& ctx, Signature sig, Native_Function f, Env* env)
{
Definition* def = make_native_function(sig, f, ctx);
def->environment(env);
(*env)[def->name() + "[f]"] = def;
}
void register_function(Context& ctx, Signature sig, Native_Function f, size_t arity, Env* env)
{
Definition* def = make_native_function(sig, f, ctx);
sass::sstream ss;
ss << def->name() << "[f]" << arity;
def->environment(env);
(*env)[ss.str()] = def;
}
void register_overload_stub(Context& ctx, sass::string name, Env* env)
{
Definition* stub = SASS_MEMORY_NEW(Definition,
SourceSpan("[built-in function]"),
0,
name,
{},
0,
true);
(*env)[name + "[f]"] = stub;
}
void register_built_in_functions(Context& ctx, Env* env)
{
using namespace Functions;
// RGB Functions
register_function(ctx, rgb_sig, rgb, env);
register_overload_stub(ctx, "rgba", env);
register_function(ctx, rgba_4_sig, rgba_4, 4, env);
register_function(ctx, rgba_2_sig, rgba_2, 2, env);
register_function(ctx, red_sig, red, env);
register_function(ctx, green_sig, green, env);
register_function(ctx, blue_sig, blue, env);
register_function(ctx, mix_sig, mix, env);
// HSL Functions
register_function(ctx, hsl_sig, hsl, env);
register_function(ctx, hsla_sig, hsla, env);
register_function(ctx, hue_sig, hue, env);
register_function(ctx, saturation_sig, saturation, env);
register_function(ctx, lightness_sig, lightness, env);
register_function(ctx, adjust_hue_sig, adjust_hue, env);
register_function(ctx, lighten_sig, lighten, env);
register_function(ctx, darken_sig, darken, env);
register_function(ctx, saturate_sig, saturate, env);
register_function(ctx, desaturate_sig, desaturate, env);
register_function(ctx, grayscale_sig, grayscale, env);
register_function(ctx, complement_sig, complement, env);
register_function(ctx, invert_sig, invert, env);
// Opacity Functions
register_function(ctx, alpha_sig, alpha, env);
register_function(ctx, opacity_sig, alpha, env);
register_function(ctx, opacify_sig, opacify, env);
register_function(ctx, fade_in_sig, opacify, env);
register_function(ctx, transparentize_sig, transparentize, env);
register_function(ctx, fade_out_sig, transparentize, env);
// Other Color Functions
register_function(ctx, adjust_color_sig, adjust_color, env);
register_function(ctx, scale_color_sig, scale_color, env);
register_function(ctx, change_color_sig, change_color, env);
register_function(ctx, ie_hex_str_sig, ie_hex_str, env);
// String Functions
register_function(ctx, unquote_sig, sass_unquote, env);
register_function(ctx, quote_sig, sass_quote, env);
register_function(ctx, str_length_sig, str_length, env);
register_function(ctx, str_insert_sig, str_insert, env);
register_function(ctx, str_index_sig, str_index, env);
register_function(ctx, str_slice_sig, str_slice, env);
register_function(ctx, to_upper_case_sig, to_upper_case, env);
register_function(ctx, to_lower_case_sig, to_lower_case, env);
// Number Functions
register_function(ctx, percentage_sig, percentage, env);
register_function(ctx, round_sig, round, env);
register_function(ctx, ceil_sig, ceil, env);
register_function(ctx, floor_sig, floor, env);
register_function(ctx, abs_sig, abs, env);
register_function(ctx, min_sig, min, env);
register_function(ctx, max_sig, max, env);
register_function(ctx, random_sig, random, env);
// List Functions
register_function(ctx, length_sig, length, env);
register_function(ctx, nth_sig, nth, env);
register_function(ctx, set_nth_sig, set_nth, env);
register_function(ctx, index_sig, index, env);
register_function(ctx, join_sig, join, env);
register_function(ctx, append_sig, append, env);
register_function(ctx, zip_sig, zip, env);
register_function(ctx, list_separator_sig, list_separator, env);
register_function(ctx, is_bracketed_sig, is_bracketed, env);
// Map Functions
register_function(ctx, map_get_sig, map_get, env);
register_function(ctx, map_merge_sig, map_merge, env);
register_function(ctx, map_remove_sig, map_remove, env);
register_function(ctx, map_keys_sig, map_keys, env);
register_function(ctx, map_values_sig, map_values, env);
register_function(ctx, map_has_key_sig, map_has_key, env);
register_function(ctx, keywords_sig, keywords, env);
// Introspection Functions
register_function(ctx, type_of_sig, type_of, env);
register_function(ctx, unit_sig, unit, env);
register_function(ctx, unitless_sig, unitless, env);
register_function(ctx, comparable_sig, comparable, env);
register_function(ctx, variable_exists_sig, variable_exists, env);
register_function(ctx, global_variable_exists_sig, global_variable_exists, env);
register_function(ctx, function_exists_sig, function_exists, env);
register_function(ctx, mixin_exists_sig, mixin_exists, env);
register_function(ctx, feature_exists_sig, feature_exists, env);
register_function(ctx, call_sig, call, env);
register_function(ctx, content_exists_sig, content_exists, env);
register_function(ctx, get_function_sig, get_function, env);
// Boolean Functions
register_function(ctx, not_sig, sass_not, env);
register_function(ctx, if_sig, sass_if, env);
// Misc Functions
register_function(ctx, inspect_sig, inspect, env);
register_function(ctx, unique_id_sig, unique_id, env);
// Selector functions
register_function(ctx, selector_nest_sig, selector_nest, env);
register_function(ctx, selector_append_sig, selector_append, env);
register_function(ctx, selector_extend_sig, selector_extend, env);
register_function(ctx, selector_replace_sig, selector_replace, env);
register_function(ctx, selector_unify_sig, selector_unify, env);
register_function(ctx, is_superselector_sig, is_superselector, env);
register_function(ctx, simple_selectors_sig, simple_selectors, env);
register_function(ctx, selector_parse_sig, selector_parse, env);
}
void register_c_functions(Context& ctx, Env* env, Sass_Function_List descrs)
{
while (descrs && *descrs) {
register_c_function(ctx, env, *descrs);
++descrs;
}
}
void register_c_function(Context& ctx, Env* env, Sass_Function_Entry descr)
{
Definition* def = make_c_function(descr, ctx);
def->environment(env);
(*env)[def->name() + "[f]"] = def;
}
}
| 37.774681 | 173 | 0.661727 | winsider |
8152dc0356a4de52efab6d2494348c83e5e59bde | 306 | hpp | C++ | test/game/sudoku_test.hpp | edwinkepler/sudoku | d227f5ce49dfb2467ec693693a9ec6db648dff8a | [
"MIT"
] | null | null | null | test/game/sudoku_test.hpp | edwinkepler/sudoku | d227f5ce49dfb2467ec693693a9ec6db648dff8a | [
"MIT"
] | null | null | null | test/game/sudoku_test.hpp | edwinkepler/sudoku | d227f5ce49dfb2467ec693693a9ec6db648dff8a | [
"MIT"
] | null | null | null | /*
* @copyright 2017 Edwin Kepler
* @license MIT
*/
#ifndef SUDOKU_TEST_HPP
#define SUDOKU_TEST_HPP
#include "game/sudoku.hpp"
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
using namespace std;
BOOST_AUTO_TEST_CASE(test)
{
BOOST_REQUIRE_EQUAL(1, 1);
}
#endif // SUDOKU_TEST_HPP
| 13.304348 | 35 | 0.74183 | edwinkepler |
81576d063e89e2bd2fbb87c1659fb599a2cb7e7b | 1,679 | hpp | C++ | a3/map_metadata_f/Tanoa/ferry01.hpp | tom4897/a3_map_metadata_f | bcb23baa3b1111629077e2d6b56faa5cd9ccd741 | [
"AAL"
] | null | null | null | a3/map_metadata_f/Tanoa/ferry01.hpp | tom4897/a3_map_metadata_f | bcb23baa3b1111629077e2d6b56faa5cd9ccd741 | [
"AAL"
] | null | null | null | a3/map_metadata_f/Tanoa/ferry01.hpp | tom4897/a3_map_metadata_f | bcb23baa3b1111629077e2d6b56faa5cd9ccd741 | [
"AAL"
] | null | null | null | /* [2017,10,10,13,52] */
/* CfgWorlds >> Tanoa >> Names >> ferry01 */
areaPosition[]={4609.91, 5239.02}; // Position x, y
areaRadiusA=105.64; // radius A of the location
areaRadiusB=110.88; // radius B of the location
areaAngle=21.54; // Rotation of the location
demography=CIV; // Demography
accessPoints[] = // Types: 0 - generic; 1 - on road; 2 - water; 3 - in forest
// [Type, [posX, posY], [radiusA, radiusB, angle]]
{
{LOCATION_AREA_ACCESSPOINT_ROAD, {3992.65, 5737.03}, 131.5},
{LOCATION_AREA_ACCESSPOINT_WATER, {4516.45, 4792.14}, 2.61},
{LOCATION_AREA_ACCESSPOINT, {4631.64, 4911.26}, 353.75},
{LOCATION_AREA_ACCESSPOINT_FOREST, {4877.27, 5293.49}, 260.38},
{LOCATION_AREA_ACCESSPOINT_WATER, {4863.08, 5493.37}, 235.14},
{LOCATION_AREA_ACCESSPOINT, {4906.77, 5210.8}, 276},
{LOCATION_AREA_ACCESSPOINT_ROAD, {5146.92, 4931.67}, 295.36}
};
landmarks[] =
{
};
class Areas
{
vehicles[] = // Types: 0 - truck or cars; 1 - Cars only; 2 - trucks only; 20 - air; 21 - planes; 22 - helicopters
// [Type, [posX, posY], [radiusA, radiusB, angle]]
{
{LOCATION_AREA_VEHICLE_CAR, {4570.34, 5208.53}, {1.5, 2.5, 214.52}},
{LOCATION_AREA_VEHICLE_TRUCK, {4582.31, 5220.13}, {1.8, 3.5, 212.43}},
{LOCATION_AREA_VEHICLE_CAR, {4604.46, 5202.68}, {1.5, 2.5, 117.7}},
{LOCATION_AREA_VEHICLE_GROUND, {4600.24, 5231.54}, {1.8, 3.5, 123.35}},
{LOCATION_AREA_VEHICLE_TRUCK, {4600.18, 5282.62}, {1.8, 3.5, 300.94}},
{LOCATION_AREA_VEHICLE_CAR, {4618.15, 5280.44}, {1.5, 2.5, 254.21}}
};
flat[] = // Types
// [Type, [posX, posY], [radiusA, radiusB, angle, maxHeight]]
{
{LOCATION_AREA_FLATSTORAGE, {4604.9, 5298.09}, {8.68055, 4.23243, 105.84, 5}}
};
};
| 36.5 | 114 | 0.656343 | tom4897 |
8159941cbc55bd7630e79388944dee599eb34ae5 | 2,867 | cpp | C++ | bindings/python/src/LibraryMathematicsPy/Geometry/3D/Objects/Segment.cpp | cowlicks/library-mathematics | f1ff3257bb2da5371a9eacfcec538b2c00871696 | [
"Apache-2.0"
] | null | null | null | bindings/python/src/LibraryMathematicsPy/Geometry/3D/Objects/Segment.cpp | cowlicks/library-mathematics | f1ff3257bb2da5371a9eacfcec538b2c00871696 | [
"Apache-2.0"
] | null | null | null | bindings/python/src/LibraryMathematicsPy/Geometry/3D/Objects/Segment.cpp | cowlicks/library-mathematics | f1ff3257bb2da5371a9eacfcec538b2c00871696 | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @project Library/Mathematics
/// @file LibraryMathematicsPy/Geometry/3D/Objects/Segment.cpp
/// @author Lucas Brémond <lucas@loftorbital.com>
/// @license Apache License 2.0
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <Library/Mathematics/Geometry/3D/Objects/Segment.hpp>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
inline void LibraryMathematicsPy_Geometry_3D_Objects_Segment ( )
{
using namespace boost::python ;
using library::math::geom::d3::Object ;
using library::math::geom::d3::objects::Point ;
using library::math::geom::d3::objects::Segment ;
using library::math::geom::d3::objects::Plane ;
using library::math::geom::d3::objects::Sphere ;
using library::math::geom::d3::objects::Ellipsoid ;
using library::math::geom::d3::Intersection ;
scope in_Segment = class_<Segment, bases<Object>>("Segment", init<const Point&, const Point&>())
.def(self == self)
.def(self != self)
.def(self_ns::str(self_ns::self))
.def(self_ns::repr(self_ns::self))
.def("isDefined", &Segment::isDefined)
.def("isDegenerate", &Segment::isDegenerate)
.def("intersectsPlane", +[] (const Segment& aSegment, const Plane& aPlane) -> bool { return aSegment.intersects(aPlane) ; })
.def("intersectsSphere", +[] (const Segment& aSegment, const Sphere& aSphere) -> bool { return aSegment.intersects(aSphere) ; })
.def("intersectsEllipsoid", +[] (const Segment& aSegment, const Ellipsoid& anEllipsoid) -> bool { return aSegment.intersects(anEllipsoid) ; })
.def("containsPoint", +[] (const Segment& aSegment, const Point& aPoint) -> bool { return aSegment.contains(aPoint) ; })
.def("getFirstPoint", &Segment::getFirstPoint)
.def("getSecondPoint", &Segment::getSecondPoint)
.def("getCenter", &Segment::getCenter)
.def("getDirection", &Segment::getDirection)
.def("getLength", &Segment::getLength)
.def("intersectionWithPlane", +[] (const Segment& aSegment, const Plane& aPlane) -> Intersection { return aSegment.intersectionWith(aPlane) ; })
.def("applyTransformation", &Segment::applyTransformation)
.def("Undefined", &Segment::Undefined).staticmethod("Undefined")
;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 50.298246 | 160 | 0.506104 | cowlicks |
815a08991af598df07f46ae0567d4d381bbe3fca | 5,165 | cpp | C++ | core/test/base/exception.cpp | prinz7/ginkgo | de51ee9a4fbec45d4af99c877a3a49ab94c8cdb5 | [
"BSD-3-Clause"
] | null | null | null | core/test/base/exception.cpp | prinz7/ginkgo | de51ee9a4fbec45d4af99c877a3a49ab94c8cdb5 | [
"BSD-3-Clause"
] | null | null | null | core/test/base/exception.cpp | prinz7/ginkgo | de51ee9a4fbec45d4af99c877a3a49ab94c8cdb5 | [
"BSD-3-Clause"
] | null | null | null | /*******************************<GINKGO LICENSE>******************************
Copyright (c) 2017-2019, the Ginkgo authors
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.
******************************<GINKGO LICENSE>*******************************/
#include <ginkgo/core/base/exception.hpp>
#include <gtest/gtest.h>
namespace {
TEST(ExceptionClasses, ErrorReturnsCorrectWhatMessage)
{
gko::Error error("test_file.cpp", 1, "test error");
ASSERT_EQ(std::string("test_file.cpp:1: test error"), error.what());
}
TEST(ExceptionClasses, NotImplementedReturnsCorrectWhatMessage)
{
gko::NotImplemented error("test_file.cpp", 25, "test_func");
ASSERT_EQ(std::string("test_file.cpp:25: test_func is not implemented"),
error.what());
}
TEST(ExceptionClasses, NotCompiledReturnsCorrectWhatMessage)
{
gko::NotCompiled error("test_file.cpp", 345, "test_func", "nvidia");
ASSERT_EQ(std::string("test_file.cpp:345: feature test_func is part of the "
"nvidia module, which is not compiled on this "
"system"),
error.what());
}
TEST(ExceptionClasses, NotSupportedReturnsCorrectWhatMessage)
{
gko::NotSupported error("test_file.cpp", 123, "test_func", "test_obj");
ASSERT_EQ(
std::string("test_file.cpp:123: Operation test_func does not support "
"parameters of type test_obj"),
error.what());
}
TEST(ExceptionClasses, CudaErrorReturnsCorrectWhatMessage)
{
gko::CudaError error("test_file.cpp", 123, "test_func", 1);
std::string expected = "test_file.cpp:123: test_func: ";
ASSERT_EQ(expected, std::string(error.what()).substr(0, expected.size()));
}
TEST(ExceptionClasses, CublasErrorReturnsCorrectWhatMessage)
{
gko::CublasError error("test_file.cpp", 123, "test_func", 1);
std::string expected = "test_file.cpp:123: test_func: ";
ASSERT_EQ(expected, std::string(error.what()).substr(0, expected.size()));
}
TEST(ExceptionClasses, CusparseErrorReturnsCorrectWhatMessage)
{
gko::CusparseError error("test_file.cpp", 123, "test_func", 1);
std::string expected = "test_file.cpp:123: test_func: ";
ASSERT_EQ(expected, std::string(error.what()).substr(0, expected.size()));
}
TEST(ExceptionClasses, DimensionMismatchReturnsCorrectWhatMessage)
{
gko::DimensionMismatch error("test_file.cpp", 243, "test_func", "a", 3, 4,
"b", 2, 5, "my_clarify");
ASSERT_EQ(std::string("test_file.cpp:243: test_func: attempting to combine "
"operators a [3 x 4] and b [2 x 5]: my_clarify"),
error.what());
}
TEST(ExceptionClasses, AllocationErrorReturnsCorrectWhatMessage)
{
gko::AllocationError error("test_file.cpp", 42, "OMP", 135);
ASSERT_EQ(
std::string("test_file.cpp:42: OMP: failed to allocate memory block "
"of 135B"),
error.what());
}
TEST(ExceptionClasses, OutOfBoundsErrorReturnsCorrectWhatMessage)
{
gko::OutOfBoundsError error("test_file.cpp", 42, 11, 10);
ASSERT_EQ(std::string("test_file.cpp:42: trying to access index 11 in a "
"memory block of 10 elements"),
error.what());
}
TEST(ExceptionClasses, StreamErrorReturnsCorrectWhatMessage)
{
gko::StreamError error("test_file.cpp", 75, "my_func", "my message");
ASSERT_EQ(std::string("test_file.cpp:75: my_func: my message"),
error.what());
}
TEST(ExceptionClasses, KernelNotFoundReturnsCorrectWhatMessage)
{
gko::KernelNotFound error("test_file.cpp", 75, "my_func");
ASSERT_EQ(
std::string(
"test_file.cpp:75: my_func: unable to find an eligible kernel"),
error.what());
}
} // namespace
| 34.66443 | 80 | 0.690416 | prinz7 |
815b14b485089a156761b4770017dfe945773353 | 1,766 | hpp | C++ | src/parser.hpp | Grypesl/ccloxx | 44d1414152ef0c5418247e8f9819c74e68393979 | [
"MIT"
] | 5 | 2020-04-08T08:58:22.000Z | 2020-09-02T07:49:03.000Z | src/parser.hpp | Gryphnl/ccloxx | 44d1414152ef0c5418247e8f9819c74e68393979 | [
"MIT"
] | null | null | null | src/parser.hpp | Gryphnl/ccloxx | 44d1414152ef0c5418247e8f9819c74e68393979 | [
"MIT"
] | null | null | null | #ifndef PARSER_HPP
#define PARSER_HPP
#include <vector>
#include "scanner.hpp"
#include "ast.hpp"
namespace lox
{
using ExprPtr = std::shared_ptr<Expr>;
using StmtPtr = std::shared_ptr<Stmt>;
using ExprList = std::vector<ExprPtr>;
using StmtList = std::vector<StmtPtr>;
class Parser
{
private:
TokenList tokens;
StmtList statements;
size_t current = 0;
public:
Parser(TokenList &&tokens_, ErrorHandler &error_) : tokens(tokens_), errorhandler(error_) {}
StmtList parse();
private:
template <typename... TokenT>
bool match(TokenT... types);
ErrorHandler &errorhandler;
StmtPtr declaration();
StmtPtr function(const std::string &type);
StmtPtr varDecl();
StmtPtr statement();
StmtPtr ifStatement();
StmtPtr forStatement();
StmtPtr whileStatement();
StmtPtr printStatement();
StmtPtr returnStatement();
StmtList blocks();
StmtPtr expressionStatement();
ExprPtr assignment();
ExprPtr logicOr();
ExprPtr logicAnd();
ExprPtr equality();
ExprPtr comparison();
ExprPtr addition();
ExprPtr multiplication();
ExprPtr unary();
ExprPtr call();
ExprPtr finishCall(ExprPtr callee);
ExprPtr primary();
bool check(TokenType type);
Token *advance();
bool isAtEnd();
Token *peek();
Token *previous();
TokenPtr releasePrevious();
ExprPtr expression()
{
return assignment();
}
TokenPtr consume(TokenType type_, const std::string &error_message);
};
} // namespace lox
#endif | 17.66 | 100 | 0.583239 | Grypesl |
815ba3b2bec22c716492e7752abe98c543a0043b | 839 | cpp | C++ | kernel/lib/rand.cpp | panix-os/Panix | 1047fc384696684a7583bda035fa580da4adbd5b | [
"MIT"
] | 68 | 2020-10-10T03:56:04.000Z | 2021-07-22T19:15:47.000Z | kernel/lib/rand.cpp | panix-os/Panix | 1047fc384696684a7583bda035fa580da4adbd5b | [
"MIT"
] | 88 | 2020-10-01T23:36:44.000Z | 2021-07-22T03:11:43.000Z | kernel/lib/rand.cpp | panix-os/Panix | 1047fc384696684a7583bda035fa580da4adbd5b | [
"MIT"
] | 5 | 2021-06-25T16:56:46.000Z | 2021-07-21T02:38:41.000Z | /**
* @file rand.cpp
* @author Brian Kernighan, Dennis Ritchie (C Standard Authors)
* Michel (JMallone) Gomes (michels@utfpr.edu.br)
* @brief Portable implementation of rand and srand as according to the
* C standard implementation by K&R.
* @version 0.1
* @date 2021-07-20
*
* @copyright C Programming Language copyright Brian Kernighan, Dennis Ritchie
* Implementation Copyright the Xyris Contributors (c) 2021.
*
* References:
* https://wiki.osdev.org/Random_Number_Generator#The_Standard.27s_Example
* https://pubs.opengroup.org/onlinepubs/9699919799/functions/rand.html
*
*/
#include <lib/rand.hpp>
unsigned long _seedrand = 1;
int rand(void)
{
_seedrand = _seedrand * 214013L + 2531011L;
return (unsigned int)(_seedrand >> 16) & MAX_RAND;
}
void srand(unsigned int seed)
{
_seedrand = seed;
}
| 25.424242 | 78 | 0.716329 | panix-os |
815c6a2665777855d0e1224dde4bc22039fa7eb0 | 3,515 | cpp | C++ | Solution.cpp | allenbrubaker/guided-local-search | 22b882a3677d445393ecd2d33bf5b8f337db2c37 | [
"MIT"
] | 1 | 2017-07-25T19:12:12.000Z | 2017-07-25T19:12:12.000Z | Solution.cpp | allenbrubaker/guided-local-search | 22b882a3677d445393ecd2d33bf5b8f337db2c37 | [
"MIT"
] | null | null | null | Solution.cpp | allenbrubaker/guided-local-search | 22b882a3677d445393ecd2d33bf5b8f337db2c37 | [
"MIT"
] | 2 | 2019-07-28T02:46:25.000Z | 2020-08-05T02:38:53.000Z | #pragma once
#include "Instance.cpp"
#include "Global.cpp"
#include "Permutation.cpp"
class Solution : public Permutation
{
private:
double *Fitness;
int LastSwap[2];
public:
double *LastSwapCost;
const Instance& Problem;
Solution(const Instance& instance) : Permutation(instance.Size), Problem(instance), LastSwapCost(NULL), Fitness(NULL)
{
LastSwap[0] = -1; LastSwap[1] = -1;
}
Solution(const Solution& solution) : Permutation(solution.Problem.Size), Problem(solution.Problem), LastSwapCost(NULL), Fitness(NULL)
{
operator=(solution);
}
Solution& operator=(const Solution &solution)
{
assert(&solution.Problem == &Problem);
for (int i=0; i<Problem.Size; ++i)
Values[i] = solution.Values[i];
ClearFitness();
Fitness = solution.Fitness != NULL ? new double(*solution.Fitness) : NULL;
LastSwapCost = solution.LastSwapCost != NULL ? new double(*solution.LastSwapCost) : NULL;
LastSwap[0] = solution.LastSwap[0];
LastSwap[1] = solution.LastSwap[1];
return *this;
}
inline double GetDeviation()
{
return (GetFitness() - Problem.OptimalFitness)/Problem.OptimalFitness * 100;
}
inline double GetFitness()
{
if (Fitness != NULL)
return *Fitness;
double sum = 0;
for (int i=0; i<Problem.Size; ++i)
for (int j=0; j<Problem.Size; ++j)
sum += Problem.Distance[i][j] * Problem.Flow[Values[i]][Values[j]];
Fitness = new double(sum);
return sum;
}
inline void Swap(int i, int j, double* swapCost)
{
if (i==j) return;
Permutation::Swap(i,j);
LastSwap[0] = i;
LastSwap[1] = j;
if (swapCost != NULL)
{
delete LastSwapCost;
LastSwapCost = new double(*swapCost);
if (Fitness != NULL)
*Fitness += *swapCost;
}
else
ClearFitness();
}
inline int Size() { return Problem.Size; }
inline int& operator[](int index) { return Values[index]; }
inline void SwapCostMatrix(double** matrix)
{
for (int i=0; i<Size(); ++i)
for (int j=i; j<Size(); ++j) // set j=i to zero out the diagonal.
matrix[j][i] = matrix[i][j] = SwapCost(i,j);
}
inline void UpdateSwapCostMatrix(double** matrix)
{
for (int i=0; i<Size(); ++i)
for (int j=i+1; j<Size(); ++j)
matrix[j][i] = matrix[i][j] = FastSwapCost(matrix[i][j], i, j);
}
inline double FastSwapCost(double lastSwapCostUV, int u, int v)
{
int r = LastSwap[0], s = LastSwap[1];
if (r != u && r != v && s != u && s != v) // Condition: {r,s} intersect {u,v} == NULL
{
double **a = Problem.Distance, **b = Problem.Flow;
int pu = Values[u], pv = Values[v], pr = Values[r], ps = Values[s];
return lastSwapCostUV + (a[r][u]-a[r][v]+a[s][v]-a[s][u]) * (b[ps][pu]-b[ps][pv]+b[pr][pv]-b[pr][pu])
+ (a[u][r]-a[v][r]+a[v][s]-a[u][s]) * (b[pu][ps]-b[pv][ps]+b[pv][pr]-b[pu][pr]);
}
return SwapCost(u,v);
}
inline double SwapCost(int r, int s)
{
if (r == s) return 0;
double **a = Problem.Distance, **b = Problem.Flow;
int pr = Values[r], ps = Values[s];
double sum = a[r][r]*(b[ps][ps]-b[pr][pr]) + a[r][s]*(b[ps][pr]-b[pr][ps]) +
a[s][r]*(b[pr][ps]-b[ps][pr]) + a[s][s]*(b[pr][pr]-b[ps][ps]);
for (int k=0; k<Problem.Size; ++k)
{
if (k == r || k == s) continue;
int pk = Values[k];
sum += a[k][r]*(b[pk][ps]-b[pk][pr]) + a[k][s]*(b[pk][pr]-b[pk][ps]) +
a[r][k]*(b[ps][pk]-b[pr][pk]) + a[s][k]*(b[pr][pk]-b[ps][pk]);
}
return sum;
}
inline void ClearFitness()
{
delete LastSwapCost;
LastSwapCost = NULL;
delete Fitness;
Fitness = NULL;
}
~Solution()
{
ClearFitness();
}
};
| 26.832061 | 134 | 0.599147 | allenbrubaker |
815d3004c3670acaeedb4c7ba93a4bebaf0cdc7d | 2,860 | cpp | C++ | src/Graphical/GUI/MainMenu.cpp | Khsime-Marwane/indie_studio | 75a84dd70f33a655a4f15ea7a9a3b8845bd39dfc | [
"MIT"
] | null | null | null | src/Graphical/GUI/MainMenu.cpp | Khsime-Marwane/indie_studio | 75a84dd70f33a655a4f15ea7a9a3b8845bd39dfc | [
"MIT"
] | null | null | null | src/Graphical/GUI/MainMenu.cpp | Khsime-Marwane/indie_studio | 75a84dd70f33a655a4f15ea7a9a3b8845bd39dfc | [
"MIT"
] | null | null | null | #include "Common/GUI.hpp"
std::vector<std::unique_ptr<indie::IComponent>> indie::GUI::loadMenu() {
std::vector<std::unique_ptr<indie::IComponent>> res;
_posBackground = 0;
///Load menu components
res.push_back(createComponent(SpriteId::MAIN_MENU_GUI, 0.0f, 0.0f, 1.0f, 1.0f, indie::Color::White, indie::Color::White));
res.push_back(createComponent(SpriteId::ARROW, 0.31f, 0.35f, 0.36f, 0.417f, indie::Color::White, indie::Color::White));
///Load Menu Events
if (!_compActions.empty())
_compActions.clear();
_compActions[indie::KeyboardKey::KB_ARROW_DOWN] = [this](){mainMenuKeyDown();};
_compActions[indie::KeyboardKey::KB_ARROW_UP] = [this](){mainMenuKeyUp();};
_compActions[indie::KeyboardKey::KB_ARROW_RIGHT] = [this](){mainMenuKeyAccess();};
_compActions[indie::KeyboardKey::KB_ENTER] = [this](){mainMenuKeyAccess();};
return (res);
}
void indie::GUI::mainMenuKeyDown() {
switch (_posBackground)
{
case 0: _components.at(1)->setPos(0.29f, 0.435f, 0.34f, 0.505f);
break;
case 1: _components.at(1)->setPos(0.27f, 0.515f, 0.32f, 0.58f);
break;
case 2: _components.at(1)->setPos(0.31f, 0.6f, 0.36f, 0.67f);
break;
default:
break;
}
if (_posBackground + 1 < 4)
++_posBackground;
}
void indie::GUI::mainMenuKeyUp() {
switch (_posBackground)
{
case 1: _components.at(1)->setPos(0.31f, 0.35f, 0.36f, 0.417f);
break;
case 2: _components.at(1)->setPos(0.29f, 0.435f, 0.34f, 0.505f);
break;
case 3: _components.at(1)->setPos(0.27f, 0.515f, 0.32f, 0.58f);
break;
default:
break;
}
if (_posBackground > 0)
--_posBackground;
}
void indie::GUI::mainMenuKeyAccess(){
switch (_posBackground)
{
case 0: {
_sounds.push_back(indie::Sound(indie::SoundId::SOUND_TURN_PAGE));
loadComponents((_gameState = indie::GameState::ROOM));
_indexPaths = 2;
_rev = false;
_hasTransition = true;
break;
}
case 1: {
_sounds.push_back(indie::Sound(indie::SoundId::SOUND_TURN_PAGE));
loadComponents((_gameState = indie::GameState::SETTINGS));
_indexPaths = 1;
_rev = false;
_hasTransition = true;
break;
}
case 2: {
_sounds.push_back(indie::Sound(indie::SoundId::SOUND_TURN_PAGE));
loadComponents((_gameState = indie::GameState::SCOREBOARD));
_indexPaths = 0;
_rev = false;
_hasTransition = true;
break;
}
case 3: loadComponents((_gameState = indie::GameState::QUIT));
break;
default:
break;
}
}
| 30.105263 | 126 | 0.570979 | Khsime-Marwane |
815f3a045551cf11a4f03fb6ef7c677b75e82324 | 5,432 | cpp | C++ | deps/lld/ELF/Target.cpp | coypoop/zig | f57182456d52615ece1133db9c33ef57e3ae187b | [
"MIT"
] | 3 | 2019-12-24T08:57:11.000Z | 2020-12-01T06:51:10.000Z | deps/lld/ELF/Target.cpp | coypoop/zig | f57182456d52615ece1133db9c33ef57e3ae187b | [
"MIT"
] | 1 | 2020-10-30T18:22:23.000Z | 2020-10-30T21:50:34.000Z | deps/lld/ELF/Target.cpp | coypoop/zig | f57182456d52615ece1133db9c33ef57e3ae187b | [
"MIT"
] | 1 | 2019-05-13T17:35:42.000Z | 2019-05-13T17:35:42.000Z | //===- Target.cpp ---------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Machine-specific things, such as applying relocations, creation of
// GOT or PLT entries, etc., are handled in this file.
//
// Refer the ELF spec for the single letter variables, S, A or P, used
// in this file.
//
// Some functions defined in this file has "relaxTls" as part of their names.
// They do peephole optimization for TLS variables by rewriting instructions.
// They are not part of the ABI but optional optimization, so you can skip
// them if you are not interested in how TLS variables are optimized.
// See the following paper for the details.
//
// Ulrich Drepper, ELF Handling For Thread-Local Storage
// http://www.akkadia.org/drepper/tls.pdf
//
//===----------------------------------------------------------------------===//
#include "Target.h"
#include "InputFiles.h"
#include "OutputSections.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "lld/Common/ErrorHandler.h"
#include "llvm/Object/ELF.h"
using namespace llvm;
using namespace llvm::object;
using namespace llvm::ELF;
using namespace lld;
using namespace lld::elf;
TargetInfo *elf::Target;
std::string lld::toString(RelType Type) {
StringRef S = getELFRelocationTypeName(elf::Config->EMachine, Type);
if (S == "Unknown")
return ("Unknown (" + Twine(Type) + ")").str();
return S;
}
TargetInfo *elf::getTarget() {
switch (Config->EMachine) {
case EM_386:
case EM_IAMCU:
return getX86TargetInfo();
case EM_AARCH64:
return getAArch64TargetInfo();
case EM_AMDGPU:
return getAMDGPUTargetInfo();
case EM_ARM:
return getARMTargetInfo();
case EM_AVR:
return getAVRTargetInfo();
case EM_HEXAGON:
return getHexagonTargetInfo();
case EM_MIPS:
switch (Config->EKind) {
case ELF32LEKind:
return getMipsTargetInfo<ELF32LE>();
case ELF32BEKind:
return getMipsTargetInfo<ELF32BE>();
case ELF64LEKind:
return getMipsTargetInfo<ELF64LE>();
case ELF64BEKind:
return getMipsTargetInfo<ELF64BE>();
default:
fatal("unsupported MIPS target");
}
case EM_PPC:
return getPPCTargetInfo();
case EM_PPC64:
return getPPC64TargetInfo();
case EM_SPARCV9:
return getSPARCV9TargetInfo();
case EM_X86_64:
if (Config->EKind == ELF32LEKind)
return getX32TargetInfo();
return getX86_64TargetInfo();
}
fatal("unknown target machine");
}
template <class ELFT> static ErrorPlace getErrPlace(const uint8_t *Loc) {
for (InputSectionBase *D : InputSections) {
auto *IS = cast<InputSection>(D);
if (!IS->getParent())
continue;
uint8_t *ISLoc = IS->getParent()->Loc + IS->OutSecOff;
if (ISLoc <= Loc && Loc < ISLoc + IS->getSize())
return {IS, IS->template getLocation<ELFT>(Loc - ISLoc) + ": "};
}
return {};
}
ErrorPlace elf::getErrorPlace(const uint8_t *Loc) {
switch (Config->EKind) {
case ELF32LEKind:
return getErrPlace<ELF32LE>(Loc);
case ELF32BEKind:
return getErrPlace<ELF32BE>(Loc);
case ELF64LEKind:
return getErrPlace<ELF64LE>(Loc);
case ELF64BEKind:
return getErrPlace<ELF64BE>(Loc);
default:
llvm_unreachable("unknown ELF type");
}
}
TargetInfo::~TargetInfo() {}
int64_t TargetInfo::getImplicitAddend(const uint8_t *Buf, RelType Type) const {
return 0;
}
bool TargetInfo::usesOnlyLowPageBits(RelType Type) const { return false; }
bool TargetInfo::needsThunk(RelExpr Expr, RelType Type, const InputFile *File,
uint64_t BranchAddr, const Symbol &S) const {
return false;
}
bool TargetInfo::adjustPrologueForCrossSplitStack(uint8_t *Loc,
uint8_t *End) const {
llvm_unreachable("Target doesn't support split stacks.");
}
bool TargetInfo::inBranchRange(RelType Type, uint64_t Src, uint64_t Dst) const {
return true;
}
void TargetInfo::writeIgotPlt(uint8_t *Buf, const Symbol &S) const {
writeGotPlt(Buf, S);
}
RelExpr TargetInfo::adjustRelaxExpr(RelType Type, const uint8_t *Data,
RelExpr Expr) const {
return Expr;
}
void TargetInfo::relaxGot(uint8_t *Loc, uint64_t Val) const {
llvm_unreachable("Should not have claimed to be relaxable");
}
void TargetInfo::relaxTlsGdToLe(uint8_t *Loc, RelType Type,
uint64_t Val) const {
llvm_unreachable("Should not have claimed to be relaxable");
}
void TargetInfo::relaxTlsGdToIe(uint8_t *Loc, RelType Type,
uint64_t Val) const {
llvm_unreachable("Should not have claimed to be relaxable");
}
void TargetInfo::relaxTlsIeToLe(uint8_t *Loc, RelType Type,
uint64_t Val) const {
llvm_unreachable("Should not have claimed to be relaxable");
}
void TargetInfo::relaxTlsLdToLe(uint8_t *Loc, RelType Type,
uint64_t Val) const {
llvm_unreachable("Should not have claimed to be relaxable");
}
uint64_t TargetInfo::getImageBase() {
// Use -image-base if set. Fall back to the target default if not.
if (Config->ImageBase)
return *Config->ImageBase;
return Config->Pic ? 0 : DefaultImageBase;
}
| 29.846154 | 80 | 0.651141 | coypoop |
8162eb8581cb71494518fd0b34458ae2c5ded592 | 838 | cpp | C++ | c++/.leetcode/701.insert-into-a-binary-search-tree.cpp | ming197/MyLeetCode | eba575765976b12db07be0857faad85b9c60d723 | [
"Apache-2.0"
] | null | null | null | c++/.leetcode/701.insert-into-a-binary-search-tree.cpp | ming197/MyLeetCode | eba575765976b12db07be0857faad85b9c60d723 | [
"Apache-2.0"
] | null | null | null | c++/.leetcode/701.insert-into-a-binary-search-tree.cpp | ming197/MyLeetCode | eba575765976b12db07be0857faad85b9c60d723 | [
"Apache-2.0"
] | null | null | null | /*
* @lc app=leetcode id=701 lang=cpp
*
* [701] Insert into a Binary Search Tree
*/
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* insertIntoBST(TreeNode *node, int val) {
if (!node) {
TreeNode *newNode = new TreeNode(val);
return newNode;
}
if (val < node->val) {
node->left = insertIntoBST(node->left, val);
}
else {
node->right = insertIntoBST(node->right, val);
}
return node;
}
};
// @lc code=end
| 22.648649 | 94 | 0.571599 | ming197 |
8164f1def063371e5f58cffa2d827be8c84e2e52 | 256 | cpp | C++ | exemplos/4_Condicionais/impar.cpp | danielgs83/cpe-unb | f958d2a4899a8d4d5c1465637d1d1b10610661e4 | [
"CC0-1.0"
] | 1 | 2022-02-04T17:16:50.000Z | 2022-02-04T17:16:50.000Z | exemplos/4_Condicionais/impar.cpp | danielgs83/cpe-unb | f958d2a4899a8d4d5c1465637d1d1b10610661e4 | [
"CC0-1.0"
] | null | null | null | exemplos/4_Condicionais/impar.cpp | danielgs83/cpe-unb | f958d2a4899a8d4d5c1465637d1d1b10610661e4 | [
"CC0-1.0"
] | null | null | null | #include <iostream>
using namespace std;
int main(){
int a;
cin >> a;
if((a%2) == 0)
cout << "O valor e par.\n";
else
cout << "O valor e impar.\n";
return 0;
}
| 14.222222 | 51 | 0.371094 | danielgs83 |
816ed5161ff3760309159aecfa482e7d8d98d99a | 4,222 | cpp | C++ | samples/common/postprocess/postprocess_classification.cpp | HFauto/CNStream | 1d4847327fff83eedbc8de6911855c5f7bb2bf22 | [
"Apache-2.0"
] | 172 | 2019-08-24T10:05:14.000Z | 2022-03-29T07:45:18.000Z | samples/common/postprocess/postprocess_classification.cpp | HFauto/CNStream | 1d4847327fff83eedbc8de6911855c5f7bb2bf22 | [
"Apache-2.0"
] | 27 | 2019-09-01T11:04:45.000Z | 2022-01-17T09:27:07.000Z | samples/common/postprocess/postprocess_classification.cpp | HFauto/CNStream | 1d4847327fff83eedbc8de6911855c5f7bb2bf22 | [
"Apache-2.0"
] | 72 | 2019-08-24T10:13:06.000Z | 2022-03-28T08:26:05.000Z | /*************************************************************************
* Copyright (C) [2019] by Cambricon, Inc. All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 <memory>
#include <string>
#include <utility>
#include <vector>
#include "cnstream_frame_va.hpp"
#include "postproc.hpp"
#include "cnstream_logging.hpp"
class PostprocClassification : public cnstream::Postproc {
public:
int Execute(const std::vector<float*>& net_outputs, const std::shared_ptr<edk::ModelLoader>& model,
const cnstream::CNFrameInfoPtr& package) override;
DECLARE_REFLEX_OBJECT_EX(PostprocClassification, cnstream::Postproc)
}; // classd PostprocClassification
IMPLEMENT_REFLEX_OBJECT_EX(PostprocClassification, cnstream::Postproc)
int PostprocClassification::Execute(const std::vector<float*>& net_outputs,
const std::shared_ptr<edk::ModelLoader>& model,
const cnstream::CNFrameInfoPtr& package) {
if (net_outputs.size() != 1) {
LOGE(DEMO) << "[Warning] classification neuron network only has one output,"
" but get " +
std::to_string(net_outputs.size());
return -1;
}
auto data = net_outputs[0];
auto len = model->OutputShape(0).DataCount();
auto pscore = data;
float mscore = 0;
int label = 0;
for (decltype(len) i = 0; i < len; ++i) {
auto score = *(pscore + i);
if (score > mscore) {
mscore = score;
label = i;
}
}
auto obj = std::make_shared<cnstream::CNInferObject>();
obj->id = std::to_string(label);
obj->score = mscore;
cnstream::CNInferObjsPtr objs_holder = package->collection.Get<cnstream::CNInferObjsPtr>(cnstream::kCNInferObjsTag);
std::lock_guard<std::mutex> objs_mutex(objs_holder->mutex_);
objs_holder->objs_.push_back(obj);
return 0;
}
class ObjPostprocClassification : public cnstream::ObjPostproc {
public:
int Execute(const std::vector<float*>& net_outputs, const std::shared_ptr<edk::ModelLoader>& model,
const cnstream::CNFrameInfoPtr& finfo, const std::shared_ptr<cnstream::CNInferObject>& obj) override;
DECLARE_REFLEX_OBJECT_EX(ObjPostprocClassification, cnstream::ObjPostproc)
}; // classd ObjPostprocClassification
IMPLEMENT_REFLEX_OBJECT_EX(ObjPostprocClassification, cnstream::ObjPostproc)
int ObjPostprocClassification::Execute(const std::vector<float*>& net_outputs,
const std::shared_ptr<edk::ModelLoader>& model,
const cnstream::CNFrameInfoPtr& finfo,
const std::shared_ptr<cnstream::CNInferObject>& obj) {
if (net_outputs.size() != 1) {
LOGE(DEMO) << "[Warning] classification neuron network only has one output,"
" but get " + std::to_string(net_outputs.size());
return -1;
}
auto data = net_outputs[0];
auto len = model->OutputShape(0).DataCount();
auto pscore = data;
float mscore = 0;
int label = 0;
for (decltype(len) i = 0; i < len; ++i) {
auto score = *(pscore + i);
if (score > mscore) {
mscore = score;
label = i;
}
}
cnstream::CNInferAttr attr;
attr.id = 0;
attr.value = label;
attr.score = mscore;
obj->AddAttribute("classification", attr);
return 0;
}
| 37.035088 | 118 | 0.648271 | HFauto |
8173d5c1184cbc7093297f9866d086e3c429948c | 3,311 | cpp | C++ | test/filtering/segmentation_test.cpp | bradparks/Restore__3d_model_from_pics_2d_multiple_images | 58f935130693e6eba2db133ce8dec3fd6a3d3dd0 | [
"MIT"
] | 21 | 2018-07-17T02:35:43.000Z | 2022-02-25T00:45:09.000Z | test/filtering/segmentation_test.cpp | bradparks/Restore__3d_model_from_pics_2d_multiple_images | 58f935130693e6eba2db133ce8dec3fd6a3d3dd0 | [
"MIT"
] | null | null | null | test/filtering/segmentation_test.cpp | bradparks/Restore__3d_model_from_pics_2d_multiple_images | 58f935130693e6eba2db133ce8dec3fd6a3d3dd0 | [
"MIT"
] | 11 | 2018-09-06T17:29:36.000Z | 2022-01-29T12:20:59.000Z | // Copyright (c) 2015-2016, Kai Wolf
//
// 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 <gtest/gtest.h>
#include <opencv2/highgui/highgui.hpp>
#include "filtering/segmentation.hpp"
using namespace ret::filtering;
TEST(SegmentationTest, BinarizeImage) {
cv::Mat Original(240, 320, CV_8UC3, cv::Scalar::all(255));
const unsigned rg_size = 50;
cv::Mat Region = Original(cv::Rect(rg_size, rg_size, rg_size, rg_size));
Region.setTo(0);
cv::Mat Binary = Binarize(Original, cv::Scalar(0, 0, 30));
ASSERT_EQ(rg_size * rg_size, cv::countNonZero(Binary));
}
TEST(SegmentationTest, AssertColorImageWhenBinarizing) {
cv::Mat Original(240, 320, CV_8U, cv::Scalar::all(17));
ASSERT_DEATH(Binarize(Original, cv::Scalar(200)), "");
}
TEST(SegmentationTest, CreateSilhouetteMask) {
cv::Mat Original(240, 320, CV_8U, cv::Scalar::all(255));
cv::Mat Black(20, 20, CV_8U, cv::Scalar::all(0));
cv::Mat SubRegion = Original(cv::Rect(100, 100, Black.cols, Black.rows));
Black.copyTo(SubRegion);
ASSERT_GT(cv::countNonZero(CreateSilhouette(Original)),
cv::countNonZero(Original));
}
TEST(SegmentationTest, CreateDistMap) {
cv::Mat Original(240, 320, CV_8U, cv::Scalar::all(255));
cv::Mat Black(20, 1, CV_8U, cv::Scalar::all(0));
cv::Mat SubRegion = Original(cv::Rect(100, 100, Black.cols, Black.rows));
Black.copyTo(SubRegion);
cv::Mat Distmap = CreateDistMap(Original);
ASSERT_TRUE(Distmap.type() == CV_32F);
ASSERT_LT(Distmap.at<float>(100, 99), Distmap.at<float>(100, 100));
ASSERT_GT(Distmap.at<float>(100, 100), Distmap.at<float>(100, 101));
}
TEST(SegmentationTest, GrabCutWithNotPowerOf2NumFrags) {
cv::Mat Tmp(240, 320, CV_8UC3, cv::Scalar::all(255));
ASSERT_DEATH(GrabCut(Tmp, 15, cv::Point(), cv::Point()), "");
}
TEST(SegmentationTest, GrabCutImage) {
cv::Mat Original(240, 320, CV_8UC3, cv::Scalar::all(255));
cv::Mat Black(20, 20, CV_8UC3, cv::Scalar::all(0));
cv::Mat SubRegion = Original(cv::Rect(100, 100, Black.cols, Black.rows));
Black.copyTo(SubRegion);
cv::Mat Segmented = GrabCut(Original, 16, cv::Point(0, 0), cv::Point(8, 8));
ASSERT_TRUE(Segmented.at<uchar>(110, 110) == 255);
ASSERT_TRUE(Segmented.at<uchar>(200, 200) == 0);
}
| 39.416667 | 80 | 0.702205 | bradparks |
8176bc277fa038fca15ad0423c08d15b301a2379 | 31,595 | hpp | C++ | sdk/include/XEvt1.hpp | qianxj/XExplorer | 00e326da03ffcaa21115a2345275452607c6bab5 | [
"MIT"
] | null | null | null | sdk/include/XEvt1.hpp | qianxj/XExplorer | 00e326da03ffcaa21115a2345275452607c6bab5 | [
"MIT"
] | null | null | null | sdk/include/XEvt1.hpp | qianxj/XExplorer | 00e326da03ffcaa21115a2345275452607c6bab5 | [
"MIT"
] | null | null | null | #define WM_NULL 0x0000
#define WM_CREATE 0x0001
#define WM_DESTROY 0x0002
#define WM_MOVE 0x0003
#define WM_SIZE 0x0005
#define WM_ACTIVATE 0x0006
#define WM_SETFOCUS 0x0007
#define WM_KILLFOCUS 0x0008
#define WM_ENABLE 0x000A
#define WM_SETREDRAW 0x000B
#define WM_SETTEXT 0x000C
#define WM_GETTEXT 0x000D
#define WM_GETTEXTLENGTH 0x000E
#define WM_PAINT 0x000F
#define WM_CLOSE 0x0010
#define WM_QUERYENDSESSION 0x0011
#define WM_QUERYOPEN 0x0013
#define WM_ENDSESSION 0x0016
#define WM_QUIT 0x0012
#define WM_ERASEBKGND 0x0014
#define WM_SYSCOLORCHANGE 0x0015
#define WM_SHOWWINDOW 0x0018
#define WM_WININICHANGE 0x001A
#define WM_SETTINGCHANGE WM_WININICHANGE
#define WM_DEVMODECHANGE 0x001B
#define WM_ACTIVATEAPP 0x001C
#define WM_FONTCHANGE 0x001D
#define WM_TIMECHANGE 0x001E
#define WM_CANCELMODE 0x001F
#define WM_SETCURSOR 0x0020
#define WM_MOUSEACTIVATE 0x0021
#define WM_CHILDACTIVATE 0x0022
#define WM_QUEUESYNC 0x0023
#define WM_GETMINMAXINFO 0x0024
#define WM_PAINTICON 0x0026
#define WM_ICONERASEBKGND 0x0027
#define WM_NEXTDLGCTL 0x0028
#define WM_SPOOLERSTATUS 0x002A
#define WM_DRAWITEM 0x002B
#define WM_MEASUREITEM 0x002C
#define WM_DELETEITEM 0x002D
#define WM_VKEYTOITEM 0x002E
#define WM_CHARTOITEM 0x002F
#define WM_SETFONT 0x0030
#define WM_GETFONT 0x0031
#define WM_SETHOTKEY 0x0032
#define WM_GETHOTKEY 0x0033
#define WM_QUERYDRAGICON 0x0037
#define WM_COMPAREITEM 0x0039
#define WM_GETOBJECT 0x003D
#define WM_COMPACTING 0x0041
#define WM_COMMNOTIFY 0x0044
#define WM_WINDOWPOSCHANGING 0x0046
#define WM_WINDOWPOSCHANGED 0x0047
#define WM_POWER 0x0048
#define WM_COPYDATA 0x004A
#define WM_CANCELJOURNAL 0x004B
#define WM_NOTIFY 0x004E
#define WM_INPUTLANGCHANGEREQUEST 0x0050
#define WM_INPUTLANGCHANGE 0x0051
#define WM_TCARD 0x0052
#define WM_HELP 0x0053
#define WM_USERCHANGED 0x0054
#define WM_NOTIFYFORMAT 0x0055
#define WM_CONTEXTMENU 0x007B
#define WM_STYLECHANGING 0x007C
#define WM_STYLECHANGED 0x007D
#define WM_DISPLAYCHANGE 0x007E
#define WM_GETICON 0x007F
#define WM_SETICON 0x0080
#define WM_NCCREATE 0x0081
#define WM_NCDESTROY 0x0082
#define WM_NCCALCSIZE 0x0083
#define WM_NCHITTEST 0x0084
#define WM_NCPAINT 0x0085
#define WM_NCACTIVATE 0x0086
#define WM_GETDLGCODE 0x0087
#define WM_SYNCPAINT 0x0088
#define WM_NCMOUSEMOVE 0x00A0
#define WM_NCLBUTTONDOWN 0x00A1
#define WM_NCLBUTTONUP 0x00A2
#define WM_NCLBUTTONDBLCLK 0x00A3
#define WM_NCRBUTTONDOWN 0x00A4
#define WM_NCRBUTTONUP 0x00A5
#define WM_NCRBUTTONDBLCLK 0x00A6
#define WM_NCMBUTTONDOWN 0x00A7
#define WM_NCMBUTTONUP 0x00A8
#define WM_NCMBUTTONDBLCLK 0x00A9
#define WM_NCXBUTTONDOWN 0x00AB
#define WM_NCXBUTTONUP 0x00AC
#define WM_NCXBUTTONDBLCLK 0x00AD
#define WM_INPUT 0x00FF
#define WM_KEYFIRST 0x0100
#define WM_KEYDOWN 0x0100
#define WM_KEYUP 0x0101
#define WM_CHAR 0x0102
#define WM_DEADCHAR 0x0103
#define WM_SYSKEYDOWN 0x0104
#define WM_SYSKEYUP 0x0105
#define WM_SYSCHAR 0x0106
#define WM_SYSDEADCHAR 0x0107
#define WM_UNICHAR 0x0109
#define WM_KEYLAST 0x0109
#define UNICODE_NOCHAR 0xFFFF
#define WM_IME_STARTCOMPOSITION 0x010D
#define WM_IME_ENDCOMPOSITION 0x010E
#define WM_IME_COMPOSITION 0x010F
#define WM_IME_KEYLAST 0x010F
#define WM_INITDIALOG 0x0110
#define WM_COMMAND 0x0111
#define WM_SYSCOMMAND 0x0112
#define WM_TIMER 0x0113
#define WM_HSCROLL 0x0114
#define WM_VSCROLL 0x0115
#define WM_INITMENU 0x0116
#define WM_INITMENUPOPUP 0x0117
#define WM_MENUSELECT 0x011F
#define WM_MENUCHAR 0x0120
#define WM_ENTERIDLE 0x0121
#define WM_MENURBUTTONUP 0x0122
#define WM_MENUDRAG 0x0123
#define WM_MENUGETOBJECT 0x0124
#define WM_UNINITMENUPOPUP 0x0125
#define WM_MENUCOMMAND 0x0126
#define WM_CHANGEUISTATE 0x0127
#define WM_UPDATEUISTATE 0x0128
#define WM_QUERYUISTATE 0x0129
#define WM_CTLCOLORMSGBOX 0x0132
#define WM_CTLCOLOREDIT 0x0133
#define WM_CTLCOLORLISTBOX 0x0134
#define WM_CTLCOLORBTN 0x0135
#define WM_CTLCOLORDLG 0x0136
#define WM_CTLCOLORSCROLLBAR 0x0137
#define WM_CTLCOLORSTATIC 0x0138
#define MN_GETHMENU 0x01E1
#define WM_MOUSEFIRST 0x0200
#define WM_MOUSEMOVE 0x0200
#define WM_LBUTTONDOWN 0x0201
#define WM_LBUTTONUP 0x0202
#define WM_LBUTTONDBLCLK 0x0203
#define WM_RBUTTONDOWN 0x0204
#define WM_RBUTTONUP 0x0205
#define WM_RBUTTONDBLCLK 0x0206
#define WM_MBUTTONDOWN 0x0207
#define WM_MBUTTONUP 0x0208
#define WM_MBUTTONDBLCLK 0x0209
#define WM_MOUSEWHEEL 0x020A
#define WM_XBUTTONDOWN 0x020B
#define WM_XBUTTONUP 0x020C
#define WM_XBUTTONDBLCLK 0x020D
#define WM_MOUSELAST 0x020D
#define WM_PARENTNOTIFY 0x0210
#define WM_ENTERMENULOOP 0x0211
#define WM_EXITMENULOOP 0x0212
#define WM_NEXTMENU 0x0213
#define WM_SIZING 0x0214
#define WM_CAPTURECHANGED 0x0215
#define WM_MOVING 0x0216
#define WM_POWERBROADCAST 0x0218
#define WM_DEVICECHANGE 0x0219
#define WM_MDICREATE 0x0220
#define WM_MDIDESTROY 0x0221
#define WM_MDIACTIVATE 0x0222
#define WM_MDIRESTORE 0x0223
#define WM_MDINEXT 0x0224
#define WM_MDIMAXIMIZE 0x0225
#define WM_MDITILE 0x0226
#define WM_MDICASCADE 0x0227
#define WM_MDIICONARRANGE 0x0228
#define WM_MDIGETACTIVE 0x0229
#define WM_MDISETMENU 0x0230
#define WM_ENTERSIZEMOVE 0x0231
#define WM_EXITSIZEMOVE 0x0232
#define WM_DROPFILES 0x0233
#define WM_MDIREFRESHMENU 0x0234
#define WM_IME_SETCONTEXT 0x0281
#define WM_IME_NOTIFY 0x0282
#define WM_IME_CONTROL 0x0283
#define WM_IME_COMPOSITIONFULL 0x0284
#define WM_IME_SELECT 0x0285
#define WM_IME_CHAR 0x0286
#define WM_IME_REQUEST 0x0288
#define WM_IME_KEYDOWN 0x0290
#define WM_IME_KEYUP 0x0291
#define WM_MOUSEHOVER 0x02A1
#define WM_MOUSELEAVE 0x02A3
#define WM_NCMOUSEHOVER 0x02A0
#define WM_NCMOUSELEAVE 0x02A2
#define WM_WTSSESSION_CHANGE 0x02B1
#define WM_TABLET_FIRST 0x02c0
#define WM_TABLET_LAST 0x02df
#define WM_CUT 0x0300
#define WM_COPY 0x0301
#define WM_PASTE 0x0302
#define WM_CLEAR 0x0303
#define WM_UNDO 0x0304
#define WM_RENDERFORMAT 0x0305
#define WM_RENDERALLFORMATS 0x0306
#define WM_DESTROYCLIPBOARD 0x0307
#define WM_DRAWCLIPBOARD 0x0308
#define WM_PAINTCLIPBOARD 0x0309
#define WM_VSCROLLCLIPBOARD 0x030A
#define WM_SIZECLIPBOARD 0x030B
#define WM_ASKCBFORMATNAME 0x030C
#define WM_CHANGECBCHAIN 0x030D
#define WM_HSCROLLCLIPBOARD 0x030E
#define WM_QUERYNEWPALETTE 0x030F
#define WM_PALETTEISCHANGING 0x0310
#define WM_PALETTECHANGED 0x0311
#define WM_HOTKEY 0x0312
#define WM_PRINT 0x0317
#define WM_PRINTCLIENT 0x0318
#define WM_APPCOMMAND 0x0319
#define WM_THEMECHANGED 0x031A
#define WM_HANDHELDFIRST 0x0358
#define WM_HANDHELDLAST 0x035F
#define WM_AFXFIRST 0x0360
#define WM_AFXLAST 0x037F
#define WM_PENWINFIRST 0x0380
#define WM_PENWINLAST 0x038F
#define WM_APP 0x8000
#define WM_USER 0x0400
#define NM_FIRST (0U- 0U) // generic to all controls
#define NM_LAST (0U- 99U)
//====== Generic WM_NOTIFY notification codes =================================
#define LVN_FIRST (0U-100U) // listview
#define LVN_LAST (0U-199U)
// Property sheet reserved (0U-200U) - (0U-299U) - see prsht.h
#define PSN_FIRST (0U-200U)
#define PSN_LAST (0U-299U)
#define HDN_FIRST (0U-300U) // header
#define HDN_LAST (0U-399U)
#define TVN_FIRST (0U-400U) // treeview
#define TVN_LAST (0U-499U)
#define TTN_FIRST (0U-520U) // tooltips
#define TTN_LAST (0U-549U)
#define TCN_FIRST (0U-550U) // tab control
#define TCN_LAST (0U-580U)
// Shell reserved (0U-580U) - (0U-589U)
#define CDN_FIRST (0U-601U) // common dialog (new)
#define CDN_LAST (0U-699U)
#define TBN_FIRST (0U-700U) // toolbar
#define TBN_LAST (0U-720U)
#define UDN_FIRST (0U-721) // updown
#define UDN_LAST (0U-740)
#if (_WIN32_IE >= 0x0300)
#define MCN_FIRST (0U-750U) // monthcal
#define MCN_LAST (0U-759U)
#define DTN_FIRST (0U-760U) // datetimepick
#define DTN_LAST (0U-799U)
#define CBEN_FIRST (0U-800U) // combo box ex
#define CBEN_LAST (0U-830U)
#define RBN_FIRST (0U-831U) // rebar
#define RBN_LAST (0U-859U)
#endif
#if (_WIN32_IE >= 0x0400)
#define IPN_FIRST (0U-860U) // internet address
#define IPN_LAST (0U-879U) // internet address
#define SBN_FIRST (0U-880U) // status bar
#define SBN_LAST (0U-899U)
#define PGN_FIRST (0U-900U) // Pager Control
#define PGN_LAST (0U-950U)
#endif
#if (_WIN32_IE >= 0x0500)
#ifndef WMN_FIRST
#define WMN_FIRST (0U-1000U)
#define WMN_LAST (0U-1200U)
#endif
#endif
#if (_WIN32_WINNT >= 0x0501)
#define BCN_FIRST (0U-1250U)
#define BCN_LAST (0U-1350U)
#endif
#define NM_OUTOFMEMORY (NM_FIRST-1)
#define NM_CLICK (NM_FIRST-2) // uses NMCLICK struct
#define NM_DBLCLK (NM_FIRST-3)
#define NM_RETURN (NM_FIRST-4)
#define NM_RCLICK (NM_FIRST-5) // uses NMCLICK struct
#define NM_RDBLCLK (NM_FIRST-6)
#define NM_SETFOCUS (NM_FIRST-7)
#define NM_KILLFOCUS (NM_FIRST-8)
#if (_WIN32_IE >= 0x0300)
#define NM_CUSTOMDRAW (NM_FIRST-12)
#define NM_HOVER (NM_FIRST-13)
#endif
#if (_WIN32_IE >= 0x0400)
#define NM_NCHITTEST (NM_FIRST-14) // uses NMMOUSE struct
#define NM_KEYDOWN (NM_FIRST-15) // uses NMKEY struct
#define NM_RELEASEDCAPTURE (NM_FIRST-16)
#define NM_SETCURSOR (NM_FIRST-17) // uses NMMOUSE struct
#define NM_CHAR (NM_FIRST-18) // uses NMCHAR struct
#endif
#if (_WIN32_IE >= 0x0401)
#define NM_TOOLTIPSCREATED (NM_FIRST-19) // notify of when the tooltips window is create
#endif
#if (_WIN32_IE >= 0x0500)
#define NM_LDOWN (NM_FIRST-20)
#define NM_RDOWN (NM_FIRST-21)
#define NM_THEMECHANGED (NM_FIRST-22)
#endif
//Property Sheet Pages
#define PSP_DEFAULT 0x00000000
#define PSP_DLGINDIRECT 0x00000001
#define PSP_USEHICON 0x00000002
#define PSP_USEICONID 0x00000004
#define PSP_USETITLE 0x00000008
#define PSP_RTLREADING 0x00000010
#define PSP_HASHELP 0x00000020
#define PSP_USEREFPARENT 0x00000040
#define PSP_USECALLBACK 0x00000080
#define PSP_PREMATURE 0x00000400
#if (_WIN32_IE >= 0x0400)
//----- New flags for wizard97 --------------
#define PSP_HIDEHEADER 0x00000800
#define PSP_USEHEADERTITLE 0x00001000
#define PSP_USEHEADERSUBTITLE 0x00002000
//-------------------------------------------
#endif
#if (_WIN32_WINNT >= 0x0501) || ISOLATION_AWARE_ENABLED
#define PSP_USEFUSIONCONTEXT 0x00004000
#endif
//====== HEADER CONTROL =======================================================
#define HDN_ITEMCHANGINGA (HDN_FIRST-0)
#define HDN_ITEMCHANGINGW (HDN_FIRST-20)
#define HDN_ITEMCHANGEDA (HDN_FIRST-1)
#define HDN_ITEMCHANGEDW (HDN_FIRST-21)
#define HDN_ITEMCLICKA (HDN_FIRST-2)
#define HDN_ITEMCLICKW (HDN_FIRST-22)
#define HDN_ITEMDBLCLICKA (HDN_FIRST-3)
#define HDN_ITEMDBLCLICKW (HDN_FIRST-23)
#define HDN_DIVIDERDBLCLICKA (HDN_FIRST-5)
#define HDN_DIVIDERDBLCLICKW (HDN_FIRST-25)
#define HDN_BEGINTRACKA (HDN_FIRST-6)
#define HDN_BEGINTRACKW (HDN_FIRST-26)
#define HDN_ENDTRACKA (HDN_FIRST-7)
#define HDN_ENDTRACKW (HDN_FIRST-27)
#define HDN_TRACKA (HDN_FIRST-8)
#define HDN_TRACKW (HDN_FIRST-28)
#if (_WIN32_IE >= 0x0300)
#define HDN_GETDISPINFOA (HDN_FIRST-9)
#define HDN_GETDISPINFOW (HDN_FIRST-29)
#define HDN_BEGINDRAG (HDN_FIRST-10)
#define HDN_ENDDRAG (HDN_FIRST-11)
#endif
#if (_WIN32_IE >= 0x0500)
#define HDN_FILTERCHANGE (HDN_FIRST-12)
#define HDN_FILTERBTNCLICK (HDN_FIRST-13)
#endif
#ifdef UNICODE
#define HDN_ITEMCHANGING HDN_ITEMCHANGINGW
#define HDN_ITEMCHANGED HDN_ITEMCHANGEDW
#define HDN_ITEMCLICK HDN_ITEMCLICKW
#define HDN_ITEMDBLCLICK HDN_ITEMDBLCLICKW
#define HDN_DIVIDERDBLCLICK HDN_DIVIDERDBLCLICKW
#define HDN_BEGINTRACK HDN_BEGINTRACKW
#define HDN_ENDTRACK HDN_ENDTRACKW
#define HDN_TRACK HDN_TRACKW
#if (_WIN32_IE >= 0x0300)
#define HDN_GETDISPINFO HDN_GETDISPINFOW
#endif
#else
#define HDN_ITEMCHANGING HDN_ITEMCHANGINGA
#define HDN_ITEMCHANGED HDN_ITEMCHANGEDA
#define HDN_ITEMCLICK HDN_ITEMCLICKA
#define HDN_ITEMDBLCLICK HDN_ITEMDBLCLICKA
#define HDN_DIVIDERDBLCLICK HDN_DIVIDERDBLCLICKA
#define HDN_BEGINTRACK HDN_BEGINTRACKA
#define HDN_ENDTRACK HDN_ENDTRACKA
#define HDN_TRACK HDN_TRACKA
#if (_WIN32_IE >= 0x0300)
#define HDN_GETDISPINFO HDN_GETDISPINFOA
#endif
#endif
//====== TOOLBAR CONTROL ======================================================
#define TBN_GETBUTTONINFOA (TBN_FIRST-0)
#define TBN_BEGINDRAG (TBN_FIRST-1)
#define TBN_ENDDRAG (TBN_FIRST-2)
#define TBN_BEGINADJUST (TBN_FIRST-3)
#define TBN_ENDADJUST (TBN_FIRST-4)
#define TBN_RESET (TBN_FIRST-5)
#define TBN_QUERYINSERT (TBN_FIRST-6)
#define TBN_QUERYDELETE (TBN_FIRST-7)
#define TBN_TOOLBARCHANGE (TBN_FIRST-8)
#define TBN_CUSTHELP (TBN_FIRST-9)
#if (_WIN32_IE >= 0x0300)
#define TBN_DROPDOWN (TBN_FIRST - 10)
#endif
#if (_WIN32_IE >= 0x0400)
#define TBN_GETOBJECT (TBN_FIRST - 12)
#endif
#define TBN_HOTITEMCHANGE (TBN_FIRST - 13)
#define TBN_DRAGOUT (TBN_FIRST - 14) // this is sent when the user clicks down on a button then drags off the button
#define TBN_DELETINGBUTTON (TBN_FIRST - 15) // uses TBNOTIFY
#define TBN_GETDISPINFOA (TBN_FIRST - 16) // This is sent when the toolbar needs some display information
#define TBN_GETDISPINFOW (TBN_FIRST - 17) // This is sent when the toolbar needs some display information
#define TBN_GETINFOTIPA (TBN_FIRST - 18)
#define TBN_GETINFOTIPW (TBN_FIRST - 19)
#define TBN_GETBUTTONINFOW (TBN_FIRST - 20)
#if (_WIN32_IE >= 0x0500)
#define TBN_RESTORE (TBN_FIRST - 21)
#define TBN_SAVE (TBN_FIRST - 22)
#define TBN_INITCUSTOMIZE (TBN_FIRST - 23)
#endif // (_WIN32_IE >= 0x0500)
#ifdef UNICODE
#define TBN_GETINFOTIP TBN_GETINFOTIPW
#else
#define TBN_GETINFOTIP TBN_GETINFOTIPA
#endif
#ifdef UNICODE
#define TBN_GETDISPINFO TBN_GETDISPINFOW
#else
#define TBN_GETDISPINFO TBN_GETDISPINFOA
#endif
#ifdef UNICODE
#define TBN_GETBUTTONINFO TBN_GETBUTTONINFOW
#else
#define TBN_GETBUTTONINFO TBN_GETBUTTONINFOA
#endif
//====== REBAR CONTROL ========================================================
#define RBN_HEIGHTCHANGE (RBN_FIRST - 0)
#define RBN_GETOBJECT (RBN_FIRST - 1)
#define RBN_LAYOUTCHANGED (RBN_FIRST - 2)
#define RBN_AUTOSIZE (RBN_FIRST - 3)
#define RBN_BEGINDRAG (RBN_FIRST - 4)
#define RBN_ENDDRAG (RBN_FIRST - 5)
#define RBN_DELETINGBAND (RBN_FIRST - 6) // Uses NMREBAR
#define RBN_DELETEDBAND (RBN_FIRST - 7) // Uses NMREBAR
#define RBN_CHILDSIZE (RBN_FIRST - 8)
#if (_WIN32_IE >= 0x0500)
#define RBN_CHEVRONPUSHED (RBN_FIRST - 10)
#endif // _WIN32_IE >= 0x0500
#if (_WIN32_IE >= 0x0500)
#define RBN_MINMAX (RBN_FIRST - 21)
#endif
#if (_WIN32_WINNT >= 0x0501)
#define RBN_AUTOBREAK (RBN_FIRST - 22)
#endif
//====== TOOLTIPS CONTROL =====================================================
#define TTN_GETDISPINFOA (TTN_FIRST - 0)
#define TTN_GETDISPINFOW (TTN_FIRST - 10)
#define TTN_SHOW (TTN_FIRST - 1)
#define TTN_POP (TTN_FIRST - 2)
#define TTN_LINKCLICK (TTN_FIRST - 3)
#ifdef UNICODE
#define TTN_GETDISPINFO TTN_GETDISPINFOW
#else
#define TTN_GETDISPINFO TTN_GETDISPINFOA
#endif
#define TTN_NEEDTEXT TTN_GETDISPINFO
#define TTN_NEEDTEXTA TTN_GETDISPINFOA
#define TTN_NEEDTEXTW TTN_GETDISPINFOW
//====== STATUS BAR CONTROL ===================================================
/// status bar notifications
#if (_WIN32_IE >= 0x0400)
#define SBN_SIMPLEMODECHANGE (SBN_FIRST - 0)
#endif
//====== MENU HELP ============================================================
//====== TRACKBAR CONTROL =====================================================
//====== DRAG LIST CONTROL ====================================================
//====== UPDOWN CONTROL =======================================================
#define UDN_DELTAPOS (UDN_FIRST - 1)
//====== PROGRESS CONTROL =====================================================
//====== HOTKEY CONTROL =======================================================
//====== COMMON CONTROL STYLES ================================================
//====== LISTVIEW CONTROL =====================================================
#define LVN_ITEMCHANGING (LVN_FIRST-0)
#define LVN_ITEMCHANGED (LVN_FIRST-1)
#define LVN_INSERTITEM (LVN_FIRST-2)
#define LVN_DELETEITEM (LVN_FIRST-3)
#define LVN_DELETEALLITEMS (LVN_FIRST-4)
#define LVN_BEGINLABELEDITA (LVN_FIRST-5)
#define LVN_BEGINLABELEDITW (LVN_FIRST-75)
#define LVN_ENDLABELEDITA (LVN_FIRST-6)
#define LVN_ENDLABELEDITW (LVN_FIRST-76)
#define LVN_COLUMNCLICK (LVN_FIRST-8)
#define LVN_BEGINDRAG (LVN_FIRST-9)
#define LVN_BEGINRDRAG (LVN_FIRST-11)
#if (_WIN32_IE >= 0x0300)
#define LVN_ODCACHEHINT (LVN_FIRST-13)
#define LVN_ODFINDITEMA (LVN_FIRST-52)
#define LVN_ODFINDITEMW (LVN_FIRST-79)
#define LVN_ITEMACTIVATE (LVN_FIRST-14)
#define LVN_ODSTATECHANGED (LVN_FIRST-15)
#ifdef UNICODE
#define LVN_ODFINDITEM LVN_ODFINDITEMW
#else
#define LVN_ODFINDITEM LVN_ODFINDITEMA
#endif
#endif // _WIN32_IE >= 0x0300
#if (_WIN32_IE >= 0x0400)
#define LVN_HOTTRACK (LVN_FIRST-21)
#endif
#define LVN_GETDISPINFOA (LVN_FIRST-50)
#define LVN_GETDISPINFOW (LVN_FIRST-77)
#define LVN_SETDISPINFOA (LVN_FIRST-51)
#define LVN_SETDISPINFOW (LVN_FIRST-78)
#ifdef UNICODE
#define LVN_BEGINLABELEDIT LVN_BEGINLABELEDITW
#define LVN_ENDLABELEDIT LVN_ENDLABELEDITW
#define LVN_GETDISPINFO LVN_GETDISPINFOW
#define LVN_SETDISPINFO LVN_SETDISPINFOW
#else
#define LVN_BEGINLABELEDIT LVN_BEGINLABELEDITA
#define LVN_ENDLABELEDIT LVN_ENDLABELEDITA
#define LVN_GETDISPINFO LVN_GETDISPINFOA
#define LVN_SETDISPINFO LVN_SETDISPINFOA
#endif
#define LVN_GETINFOTIPA (LVN_FIRST-57)
#define LVN_GETINFOTIPW (LVN_FIRST-58)
#ifdef UNICODE
#define LVN_GETINFOTIP LVN_GETINFOTIPW
#define NMLVGETINFOTIP NMLVGETINFOTIPW
#define LPNMLVGETINFOTIP LPNMLVGETINFOTIPW
#else
#define LVN_GETINFOTIP LVN_GETINFOTIPA
#define NMLVGETINFOTIP NMLVGETINFOTIPA
#define LPNMLVGETINFOTIP LPNMLVGETINFOTIPA
#endif
#define LVN_BEGINSCROLL (LVN_FIRST-80)
#define LVN_ENDSCROLL (LVN_FIRST-81)
//====== TREEVIEW CONTROL =====================================================
#define TVN_SELCHANGINGA (TVN_FIRST-1)
#define TVN_SELCHANGINGW (TVN_FIRST-50)
#define TVN_SELCHANGEDA (TVN_FIRST-2)
#define TVN_SELCHANGEDW (TVN_FIRST-51)
#define TVN_GETDISPINFOA (TVN_FIRST-3)
#define TVN_GETDISPINFOW (TVN_FIRST-52)
#define TVN_SETDISPINFOA (TVN_FIRST-4)
#define TVN_SETDISPINFOW (TVN_FIRST-53)
#define TVN_ITEMEXPANDINGA (TVN_FIRST-5)
#define TVN_ITEMEXPANDINGW (TVN_FIRST-54)
#define TVN_ITEMEXPANDEDA (TVN_FIRST-6)
#define TVN_ITEMEXPANDEDW (TVN_FIRST-55)
#define TVN_BEGINDRAGA (TVN_FIRST-7)
#define TVN_BEGINDRAGW (TVN_FIRST-56)
#define TVN_BEGINRDRAGA (TVN_FIRST-8)
#define TVN_BEGINRDRAGW (TVN_FIRST-57)
#define TVN_DELETEITEMA (TVN_FIRST-9)
#define TVN_DELETEITEMW (TVN_FIRST-58)
#define TVN_BEGINLABELEDITA (TVN_FIRST-10)
#define TVN_BEGINLABELEDITW (TVN_FIRST-59)
#define TVN_ENDLABELEDITA (TVN_FIRST-11)
#define TVN_ENDLABELEDITW (TVN_FIRST-60)
#define TVN_KEYDOWN (TVN_FIRST-12)
#if (_WIN32_IE >= 0x0400)
#define TVN_GETINFOTIPA (TVN_FIRST-13)
#define TVN_GETINFOTIPW (TVN_FIRST-14)
#define TVN_SINGLEEXPAND (TVN_FIRST-15)
#endif // 0x400
#ifdef UNICODE
#define TVN_SELCHANGING TVN_SELCHANGINGW
#define TVN_SELCHANGED TVN_SELCHANGEDW
#define TVN_GETDISPINFO TVN_GETDISPINFOW
#define TVN_SETDISPINFO TVN_SETDISPINFOW
#define TVN_ITEMEXPANDING TVN_ITEMEXPANDINGW
#define TVN_ITEMEXPANDED TVN_ITEMEXPANDEDW
#define TVN_BEGINDRAG TVN_BEGINDRAGW
#define TVN_BEGINRDRAG TVN_BEGINRDRAGW
#define TVN_DELETEITEM TVN_DELETEITEMW
#define TVN_BEGINLABELEDIT TVN_BEGINLABELEDITW
#define TVN_ENDLABELEDIT TVN_ENDLABELEDITW
#else
#define TVN_SELCHANGING TVN_SELCHANGINGA
#define TVN_SELCHANGED TVN_SELCHANGEDA
#define TVN_GETDISPINFO TVN_GETDISPINFOA
#define TVN_SETDISPINFO TVN_SETDISPINFOA
#define TVN_ITEMEXPANDING TVN_ITEMEXPANDINGA
#define TVN_ITEMEXPANDED TVN_ITEMEXPANDEDA
#define TVN_BEGINDRAG TVN_BEGINDRAGA
#define TVN_BEGINRDRAG TVN_BEGINRDRAGA
#define TVN_DELETEITEM TVN_DELETEITEMA
#define TVN_BEGINLABELEDIT TVN_BEGINLABELEDITA
#define TVN_ENDLABELEDIT TVN_ENDLABELEDITA
#endif
#ifdef UNICODE
#define TVN_GETINFOTIP TVN_GETINFOTIPW
#else
#defne TVN_GETINFOTIP TVN_GETINFOTIPA
#endif
//////////////////// ComboBoxEx ////////////////////////////////
#define CBEN_GETDISPINFOW (CBEN_FIRST - 7)
#define CBEN_GETDISPINFOA (CBEN_FIRST - 0)
#ifdef UNICODE
#define CBEN_GETDISPINFO CBEN_GETDISPINFOW
#else
#define CBEN_GETDISPINFO CBEN_GETDISPINFOA
#endif
#define CBEN_INSERTITEM (CBEN_FIRST - 1)
#define CBEN_DELETEITEM (CBEN_FIRST - 2)
#define CBEN_BEGINEDIT (CBEN_FIRST - 4)
#define CBEN_ENDEDITA (CBEN_FIRST - 5)
#define CBEN_ENDEDITW (CBEN_FIRST - 6)
#define CBEN_DRAGBEGINA (CBEN_FIRST - 8)
#define CBEN_DRAGBEGINW (CBEN_FIRST - 9)
#ifdef UNICODE
#define CBEN_DRAGBEGIN CBEN_DRAGBEGINW
#else
#define CBEN_DRAGBEGIN CBEN_DRAGBEGINA
#endif
// lParam specifies why the endedit is happening
#ifdef UNICODE
#define CBEN_ENDEDIT CBEN_ENDEDITW
#else
#define CBEN_ENDEDIT CBEN_ENDEDITA
#endif
//====== TAB CONTROL ==========================================================
#define TCN_KEYDOWN (TCN_FIRST - 0)
#define TCN_SELCHANGE (TCN_FIRST - 1)
#define TCN_SELCHANGING (TCN_FIRST - 2)
#if (_WIN32_IE >= 0x0400)
#define TCN_GETOBJECT (TCN_FIRST - 3)
#endif // _WIN32_IE >= 0x0400
#if (_WIN32_IE >= 0x0500)
#define TCN_FOCUSCHANGE (TCN_FIRST - 4)
#endif // _WIN32_IE >= 0x0500
//====== ANIMATE CONTROL ======================================================
#define ACN_START 1
#define ACN_STOP 2
//====== MONTHCAL CONTROL ======================================================
#define MCN_SELCHANGE (MCN_FIRST + 1)
#define MCN_GETDAYSTATE (MCN_FIRST + 3)
#define MCN_SELECT (MCN_FIRST + 4)
//====== DATETIMEPICK CONTROL ==================================================
#ifdef UNICODE
#define DTN_WMKEYDOWN DTN_WMKEYDOWNW
#define NMDATETIMEWMKEYDOWN NMDATETIMEWMKEYDOWNW
#define LPNMDATETIMEWMKEYDOWN LPNMDATETIMEWMKEYDOWNW
#else
#define DTN_WMKEYDOWN DTN_WMKEYDOWNA
#define NMDATETIMEWMKEYDOWN NMDATETIMEWMKEYDOWNA
#define LPNMDATETIMEWMKEYDOWN LPNMDATETIMEWMKEYDOWNA
#endif
#define DTN_FORMATA (DTN_FIRST + 4) // query display for app format field (X)
#define DTN_FORMATW (DTN_FIRST + 17)
#ifdef UNICODE
#define DTN_FORMAT DTN_FORMATW
#define NMDATETIMEFORMAT NMDATETIMEFORMATW
#define LPNMDATETIMEFORMAT LPNMDATETIMEFORMATW
#else
#define DTN_FORMAT DTN_FORMATA
#define NMDATETIMEFORMAT NMDATETIMEFORMATA
#define LPNMDATETIMEFORMAT LPNMDATETIMEFORMATA
#endif
#define DTN_FORMATQUERYA (DTN_FIRST + 5) // query formatting info for app format field (X)
#define DTN_FORMATQUERYW (DTN_FIRST + 18)
#ifdef UNICODE
#define DTN_FORMATQUERY DTN_FORMATQUERYW
#else
#define DTN_FORMATQUERY DTN_FORMATQUERYA
#endif
#define DTN_DROPDOWN (DTN_FIRST + 6) // MonthCal has dropped down
#define DTN_CLOSEUP (DTN_FIRST + 7) // MonthCal is popping up
// IP Address edit control
#define IPN_FIELDCHANGED (IPN_FIRST - 0)
// ====================== Pager Control =============================
#define PGN_CALCSIZE (PGN_FIRST-2)
#define PGN_HOTITEMCHANGE (PGN_FIRST-3)
// === Native Font Control ===
/// ====================== Button Control =============================
#define BN_CLICKED 0
#define BN_PAINT 1
#define BN_HILITE 2
#define BN_UNHILITE 3
#define BN_DISABLE 4
#define BN_DOUBLECLICKED 5
#if(WINVER >= 0x0400)
#define BN_PUSHED BN_HILITE
#define BN_UNPUSHED BN_UNHILITE
#define BN_DBLCLK BN_DOUBLECLICKED
#define BN_SETFOCUS 6
#define BN_KILLFOCUS 7
#endif /* WINVER >= 0x0400 */
/// ====================== Static Control =============================
#define STN_CLICKED 0
#define STN_DBLCLK 1
#define STN_ENABLE 2
#define STN_DISABLE 3
/// ====================== Edit Control =============================
/*
* Edit Control Notification Codes
*/
#define EN_SETFOCUS 0x0100
#define EN_KILLFOCUS 0x0200
#define EN_CHANGE 0x0300
#define EN_UPDATE 0x0400
#define EN_ERRSPACE 0x0500
#define EN_MAXTEXT 0x0501
#define EN_HSCROLL 0x0601
#define EN_VSCROLL 0x0602
#if(_WIN32_WINNT >= 0x0500)
#define EN_ALIGN_LTR_EC 0x0700
#define EN_ALIGN_RTL_EC 0x0701
#endif /* _WIN32_WINNT >= 0x0500 */
/// ====================== Listbox Control =============================
#define LBN_ERRSPACE (-2)
#define LBN_SELCHANGE 1
#define LBN_DBLCLK 2
#define LBN_SELCANCEL 3
#define LBN_SETFOCUS 4
#define LBN_KILLFOCUS 5
/// ====================== Combobox Control =============================
#define CBN_ERRSPACE (-1)
#define CBN_SELCHANGE 1
#define CBN_DBLCLK 2
#define CBN_SETFOCUS 3
#define CBN_KILLFOCUS 4
#define CBN_EDITCHANGE 5
#define CBN_EDITUPDATE 6
#define CBN_DROPDOWN 7
#define CBN_CLOSEUP 8
#define CBN_SELENDOK 9
#define CBN_SELENDCANCEL 10
/// ====================== Scrollbar Control ============================
//====== SysLink control =========================================
// === MUI APIs ===
//====== TrackMouseEvent =====================================================
#ifndef WM_MOUSEHOVER
#define WM_MOUSEHOVER 0x02A1
#define WM_MOUSELEAVE 0x02A3
#endif
//====== Flat Scrollbar APIs=========================================
BN_CLICKED | 36.067352 | 128 | 0.585061 | qianxj |
40be5d932f39af6bb9ef75177c111f5a14254c39 | 1,274 | cpp | C++ | src/common/persistence/base/Save.cpp | dataliz9r/MDE4CPP | 9c5ce01c800fb754c371f1a67f648366eeabae49 | [
"MIT"
] | 12 | 2017-02-17T10:33:51.000Z | 2022-03-01T02:48:10.000Z | src/common/persistence/base/Save.cpp | dataliz9r/MDE4CPP | 9c5ce01c800fb754c371f1a67f648366eeabae49 | [
"MIT"
] | 28 | 2017-10-17T20:23:52.000Z | 2021-03-04T16:07:13.000Z | src/common/persistence/base/Save.cpp | dataliz9r/MDE4CPP | 9c5ce01c800fb754c371f1a67f648366eeabae49 | [
"MIT"
] | 22 | 2017-03-24T19:03:58.000Z | 2022-03-31T12:10:07.000Z | /*
* Save.cpp
*
* Created on: 29.05.2017
* Author: Alexander
*/
#include "persistence/base/Save.hpp"
#include "PersistenceDefine.hpp"
#include <iostream>
#include "ecore/EClass.hpp"
#include "ecore/EObject.hpp"
#include "ecore/EPackage.hpp"
#include "persistence/base/SaveHandler.hpp"
using namespace persistence::base;
Save::Save ()
{
}
Save::~Save ()
{
}
bool Save::save ( const std::string &filename, std::shared_ptr<ecore::EObject> model, std::shared_ptr<ecore::EPackage> metaMetaPackage, bool xsiMode)
{
std::shared_ptr<ecore::EClass> metaClass = model->eClass();
MSG_DEBUG( "metaClass: " << metaClass->getName() );
MSG_DEBUG( "metaMetaPck-NS: " << metaMetaPackage->getNsPrefix() );
MSG_DEBUG( "metaMetaPck-Uri: " << metaMetaPackage->getNsURI() );
m_handler->setIsXSIMode(xsiMode);
m_handler->setRootObject( model );
m_handler->createRootNode( metaMetaPackage->getNsPrefix(), metaClass->getName(), metaMetaPackage->getNsURI() );
MSG_DEBUG( m_handler->extractType( model ) );
model->save( m_handler );
m_handler->finalize();
// Call write() method in corresponding derived class
return write( filename );
}
void Save::setTypesMap(std::map<std::string, std::shared_ptr<ecore::EObject>> typesMap)
{
m_handler->setTypesMap(typesMap);
}
| 24.037736 | 149 | 0.716641 | dataliz9r |
40c450720b3a5058eb1a32c7295502c7f29aa13b | 6,445 | cpp | C++ | dp/third-party/hyperscan/unit/hyperscan/allocators.cpp | jtravee/neuvector | a88b9363108fc5c412be3007c3d4fb700d18decc | [
"Apache-2.0"
] | 2,868 | 2017-10-26T02:25:23.000Z | 2022-03-31T23:24:16.000Z | unit/hyperscan/allocators.cpp | kuangxiaohong/phytium-hyperscan | ae1932734859906278dba623b77f99bba1010d5c | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 270 | 2017-10-30T19:53:54.000Z | 2022-03-30T22:03:17.000Z | unit/hyperscan/allocators.cpp | kuangxiaohong/phytium-hyperscan | ae1932734859906278dba623b77f99bba1010d5c | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 403 | 2017-11-02T01:18:22.000Z | 2022-03-14T08:46:20.000Z | /*
* Copyright (c) 2015-2016, Intel Corporation
*
* 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 Intel Corporation nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "gtest/gtest.h"
#include "hs.h"
#include "test_util.h"
#include <cstdlib>
#include <string>
using std::string;
static void *null_malloc(size_t) { return nullptr; }
TEST(CustomAllocator, DatabaseInfoBadAlloc) {
hs_database_t *db = buildDB("foobar", 0, 0, HS_MODE_BLOCK);
ASSERT_TRUE(db != nullptr);
hs_set_allocator(null_malloc, nullptr);
char *info = nullptr;
hs_error_t err = hs_database_info(db, &info);
ASSERT_EQ(HS_NOMEM, err);
hs_set_allocator(nullptr, nullptr);
hs_free_database(db);
}
static
void * two_aligned_malloc(size_t len) {
void *mem = malloc(len + 2);
if (!mem) {
return nullptr;
}
return (char *)mem + 2;
}
static
void two_aligned_free(void *mem) {
if (!mem) {
return;
}
// Allocated with two_aligned_malloc above.
free((char *)mem - 2);
}
TEST(CustomAllocator, TwoAlignedCompile) {
hs_set_database_allocator(two_aligned_malloc, two_aligned_free);
hs_database_t *db = nullptr;
hs_compile_error_t *compile_err = nullptr;
const hs_platform_info_t *platform = nullptr;
hs_error_t err =
hs_compile("foobar", 0, HS_MODE_BLOCK, platform, &db, &compile_err);
ASSERT_EQ(HS_COMPILER_ERROR, err);
ASSERT_EQ(nullptr, db);
ASSERT_NE(nullptr, compile_err);
hs_free_compile_error(compile_err);
hs_set_database_allocator(nullptr, nullptr);
}
TEST(CustomAllocator, TwoAlignedCompileError) {
hs_set_misc_allocator(two_aligned_malloc, two_aligned_free);
hs_database_t *db = nullptr;
hs_compile_error_t *compile_err = nullptr;
const hs_platform_info_t *platform = nullptr;
hs_error_t err =
hs_compile("\\1", 0, HS_MODE_BLOCK, platform, &db, &compile_err);
ASSERT_EQ(HS_COMPILER_ERROR, err);
ASSERT_EQ(nullptr, db);
ASSERT_NE(nullptr, compile_err);
EXPECT_STREQ("Allocator returned misaligned memory.", compile_err->message);
hs_free_compile_error(compile_err);
hs_set_database_allocator(nullptr, nullptr);
}
TEST(CustomAllocator, TwoAlignedDatabaseInfo) {
hs_database_t *db = buildDB("foobar", 0, 0, HS_MODE_BLOCK);
ASSERT_TRUE(db != nullptr);
hs_set_misc_allocator(two_aligned_malloc, two_aligned_free);
char *info = nullptr;
hs_error_t err = hs_database_info(db, &info);
ASSERT_EQ(HS_BAD_ALLOC, err);
hs_set_misc_allocator(nullptr, nullptr);
hs_free_database(db);
}
TEST(CustomAllocator, TwoAlignedSerialize) {
hs_database_t *db = buildDB("foobar", 0, 0, HS_MODE_BLOCK);
ASSERT_TRUE(db != nullptr);
hs_set_misc_allocator(two_aligned_malloc, two_aligned_free);
char *bytes = nullptr;
size_t serialized_len = 0;
hs_error_t err = hs_serialize_database(db, &bytes, &serialized_len);
ASSERT_EQ(HS_BAD_ALLOC, err);
hs_set_misc_allocator(nullptr, nullptr);
hs_free_database(db);
}
TEST(CustomAllocator, TwoAlignedDeserialize) {
hs_database_t *db = buildDB("foobar", 0, 0, HS_MODE_BLOCK);
ASSERT_TRUE(db != nullptr);
char *bytes = nullptr;
size_t serialized_len = 0;
hs_error_t err = hs_serialize_database(db, &bytes, &serialized_len);
ASSERT_EQ(HS_SUCCESS, err);
ASSERT_NE(nullptr, bytes);
hs_free_database(db);
db = nullptr;
hs_set_database_allocator(two_aligned_malloc, two_aligned_free);
err = hs_deserialize_database(bytes, serialized_len, &db);
ASSERT_EQ(HS_BAD_ALLOC, err);
ASSERT_EQ(nullptr, db);
hs_set_database_allocator(nullptr, nullptr);
free(bytes);
}
TEST(CustomAllocator, TwoAlignedAllocScratch) {
hs_database_t *db = buildDB("foobar", 0, 0, HS_MODE_BLOCK);
ASSERT_TRUE(db != nullptr);
hs_set_scratch_allocator(two_aligned_malloc, two_aligned_free);
hs_scratch_t *scratch = nullptr;
hs_error_t err = hs_alloc_scratch(db, &scratch);
ASSERT_EQ(HS_BAD_ALLOC, err);
hs_set_scratch_allocator(nullptr, nullptr);
hs_free_database(db);
}
TEST(CustomAllocator, NullMallocExpressionInfo) {
hs_set_allocator(null_malloc, nullptr);
string pattern = "foobar";
hs_expr_info_t *info = nullptr;
hs_compile_error_t *c_err = nullptr;
hs_error_t err = hs_expression_info(pattern.c_str(), 0, &info, &c_err);
ASSERT_EQ(HS_COMPILER_ERROR, err);
ASSERT_NE(nullptr, c_err);
hs_free_compile_error(c_err);
hs_set_allocator(nullptr, nullptr);
}
TEST(CustomAllocator, TwoAlignedExpressionInfo) {
hs_set_misc_allocator(two_aligned_malloc, two_aligned_free);
string pattern = "\\1";
hs_expr_info_t *info = nullptr;
hs_compile_error_t *c_err = nullptr;
hs_error_t err = hs_expression_info(pattern.c_str(), 0, &info, &c_err);
ASSERT_EQ(HS_COMPILER_ERROR, err);
ASSERT_NE(nullptr, c_err);
EXPECT_STREQ("Allocator returned misaligned memory.", c_err->message);
hs_free_compile_error(c_err);
hs_set_allocator(nullptr, nullptr);
}
| 32.550505 | 80 | 0.729247 | jtravee |
40c6f54b09a261ce5d9cc090bf9027d6d8db7a07 | 2,333 | cpp | C++ | modules/largest-subseq/src/largest_subseq.cpp | gurylev-nikita/devtools-course-practice | bab6ba4e39f04940e27c9ac148505eb152c05d17 | [
"CC-BY-4.0"
] | null | null | null | modules/largest-subseq/src/largest_subseq.cpp | gurylev-nikita/devtools-course-practice | bab6ba4e39f04940e27c9ac148505eb152c05d17 | [
"CC-BY-4.0"
] | 3 | 2021-04-22T17:12:19.000Z | 2021-05-14T12:16:25.000Z | modules/largest-subseq/src/largest_subseq.cpp | taktaev-artyom/devtools-course-practice | 7cf19defe061c07cfb3ebb71579456e807430a5d | [
"CC-BY-4.0"
] | null | null | null | // Copyright 2021 Kirillov Konstantin
#include "include/largest_subseq.h"
#include <vector>
#include <limits>
#include <algorithm>
#include <string>
Sequential::Sequential(std::vector <int> seq)
:
m_seq(seq) {
}
std::vector<int> Sequential::findLargSubseqNlogN(std::vector <int> fSec) {
int n = fSec.size();
std::vector<int> d(n+1), pos(n+1), prev(n);
int length = 0;
pos[0] = -1;
d[0] = -std::numeric_limits<int>::max();
for (int i = 1; i < n+1; i ++) {
d[i] = std::numeric_limits<int>::max();
}
for (int i = 0; i < n; i++) {
int j = upper_bound(d.begin(), d.end(), fSec[i]) - d.begin();
if (d[j - 1] < fSec[i] && fSec[i] < d[j]) {
d[j] = fSec[i];
pos[j] = i;
prev[i] = pos[j - 1];
length = std::max(length, j);
}
}
std::vector<int> answer;
int i = pos[length];
if (length == 1) {
answer.push_back(fSec[0]);
} else {
while (i != -1) {
answer.push_back(fSec[i]);
i = prev[i];
}
}
std::reverse(answer.begin(), answer.end());
return answer;
}
std::vector<int> Sequential::findLargSubseqN2(std::vector <int> fSec) {
int n = fSec.size();
std::vector<int> d(n + 1), prev(n);
d[0] = -std::numeric_limits<int>::max();
for (int i = 0; i < n; i++) {
d[i] = 1;
prev[i] = -1;
for (int j = 0; j < i; j++) {
if (fSec[j] < fSec[i] && d[j] + 1 > d[i]) {
d[i] = d[j] + 1;
prev[i] = j;
}
}
}
std::vector<int> answer;
int pos = 0;
int length = d[0];
for (int i = 0; i < n; i++) {
if (d[i] > length) {
pos = i;
length = d[i];
}
}
if (length == 1) {
answer.push_back(fSec[0]);
} else {
while (pos != -1) {
answer.push_back(fSec[pos]);
pos = prev[pos];
}
}
std::reverse(answer.begin(), answer.end());
return answer;
}
std::vector<int> Sequential::getLargSubseq(std::string name) {
std::vector<int> answer;
if (name == "NlogN") {
answer = findLargSubseqNlogN(Sequential::m_seq);
} else if (name == "N2") {
answer = findLargSubseqN2(Sequential::m_seq);
}
return answer;
}
| 24.051546 | 74 | 0.474068 | gurylev-nikita |
40ca2c120728ebbe9e5be0b6a999262a9be1af5e | 7,215 | cpp | C++ | x3daudio1_7/xaudio2-hook/XAPO/HrtfEffect.cpp | kosumosu/x3daudio1_7_hrtf | 28cd541ee2cfee91f69b5099e202272d0710e4c8 | [
"Unlicense"
] | 239 | 2015-07-25T21:12:51.000Z | 2022-02-25T23:22:43.000Z | x3daudio1_7/xaudio2-hook/XAPO/HrtfEffect.cpp | kosumosu/x3daudio1_7_hrtf | 28cd541ee2cfee91f69b5099e202272d0710e4c8 | [
"Unlicense"
] | 28 | 2017-06-05T06:11:52.000Z | 2022-02-21T07:09:31.000Z | x3daudio1_7/xaudio2-hook/XAPO/HrtfEffect.cpp | kosumosu/x3daudio1_7_hrtf | 28cd541ee2cfee91f69b5099e202272d0710e4c8 | [
"Unlicense"
] | 25 | 2016-08-13T22:01:12.000Z | 2021-12-01T05:40:25.000Z | #include "stdafx.h"
#include "HrtfEffect.h"
#include "logger.h"
#include <algorithm>
#include <numeric>
#include <utility>
constexpr UINT32 OutputChannelCount = 2;
XAPO_REGISTRATION_PROPERTIES HrtfXapoEffect::_regProps = {
__uuidof(HrtfXapoEffect),
L"HRTF Effect",
L"Copyright (C)2015 Roman Zavalov",
1,
0,
XAPO_FLAG_FRAMERATE_MUST_MATCH
| XAPO_FLAG_BITSPERSAMPLE_MUST_MATCH
| XAPO_FLAG_BUFFERCOUNT_MUST_MATCH
| XAPO_FLAG_INPLACE_SUPPORTED,
1, 1, 1, 1 };
HrtfXapoEffect::HrtfXapoEffect(std::shared_ptr<IHrtfDataSet> hrtfData) :
CXAPOParametersBase(&_regProps, reinterpret_cast<BYTE*>(_params), sizeof(HrtfXapoParam), FALSE)
, _timePerFrame(0)
, _hrtfDataSet(std::move(hrtfData))
, _hrtfData(nullptr)
, _invalidBuffersCount(0)
, _buffersPerHistory(0)
, _historySize(0)
{
_params[0] = { };
_params[1] = { };
_params[2] = { };
_signal.reserve(192);
_hrtfDataLeft.impulse_response.reserve(128);
_hrtfDataRight.impulse_response.reserve(128);
}
HRESULT HrtfXapoEffect::LockForProcess(UINT32 InputLockedParameterCount, const XAPO_LOCKFORPROCESS_BUFFER_PARAMETERS * pInputLockedParameters, UINT32 OutputLockedParameterCount, const XAPO_LOCKFORPROCESS_BUFFER_PARAMETERS * pOutputLockedParameters)
{
_ASSERT(pInputLockedParameters[0].pFormat->nChannels == 1 || pInputLockedParameters[0].pFormat->nChannels == 2);
_ASSERT(pOutputLockedParameters[0].pFormat->nChannels == 2);
const HRESULT hr = CXAPOParametersBase::LockForProcess(
InputLockedParameterCount,
pInputLockedParameters,
OutputLockedParameterCount,
pOutputLockedParameters);
if (SUCCEEDED(hr))
{
memcpy(&_inputFormat, pInputLockedParameters[0].pFormat, sizeof(_inputFormat));
memcpy(&_outputFormat, pOutputLockedParameters[0].pFormat, sizeof(_outputFormat));
_timePerFrame = 1.0f / float(_inputFormat.nSamplesPerSec);
//_ASSERT(_hrtf_data_set->has_sample_rate(_input_format.nSamplesPerSec));
if (_hrtfDataSet->HasSampleRate(_inputFormat.nSamplesPerSec))
{
_hrtfData = &_hrtfDataSet->GetSampleRateData(_inputFormat.nSamplesPerSec);
_historySize = _hrtfData->GetLongestDelay() + _hrtfData->GetResponseLength();
_buffersPerHistory = _historySize / (pInputLockedParameters[0].MaxFrameCount + _historySize - 1);
_invalidBuffersCount = _buffersPerHistory;
_signal.resize(_historySize + pInputLockedParameters[0].MaxFrameCount);
std::fill(std::begin(_signal), std::begin(_signal) + _historySize, 0.0f);
}
else
{
logger::logRelease("ERROR [HRTF]: There's no dataset for sample rate ", _inputFormat.nSamplesPerSec, " Hz");
_hrtfData = nullptr;
}
}
return hr;
}
void HrtfXapoEffect::ProcessValidBuffer(const float * pInput, float * pOutput, const UINT32 frameCount, const HrtfXapoParam & params)
{
const float volume = params.VolumeMultiplier;
if (_inputFormat.nChannels == 1)
{
std::transform(pInput, pInput + frameCount, std::begin(_signal) + _historySize, [=](float value) { return value * volume; });
}
else if (_inputFormat.nChannels == 2)
{
for (UINT32 i = 0; i < frameCount; i++)
{
_signal[i + _historySize] = (pInput[i * 2 + 0] + pInput[i * 2 + 1]) * volume;
}
}
for (UINT32 i = 0; i < frameCount; i++)
{
ProcessFrame(pOutput[i * OutputChannelCount + 0], pOutput[i * OutputChannelCount + 1], i);
}
std::copy(std::end(_signal) - _historySize, std::end(_signal), std::begin(_signal));
_invalidBuffersCount = 0;
}
void HrtfXapoEffect::ProcessInvalidBuffer(float * pOutput, const UINT32 framesToWriteCount, UINT32 & validFramesCounter, const HrtfXapoParam & params)
{
std::fill(std::begin(_signal) + _historySize, std::end(_signal), 0.0f);
for (UINT32 i = 0; i < framesToWriteCount; i++)
{
ProcessFrame(pOutput[i * OutputChannelCount + 0], pOutput[i * OutputChannelCount + 1], i);
}
validFramesCounter = framesToWriteCount;
std::copy(std::end(_signal) - _historySize, std::end(_signal), std::begin(_signal));
_invalidBuffersCount++;
}
void HrtfXapoEffect::Bypass(const float * pInput, float * pOutput, const UINT32 frameCount, const bool isInputValid)
{
const bool inPlace = (pInput == pOutput);
if (isInputValid)
{
if (_inputFormat.nChannels == 1)
{
for (UINT32 i = 0; i < frameCount; i++)
{
pOutput[i * OutputChannelCount + 0] = pInput[i];
pOutput[i * OutputChannelCount + 1] = pInput[i];
}
}
else if (_inputFormat.nChannels == 2)
{
if (!inPlace)
{
for (UINT32 i = 0; i < frameCount; i++)
{
pOutput[i * OutputChannelCount + 0] = pInput[i * 2 + 0];
pOutput[i * OutputChannelCount + 1] = pInput[i * 2 + 1];
}
}
}
}
}
void HrtfXapoEffect::Convolve(const UINT32 frameIndex, DirectionData& hrtfData, float& output)
{
const int startSignalIndex = _historySize + frameIndex - static_cast<int>(hrtfData.delay);
_ASSERT(static_cast<int>(startSignalIndex) - static_cast<int>(hrtfData.impulse_response.size()) >= 0);
output = std::transform_reduce(std::begin(_signal) + startSignalIndex - hrtfData.impulse_response.size(), std::begin(_signal) + startSignalIndex, std::begin(hrtfData.impulse_response), 0.0f);
}
void HrtfXapoEffect::ProcessFrame(float& leftOutput, float& rightOutput, const UINT32 frameIndex)
{
Convolve(frameIndex, _hrtfDataLeft, leftOutput);
Convolve(frameIndex, _hrtfDataRight, rightOutput);
}
void HrtfXapoEffect::Process(UINT32 InputProcessParameterCount, const XAPO_PROCESS_BUFFER_PARAMETERS * pInputProcessParameters, UINT32 OutputProcessParameterCount, XAPO_PROCESS_BUFFER_PARAMETERS * pOutputProcessParameters, BOOL IsEnabled)
{
_ASSERT(IsLocked());
_ASSERT(InputProcessParameterCount == 1);
_ASSERT(OutputProcessParameterCount == 1);
const UINT32 inputFrameCount = pInputProcessParameters[0].ValidFrameCount;
const UINT32 framesToWriteCount = pOutputProcessParameters[0].ValidFrameCount;
const auto pInput = reinterpret_cast<const float*>(pInputProcessParameters[0].pBuffer);
const auto pOutput = reinterpret_cast<float*>(pOutputProcessParameters[0].pBuffer);
const bool isInputValid = pInputProcessParameters[0].BufferFlags == XAPO_BUFFER_VALID;
const auto params = reinterpret_cast<const HrtfXapoParam *>(BeginProcess());
if (IsEnabled && _hrtfData != nullptr)
{
_hrtfData->GetDirectionData(params->Elevation, params->Azimuth, params->Distance, _hrtfDataLeft, _hrtfDataRight);
if (isInputValid)
{
pOutputProcessParameters[0].BufferFlags = XAPO_BUFFER_VALID;
pOutputProcessParameters[0].ValidFrameCount = inputFrameCount;
ProcessValidBuffer(pInput, pOutput, inputFrameCount, *params);
}
else if (HasHistory())
{
UINT32 validFramesCounter;
ProcessInvalidBuffer(pOutput, framesToWriteCount, validFramesCounter, *params);
pOutputProcessParameters[0].BufferFlags = XAPO_BUFFER_VALID;
pOutputProcessParameters[0].ValidFrameCount = validFramesCounter;
}
else
{
pOutputProcessParameters[0].BufferFlags = XAPO_BUFFER_SILENT;
}
}
else
{
pOutputProcessParameters[0].BufferFlags = pInputProcessParameters[0].BufferFlags;
pOutputProcessParameters[0].ValidFrameCount = pInputProcessParameters[0].ValidFrameCount;
Bypass(pInput, pOutput, inputFrameCount, isInputValid);
}
EndProcess();
}
bool HrtfXapoEffect::HasHistory() const
{
return _invalidBuffersCount < _buffersPerHistory;
}
| 33.873239 | 248 | 0.752737 | kosumosu |
40cb83bb7071f5999098b4efb86f0ebc364d9363 | 10,204 | hpp | C++ | include/optimizer.hpp | lefticus/x86-to-6502 | 165c63701a7af0a1302dfa7c6415b7d8524b922d | [
"Unlicense"
] | 200 | 2016-07-07T14:25:14.000Z | 2021-05-04T15:54:57.000Z | include/optimizer.hpp | lefticus/6502-cpp | 165c63701a7af0a1302dfa7c6415b7d8524b922d | [
"Unlicense"
] | 8 | 2016-07-13T01:33:28.000Z | 2018-10-02T15:51:07.000Z | include/optimizer.hpp | lefticus/x86-to-6502 | 165c63701a7af0a1302dfa7c6415b7d8524b922d | [
"Unlicense"
] | 28 | 2016-10-01T18:28:51.000Z | 2021-01-25T16:49:58.000Z | #ifndef INC_6502_CPP_OPTIMIZER_HPP
#define INC_6502_CPP_OPTIMIZER_HPP
#include "6502.hpp"
#include "personality.hpp"
#include <span>
#include <vector>
constexpr bool consume_directives(auto &begin, const auto &end)
{
if (begin != end && begin->type == ASMLine::Type::Directive) {
++begin;
return true;
}
return false;
}
constexpr bool consume_labels(auto &begin, const auto &end)
{
if (begin != end && begin->type == ASMLine::Type::Label) {
++begin;
return true;
}
return false;
}
constexpr bool is_opcode(const mos6502 &op, const auto... opcodes) { return ((op.opcode == opcodes) || ...); }
constexpr bool is_end_of_block(const auto &begin)
{
if (begin->text.ends_with("__optimizable") || begin->op.value.ends_with("__optimizable")) {
return false;
}
if (begin->type == ASMLine::Type::Label) { return true; }
return is_opcode(*begin,
mos6502::OpCode::jsr,
mos6502::OpCode::jmp,
mos6502::OpCode::bcc,
mos6502::OpCode::bcs,
mos6502::OpCode::beq,
mos6502::OpCode::bne,
mos6502::OpCode::bpl);
}
constexpr bool consume_end_of_block(auto &begin, const auto &end)
{
if (begin != end && is_end_of_block(begin)) {
++begin;
return true;
}
return false;
}
static std::vector<std::span<mos6502>> get_optimizable_blocks(std::vector<mos6502> &statements)
{
std::vector<std::span<mos6502>> blocks;
auto begin = std::begin(statements);
auto end = std::end(statements);
const auto find_end_of_block = [](auto &find_begin, const auto &find_end) {
while (find_begin != find_end) {
if (is_end_of_block(find_begin)) { return; }
++find_begin;
}
};
while (begin != end) {
while (consume_end_of_block(begin, end) || consume_directives(begin, end) || consume_labels(begin, end)) {}
const auto block_start = begin;
find_end_of_block(begin, end);
blocks.emplace_back(block_start, begin);
}
return blocks;
}
static bool is_virtual_register_op(const mos6502 &op, const Personality &personality)
{
for (int i = 0; i < 32; ++i) {
if (personality.get_register(i).value == op.op.value) { return true; }
}
return false;
}
static bool optimize_dead_tax(std::span<mos6502> &block)
{
for (auto itr = block.begin(); itr != block.end(); ++itr) {
if (is_opcode(*itr, mos6502::OpCode::tax, mos6502::OpCode::tsx, mos6502::OpCode::ldx)) {
for (auto inner = std::next(itr); inner != block.end(); ++inner) {
if (is_opcode(*inner,
mos6502::OpCode::txa,
mos6502::OpCode::txs,
mos6502::OpCode::stx,
mos6502::OpCode::inx,
mos6502::OpCode::dex,
mos6502::OpCode::cpx)) {
break;
}
if (is_opcode(*inner, mos6502::OpCode::tax, mos6502::OpCode::tsx, mos6502::OpCode::ldx)) {
// redundant store found
*itr = mos6502(ASMLine::Type::Directive, "; removed dead load of X: " + itr->to_string());
return true;
}
}
}
}
return false;
}
bool optimize_dead_sta(std::span<mos6502> &block, const Personality &personality)
{
for (auto itr = block.begin(); itr != block.end(); ++itr) {
if (itr->opcode == mos6502::OpCode::sta && is_virtual_register_op(*itr, personality)) {
for (auto inner = std::next(itr); inner != block.end(); ++inner) {
if (not inner->op.value.starts_with("#<(") && inner->op.value.find('(') != std::string::npos) {
// this is an indexed operation, which is risky to optimize a sta around on the virtual registers,
// so we'll skip this block
break;
}
if (inner->op.value == itr->op.value) {
if (is_opcode(*inner, mos6502::OpCode::sta)) {
// redundant store found
*itr = mos6502(ASMLine::Type::Directive, "; removed dead store of a: " + itr->to_string());
return true;
} else {
// someone else is operating on us, time to abort
break;
}
}
}
}
}
return false;
}
bool optimize_redundant_ldy(std::span<mos6502> &block)
{
for (auto itr = block.begin(); itr != block.end(); ++itr) {
if (itr->opcode == mos6502::OpCode::ldy && itr->op.value.starts_with('#')) {
for (auto inner = std::next(itr); inner != block.end(); ++inner) {
if (is_opcode(*inner,
mos6502::OpCode::cpy,
mos6502::OpCode::tya,
mos6502::OpCode::tay,
mos6502::OpCode::sty,
mos6502::OpCode::iny,
mos6502::OpCode::dey)) {
break;// break, these all operate on Y
}
// we found a matching ldy
if (is_opcode(*inner, mos6502::OpCode::ldy)) {
// with the same value
// note: this operation is only safe because we know that our system only uses Y
// for index operations and we don't rely (or even necessarily *want* the changes to N,Z)
if (inner->op.value == itr->op.value) {
*inner = mos6502(ASMLine::Type::Directive, "; removed redundant ldy: " + inner->to_string());
return true;
} else {
break;
}
}
}
}
}
return false;
}
bool optimize_redundant_lda(std::span<mos6502> &block, const Personality &personality)
{
// look for a literal or virtual register load into A
// that is redundant later
for (auto itr = block.begin(); itr != block.end(); ++itr) {
if (itr->opcode == mos6502::OpCode::lda
&& (itr->op.value.starts_with('#') || is_virtual_register_op(*itr, personality))) {
for (auto inner = std::next(itr); inner != block.end(); ++inner) {
if (is_opcode(*inner,
mos6502::OpCode::tay,
mos6502::OpCode::tax,
mos6502::OpCode::sta,
mos6502::OpCode::pha,
mos6502::OpCode::nop)) {
continue;// OK to skip instructions that don't modify A or change flags
}
if (inner->type == ASMLine::Type::Directive) {
continue;// OK to skip directives
}
if (is_opcode(*inner, mos6502::OpCode::lda)) {
if (inner->op == itr->op) {
// we found a matching lda, after an sta, we can remove it
*inner = mos6502(ASMLine::Type::Directive, "; removed redundant lda: " + inner->to_string());
return true;
} else {
break;
}
}
break;// we can only optimize around tax and comments right now
}
}
}
return false;
}
bool optimize_redundant_lda_after_sta(std::span<mos6502> &block)
{
for (auto itr = block.begin(); itr != block.end(); ++itr) {
if (itr->opcode == mos6502::OpCode::sta) {
for (auto inner = std::next(itr); inner != block.end(); ++inner) {
if (is_opcode(*inner,
mos6502::OpCode::tax,
mos6502::OpCode::tay,
mos6502::OpCode::clc,
mos6502::OpCode::sec,
mos6502::OpCode::sta,
mos6502::OpCode::pha,
mos6502::OpCode::txs,
mos6502::OpCode::php,
mos6502::OpCode::sty,
mos6502::OpCode::nop)) {
continue;// OK to skip instructions that don't modify A or change flags
}
if (inner->type == ASMLine::Type::Directive) {
continue;// OK to skip directives
}
if (is_opcode(*inner, mos6502::OpCode::lda)) {
if (inner->op == itr->op) {
// we found a matching lda, after a sta, we can remove it
*inner = mos6502(ASMLine::Type::Directive, "; removed redundant lda: " + inner->to_string());
return true;
} else {
break;
}
}
break;// we can only optimize around tax and comments right now
}
}
}
return false;
}
bool optimize(std::vector<mos6502> &instructions, [[maybe_unused]] const Personality &personality)
{
// remove unused flag-fix-up blocks
// it might make sense in the future to only insert these if determined they are needed?
for (size_t op = 10; op < instructions.size(); ++op) {
if (instructions[op].opcode == mos6502::OpCode::lda || instructions[op].opcode == mos6502::OpCode::bcc
|| instructions[op].opcode == mos6502::OpCode::bcs || instructions[op].opcode == mos6502::OpCode::ldy
|| instructions[op].opcode == mos6502::OpCode::inc || instructions[op].opcode == mos6502::OpCode::clc
|| instructions[op].opcode == mos6502::OpCode::sec || instructions[op].text.starts_with("; Handle N / S")) {
if (instructions[op - 1].text == "; END remove if next is lda, bcc, bcs, ldy, inc, clc, sec"
|| (instructions[op - 2].text == "; END remove if next is lda, bcc, bcs, ldy, inc, clc, sec"
&& instructions[op - 1].type == ASMLine::Type::Directive)) {
for (size_t inner_op = op - 1; inner_op > 1; --inner_op) {
instructions[inner_op] =
mos6502(ASMLine::Type::Directive, "; removed unused flag fix-up: " + instructions[inner_op].to_string());
if (instructions[inner_op].text.find("; BEGIN") != std::string::npos) { return true; }
}
}
}
}
// replace use of __zero_reg__ with literal 0
for (auto &op : instructions) {
if (op.type == ASMLine::Type::Instruction && op.op.type == Operand::Type::literal
&& op.op.value == personality.get_register(1).value && op.opcode != mos6502::OpCode::sta) {
// replace use of zero reg with literal 0
const auto old_string = op.to_string();
op.op.value = "#0";
op.comment = "replaced use of register 1 with a literal 0, because of AVR GCC __zero_reg__ ; " + old_string;
}
}
bool optimizer_run = false;
for (auto &block : get_optimizable_blocks(instructions)) {
const bool block_optimized = optimize_redundant_lda_after_sta(block)
|| optimize_dead_sta(block, personality) || optimize_dead_tax(block)
|| optimize_redundant_ldy(block) || optimize_redundant_lda(block, personality);
optimizer_run = optimizer_run || block_optimized;
}
return optimizer_run;
}
#endif// INC_6502_CPP_OPTIMIZER_HPP
| 33.788079 | 117 | 0.588887 | lefticus |
40cdafcb3b49a493545e423051ddbe81f6f708d1 | 11,392 | cc | C++ | flare/base/net/endpoint.cc | AriCheng/flare | b2c84588fe4ac52f0875791d22284d7e063fd057 | [
"CC-BY-3.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | 868 | 2021-05-28T04:00:22.000Z | 2022-03-31T08:57:14.000Z | flare/base/net/endpoint.cc | AriCheng/flare | b2c84588fe4ac52f0875791d22284d7e063fd057 | [
"CC-BY-3.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | 33 | 2021-05-28T08:44:47.000Z | 2021-09-26T13:09:21.000Z | flare/base/net/endpoint.cc | AriCheng/flare | b2c84588fe4ac52f0875791d22284d7e063fd057 | [
"CC-BY-3.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | 122 | 2021-05-28T08:22:23.000Z | 2022-03-29T09:52:09.000Z | // Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the
// License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
#include "flare/base/net/endpoint.h"
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <linux/if_packet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "flare/base/string.h"
using namespace std::literals;
namespace flare {
namespace {
std::string SockAddrToString(const sockaddr* addr) {
static constexpr auto kPortChars = 6; // ":12345"
auto af = addr->sa_family;
switch (af) {
case AF_INET: {
std::string result;
auto p = reinterpret_cast<const sockaddr_in*>(addr);
result.resize(INET_ADDRSTRLEN + kPortChars + 1 /* '\x00' */);
FLARE_CHECK(inet_ntop(af, &p->sin_addr, result.data(), result.size()));
auto ptr = result.data() + result.find('\x00');
*ptr++ = ':';
snprintf(ptr, kPortChars, "%d", ntohs(p->sin_port));
result.resize(result.find('\x00'));
return result;
}
case AF_INET6: {
std::string result;
auto p = reinterpret_cast<const sockaddr_in6*>(addr);
result.resize(INET6_ADDRSTRLEN + 2 /* "[]" */ + kPortChars +
1 /* '\x00' */);
result[0] = '[';
FLARE_CHECK(
inet_ntop(af, &p->sin6_addr, result.data() + 1, result.size()));
auto ptr = result.data() + result.find('\x00');
*ptr++ = ']';
*ptr++ = ':';
snprintf(ptr, kPortChars, "%d", ntohs(p->sin6_port));
result.resize(result.find('\x00'));
return result;
}
case AF_UNIX: {
auto p = reinterpret_cast<const sockaddr_un*>(addr);
if (p->sun_path[0] == '\0' && p->sun_path[1] != '\0') {
return "@"s + &p->sun_path[1];
} else {
return p->sun_path;
}
}
default: {
return Format("TODO: Endpoint::ToString() for AF #{}.", af);
}
}
}
} // namespace
#define INTERNAL_PTR() (*reinterpret_cast<sockaddr_storage**>(&storage_))
#define INTERNAL_CPTR() (*reinterpret_cast<sockaddr_storage* const*>(&storage_))
sockaddr* EndpointRetriever::RetrieveAddr() {
return reinterpret_cast<sockaddr*>(&storage_);
}
socklen_t* EndpointRetriever::RetrieveLength() { return &length_; }
Endpoint EndpointRetriever::Build() {
return Endpoint(RetrieveAddr(), length_);
}
Endpoint::Endpoint(const sockaddr* addr, socklen_t len) : length_(len) {
if (length_ <= kOptimizedSize) {
memcpy(&storage_, addr, length_);
} else {
INTERNAL_PTR() = new sockaddr_storage;
memcpy(INTERNAL_PTR(), addr, length_);
}
}
void Endpoint::SlowDestroy() { delete INTERNAL_PTR(); }
void Endpoint::SlowCopyUninitialized(const Endpoint& ep) {
length_ = ep.Length();
INTERNAL_PTR() = new sockaddr_storage;
memcpy(INTERNAL_PTR(), ep.Get(), length_);
}
void Endpoint::SlowCopy(const Endpoint& ep) {
if (!IsTriviallyCopyable()) {
SlowDestroy();
}
if (ep.IsTriviallyCopyable()) {
length_ = ep.length_;
memcpy(&storage_, &ep.storage_, length_);
} else {
length_ = ep.length_;
INTERNAL_PTR() = new sockaddr_storage;
memcpy(INTERNAL_PTR(), ep.Get(), length_);
}
}
const sockaddr* Endpoint::SlowGet() const {
return reinterpret_cast<const sockaddr*>(INTERNAL_CPTR());
}
std::string Endpoint::ToString() const {
if (FLARE_UNLIKELY(Empty())) {
// We don't want to `CHECK(0)` here. Checking if the endpoint is initialized
// before calling `ToString()` each time is way too complicated.
return "(null)";
}
return SockAddrToString(Get());
}
bool operator==(const Endpoint& left, const Endpoint& right) {
return memcmp(left.Get(), right.Get(), left.Length()) == 0;
}
Endpoint EndpointFromIpv4(const std::string& ip, std::uint16_t port) {
EndpointRetriever er;
auto addr = er.RetrieveAddr();
auto p = reinterpret_cast<sockaddr_in*>(addr);
memset(p, 0, sizeof(sockaddr_in));
FLARE_PCHECK(inet_pton(AF_INET, ip.c_str(), &p->sin_addr),
"Cannot parse [{}].", ip);
p->sin_port = htons(port);
p->sin_family = AF_INET;
*er.RetrieveLength() = sizeof(sockaddr_in);
return er.Build();
}
Endpoint EndpointFromIpv6(const std::string& ip, std::uint16_t port) {
EndpointRetriever er;
auto addr = er.RetrieveAddr();
auto p = reinterpret_cast<sockaddr_in6*>(addr);
memset(p, 0, sizeof(sockaddr_in6));
FLARE_PCHECK(inet_pton(AF_INET6, ip.c_str(), &p->sin6_addr),
"Cannot parse [{}].", ip);
p->sin6_port = htons(port);
p->sin6_family = AF_INET6;
*er.RetrieveLength() = sizeof(sockaddr_in6);
return er.Build();
}
std::string EndpointGetIp(const Endpoint& endpoint) {
std::string result;
if (endpoint.Family() == AF_INET) {
result.resize(INET_ADDRSTRLEN + 1 /* '\x00' */);
FLARE_CHECK(inet_ntop(endpoint.Family(),
&endpoint.UnsafeGet<sockaddr_in>()->sin_addr,
result.data(), result.size()));
} else if (endpoint.Family() == AF_INET6) {
result.resize(INET6_ADDRSTRLEN + 1 /* '\x00' */);
FLARE_CHECK(inet_ntop(endpoint.Family(),
&endpoint.UnsafeGet<sockaddr_in6>()->sin6_addr,
result.data(), result.size()));
} else {
FLARE_CHECK(
0, "Unexpected: Address family #{} is not a valid IP address family.",
endpoint.Family());
}
return result.substr(0, result.find('\x00'));
}
std::uint16_t EndpointGetPort(const Endpoint& endpoint) {
FLARE_CHECK(
endpoint.Family() == AF_INET || endpoint.Family() == AF_INET6,
"Unexpected: Address family #{} is not a valid IP address family.",
endpoint.Family());
if (endpoint.Family() == AF_INET) {
return ntohs(
reinterpret_cast<const sockaddr_in*>(endpoint.Get())->sin_port);
} else if (endpoint.Family() == AF_INET6) {
return ntohs(
reinterpret_cast<const sockaddr_in6*>(endpoint.Get())->sin6_port);
}
FLARE_UNREACHABLE();
}
std::vector<Endpoint> GetInterfaceAddresses() {
ifaddrs* ifs_raw;
FLARE_PCHECK(getifaddrs(&ifs_raw) == 0, "Cannot enumerate NICs.");
std::unique_ptr<ifaddrs, decltype(&freeifaddrs)> ifs(ifs_raw, &freeifaddrs);
std::vector<Endpoint> result;
for (auto current = ifs.get(); current; current = current->ifa_next) {
EndpointRetriever er;
auto addr = current->ifa_addr;
if (!addr) {
FLARE_LOG_WARNING_ONCE(
"Skipping device [{}] when enumerating interface addresses. No "
"address is assigned to this device.",
current->ifa_name);
continue;
}
auto af = addr->sa_family;
#define TEST_AF_AND_COPY(AddressFamily, Storage) \
case AddressFamily: { \
memcpy(er.RetrieveAddr(), addr, sizeof(Storage)); \
*er.RetrieveLength() = sizeof(Storage); \
break; \
}
switch (af) {
TEST_AF_AND_COPY(AF_INET, sockaddr_in)
TEST_AF_AND_COPY(AF_INET6, sockaddr_in6)
TEST_AF_AND_COPY(AF_UNIX, sockaddr_un)
case AF_PACKET: {
continue; // Ignored.
}
default: {
FLARE_LOG_WARNING_ONCE("Unrecognized address family #{} is ignored.",
af);
continue;
}
#undef TEST_AF_AND_COPY
}
result.push_back(er.Build());
}
return result;
}
bool IsPrivateIpv4AddressRfc(const Endpoint& addr) {
constexpr std::pair<std::uint32_t, std::uint32_t> kRanges[] = {
{0xFF000000, 0x0A000000}, // 10.0.0.0/8
{0xFFF00000, 0xAC100000}, // 172.16.0.0/12
{0xFFFF0000, 0xC0A80000}, // 192.168.0.0/16
};
if (addr.Family() != AF_INET) {
return false;
}
auto ip = ntohl(addr.UnsafeGet<sockaddr_in>()->sin_addr.s_addr);
for (auto&& [mask, expected] : kRanges) {
if ((ip & mask) == expected) {
return true;
}
}
return false;
}
bool IsPrivateIpv4AddressCorp(const Endpoint& addr) {
constexpr std::pair<std::uint32_t, std::uint32_t> kRanges[] = {
{0xFF000000, 0x0A000000}, // 10.0.0.0/8
{0xFFC00000, 0x64400000}, // 100.64.0.0/10
{0xFFF00000, 0xAC100000}, // 172.16.0.0/12
{0xFFFF0000, 0xC0A80000}, // 192.168.0.0/16
{0xFF000000, 0x09000000}, // 9.0.0.0/8
{0xFF000000, 0x0B000000}, // 11.0.0.0/8
{0xFF000000, 0x1E000000}, // 30.0.0.0/8
};
if (addr.Family() != AF_INET) {
return false;
}
auto ip = ntohl(addr.UnsafeGet<sockaddr_in>()->sin_addr.s_addr);
for (auto&& [mask, expected] : kRanges) {
if ((ip & mask) == expected) {
return true;
}
}
return false;
}
bool IsGuaIpv6Address(const Endpoint& addr) {
if (addr.Family() != AF_INET6) {
return false;
}
auto v6 = addr.UnsafeGet<sockaddr_in6>()->sin6_addr;
// 2000::/3
return v6.s6_addr[0] >= 0x20 && v6.s6_addr[0] <= 0x3f;
}
std::ostream& operator<<(std::ostream& os, const Endpoint& endpoint) {
return os << endpoint.ToString();
}
std::optional<Endpoint> TryParseTraits<Endpoint>::TryParse(std::string_view s,
from_ipv4_t) {
auto pos = s.find(':');
if (pos == std::string_view::npos) {
return {};
}
auto ip = std::string(s.substr(0, pos));
auto port = flare::TryParse<std::uint16_t>(s.substr(pos + 1));
if (!port) {
return {};
}
EndpointRetriever er;
auto addr = er.RetrieveAddr();
auto p = reinterpret_cast<sockaddr_in*>(addr);
memset(p, 0, sizeof(sockaddr_in));
if (inet_pton(AF_INET, ip.c_str(), &p->sin_addr) != 1) {
return {};
}
p->sin_port = htons(*port);
p->sin_family = AF_INET;
*er.RetrieveLength() = sizeof(sockaddr_in);
return er.Build();
}
std::optional<Endpoint> TryParseTraits<Endpoint>::TryParse(std::string_view s,
from_ipv6_t) {
auto pos = s.find_last_of(':');
if (pos == std::string_view::npos) {
return {};
}
if (pos < 2) {
return {};
}
auto ip = std::string(s.substr(1, pos - 2));
auto port = flare::TryParse<std::uint16_t>(s.substr(pos + 1));
if (!port) {
return {};
}
EndpointRetriever er;
auto addr = er.RetrieveAddr();
auto p = reinterpret_cast<sockaddr_in6*>(addr);
memset(p, 0, sizeof(sockaddr_in6));
if (inet_pton(AF_INET6, ip.c_str(), &p->sin6_addr) != 1) {
return {};
}
p->sin6_port = htons(*port);
p->sin6_family = AF_INET6;
*er.RetrieveLength() = sizeof(sockaddr_in6);
return er.Build();
}
std::optional<Endpoint> TryParseTraits<Endpoint>::TryParse(std::string_view s) {
if (auto opt = TryParse(s, from_ipv4)) {
return opt;
} else {
return TryParse(s, from_ipv6);
}
}
Endpoint EndpointFromString(const std::string& ip_port) {
auto opt = TryParse<Endpoint>(ip_port);
FLARE_CHECK(!!opt, "Cannot parse endpoint [{}].", ip_port);
return *opt;
}
} // namespace flare
| 30.378667 | 80 | 0.62658 | AriCheng |
40d027beb002931d2e47bc43e282154a2a0755be | 2,050 | cpp | C++ | Sudoku/Solvers/C++/Dynamic/alg06d/dynamic6.cpp | oddbear/Algorithms | f229be3e96899def1f662d0c8a16955097b8acea | [
"MIT"
] | null | null | null | Sudoku/Solvers/C++/Dynamic/alg06d/dynamic6.cpp | oddbear/Algorithms | f229be3e96899def1f662d0c8a16955097b8acea | [
"MIT"
] | null | null | null | Sudoku/Solvers/C++/Dynamic/alg06d/dynamic6.cpp | oddbear/Algorithms | f229be3e96899def1f662d0c8a16955097b8acea | [
"MIT"
] | null | null | null | /*
* A version that does support dynamic sizes of the board.
*/
#include "dynamic6.h"
using namespace std;
namespace d6
{
int LWIDTH;
int LHEIGHT;
int COLUMNS;
int SIZE;
int FindUsedForLocal(int n, int s[]);
bool find_solution(int n, int s[]);
void find_solution(int arr[], int x, int y)
{
LWIDTH = x;
LHEIGHT = y;
COLUMNS = LWIDTH * LHEIGHT;
SIZE = COLUMNS * COLUMNS;
find_solution(0, arr);
}
bool find_solution(int n, int s[])
{
for (; n < SIZE && s[n] != 0; n++) ; //Skips those who already has values.
if (n == SIZE) return true; //solution found, if compiled with false, it will do all posible combinations.
int brukt = FindUsedForLocal(n, s); //Find all posible values to try.
for (int i = 1; i <= COLUMNS; i++)
if ((brukt & (1 << i)) == 0) //Checks if value(i) is a posible,
{ // 0 means that it is not a conflict on x, y or g, and might be a posibility.
s[n] = i; //Sets i as a posbile.
if (find_solution(n + 1, s)) //Tries next position.
return true; //if solution is found, don't do more work.
}
s[n] = 0; //None of the posibles worked. Resets the value.
return false; //solution not found, yet.
}
int FindUsedForLocal(int n, int s[])
{
int local_x = n % COLUMNS; //Finds the first position in the y axis.
int local_y = n / COLUMNS;
int start_y = local_y * COLUMNS; //Finds the first position in the x axis.
int anchor = n //Finds the first position in the group.
- local_x % LWIDTH
- (local_y % LHEIGHT) * COLUMNS;
int brukt = 0;
for (int i = 0; i < COLUMNS; i++) //Test all x, y and group values,
{ // does not mather if it also checks the value in the n position.
brukt |= 1 << s[start_y + i]; //Gather info from the y axis.
brukt |= 1 << s[i * COLUMNS + local_x]; //Gather info from the x axis.
brukt |= 1 << s[ //Gather info from the group.
anchor
+ (i / LWIDTH) * COLUMNS
+ (i % LWIDTH)
];
}
return brukt; //Returns all the values it cannot be. All not set is a posiblity.
}
}
| 27.333333 | 109 | 0.616098 | oddbear |
40d6b2c4987daea6ad6b94ba5ff9a370eeeb5100 | 53 | cpp | C++ | msvc/gloop/dummy.cpp | practisebody/gloop | ff34fb821fc8d35b29d831ba2fcce430b09095f8 | [
"MIT"
] | null | null | null | msvc/gloop/dummy.cpp | practisebody/gloop | ff34fb821fc8d35b29d831ba2fcce430b09095f8 | [
"MIT"
] | null | null | null | msvc/gloop/dummy.cpp | practisebody/gloop | ff34fb821fc8d35b29d831ba2fcce430b09095f8 | [
"MIT"
] | null | null | null | #include <gloop/gloop.hpp>
int main()
{
return 0;
} | 8.833333 | 26 | 0.641509 | practisebody |
40dbbf8cf248e09243532432f140e226da93f8fa | 1,167 | cc | C++ | src/RTT_Format_Reader/Flags.cc | keadyk/Draco | 129fbff1d74a3f5498670e952b7d4142f37b2aac | [
"BSD-3-Clause-Open-MPI"
] | 1 | 2020-03-19T07:05:08.000Z | 2020-03-19T07:05:08.000Z | src/RTT_Format_Reader/Flags.cc | 5l1v3r1/Draco | 0480d4c7c1ff7f40e0aece3be785dc0e4e23ece1 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | src/RTT_Format_Reader/Flags.cc | 5l1v3r1/Draco | 0480d4c7c1ff7f40e0aece3be785dc0e4e23ece1 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | //----------------------------------*-C++-*--------------------------------//
/*!
* \file RTT_Format_Reader/Flags.cc
* \author B.T. Adams
* \date Wed Jun 7 10:33:26 2000
* \brief Implementation file for RTT_Format_Reader/Flags class.
* \note Copyright (C) 2016-2020 Triad National Security, LLC.
* All rights reserved. */
//----------------------------------------------------------------------------//
#include "Flags.hh"
namespace rtt_RTT_Format_Reader {
//----------------------------------------------------------------------------//
/*!
* \brief Used by the NodeFlags, SideFlags, and CellFlags class objects to
* parse the flag numbers and names.
* \param meshfile Mesh file name.
*/
void Flags::readFlags(ifstream &meshfile) {
string dummyString;
for (size_t i = 0; i < nflags; ++i) {
meshfile >> flag_nums[i] >> flag_names[i];
std::getline(meshfile, dummyString);
}
}
} // end namespace rtt_RTT_Format_Reader
//----------------------------------------------------------------------------//
// end of RTT_Format_Reader/Flags.cc
//----------------------------------------------------------------------------//
| 33.342857 | 80 | 0.448158 | keadyk |
40de6017e3bbbbd1d28fa1b4ef4fb338beb91475 | 410 | cpp | C++ | Problems/Problem_005/main.cpp | AriaaRy/Project-Euler | 6d40f9e0b2ea877773bfef3370d39858a0c13e85 | [
"MIT"
] | 2 | 2020-09-11T17:17:46.000Z | 2020-11-19T05:29:20.000Z | Problems/Problem_005/main.cpp | AriaaRy/Project-Euler | 6d40f9e0b2ea877773bfef3370d39858a0c13e85 | [
"MIT"
] | null | null | null | Problems/Problem_005/main.cpp | AriaaRy/Project-Euler | 6d40f9e0b2ea877773bfef3370d39858a0c13e85 | [
"MIT"
] | 1 | 2020-09-23T18:44:07.000Z | 2020-09-23T18:44:07.000Z | #include <iostream>
int main() {
int range = 20;
long number = 1;
while(true) {
bool isMine = true;
for (int i = 1; i <= range; i++) {
if (number % i) {
isMine = false;
break;
}
}
if (isMine) {
std::cout << number << std::endl;
break;
}
number++;
}
return 0;
}
| 18.636364 | 45 | 0.370732 | AriaaRy |
40dfb684fca0f5a4ac0256df744b91116d0d0717 | 5,724 | hh | C++ | src/outlinertypes.hh | jariarkko/cave-outliner | 2077a24627881f45a27aec3eb4e5b4855f6b7fec | [
"BSD-3-Clause"
] | 4 | 2021-09-02T16:52:23.000Z | 2022-02-07T16:39:50.000Z | src/outlinertypes.hh | jariarkko/cave-outliner | 2077a24627881f45a27aec3eb4e5b4855f6b7fec | [
"BSD-3-Clause"
] | 87 | 2021-09-12T06:09:57.000Z | 2022-02-15T00:05:43.000Z | src/outlinertypes.hh | jariarkko/cave-outliner | 2077a24627881f45a27aec3eb4e5b4855f6b7fec | [
"BSD-3-Clause"
] | 1 | 2021-09-28T21:38:30.000Z | 2021-09-28T21:38:30.000Z | ///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
//
// CCC AAA V V EEEEE OOO UU UU TTTTTT LL II NN NN EEEEE RRRRR
// CC CC AA AA V V EE OO OO UU UU TT LL II NNN NN EE RR RR
// CC AA AA V V EEE OO OO UU UU TT LL II NN N NN EEE RRRRR
// CC CC AAAAAA V V EE OO OO UU UU TT LL II NN NNN EE RR R
// CCc AA AA V EEEEE OOO UUUUU TT LLLLL II NN NN EEEEE RR R
//
// CAVE OUTLINER -- Cave 3D model processing software
//
// Copyright (C) 2021 by Jari Arkko -- See LICENSE.txt for license information.
//
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
#ifndef OUTLINERTYPES_HH
#define OUTLINERTYPES_HH
///////////////////////////////////////////////////////////////////////////////////////////////
// Includes ///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include "outlinerconstants.hh"
///////////////////////////////////////////////////////////////////////////////////////////////
// Defines ////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
#define outlinerreal double
///////////////////////////////////////////////////////////////////////////////////////////////
// Enumerated types ///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
enum outlineralgorithm {
alg_pixel,
alg_pixelform,
alg_triangle,
alg_depthmap,
alg_depthdiffmap,
alg_borderpixel,
alg_borderline,
alg_borderactual
};
#define outlineralgorithm_generatespicture(a) \
((a) == alg_pixel || (a) == alg_borderpixel || (a) == alg_borderline || (a) == alg_borderactual)
///////////////////////////////////////////////////////////////////////////////////////////////
// Common macros //////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
#define outlinerisnumber(s) ((isdigit(*(s)) || (*(s) == '-' && isdigit(*((s)+1))) || (*(s) == '+' && isdigit(*((s)+1))) ))
#define outlinermin(a,b) (((a) < (b)) ? (a) : (b))
#define outlinermax(a,b) (((a) > (b)) ? (a) : (b))
#define outlinermin3(a,b,c) (outlinermin((a),outlinermin((b),(c))))
#define outlinermax3(a,b,c) (outlinermax((a),outlinermax((b),(c))))
#define outlinersaneindex(x) ((x) < (2U*1000U*1000U*1000U))
#define outlinerabs(x) ((x) < 0 ? -(x) : (x))
#define outlineravg(a,b) (((a)+(b))/2.0)
#define outlineravg3(a,b,c) (((a)+(b)+(c))/3.0)
#define outlinerunsignedabsdiff(a,b) ((a) < (b) ? (b)-(a) : (a)-(b))
#define outlinersquared(x) ((x)*(x))
///////////////////////////////////////////////////////////////////////////////////////////////
// Math common utilities //////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
#define outlinerle(a,b) ((a) <= (b))
#define outlinerleepsilon(a,b) ((a) <= ((b)+outlinerepsilon))
#define outlinerge(a,b) (((a)+outlinerepsilon) >= (b))
#define outlinergeepsilon(a,b) (((a)+outlinerepsilon) >= (b))
#define outlinerbetweenanyorder(a,b,c) ((a) < (c) ? outlinerbetween(a,b,c) : \
outlinerbetween(c,b,a))
#define outlinerbetweenanyorderepsilon(a,b,c) ((a) < (c) ? outlinerbetweenepsilon(a,b,c) : \
outlinerbetweenepsilon(c,b,a))
#define outlinerbetween(a,b,c) ((a) <= (b) && (b) <= (c))
#define outlinerbetweenepsilon(a,b,c) ((a) <= ((b)+outlinerepsilon) && (b) <= ((c)+outlinerepsilon))
#define outlineroverlapanyorder(a,b,c,d) (((a) <= (b) && (c) <= (d)) ? outlineroverlap(a,b,c,d) : \
(((b) <= (a) && (c) <= (d)) ? outlineroverlap(b,a,c,d) : \
(((b) <= (a) && (d) <= (c)) ? outlineroverlap(b,a,d,c) : \
outlineroverlap(a,b,d,c))))
#define outlineroverlap(a,b,c,d) ((((a) <= (c)) && ((c) <= (b))) || \
(((c) <= (a)) && ((a) <= (d))))
#define outlineroverlapepsilon(a,b,c,d) ((((a) <= (c)+outlinerepsilon) && ((c) <= (b)+outlinerepsilon)) || \
(((c) <= (a)+outlinerepsilon) && ((a) <= (d)+outlinerepsilon)))
#endif // OUTLINERTYPES_HH
| 60.252632 | 133 | 0.306254 | jariarkko |
40e254e80a5927fcc65287581d1b4c066430e8c8 | 1,183 | cpp | C++ | unittests/ObjectPoolTest.cpp | zavadovsky/stingraykit | 33e6587535325f08769bd8392381d70d4d316410 | [
"0BSD"
] | 24 | 2015-03-04T16:30:03.000Z | 2022-02-04T15:03:42.000Z | unittests/ObjectPoolTest.cpp | zavadovsky/stingraykit | 33e6587535325f08769bd8392381d70d4d316410 | [
"0BSD"
] | null | null | null | unittests/ObjectPoolTest.cpp | zavadovsky/stingraykit | 33e6587535325f08769bd8392381d70d4d316410 | [
"0BSD"
] | 7 | 2015-04-08T12:22:58.000Z | 2018-06-14T09:58:45.000Z | #include <stingraykit/thread/Thread.h>
#include <stingraykit/time/ElapsedTime.h>
#include <stingraykit/ObjectPool.h>
#include <gtest/gtest.h>
using namespace stingray;
namespace
{
class SomeObject
{
private:
bool& _threadNameError;
std::string _threadName;
public:
SomeObject(bool& threadNameError, const std::string& threadName) :
_threadNameError(threadNameError),
_threadName(threadName)
{ }
~SomeObject()
{
if (Thread::GetCurrentThreadName() != _threadName)
_threadNameError = true;
}
};
STINGRAYKIT_DECLARE_PTR(SomeObject);
void GcFunc(ObjectPool& objectPool)
{
ElapsedTime t;
while (t.ElapsedMilliseconds() < 3000)
objectPool.CollectGarbage();
}
}
TEST(ObjectPoolTest, ObjectDeletion)
{
ObjectPool object_pool;
bool thread_name_error = false;
ThreadPtr th = make_shared_ptr<Thread>("gcThread", Bind(&GcFunc, wrap_ref(object_pool)));
ElapsedTime t;
SomeObjectWeakPtr weak_o;
while (t.ElapsedMilliseconds() < 2500)
{
SomeObjectPtr o(new SomeObject(thread_name_error, "gcThread"));
weak_o = o;
object_pool.AddObject(o);
o.reset();
o = weak_o.lock();
}
th.reset();
ASSERT_TRUE(!thread_name_error);
}
| 18.2 | 90 | 0.724429 | zavadovsky |
40e754945536704df2a5c9ba1e81ab58c5fec024 | 1,517 | hh | C++ | cc/report.hh | acorg/hidb-make | 3db8e408d548eda83070f793d1e5d94b71e6c562 | [
"MIT"
] | null | null | null | cc/report.hh | acorg/hidb-make | 3db8e408d548eda83070f793d1e5d94b71e6c562 | [
"MIT"
] | null | null | null | cc/report.hh | acorg/hidb-make | 3db8e408d548eda83070f793d1e5d94b71e6c562 | [
"MIT"
] | null | null | null | #pragma once
#include "hidb-5/hidb.hh"
// ----------------------------------------------------------------------
namespace hidb
{
enum class report_tables { none, all, oldest, recent };
void report_antigens(const hidb::HiDb& hidb, const AntigenIndexList& aIndexes, report_tables aReportTables, std::string_view aPrefix = {});
void report_antigen(const hidb::HiDb& hidb, const hidb::Antigen& aAntigen, report_tables aReportTables, std::string_view aPrefix = {});
inline void report_antigen(const hidb::HiDb& hidb, AntigenIndex aIndex, report_tables aReportTables, std::string_view aPrefix = {}) { report_antigen(hidb, *hidb.antigens()->at(aIndex), aReportTables, aPrefix); }
void report_sera(const hidb::HiDb& hidb, const SerumIndexList& aIndexes, report_tables aReportTables, std::string_view aPrefix = {});
void report_serum(const hidb::HiDb& hidb, const hidb::Serum& aSerum, report_tables aReportTables, std::string_view aPrefix = {});
inline void report_serum(const hidb::HiDb& hidb, SerumIndex aIndex, report_tables aReportTables, std::string_view aPrefix = {}) { report_serum(hidb, *hidb.sera()->at(aIndex), aReportTables, aPrefix); }
std::string report_tables(const hidb::HiDb& hidb, const TableIndexList& aIndexes, enum hidb::report_tables aReportTables, std::string_view aPrefix = {});
} // namespace hidb
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
| 63.208333 | 215 | 0.669743 | acorg |
40ec6fcce57904e044d6ec9dfe5aa77b2e2a7123 | 4,237 | cpp | C++ | Anim/AnimSet.cpp | gildor2/SkelEdit | 7e413703962e3618b2c52f2a08bf6a0da46e3ab9 | [
"BSD-3-Clause"
] | 41 | 2020-02-19T12:37:29.000Z | 2021-11-18T22:39:55.000Z | Anim/AnimSet.cpp | gildor2/SkelEdit | 7e413703962e3618b2c52f2a08bf6a0da46e3ab9 | [
"BSD-3-Clause"
] | null | null | null | Anim/AnimSet.cpp | gildor2/SkelEdit | 7e413703962e3618b2c52f2a08bf6a0da46e3ab9 | [
"BSD-3-Clause"
] | 7 | 2020-02-27T08:11:21.000Z | 2022-02-12T13:11:38.000Z | #include "Core.h"
#include "AnimClasses.h"
/*-----------------------------------------------------------------------------
CMeshAnimSeq class
-----------------------------------------------------------------------------*/
#define MAX_LINEAR_KEYS 4
// debugging staff ...
//#define DEBUG_BIN_SEARCH 1
#if 0
# define DBG printf
#else
# define DBG if (1) {} else printf
#endif
void CMeshAnimSeq::GetBonePosition(int TrackIndex, float Frame, bool Loop, CVec3 &DstPos, CQuat &DstQuat) const
{
guard(CMeshAnimSeq::GetBonePosition);
int i;
const CAnalogTrack &A = Tracks[TrackIndex];
// fast case: 1 frame only
if (A.KeyTime.Num() == 1)
{
DstPos = A.KeyPos[0];
DstQuat = A.KeyQuat[0];
return;
}
// find index in time key array
int NumKeys = A.KeyTime.Num();
// *** binary search ***
int Low = 0, High = NumKeys-1;
DBG(">>> find %.5f\n", Frame);
while (Low + MAX_LINEAR_KEYS < High)
{
int Mid = (Low + High) / 2;
DBG(" [%d..%d] mid: [%d]=%.5f", Low, High, Mid, A.KeyTime[Mid]);
if (Frame < A.KeyTime[Mid])
High = Mid-1;
else
Low = Mid;
DBG(" d=%f\n", A.KeyTime[Mid]-Frame);
}
// *** linear search ***
DBG(" linear: %d..%d\n", Low, High);
for (i = Low; i <= High; i++)
{
float CurrKeyTime = A.KeyTime[i];
DBG(" #%d: %.5f\n", i, CurrKeyTime);
if (Frame == CurrKeyTime)
{
// exact key found
DstPos = (A.KeyPos.Num() > 1) ? A.KeyPos[i] : A.KeyPos[0];
DstQuat = (A.KeyQuat.Num() > 1) ? A.KeyQuat[i] : A.KeyQuat[0];
return;
}
if (Frame < CurrKeyTime)
{
i--;
break;
}
}
if (i > High)
i = High;
#if DEBUG_BIN_SEARCH
EXEC_ONCE(appPrintf("!!! WARNING: DEBUG_BIN_SEARCH enabled !!!\n"))
//!! --- checker ---
int i1;
for (i1 = 0; i1 < NumKeys; i1++)
{
float CurrKeyTime = A.KeyTime[i1];
if (Frame == CurrKeyTime)
{
// exact key found
DstPos = (A.KeyPos.Num() > 1) ? A.KeyPos[i] : A.KeyPos[0];
DstQuat = (A.KeyQuat.Num() > 1) ? A.KeyQuat[i] : A.KeyQuat[0];
return;
}
if (Frame < CurrKeyTime)
{
i1--;
break;
}
}
if (i1 > NumKeys-1)
i1 = NumKeys-1;
if (i != i1)
{
appError("i=%d != i1=%d", i, i1);
}
#endif
int X = i;
int Y = i+1;
float frac;
if (Y >= NumKeys)
{
if (!Loop)
{
// clamp animation
Y = NumKeys-1;
assert(X == Y);
frac = 0;
}
else
{
// loop animation
Y = 0;
frac = (Frame - A.KeyTime[X]) / (NumFrames - A.KeyTime[X]);
}
}
else
{
frac = (Frame - A.KeyTime[X]) / (A.KeyTime[Y] - A.KeyTime[X]);
}
assert(X >= 0 && X < NumKeys);
assert(Y >= 0 && Y < NumKeys);
// get position
if (A.KeyPos.Num() > 1)
Lerp(A.KeyPos[X], A.KeyPos[Y], frac, DstPos);
else
DstPos = A.KeyPos[0];
// get orientation
if (A.KeyQuat.Num() > 1)
Slerp(A.KeyQuat[X], A.KeyQuat[Y], frac, DstQuat);
else
DstQuat = A.KeyQuat[0];
unguard;
}
void CMeshAnimSeq::GetMemFootprint(int *Compressed, int *Uncompressed)
{
int uncompr = sizeof(CMeshAnimSeq) + sizeof(CAnalogTrack);
int compr = uncompr;
uncompr += (sizeof(CQuat) + sizeof(CVec3) + sizeof(CVec3) + sizeof(float)) * NumFrames * Tracks.Num();
for (int track = 0; track < Tracks.Num(); track++)
{
const CAnalogTrack &T = Tracks[track];
compr += sizeof(CQuat) * T.KeyQuat.Num()
+ sizeof(CVec3) * T.KeyPos.Num()
+ sizeof(CVec3) * T.KeyScale.Num()
+ sizeof(float) * T.KeyTime.Num();
}
if (Compressed) *Compressed = compr;
if (Uncompressed) *Uncompressed = uncompr;
}
/*-----------------------------------------------------------------------------
CAnimSet class
-----------------------------------------------------------------------------*/
void CAnimSet::GetMemFootprint(int *Compressed, int *Uncompressed)
{
int uncompr = sizeof(CAnimSet) + sizeof(CAnimBone) * TrackBoneName.Num();
int compr = uncompr;
for (int seq = 0; seq < Sequences.Num(); seq++)
{
int c, u;
Sequences[seq].GetMemFootprint(&c, &u);
compr += c;
uncompr += u;
}
if (Compressed) *Compressed = compr;
if (Uncompressed) *Uncompressed = uncompr;
}
const CMeshAnimSeq *CAnimSet::FindAnim(const char *AnimName) const
{
for (int i = 0; i < Sequences.Num(); i++)
{
const CMeshAnimSeq *Seq = &Sequences[i];
if (!stricmp(Seq->Name, AnimName))
return Seq;
}
return NULL;
}
| 21.728205 | 111 | 0.548501 | gildor2 |
40ed214d96d422eafbe2cfc3d6b03b4c090f5aee | 4,413 | hpp | C++ | include/adapters/net.hpp | jamespeapen/polybar | 1ee11f7c9e72719f62981167a24fe7239774fa69 | [
"MIT"
] | 4,807 | 2016-11-19T05:17:55.000Z | 2019-05-05T16:41:43.000Z | include/adapters/net.hpp | jamespeapen/polybar | 1ee11f7c9e72719f62981167a24fe7239774fa69 | [
"MIT"
] | 1,482 | 2016-11-19T15:48:40.000Z | 2019-05-05T12:47:25.000Z | include/adapters/net.hpp | jamespeapen/polybar | 1ee11f7c9e72719f62981167a24fe7239774fa69 | [
"MIT"
] | 392 | 2016-11-21T01:41:42.000Z | 2019-05-04T14:42:02.000Z | #pragma once
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <chrono>
#include <cstdlib>
#include "common.hpp"
#include "components/logger.hpp"
#include "errors.hpp"
#include "settings.hpp"
#include "utils/math.hpp"
#if WITH_LIBNL
#include <net/if.h>
struct nl_msg;
struct nlattr;
#else
#include <iwlib.h>
/*
* wirless_tools 29 (and possibly earlier) redefines 'inline' in iwlib.h
* With clang this leads to a conflict in the POLYBAR_NS macro
* wirless_tools 30 doesn't have that issue anymore
*/
#ifdef inline
#undef inline
#endif
#endif
POLYBAR_NS
class file_descriptor;
namespace net {
DEFINE_ERROR(network_error);
bool is_interface_valid(const string& ifname);
std::pair<string, bool> get_canonical_interface(const string& ifname);
bool is_wireless_interface(const string& ifname);
std::string find_wireless_interface();
std::string find_wired_interface();
// types {{{
struct quality_range {
int val{0};
int max{0};
int percentage() const {
if (val < 0) {
return std::max(std::min(std::abs(math_util::percentage(val, max, -20)), 100), 0);
}
return std::max(std::min(math_util::percentage(val, 0, max), 100), 0);
}
};
using bytes_t = unsigned int;
struct link_activity {
bytes_t transmitted{0};
bytes_t received{0};
std::chrono::steady_clock::time_point time;
};
struct link_status {
string ip;
string ip6;
string mac;
link_activity previous{};
link_activity current{};
};
// }}}
// class : network {{{
class network {
public:
explicit network(string interface);
virtual ~network() {}
virtual bool query(bool accumulate = false);
virtual bool connected() const = 0;
virtual bool ping() const;
string ip() const;
string ip6() const;
string mac() const;
string downspeed(int minwidth = 3, const string& unit = "B/s") const;
string upspeed(int minwidth = 3, const string& unit = "B/s") const;
string netspeed(int minwidth = 3, const string& unit = "B/s") const;
void set_unknown_up(bool unknown = true);
protected:
void check_tuntap_or_bridge();
bool test_interface() const;
string format_speedrate(float bytes_diff, int minwidth, const string& unit) const;
void query_ip6();
const logger& m_log;
unique_ptr<file_descriptor> m_socketfd;
link_status m_status{};
string m_interface;
bool m_tuntap{false};
bool m_bridge{false};
bool m_unknown_up{false};
};
// }}}
// class : wired_network {{{
class wired_network : public network {
public:
explicit wired_network(string interface) : network(interface) {}
bool query(bool accumulate = false) override;
bool connected() const override;
string linkspeed() const;
private:
int m_linkspeed{0};
};
// }}}
#if WITH_LIBNL
// class : wireless_network {{{
class wireless_network : public network {
public:
wireless_network(string interface) : network(interface), m_ifid(if_nametoindex(interface.c_str())){};
bool query(bool accumulate = false) override;
bool connected() const override;
string essid() const;
int signal() const;
int quality() const;
protected:
static int scan_cb(struct nl_msg* msg, void* instance);
bool associated_or_joined(struct nlattr** bss);
void parse_essid(struct nlattr** bss);
void parse_frequency(struct nlattr** bss);
void parse_quality(struct nlattr** bss);
void parse_signal(struct nlattr** bss);
private:
unsigned int m_ifid{};
string m_essid{};
int m_frequency{};
quality_range m_signalstrength{};
quality_range m_linkquality{};
};
// }}}
#else
// class : wireless_network {{{
class wireless_network : public network {
public:
wireless_network(string interface) : network(interface) {}
bool query(bool accumulate = false) override;
bool connected() const override;
string essid() const;
int signal() const;
int quality() const;
protected:
void query_essid(const int& socket_fd);
void query_quality(const int& socket_fd);
private:
shared_ptr<wireless_info> m_info{};
string m_essid{};
quality_range m_signalstrength{};
quality_range m_linkquality{};
};
// }}}
#endif
using wireless_t = unique_ptr<wireless_network>;
using wired_t = unique_ptr<wired_network>;
} // namespace net
POLYBAR_NS_END
| 22.984375 | 105 | 0.677317 | jamespeapen |
40f42109804cf6df38aebdf0264f592d1509ae45 | 4,027 | hpp | C++ | include/GlobalNamespace/RandomAnimatorStartTime.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/RandomAnimatorStartTime.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/RandomAnimatorStartTime.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Animator
class Animator;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Size: 0x28
#pragma pack(push, 1)
// Autogenerated type: RandomAnimatorStartTime
// [TokenAttribute] Offset: FFFFFFFF
class RandomAnimatorStartTime : public UnityEngine::MonoBehaviour {
public:
// private UnityEngine.Animator _animator
// Size: 0x8
// Offset: 0x18
UnityEngine::Animator* animator;
// Field size check
static_assert(sizeof(UnityEngine::Animator*) == 0x8);
// private System.String _stateName
// Size: 0x8
// Offset: 0x20
::Il2CppString* stateName;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// Creating value type constructor for type: RandomAnimatorStartTime
RandomAnimatorStartTime(UnityEngine::Animator* animator_ = {}, ::Il2CppString* stateName_ = {}) noexcept : animator{animator_}, stateName{stateName_} {}
// Deleting conversion operator: operator System::IntPtr
constexpr operator System::IntPtr() const noexcept = delete;
// Get instance field reference: private UnityEngine.Animator _animator
UnityEngine::Animator*& dyn__animator();
// Get instance field reference: private System.String _stateName
::Il2CppString*& dyn__stateName();
// protected System.Void Start()
// Offset: 0x126FD14
void Start();
// public System.Void .ctor()
// Offset: 0x126FD58
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static RandomAnimatorStartTime* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::RandomAnimatorStartTime::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<RandomAnimatorStartTime*, creationType>()));
}
}; // RandomAnimatorStartTime
#pragma pack(pop)
static check_size<sizeof(RandomAnimatorStartTime), 32 + sizeof(::Il2CppString*)> __GlobalNamespace_RandomAnimatorStartTimeSizeCheck;
static_assert(sizeof(RandomAnimatorStartTime) == 0x28);
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::RandomAnimatorStartTime*, "", "RandomAnimatorStartTime");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::RandomAnimatorStartTime::Start
// Il2CppName: Start
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::RandomAnimatorStartTime::*)()>(&GlobalNamespace::RandomAnimatorStartTime::Start)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RandomAnimatorStartTime*), "Start", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::RandomAnimatorStartTime::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 47.376471 | 175 | 0.735783 | Fernthedev |
40f495d41a93bf3646c6efdfa69a67f567bf4b7e | 7,721 | hpp | C++ | include/cppdevtk/base/any.hpp | CoSoSys/cppdevtk | 99d6c3d328c05a55dae54e82fcbedad93d0cfaa0 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | include/cppdevtk/base/any.hpp | CoSoSys/cppdevtk | 99d6c3d328c05a55dae54e82fcbedad93d0cfaa0 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | include/cppdevtk/base/any.hpp | CoSoSys/cppdevtk | 99d6c3d328c05a55dae54e82fcbedad93d0cfaa0 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// \file
///
/// \copyright Copyright (C) 2015 - 2020 CoSoSys Ltd <info@cososys.com>\n
/// Licensed under the Apache License, Version 2.0 (the "License");\n
/// you may not use this file except in compliance with the License.\n
/// You may obtain a copy of the License at\n
/// http://www.apache.org/licenses/LICENSE-2.0\n
/// Unless required by applicable law or agreed to in writing, software\n
/// distributed under the License is distributed on an "AS IS" BASIS,\n
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n
/// See the License for the specific language governing permissions and\n
/// limitations under the License.\n
/// Please see the file COPYING.
///
/// \authors Cristian ANITA <cristian.anita@cososys.com>, <cristian_anita@yahoo.com>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef CPPDEVTK_BASE_ANY_HPP_INCLUDED_
#define CPPDEVTK_BASE_ANY_HPP_INCLUDED_
#include "config.hpp"
#include "typeinfo.hpp"
#include "bad_any_cast_exception.hpp"
#include "cloneable.hpp"
#include "static_assert.hpp"
#include <cstddef>
#include <new>
#include <algorithm> // swap(), C++98
#include <utility> // swap(), C++11
#include CPPDEVTK_TR1_HEADER(type_traits)
namespace cppdevtk {
namespace base {
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// A type-safe container for single values of any \c CopyConstructible type with no-throw destructor.
/// \attention Arrays are not supported!
/// \note C++ 17 std says that implementations are encouraged to avoid dynamic allocations for small objects.
/// Currently our implementation always uses dynamic allocations.
/// \sa
/// - <a href="http://en.cppreference.com/w/cpp/utility/any">C++17 any</a>
/// - <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4562.html#any">C++ Extensions for Library Fundamentals, Version 2, 6 Class any</a>
/// - <a href="http://www.boost.org/doc/libs/1_65_1/doc/html/any.html">Boost.Any</a>
class CPPDEVTK_BASE_API Any {
template <typename TValue>
friend TValue* AnyCast(Any*);
public:
Any() CPPDEVTK_NOEXCEPT;
template <typename TValue>
Any(const TValue& value);
Any(const Any& other);
~Any() CPPDEVTK_NOEXCEPT;
Any& operator=(const Any& other);
template <typename TValue>
Any& operator=(const TValue& value);
bool HasValue() const CPPDEVTK_NOEXCEPT;
void Reset() CPPDEVTK_NOEXCEPT;
/// \return The \c TypeInfo of the contained value if instance is non-empty, otherwise \c TypeInfo(typeid(void))
TypeInfo GetTypeInfo() const CPPDEVTK_NOEXCEPT;
void Swap(Any& other) CPPDEVTK_NOEXCEPT;
private:
class CPPDEVTK_BASE_API TypeErasedValue: public Cloneable {
public:
TypeErasedValue();
TypeErasedValue(const TypeErasedValue& other);
virtual TypeInfo GetTypeInfo() const CPPDEVTK_NOEXCEPT = 0;
private:
TypeErasedValue& operator=(const TypeErasedValue&);
};
template <typename TValue>
class Value: public TypeErasedValue {
CPPDEVTK_STATIC_ASSERT(!CPPDEVTK_TR1_NS::is_array<TValue>::value);
template <typename TValue1>
friend TValue1* AnyCast(Any*);
public:
typedef TValue ValueType;
Value(const TValue& value);
Value(const Value& other);
virtual TypeInfo GetTypeInfo() const CPPDEVTK_NOEXCEPT;
::std::auto_ptr<Value> Clone() const;
protected:
# if (CPPDEVTK_COMPILER_HAVE_MVI_CRT_BUG)
virtual Cloneable* DoClone() const;
# else
virtual Value* DoClone() const;
# endif
private:
Value& operator=(const Value&);
TValue value_;
};
TypeErasedValue* pTypeErasedValue_;
};
CPPDEVTK_BASE_API void swap(Any& x, Any& y) CPPDEVTK_NOEXCEPT;
template <typename TValue>
TValue* AnyCast(Any* pAny); ///< \return \c NULL if conversion fails
template <typename TValue>
const TValue* AnyCast(const Any* pAny); ///< \return \c NULL if conversion fails
template <typename TValue>
TValue AnyCast(Any& any); ///< \throw BadAnyCastException if conversion fails
template <typename TValue>
TValue AnyCast(const Any& any); ///< \throw BadAnyCastException if conversion fails
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Inline functions
inline Any::Any() CPPDEVTK_NOEXCEPT: pTypeErasedValue_(NULL) {}
template <typename TValue>
inline Any::Any(const TValue& value): pTypeErasedValue_(new Value<TValue>(value)) {}
inline Any::Any(const Any& other): pTypeErasedValue_(
(other.pTypeErasedValue_ == NULL) ? NULL : static_cast<TypeErasedValue*>(other.pTypeErasedValue_->Clone().release())) {}
inline Any::~Any() CPPDEVTK_NOEXCEPT {
Reset();
}
inline Any& Any::operator=(const Any& other) {
Any tmp(other);
Swap(tmp);
return *this;
}
template <typename TValue>
inline Any& Any::operator=(const TValue& value) {
Any tmp(value);
Swap(tmp);
return *this;
}
inline bool Any::HasValue() const CPPDEVTK_NOEXCEPT {
return pTypeErasedValue_ != NULL;
}
inline TypeInfo Any::GetTypeInfo() const CPPDEVTK_NOEXCEPT {
return (pTypeErasedValue_ == NULL) ? typeid(void) : pTypeErasedValue_->GetTypeInfo();
}
inline void Any::Swap(Any& other) CPPDEVTK_NOEXCEPT {
using ::std::swap;
swap(pTypeErasedValue_, other.pTypeErasedValue_);
}
inline Any::TypeErasedValue::TypeErasedValue(): Cloneable() {}
inline Any::TypeErasedValue::TypeErasedValue(const TypeErasedValue& other): Cloneable(other) {}
template <typename TValue>
inline Any::Value<TValue>::Value(const TValue& value): TypeErasedValue(), value_(value) {}
template <typename TValue>
inline Any::Value<TValue>::Value(const Value& other): TypeErasedValue(other), value_(other.value_) {}
template <typename TValue>
inline TypeInfo Any::Value<TValue>::GetTypeInfo() const CPPDEVTK_NOEXCEPT {
return typeid(TValue);
}
template <typename TValue>
inline ::std::auto_ptr<Any::Value<TValue> > Any::Value<TValue>::Clone() const {
return ::std::auto_ptr<Value>(static_cast<Value*>(Cloneable::Clone().release()));
}
template <typename TValue>
#if (CPPDEVTK_COMPILER_HAVE_MVI_CRT_BUG)
inline Cloneable* Any::Value<TValue>::DoClone() const {
#else
inline Any::Value<TValue>* Any::Value<TValue>::DoClone() const {
#endif
return new Value(*this);
}
inline CPPDEVTK_BASE_API void swap(Any& x, Any& y) CPPDEVTK_NOEXCEPT {
x.Swap(y);
}
template <typename TValue>
inline TValue* AnyCast(Any* pAny) {
return ((pAny != NULL) && (pAny->GetTypeInfo() == typeid(TValue))) ?
&(static_cast<Any::Value<TValue>*>(pAny->pTypeErasedValue_)->value_) : NULL;
}
template <typename TValue>
inline const TValue* AnyCast(const Any* pAny) {
return AnyCast<TValue>(const_cast<Any*>(pAny));
}
template <typename TValue>
inline TValue AnyCast(Any& any) {
typedef typename CPPDEVTK_TR1_NS::remove_reference<TValue>::type NonRefValueType;
NonRefValueType* pNonRefValueType = AnyCast<NonRefValueType>(&any);
if (pNonRefValueType == NULL) {
throw CPPDEVTK_BAD_ANY_CAST_EXCEPTION();
}
return *pNonRefValueType;
}
template <typename TValue>
inline TValue AnyCast(const Any& any) {
typedef typename CPPDEVTK_TR1_NS::remove_reference<TValue>::type NonRefValueType;
return AnyCast<const NonRefValueType&>(const_cast<Any&>(any));
}
} // namespace base
} // namespace cppdevtk
#endif // CPPDEVTK_BASE_ANY_HPP_INCLUDED_
| 30.397638 | 155 | 0.666364 | CoSoSys |
40f57cfb922844131b2059f14c4b0551b0eb06b7 | 517 | cpp | C++ | external/RNAlib/plot/forceclass.cpp | tsznxx/rsq | 8c2da449445445c55a1b07c21644b380f0809781 | [
"CNRI-Python"
] | null | null | null | external/RNAlib/plot/forceclass.cpp | tsznxx/rsq | 8c2da449445445c55a1b07c21644b380f0809781 | [
"CNRI-Python"
] | null | null | null | external/RNAlib/plot/forceclass.cpp | tsznxx/rsq | 8c2da449445445c55a1b07c21644b380f0809781 | [
"CNRI-Python"
] | null | null | null |
#include "forceclass.h"
// forceclass encapsulates a large 2-d arrays of char used by the
// dynamic algorithm to enforce folding constraints
forceclass::forceclass(int size) {
Size = size;
register int i,j;
dg = new char *[size+1];
for (i=0;i<=(size);i++) {
dg[i] = new char [size+1];
}
for (i=0;i<=size;i++) {
for (j=0;j<size+1;j++) {
dg[i][j] = 0;
}
}
}
forceclass::~forceclass() {
for (int i = 0; i <= Size; i++) {
delete[] dg[i];
}
delete[] dg;
}
| 16.15625 | 65 | 0.539652 | tsznxx |
40fa8716676ed52d0d6cfc067b77a96d6744c125 | 10,087 | hpp | C++ | src/media.hpp | rainstormstudio/TetrisD3 | 5079a33781e08b00eac2e01a3149a1d2b10b9e36 | [
"MIT"
] | null | null | null | src/media.hpp | rainstormstudio/TetrisD3 | 5079a33781e08b00eac2e01a3149a1d2b10b9e36 | [
"MIT"
] | null | null | null | src/media.hpp | rainstormstudio/TetrisD3 | 5079a33781e08b00eac2e01a3149a1d2b10b9e36 | [
"MIT"
] | null | null | null | /**
* @file media.hpp
* @author Daneil Hongyu Ding
* @brief This is a simple media port using SDL2
* @version 0.5
* @date 2020-08-18
*
* @copyright Copyright (c) 2020
*
*/
#ifndef MEDIA_HPP
#define MEDIA_HPP
#ifdef __linux__
#include "SDL2/SDL.h"
#include "SDL2/SDL_image.h"
#include "SDL2/SDL_mixer.h"
#include "SDL2/SDL_ttf.h"
#elif _WIN32
#include "SDL.h"
#include "SDL_image.h"
#include "SDL_mixer.h"
#include "SDL_ttf.h"
#endif
#include "ctexture.hpp"
#include "texture.hpp"
#include <vector>
#include <string>
#include <fstream>
#include <memory>
class Media {
std::string title;
SDL_Window* window;
SDL_Renderer* renderer;
TTF_Font* font;
SDL_Texture* tileset;
unsigned int numSrcRows;
unsigned int numSrcCols;
unsigned int tileWidth;
unsigned int tileHeight;
Uint32 fullscreen;
unsigned int screenWidth;
unsigned int screenHeight;
unsigned int numRows;
unsigned int numCols;
std::vector<std::vector<std::shared_ptr<CTexture>>> textDisplay;
public:
/**
* @brief Construct a new Media object
*
* @param title the title of the window
* @param tilesetFilename the file path to the tileset image
* @param numSrcRows number of rows in the tileset
* @param numSrcCols number of columns in the tileset
* @param fullscreenFlag SDL flag for fullscreen. Use 0 for none
* @param fontPath the file path to the ttf font
* @param screenWidth the width of the window
* @param screenHeight the height of the window
* @param numRows number of rows will be shown on the screen
* @param numCols number of columns will be shown on the screen
*/
Media(std::string title, std::string tilesetFilename,
unsigned int numSrcRows, unsigned int numSrcCols,
Uint32 fullscreenFlag, std::string fontPath,
unsigned int screenWidth, unsigned int screenHeight,
unsigned int numRows, unsigned int numCols);
/**
* @brief Destroy the Media object
*
*/
~Media();
/**
* @brief Set the character at the y-th row and the x-th column
*
* @param index the character you want to put on screen
* @param x the column number
* @param y the row number
*/
void setCh(Uint8 index, int x, int y);
/**
* @brief Set the Fore Color to be (r, b, g, a) at
* the y-th row and the x-th column
*
* @param r red
* @param g green
* @param b blue
* @param a alpha
* @param x the column number
* @param y the row number
*/
void setForeColor(Uint8 r, Uint8 g, Uint8 b, Uint8 a, int x, int y);
/**
* @brief Set the Back Color to be (r, b, g, a) at
* the y-th row and the x-th column
*
* @param r red
* @param g green
* @param b blue
* @param a alpha
* @param x the column number
* @param y the row number
*/
void setBackColor(Uint8 r, Uint8 g, Uint8 b, Uint8 a, int x, int y);
/**
* @brief add the color to the current fore color
*
* @param r red
* @param g green
* @param b blue
* @param a alpha
* @param x the column number
* @param y the row number
*/
void addForeColor(Uint8 r, Uint8 g, Uint8 b, Uint8 a, int x, int y);
/**
* @brief add the color to the current back color
*
* @param r red
* @param g green
* @param b blue
* @param a alpha
* @param x the column number
* @param y the row number
*/
void addBackColor(Uint8 r, Uint8 g, Uint8 b, Uint8 a, int x, int y);
/**
* @brief Get the Fore Color
*
* @param x the column number
* @param y the row number
* @return SDL_Color
*/
SDL_Color getForeColor(int x, int y) const;
/**
* @brief Get the Back Color
*
* @param x the column number
* @param y the row number
* @return SDL_Color
*/
SDL_Color getBackColor(int x, int y) const;
/**
* @brief import txt file to the screen; if transparent is true,
* the spaces in txt file will not replace the original content
* (ignoring spaces)
*
* @param filename the file path to the txt file
* @param transparent true for ignoring spaces and false otherwise
*/
void importTxt(std::string filename, bool transparent);
/**
* @brief draws a point based on a CPixel type
* at the y-th row and the x-th column
*
* @param cpixel
* @param x the column number
* @param y the row number
*/
void drawPoint(CPixel* cpixel, int x, int y);
/**
* @brief draws a point based on give info
*
* @param ch the character to be drawn
* @param r red for foreColor
* @param g green for foreColor
* @param b blue for foreColor
* @param a alpha for foreColor
* @param br red for backColor
* @param bg green for backColor
* @param bb blue for backColor
* @param ba alpha for backColor
* @param x the column number
* @param y the row number
*/
void drawPoint(Uint8 ch, Uint8 r, Uint8 g, Uint8 b, Uint8 a, Uint8 br, Uint8 bg, Uint8 bb, Uint8 ba, int x, int y);
/**
* @brief write content starting at the y-th row and the x-th column
*
* @param content the content to be written
* @param x the column number
* @param y the row number
*/
void write(std::string content, int x, int y);
/**
* @brief write content with foreColor starting at
* the y-th row and the x-th column
*
* @param content the content to be written
* @param x the column number
* @param y the row number
* @param r red for foreColor
* @param g green for foreColor
* @param b blue for foreColor
* @param a alpha for foreColor
*/
void write(std::string content, int x, int y, Uint8 r, Uint8 g, Uint8 b, Uint8 a);
/**
* @brief write content with foreColor and backColor starting
* at the y-th row and the x-th column
*
* @param content the content to be written
* @param x the content number
* @param y the row number
* @param r red for foreColor
* @param g green for foreColor
* @param b blue for foreColor
* @param a alpha for foreColor
* @param br red for backColor
* @param bg green for backColor
* @param bb blue for backColor
* @param ba alpha for backColor
*/
void write(std::string content, int x, int y, Uint8 r, Uint8 g, Uint8 b, Uint8 a, Uint8 br, Uint8 bg, Uint8 bb, Uint8 ba);
/**
* @brief write content starting at the y-th row and the x-th column
* it creates new line every time the length reaches width
*
* @param content the content to be written
* @param x the column number
* @param y the row number
* @param width the width of every line
*/
void writeln(std::string content, int x, int y, int width);
/**
* @brief write content with foreColor starting at
* the y-th row and the x-th column;
* it creates new line every time the length reaches width
*
* @param content content to be written
* @param x the column number
* @param y the row number
* @param width the width of every line
* @param r red for foreColor
* @param g green for foreColor
* @param b blue for foreColor
* @param a alpha for foreColor
*/
void writeln(std::string content, int x, int y, int width, Uint8 r, Uint8 g, Uint8 b, Uint8 a);
/**
* @brief write content with foreColor and backColor starting at
* the y-th row and the x-th column;
* it creates new line every time the length reaches width
*
* @param content content to be written
* @param x the column number
* @param y the row number
* @param width the width of every line
* @param r red for foreColor
* @param g green for foreColor
* @param b blue for foreColor
* @param a alpha for foreColor
* @param br red for backColor
* @param bg green for backColor
* @param bb blue for backColor
* @param ba alpha for backColor
*/
void writeln(std::string content, int x, int y, int width, Uint8 r, Uint8 g, Uint8 b, Uint8 a, Uint8 br, Uint8 bg, Uint8 bb, Uint8 ba);
/**
* @brief draws the src content from Texture to dest on buffer
*
* @param texture txt texture
* @param src src rectangle content in Texture
* @param dest dest on buffer
*/
void drawTexture(const Texture* texture, const SDL_Rect &src, const SDL_Rect &dest);
/**
* @brief draws the src content from Texture to dest on buffer with alpha ratio
*
* @param texture txt texture
* @param src src rectangle content in Texture
* @param dest dest on buffer
* @param ratio alpha ratio
*/
void drawTexture(const Texture* texture, const SDL_Rect &src, const SDL_Rect &dest, double ratio);
/**
* @brief add a layer of filter on the current buffer
*
* @param ratio ratio of alpha
*/
void addFilter(double ratio);
/**
* @brief clear the screen buffer and textDisplay
*
*/
void clear();
/**
* @brief render the buffer(textDisplay) to the screen
*
*/
void render();
/**
* @brief Get the Screen Rows
*
* @return unsigned int
*/
unsigned int getScreenRows() const;
/**
* @brief Get the Screen Cols
*
* @return unsigned int
*/
unsigned int getScreenCols() const;
/**
* @brief Get the index of column number given the x-coordinate
* of the screen
*
* @param x the x-coordinate of the screen
* @return unsigned int
*/
unsigned int getPosCol(int x) const;
/**
* @brief Get the index of row number given the y-coordinate
* of the screen
*
* @param y the y-coordinate of the screen
* @return unsigned int
*/
unsigned int getPosRow(int y) const;
};
#endif
| 28.414085 | 139 | 0.614256 | rainstormstudio |
40fcdab0cdfefac160088ec0bf51ab8f35c5e8f8 | 790 | cxx | C++ | examples/HasNegativeCycle.cxx | razmikTovmas/Graph | 895404f72b33755d02374dd6ff428014635f79a5 | [
"MIT"
] | 1 | 2021-09-23T14:14:33.000Z | 2021-09-23T14:14:33.000Z | examples/HasNegativeCycle.cxx | razmikTovmas/Graph | 895404f72b33755d02374dd6ff428014635f79a5 | [
"MIT"
] | null | null | null | examples/HasNegativeCycle.cxx | razmikTovmas/Graph | 895404f72b33755d02374dd6ff428014635f79a5 | [
"MIT"
] | null | null | null | #include <iostream>
#include "core/graph.hpp"
int main()
{
impl::graph g;
g.add_edge("A", "B", -1);
g.add_edge("A", "C", 4);
g.add_edge("B", "C", 3);
g.add_edge("B", "D", 2);
g.add_edge("A", "E", 2);
g.add_edge("D", "C", 5);
g.add_edge("D", "B", 1);
g.add_edge("E", "D", -3);
std::cout << "Size: " << g.size() << std::endl;
if (g.has_negative_cycle()) {
std::cout << "Graph has negative cycle" << std::endl;
} else {
std::cout << "Graph doas not have negative cycle" << std::endl;
}
g.add_edge("D", "A", -1);
if (g.has_negative_cycle()) {
std::cout << "Graph has negative cycle" << std::endl;
} else {
std::cout << "Graph doas not have negative cycle" << std::endl;
}
return 0;
}
| 23.235294 | 71 | 0.5 | razmikTovmas |
dc089aa8fe8e93698c2e10dc56b81bc7a564f721 | 24,648 | cpp | C++ | src/powerful.cpp | patrick-schwarz/HElib | cd267e2ddc6e92886b89f3aa51c416d5c1d2dc59 | [
"Apache-2.0"
] | 1 | 2020-12-01T07:18:47.000Z | 2020-12-01T07:18:47.000Z | src/powerful.cpp | wangjinglin0721/HElib | cd267e2ddc6e92886b89f3aa51c416d5c1d2dc59 | [
"Apache-2.0"
] | null | null | null | src/powerful.cpp | wangjinglin0721/HElib | cd267e2ddc6e92886b89f3aa51c416d5c1d2dc59 | [
"Apache-2.0"
] | null | null | null | /* Copyright (C) 2012-2019 IBM Corp.
* This program is Licensed under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. See accompanying LICENSE file.
*/
/* a prelimary test program for playing around with Peikert's "powerful" basis.
* EXPERIMENTAL CODE, not usable yet
*/
#include "powerful.h"
namespace helib {
// powVec[d] = p_d^{e_d}, m = \prod_d p_d^{e_d}
// computes divVec[d] = m/p_d^{e_d}
inline void computeDivVec(NTL::Vec<long>& divVec, long m,
const NTL::Vec<long>& powVec)
{
long k = powVec.length();
divVec.SetLength(k);
for (long d = 0; d < k; d++)
divVec[d] = m/powVec[d];
}
// divVec[d] = m/p_d^{e_d}, powVec[d] = p^{e_d}
// computes invVec[d] = divVec[d]^{-1} mod powVec[d]
inline void computeInvVec(NTL::Vec<long>& invVec,
const NTL::Vec<long>& divVec, const NTL::Vec<long>& powVec)
{
long k = divVec.length();
invVec.SetLength(k);
for (long d = 0; d < k; d++) {
long t1 = divVec[d] % powVec[d];
long t2 = NTL::InvMod(t1, powVec[d]);
invVec[d] = t2;
}
}
// m = m_1 ... m_k, m_d = p_d^{e_d}
// powVec[d] = m_d
// invVec[d] = (m/m_d)^{-1} mod m_d
// computes polyToCubeMap[i] and cubeToPolyMap[i]
// where polyToCubeMap[i] is the index of (i_1, ..., i_k)
// in the cube with CubeSignature longSig = (m_1, ..., m_k),
// and (i_1, ..., i_k) is the unique tuple satistifying
// i = i_1 (m/m_1) + ... + i_k (m/m_k) mod m
// and
// cubeToPolyMap is the inverse map.
static void computePowerToCubeMap(NTL::Vec<long>& polyToCubeMap,
NTL::Vec<long>& cubeToPolyMap,
long m,
const NTL::Vec<long>& powVec,
const NTL::Vec<long>& invVec,
const CubeSignature& longSig)
{
long k = powVec.length();
polyToCubeMap.SetLength(m);
cubeToPolyMap.SetLength(m);
for (long i = 0; i < m; i++) {
long j = 0;
for (long d = 0; d < k; d++) {
long i_d = NTL::MulMod((i % powVec[d]), invVec[d], powVec[d]);
j += i_d * longSig.getProd(d+1);
}
polyToCubeMap[i] = j;
cubeToPolyMap[j] = i;
}
}
// shortSig is a CubeSignature for (phi(m_1), .., phi(m_k)),
// longSig is a CubeSignature for (m_1, ..., m_k).
// computes shortToLongMap[i] that maps an index i
// with respect to shortSig to the corresponding index
// with respect to longSig.
static void computeShortToLongMap(NTL::Vec<long>& shortToLongMap,
const CubeSignature& shortSig,
const CubeSignature& longSig)
{
long phim = shortSig.getSize();
long k = shortSig.getNumDims();
shortToLongMap.SetLength(phim);
for (long i = 0; i < phim; i++) {
long j = 0;
for (long d = 0; d < k; d++) {
long i_d = shortSig.getCoord(i, d);
j += i_d * longSig.getProd(d+1);
}
shortToLongMap[i] = j;
}
}
// This routine recursively reduces each hypercolumn
// in dimension d (viewed as a coeff vector) by Phi_{m_d}(X)
// If one starts with a cube of dimension (m_1, ..., m_k),
// one ends up with a cube that is effectively of dimension
// phi(m_1, ..., m_k). Viewed as an element of the ring
// F_p[X_1,...,X_k]/(Phi_{m_1}(X_1), ..., Phi_{m_k}(X_k)),
// the cube remains unchanged.
static void recursiveReduce(const CubeSlice<NTL::zz_p>& s,
const NTL::Vec<NTL::zz_pXModulus>& cycVec,
long d,
NTL::zz_pX& tmp1,
NTL::zz_pX& tmp2)
{
long numDims = s.getNumDims();
//OLD: assert(numDims > 0);
helib::assertTrue(numDims > 0l, "CubeSlice s has negative number of dimensions");
long deg0 = deg(cycVec[d]);
long posBnd = s.getProd(1);
for (long pos = 0; pos < posBnd; pos++) {
getHyperColumn(tmp1.rep, s, pos);
tmp1.normalize();
// tmp2 may not be normalized, so clear it first
clear(tmp2);
rem(tmp2, tmp1, cycVec[d]);
// now pad tmp2.rep with zeros to length deg0...
// tmp2 may not be normalized
long len = tmp2.rep.length();
tmp2.rep.SetLength(deg0);
for (long i = len; i < deg0; i++) tmp2.rep[i] = 0;
setHyperColumn(tmp2.rep, s, pos);
}
if (numDims == 1) return;
for (long i = 0; i < deg0; i++)
recursiveReduce(CubeSlice<NTL::zz_p>(s, i), cycVec, d+1, tmp1, tmp2);
}
PowerfulTranslationIndexes::PowerfulTranslationIndexes(const NTL::Vec<long>& mv):
mvec(mv) // copy the vector of factors
{
// mvec contains the prime-power factorization of m = \prod_{i=1}^k mi
long nfactors = mvec.length(); // = k
m = computeProd(mvec); // compute m itself
// phivec holds phi(mi) for all factors mi
phivec.SetLength(nfactors);
for (long i = 0; i < nfactors; i++) phivec[i] = phi_N(mvec[i]);
phim = computeProd(phivec); // phi(m) = prod_i phi(mi)
computeDivVec(divvec, m, mvec); // divvec[i] = m/mi
computeInvVec(invvec, divvec, mvec); // invvec[i] = (m/mi)^{-1} mod mi
// Let (i_1,...,i_k) be the representation of i in base
// (m/m1,...,m/mk), namely i = i_1 (m/m_1)+...+i_k (m/m_k) mod m.
// Then polyToCubeMap[i] is the lexicographic index of the tuple
// (i_1,...,i_k) in the cube with dimensions (m_1, ..., m_k).
// cubeToPolyMap is the inverse map, polyToCubeMap[cubeToPolyMap[j]]=j.
longSig.initSignature(mvec);
shortSig.initSignature(phivec);
computePowerToCubeMap(polyToCubeMap, cubeToPolyMap, m, mvec, invvec, longSig);
// shortSig is a CubeSignature for (phi(m_1),..., phi(m_k)), and longSig
// is a CubeSignature for (m_1, ..., m_k). shortToLongMap[i] maps an
// index i wrt shortSig to an index i' wrt longSig so that both indexes
// correspond to the same tuple (i_1,...,i_k).
computeShortToLongMap(shortToLongMap, shortSig, longSig);
cycVec.SetLength(nfactors);
for (long d = 0; d < nfactors; d++) cycVec[d] = Cyclotomic(mvec[d]);
phimX = Cyclotomic(m);
}
// This routine implements the isomorphism from F_p[X]/(Phi_m(X)) to
// F_p[X_1, ..., X_k]/(Phi_{m_1}(X_1), ..., Phi_{m_k}(X_k)). The input
// is a polynomial mod q, which must be of degree < m. The output is a
// HyperCube of dimension (phi(m_1), ..., phi(m_k)).
//
// It is assumed that the current modulus is already set.
// For convenience, this method returns the value of the modulus q.
long PowerfulConversion::polyToPowerful(HyperCube<NTL::zz_p>& powerful,
const NTL::zz_pX& poly) const
{
HyperCube<NTL::zz_p> tmpCube(getLongSig());
long n = deg(poly);
//OLD: assert(n < indexes->m);
helib::assertTrue(n < indexes->m, "Degree of polynomial poly is greater or equal than indexes->m");
for (long i = 0; i <= n; i++)
tmpCube[indexes->polyToCubeMap[i]] = poly[i];
for (long i = n+1; i < indexes->m; i++)
tmpCube[indexes->polyToCubeMap[i]] = 0;
NTL::zz_pX tmp1, tmp2;
recursiveReduce(CubeSlice<NTL::zz_p>(tmpCube), cycVec_p, 0, tmp1, tmp2);
for (long i = 0; i < indexes->phim; i++)
powerful[i] = tmpCube[indexes->shortToLongMap[i]];
return NTL::zz_p::modulus();
}
long PowerfulConversion::powerfulToPoly(NTL::zz_pX& poly,
const HyperCube<NTL::zz_p>& powerful) const
{
// convertPowerfulToPoly(poly, powerful, indexes->m, indexes.shortToLongMap,
// indexes->cubeToPolyMap, phimX_p);
NTL::zz_pX tmp; // a temporary degree-(m-1) polynomial, initialized to all-zero
tmp.SetLength(indexes->m);
for (long i = 0; i < indexes->m; i++)
tmp[i] = 0;
// copy the coefficienct from hypercube in the right order
for (long i = 0; i < indexes->phim; i++)
tmp[indexes->cubeToPolyMap[indexes->shortToLongMap[i]]] = powerful[i];
// FIXME: these two maps could be composed into a single map
tmp.normalize();
rem(poly, tmp, phimX_p); // reduce modulo Phi_m(X)
return NTL::zz_p::modulus();
}
PowerfulDCRT::PowerfulDCRT(const FHEcontext& _context, const NTL::Vec<long>& mvec):
context(_context), indexes(mvec)
{
NTL::zz_pBak bak; bak.save(); // backup NTL's current modulus
// initialize the modulus-dependent tables for all the moduli in the chain
long n = context.numPrimes();
pConvVec.SetLength(n); // allocate space
for (long i=0; i<n; i++) { // initialize
context.ithModulus(i).restoreModulus(); // set current mod to i'th prime
pConvVec[i].initPConv(indexes); // initialize tables
}
} // NTL's modulus restored upon exit
void PowerfulDCRT::dcrtToPowerful(NTL::Vec<NTL::ZZ>& out, const DoubleCRT& dcrt) const
{
const IndexSet& set = dcrt.getIndexSet();
if (empty(set)) { // sanity check
clear(out);
return;
}
NTL::zz_pBak bak; bak.save(); // backup NTL's current modulus
NTL::ZZ product = NTL::conv<NTL::ZZ>(1L);
for (long i = set.first(); i <= set.last(); i = set.next(i)) {
pConvVec[i].restoreModulus();
NTL::zz_pX oneRowPoly;
long newPrime = dcrt.getOneRow(oneRowPoly,i);
HyperCube<NTL::zz_p> oneRowPwrfl(indexes.shortSig);
pConvVec[i].polyToPowerful(oneRowPwrfl, oneRowPoly);
if (i == set.first()) // just copy
NTL::conv(out, oneRowPwrfl.getData());
else // CRT
intVecCRT(out, product, oneRowPwrfl.getData(), newPrime); // in NumbTh
product *= newPrime;
}
}
void PowerfulDCRT::powerfulToDCRT(DoubleCRT& dcrt, const NTL::Vec<NTL::ZZ>& in) const
{
throw helib::LogicError("powerfulToDCRT not implemented yet");
}
// If the IndexSet is omitted, default to all the primes in the chain
void PowerfulDCRT::ZZXtoPowerful(NTL::Vec<NTL::ZZ>& out, const NTL::ZZX& poly,
IndexSet set) const
{
if (empty(set))
set = IndexSet(0, pConvVec.length()-1);
NTL::zz_pBak bak; bak.save(); // backup NTL's current modulus
NTL::ZZ product = NTL::conv<NTL::ZZ>(1L);
for (long i = set.first(); i <= set.last(); i = set.next(i)) {
pConvVec[i].restoreModulus();
long newPrime = NTL::zz_p::modulus();
NTL::zz_pX oneRowPoly;
NTL::conv(oneRowPoly, poly); // reduce mod p and convert to NTL::zz_pX
HyperCube<NTL::zz_p> oneRowPwrfl(indexes.shortSig);
pConvVec[i].polyToPowerful(oneRowPwrfl, oneRowPoly);
if (i == set.first()) // just copy
NTL::conv(out, oneRowPwrfl.getData());
else // CRT
intVecCRT(out, product, oneRowPwrfl.getData(), newPrime); // in NumbTh
product *= newPrime;
}
}
//FIXME: both the reduction from powerful to the individual primes and
// the CRT back to poly can be made more efficient
void PowerfulDCRT::powerfulToZZX(NTL::ZZX& poly, const NTL::Vec<NTL::ZZ>& powerful,
IndexSet set) const
{
NTL::zz_pBak bak; bak.save(); // backup NTL's current modulus
if (empty(set)) set = IndexSet(0, pConvVec.length()-1);
clear(poly);
// poly.SetLength(powerful.length());
NTL::ZZ product = NTL::conv<NTL::ZZ>(1L);
for (long i = set.first(); i <= set.last(); i = set.next(i)) {
pConvVec[i].restoreModulus();
// long newPrime = NTL::zz_p::modulus();
HyperCube<NTL::zz_p> oneRowPwrfl(indexes.shortSig);
NTL::conv(oneRowPwrfl.getData(), powerful); // reduce and convert to NTL::Vec<NTL::zz_p>
NTL::zz_pX oneRowPoly;
pConvVec[i].powerfulToPoly(oneRowPoly, oneRowPwrfl);
CRT(poly, product, oneRowPoly); // NTL :-)
}
poly.normalize();
}
/********************************************************************/
/**************** UNUSED CODE - COMMENTED OUT ******************/
/********************************************************************/
#if 0
static void convertPolyToPowerful(HyperCube<NTL::zz_p>& cube,
HyperCube<NTL::zz_p>& tmpCube,
const NTL::zz_pX& poly,
const NTL::Vec<NTL::zz_pXModulus>& cycVec,
const NTL::Vec<long>& polyToCubeMap,
const NTL::Vec<long>& shortToLongMap)
{
long m = tmpCube.getSize();
long phim = cube.getSize();
long n = deg(poly);
//OLD: assert(n < m);
helib::assertTrue(n < m, "Degree of polynomial poly must be less than size of the hypercube tmpCube");
for (long i = 0; i <= n; i++)
tmpCube[polyToCubeMap[i]] = poly[i];
for (long i = n+1; i < m; i++)
tmpCube[polyToCubeMap[i]] = 0;
NTL::zz_pX tmp1, tmp2;
recursiveReduce(CubeSlice<NTL::zz_p>(tmpCube), cycVec, 0, tmp1, tmp2);
for (long i = 0; i < phim; i++)
cube[i] = tmpCube[shortToLongMap[i]];
}
// This implements the inverse of the above isomorphism.
static void convertPowerfulToPoly(NTL::zz_pX& poly,
const HyperCube<NTL::zz_p>& cube,
long m,
const NTL::Vec<long>& shortToLongMap,
const NTL::Vec<long>& cubeToPolyMap,
const NTL::zz_pXModulus& phimX)
{
long phim = cube.getSize();
NTL::zz_pX tmp;
tmp.SetLength(m);
for (long i = 0; i < m; i++)
tmp[i] = 0;
for (long i = 0; i < phim; i++)
tmp[cubeToPolyMap[shortToLongMap[i]]] = cube[i];
// FIXME: these two maps could be composed into a single map
tmp.normalize();
rem(poly, tmp, phimX);
}
// powVec[d] = p_d^{e_d}
// cycVec[d] = Phi_{p_d^{e_d}}(X) mod p
void computeCycVec(NTL::Vec<NTL::zz_pXModulus>& cycVec, const NTL::Vec<long>& powVec)
{
long k = powVec.length();
cycVec.SetLength(k);
for (long d = 0; d < k; d++) {
NTL::ZZX PhimX = Cyclotomic(powVec[d]);
cycVec[d] = NTL::conv<NTL::zz_pX>(PhimX);
}
}
// factors[d] = (p_d, e_d)
// computes phiVec[d] = phi(p_d^{e_d}) = (p_d-1) p_i{e_d-1}
static void computePhiVec(NTL::Vec<long>& phiVec,
const NTL::Vec< Pair<long, long> >& factors)
{
long k = factors.length();
phiVec.SetLength(k);
for (long d = 0; d < k; d++)
phiVec[d] = computePhi(factors[d]);
}
void mapIndexToPowerful(NTL::Vec<long>& pow, long j, const NTL::Vec<long>& phiVec)
// this maps an index j in [phi(m)] to a vector
// representing the powerful basis coordinates
{
long k = phiVec.length();
long phim = computeProd(phiVec);
//OLD: assert(j >= 0 && j < phim);
helib::assertInRange(j, 0l, phim, "Index j is not in [0, computeProd(phiVec))");
pow.SetLength(k);
for (long i = k-1; i >= 0; i--) {
pow[i] = j % phiVec[i];
j = (j - pow[i])/phiVec[i];
}
}
void mapPowerfulToPoly(NTL::ZZX& poly,
const NTL::Vec<long>& pow,
const NTL::Vec<long>& divVec,
long m,
const NTL::ZZX& phimX)
{
long k = pow.length();
//OLD: assert(divVec.length() == k);
helib::assertEq(divVec.length(), k, "pow and divVec have different sizes");
long j = 0;
for (long i = 0; i < k; i++)
j += pow[i] * divVec[i];
j %= m;
NTL::ZZX f = NTL::ZZX(j, 1);
poly = f % phimX;
}
// powVec[d] = p_d^{e_d}
// cycVec[d] = Phi_{p_d^{e_d}}(X) mod p
void computeCycVec(NTL::Vec<NTL::zz_pXModulus>& cycVec, const NTL::Vec<long>& powVec)
{
long k = powVec.length();
cycVec.SetLength(k);
for (long d = 0; d < k; d++) {
NTL::ZZX PhimX = Cyclotomic(powVec[d]);
cycVec[d] = NTL::conv<NTL::zz_pX>(PhimX);
}
}
// vec[d] = (a_d , b_d)
// returns \prod_d a_d^{b_d}
long computeProd(const NTL::Vec< Pair<long, long> >& vec)
{
long prod = 1;
long k = vec.length();
for (long d = 0; d < k; d++) {
prod = prod * computePow(vec[d]);
}
return prod;
}
// factors[d] = (p_d, e_d)
// computes powVec[d] = p_d^{e_d}
void computePowVec(NTL::Vec<long>& powVec,
const NTL::Vec< Pair<long, long> >& factors)
{
long k = factors.length();
powVec.SetLength(k);
for (long d = 0; d < k; d++)
powVec[d] = computePow(factors[d]);
}
// Computes the inverse of the shortToLongMap, computed above.
// "undefined" entries are initialzed to -1.
void computeLongToShortMap(NTL::Vec<long>& longToShortMap,
long m,
const NTL::Vec<long>& shortToLongMap)
{
long n = shortToLongMap.length();
longToShortMap.SetLength(m);
for (long i = 0; i < m; i++) longToShortMap[i] = -1;
for (long j = 0; j < n; j++) {
long i = shortToLongMap[j];
longToShortMap[i] = j;
}
}
// powVec[d] = m_d = p_d^{e_d}
// computes multiEvalPoints[d] as a vector of length phi(m_d)
// containing base^{(m/m_d) j} for j in Z_{m_d}^*
void computeMultiEvalPoints(NTL::Vec< NTL::Vec<NTL::zz_p> >& multiEvalPoints,
const NTL::zz_p& base,
long m,
const NTL::Vec<long>& powVec,
const NTL::Vec<long>& phiVec)
{
long k = powVec.length();
multiEvalPoints.SetLength(k);
for (long d = 0; d < k; d++) {
long m_d = powVec[d];
long phi_d = phiVec[d];
long count = 0;
NTL::zz_p pow = NTL::conv<NTL::zz_p>(1);
NTL::zz_p mult = power(base, m/m_d);
multiEvalPoints[d].SetLength(phi_d);
for (long j = 0; j < m_d; j++) {
if (GCD(j, m_d) == 1) {
multiEvalPoints[d][count] = pow;
count++;
}
pow = pow * mult;
}
}
}
// computes linearEvalPoints[i] = base^i, i in Z_m^*
void computeLinearEvalPoints(NTL::Vec<NTL::zz_p>& linearEvalPoints,
const NTL::zz_p& base,
long m, long phim)
{
linearEvalPoints.SetLength(phim);
NTL::zz_p pow = NTL::conv<NTL::zz_p>(1);
for (long i = 0, j = 0; i < m; i++) {
if (GCD(i, m) == 1) linearEvalPoints[j++] = pow;
pow = pow * base;
}
}
// powVec[d] = m_d = p_d^{e_d}
// computes compressedIndex[d] as a vector of length m_d,
// where compressedIndex[d][j] = -1 if GCD(j, m_d) != 1,
// and otherwise is set to the relative numerical position
// of j among Z_{m_d}^*
void computeCompressedIndex(NTL::Vec< NTL::Vec<long> >& compressedIndex,
const NTL::Vec<long>& powVec)
{
long k = powVec.length();
compressedIndex.SetLength(k);
for (long d = 0; d < k; d++) {
long m_d = powVec[d];
long count = 0;
compressedIndex[d].SetLength(m_d);
for (long j = 0; j < m_d; j++) {
if (GCD(j, m_d) == 1) {
compressedIndex[d][j] = count;
count++;
}
else {
compressedIndex[d][j] = -1;
}
}
}
}
// computes powToCompressedIndexMap[i] as
// -1 if GCD(i, m) != 1,
// and otherwise as the index of the point (j_1, ..., j_k)
// relative to a a cube of dimension (phi(m_1), ..., phi(m_k)),
// where each j_d is the compressed index of i_d = i mod m_d.
void computePowToCompressedIndexMap(NTL::Vec<long>& powToCompressedIndexMap,
long m,
const NTL::Vec<long>& powVec,
const NTL::Vec< NTL::Vec<long> >& compressedIndex,
const CubeSignature& shortSig
)
{
long k = powVec.length();
powToCompressedIndexMap.SetLength(m);
for (long i = 0; i < m; i++) {
if (GCD(i, m) != 1)
powToCompressedIndexMap[i] = -1;
else {
long j = 0;
for (long d = 0; d < k; d++) {
long i_d = i % powVec[d];
long j_d = compressedIndex[d][i_d];
j += j_d * shortSig.getProd(d+1);
}
powToCompressedIndexMap[i] = j;
}
}
}
void recursiveEval(const CubeSlice<NTL::zz_p>& s,
const NTL::Vec< NTL::Vec<NTL::zz_p> >& multiEvalPoints,
long d,
NTL::zz_pX& tmp1,
NTL::Vec<NTL::zz_p>& tmp2)
{
long numDims = s.getNumDims();
//OLD: assert(numDims > 0);
helib::assertTrue(numDims > 0, "CubeSlice s has negative dimension number");
if (numDims > 1) {
long dim0 = s.getDim(0);
for (long i = 0; i < dim0; i++)
recursiveEval(CubeSlice<NTL::zz_p>(s, i), multiEvalPoints, d+1, tmp1, tmp2);
}
long posBnd = s.getProd(1);
for (long pos = 0; pos < posBnd; pos++) {
getHyperColumn(tmp1.rep, s, pos);
tmp1.normalize();
eval(tmp2, tmp1, multiEvalPoints[d]);
setHyperColumn(tmp2, s, pos);
}
}
#endif
/********************************************************************/
#if 0
// Implementation of FFTHelper
#include "bluestein.h"
#include "clonedPtr.h"
FFTHelper::FFTHelper(long _m, NTL::zz_p x)
{
m = _m;
m_inv = 1/NTL::conv<NTL::zz_p>(m);
root = NTL::conv<NTL::zz_p>( SqrRootMod( NTL::conv<NTL::ZZ>(x), NTL::conv<NTL::ZZ>(NTL::zz_p::modulus())) );
// NOTE: the previous line is a pain because NTL does not have
// a single-precision variant of SqrRootMod...
iroot = 1/root;
phim = 0;
coprime.SetLength(m);
for (long i = 0; i < m; i++) {
coprime[i] = (GCD(i, m) == 1);
if (coprime[i]) phim++;
}
build(phimx, NTL::conv<NTL::zz_pX>( Cyclotomic(m) ));
}
void FFTHelper::FFT(const NTL::zz_pX& f, NTL::Vec<NTL::zz_p>& v) const
{
tmp = f;
BluesteinFFT(tmp, m, root, powers, powers_aux, Rb, Rb_aux, Ra);
v.SetLength(phim);
for (long i = 0, j = 0; i < m; i++)
if (coprime[i]) v[j++] = coeff(tmp, i);
}
void FFTHelper::iFFT(NTL::zz_pX& f, const NTL::Vec<NTL::zz_p>& v, bool normalize) const
{
tmp.rep.SetLength(m);
for (long i = 0, j = 0; i < m; i++) {
if (coprime[i]) tmp.rep[i] = v[j++];
}
tmp.normalize();
BluesteinFFT(tmp, m, iroot, ipowers, ipowers_aux, iRb, iRb_aux, Ra);
rem(f, tmp, phimx);
if (normalize) f *= m_inv;
}
// powVec[d] = m_d = p_d^{e_d}
// computes multiEvalPoints[d] as an FFTHelper for base^{m/m_d}
void computeMultiEvalPoints(NTL::Vec< copied_ptr<FFTHelper> >& multiEvalPoints,
const NTL::zz_p& base,
long m,
const NTL::Vec<long>& powVec,
const NTL::Vec<long>& phiVec)
{
long k = powVec.length();
multiEvalPoints.SetLength(k);
for (long d = 0; d < k; d++) {
long m_d = powVec[d];
multiEvalPoints[d].set_ptr(new FFTHelper(m_d, power(base, m/m_d)));
}
}
void recursiveEval(const CubeSlice<NTL::zz_p>& s,
const NTL::Vec< copied_ptr<FFTHelper> >& multiEvalPoints,
long d,
NTL::zz_pX& tmp1,
NTL::Vec<NTL::zz_p>& tmp2)
{
long numDims = s.getNumDims();
//OLD: assert(numDims > 0);
helib::assertTrue(numDims > 0, "CubeSlice s has negative dimension number");
if (numDims > 1) {
long dim0 = s.getDim(0);
for (long i = 0; i < dim0; i++)
recursiveEval(CubeSlice<NTL::zz_p>(s, i), multiEvalPoints, d+1, tmp1, tmp2);
}
long posBnd = s.getProd(1);
for (long pos = 0; pos < posBnd; pos++) {
getHyperColumn(tmp1.rep, s, pos);
tmp1.normalize();
multiEvalPoints[d]->FFT(tmp1, tmp2);
setHyperColumn(tmp2, s, pos);
}
}
void recursiveInterp(const CubeSlice<NTL::zz_p>& s,
const NTL::Vec< copied_ptr<FFTHelper> >& multiEvalPoints,
long d,
NTL::zz_pX& tmp1,
NTL::Vec<NTL::zz_p>& tmp2)
{
long numDims = s.getNumDims();
//OLD: assert(numDims > 0);
helib::assertTrue(numDims > 0, "CubeSlice s has negative dimension number");
long posBnd = s.getProd(1);
for (long pos = 0; pos < posBnd; pos++) {
getHyperColumn(tmp2, s, pos);
multiEvalPoints[d]->iFFT(tmp1, tmp2, false); // do not normalize
setHyperColumn(tmp1.rep, s, pos, NTL::zz_p::zero());
}
if (numDims > 1) {
long dim0 = s.getDim(0);
for (long i = 0; i < dim0; i++)
recursiveInterp(CubeSlice<NTL::zz_p>(s, i), multiEvalPoints, d+1, tmp1, tmp2);
}
}
void interp(HyperCube<NTL::zz_p>& cube,
const NTL::Vec< copied_ptr<FFTHelper> >& multiEvalPoints)
{
NTL::zz_pX tmp1;
NTL::Vec<NTL::zz_p> tmp2;
recursiveInterp(CubeSlice<NTL::zz_p>(cube), multiEvalPoints, 0, tmp1, tmp2);
// result is not normalized, so we fix that now...
long k = multiEvalPoints.length();
NTL::zz_p m_inv = NTL::conv<NTL::zz_p>(1);
for (long d = 0; d < k; d++) m_inv *= multiEvalPoints[d]->get_m_inv();
cube.getData() *= m_inv;
}
#endif
}
| 31.042821 | 110 | 0.581954 | patrick-schwarz |
dc097bd611910a7220604f3f0b96b9acdac5aea5 | 1,815 | cpp | C++ | regression/esbmc-cpp/inheritance/ch22_4/derived.cpp | shmarovfedor/esbmc | 3226a3d68b009d44b9535a993ac0f25e1a1fbedd | [
"BSD-3-Clause"
] | 143 | 2015-06-22T12:30:01.000Z | 2022-03-21T08:41:17.000Z | regression/esbmc-cpp/inheritance/ch22_4/derived.cpp | shmarovfedor/esbmc | 3226a3d68b009d44b9535a993ac0f25e1a1fbedd | [
"BSD-3-Clause"
] | 542 | 2017-06-02T13:46:26.000Z | 2022-03-31T16:35:17.000Z | regression/esbmc-cpp/inheritance/ch22_4/derived.cpp | shmarovfedor/esbmc | 3226a3d68b009d44b9535a993ac0f25e1a1fbedd | [
"BSD-3-Clause"
] | 81 | 2015-10-21T22:21:59.000Z | 2022-03-24T14:07:55.000Z | // Fig. 22.17: derived.cpp
// Member function definitions for class Derived
#include "derived.h"
// constructor for Derived calls constructors for
// class Base1 and class Base2.
// use member initializers to call base-class constructors
Derived::Derived( int integer, char character, double double1 )
: Base1( integer ), Base2( character ), real( double1 ) { }
// return real
double Derived::getReal() const { return real; }
// display all data members of Derived
ostream &operator<<( ostream &output, const Derived &derived )
{
output << " Integer: " << derived.value
<< "\n Character: " << derived.letter
<< "\nReal number: " << derived.real;
return output; // enables cascaded calls
} // end operator<<
/**************************************************************************
* (C) Copyright 1992-2003 by Deitel & Associates, Inc. and Prentice *
* Hall. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/
| 46.538462 | 75 | 0.579063 | shmarovfedor |
dc0aa4d8cbd81f32d58f0fcce5e51a839829d98e | 2,504 | cpp | C++ | src/utility/SuspendMonitor.cpp | d4ddi0/uldaq | cf0445561d9b511e42c10bb04a61289887b51aee | [
"MIT"
] | 73 | 2018-05-11T02:36:01.000Z | 2022-03-24T22:41:51.000Z | src/utility/SuspendMonitor.cpp | d4ddi0/uldaq | cf0445561d9b511e42c10bb04a61289887b51aee | [
"MIT"
] | 35 | 2018-06-05T13:04:11.000Z | 2022-03-31T17:38:56.000Z | src/utility/SuspendMonitor.cpp | d4ddi0/uldaq | cf0445561d9b511e42c10bb04a61289887b51aee | [
"MIT"
] | 30 | 2018-06-21T21:07:04.000Z | 2022-03-30T21:13:37.000Z | /*
* SuspendMonitor.cpp
*
* Author: Measurement Computing Corporation
*/
#include <unistd.h>
#include <stdint.h>
#include <sys/resource.h>
#include "SuspendMonitor.h"
#include "FnLog.h"
namespace ul
{
SuspendMonitor::SuspendMonitor()
{
mSuspendDetectionThread = 0;
mTerminateSuspendDetectionThread = false;
mSystemTimeRecorded = 0;
mSystemSuspendCount = 0;
}
SuspendMonitor::~SuspendMonitor()
{
FnLog log("SuspendMonitor::~SuspendMonitor()");
terminate();
}
void SuspendMonitor::start()
{
FnLog log("SuspendMonitor::startSuspendDetectionThread");
mEvent.reset();
pthread_attr_t attr;
int status = pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
if(!status)
{
status = pthread_create(&mSuspendDetectionThread, &attr, &suspendDetectionThread, this);
#ifndef __APPLE__
pthread_setname_np(mSuspendDetectionThread, "suspend_td");
#endif
if(status)
UL_LOG("#### Unable to start suspend detection thread");
status = pthread_attr_destroy(&attr);
}
else
UL_LOG("#### Unable to initialize attributes for the suspend detection thread");
}
void* SuspendMonitor::suspendDetectionThread(void *arg)
{
UL_LOG("Suspend detection handler started");
SuspendMonitor* This = (SuspendMonitor*) arg;
int niceVal = 10; // make sure this thread does not get a high priority if the parent thread is running with high priority
setpriority(PRIO_PROCESS, 0, niceVal);
unsigned long long currentTime;
const unsigned int MAX_TIME = 1000; //ms
struct timespec now;
ul_clock_realtime(&now);
This->mSystemTimeRecorded = ((uint64_t) now.tv_sec) * 1000 + ((uint64_t) now.tv_nsec / 1000000);
while (!This->mTerminateSuspendDetectionThread && This->mEvent.wait_for_signal(100000) == ETIMEDOUT)
{
ul_clock_realtime(&now);
currentTime = ((uint64_t) now.tv_sec) * 1000 + ((uint64_t) now.tv_nsec / 1000000);
if((currentTime > This->mSystemTimeRecorded) && (currentTime - This->mSystemTimeRecorded > MAX_TIME))
{
//UL_LOG("System suspended " << currentTime - mSystemTimeRecorded);
This->mSystemSuspendCount++;
}
This->mSystemTimeRecorded = currentTime;
usleep(100000);
}
UL_LOG("Suspend Detection Thread terminated");
return NULL;
}
void SuspendMonitor::terminate()
{
FnLog log("terminateSuspendDetectionThread");
mTerminateSuspendDetectionThread = true;
mEvent.signal();
if(mSuspendDetectionThread)
pthread_join(mSuspendDetectionThread, NULL);
mSuspendDetectionThread = 0;
}
} /* namespace ul */
| 21.964912 | 124 | 0.740815 | d4ddi0 |
dc123bc43140a1398a1eac4b30944d99543e193d | 6,294 | hpp | C++ | OREData/ored/configuration/capfloorvolcurveconfig.hpp | nvolfango/Engine | a5ee0fc09d5a50ab36e50d55893b6e484d6e7004 | [
"BSD-3-Clause"
] | 1 | 2021-03-30T17:24:17.000Z | 2021-03-30T17:24:17.000Z | OREData/ored/configuration/capfloorvolcurveconfig.hpp | zhangjiayin/Engine | a5ee0fc09d5a50ab36e50d55893b6e484d6e7004 | [
"BSD-3-Clause"
] | null | null | null | OREData/ored/configuration/capfloorvolcurveconfig.hpp | zhangjiayin/Engine | a5ee0fc09d5a50ab36e50d55893b6e484d6e7004 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (C) 2016 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file ored/configuration/capfloorvolcurveconfig.hpp
\brief Cap floor volatility curve configuration class
\ingroup configuration
*/
#pragma once
#include <ored/configuration/bootstrapconfig.hpp>
#include <ored/configuration/curveconfig.hpp>
#include <ql/termstructures/volatility/volatilitytype.hpp>
#include <ql/time/calendar.hpp>
#include <ql/time/daycounter.hpp>
#include <ql/time/period.hpp>
#include <ql/types.hpp>
#include <qle/termstructures/capfloortermvolsurface.hpp>
namespace ore {
namespace data {
/*! Cap floor volatility curve configuration class
\ingroup configuration
*/
class CapFloorVolatilityCurveConfig : public CurveConfig {
public:
//! The type of volatility quotes that have been configured.
enum class VolatilityType { Lognormal, Normal, ShiftedLognormal };
//! The type of structure that has been configured
enum class Type { Atm, Surface, SurfaceWithAtm };
//! Default constructor
CapFloorVolatilityCurveConfig() {}
//! Detailed constructor
CapFloorVolatilityCurveConfig(
const std::string& curveID, const std::string& curveDescription, const VolatilityType& volatilityType,
bool extrapolate, bool flatExtrapolation, bool inlcudeAtm, const std::vector<std::string>& tenors,
const std::vector<std::string>& strikes, const QuantLib::DayCounter& dayCounter, QuantLib::Natural settleDays,
const QuantLib::Calendar& calendar, const QuantLib::BusinessDayConvention& businessDayConvention,
const std::string& iborIndex, const std::string& discountCurve,
const std::string& interpolationMethod = "BicubicSpline", const std::string& interpolateOn = "TermVolatilities",
const std::string& timeInterpolation = "LinearFlat", const std::string& strikeInterpolation = "LinearFlat",
const std::vector<std::string>& atmTenors = {}, const BootstrapConfig& bootstrapConfig = BootstrapConfig());
//! \name XMLSerializable interface
//@{
void fromXML(XMLNode* node) override;
XMLNode* toXML(XMLDocument& doc) override;
//@}
//! \name Inspectors
//@{
const VolatilityType& volatilityType() const { return volatilityType_; }
bool extrapolate() const { return extrapolate_; }
bool flatExtrapolation() const { return flatExtrapolation_; }
bool includeAtm() const { return includeAtm_; }
const std::vector<std::string>& tenors() const { return tenors_; }
const std::vector<std::string>& strikes() const { return strikes_; }
const QuantLib::DayCounter& dayCounter() const { return dayCounter_; }
const QuantLib::Natural& settleDays() const { return settleDays_; }
const QuantLib::Calendar& calendar() const { return calendar_; }
const QuantLib::BusinessDayConvention& businessDayConvention() const { return businessDayConvention_; }
const std::string& iborIndex() const { return iborIndex_; }
const std::string& discountCurve() const { return discountCurve_; }
QuantExt::CapFloorTermVolSurface::InterpolationMethod interpolationMethod() const;
const std::string& interpolateOn() const { return interpolateOn_; }
const std::string& timeInterpolation() const { return timeInterpolation_; }
const std::string& strikeInterpolation() const { return strikeInterpolation_; }
const std::vector<std::string>& atmTenors() const { return atmTenors_; }
const BootstrapConfig& bootstrapConfig() const { return bootstrapConfig_; }
Type type() const { return type_; }
//@}
//! Convert VolatilityType \p type to string
std::string toString(VolatilityType type) const;
private:
VolatilityType volatilityType_;
bool extrapolate_;
bool flatExtrapolation_;
bool includeAtm_;
std::vector<std::string> tenors_;
std::vector<std::string> strikes_;
QuantLib::DayCounter dayCounter_;
QuantLib::Natural settleDays_;
QuantLib::Calendar calendar_;
QuantLib::BusinessDayConvention businessDayConvention_;
std::string iborIndex_;
std::string discountCurve_;
std::string interpolationMethod_;
std::string interpolateOn_;
std::string timeInterpolation_;
std::string strikeInterpolation_;
std::vector<std::string> atmTenors_;
BootstrapConfig bootstrapConfig_;
Type type_;
std::string extrapolation_;
//! Populate the quotes vector
void populateQuotes();
/*! Set the values of \c extrapolate_ and \c flatExtrapolation_ based on the value of \p extrapolation.
The \p extrapolation string can take the values \c "Linear", \c "Flat" or \c "None".
- \c "Linear" is for backwards compatibility and means extrapolation is on and flat extrapolation is off
- \c "Flat" means extrapolation is on and it is flat
- \c "None" means extrapolation is off
*/
void configureExtrapolation(const std::string& extrapolation);
//! Set the value of \c volatilityType_ based on the value of \p type
void configureVolatilityType(const std::string& type);
//! Set the value of \c type_ i.e. the type of cap floor structure that is configured
void configureType();
//! Validate the configuration
void validate() const;
};
//! Imply market datum quote type from CapFloorVolatilityCurveConfig::VolatilityType
std::string quoteType(CapFloorVolatilityCurveConfig::VolatilityType type);
//! Imply QuantLib::VolatilityType from CapFloorVolatilityCurveConfig::VolatilityType
QuantLib::VolatilityType volatilityType(CapFloorVolatilityCurveConfig::VolatilityType type);
} // namespace data
} // namespace ore
| 43.109589 | 120 | 0.739276 | nvolfango |
dc16068a80592b1b0fe1cbaee5c28166a1c707b1 | 6,128 | cpp | C++ | redis/src/v20180412/model/InstanceParamHistory.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | redis/src/v20180412/model/InstanceParamHistory.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | redis/src/v20180412/model/InstanceParamHistory.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/redis/v20180412/model/InstanceParamHistory.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Redis::V20180412::Model;
using namespace std;
InstanceParamHistory::InstanceParamHistory() :
m_paramNameHasBeenSet(false),
m_preValueHasBeenSet(false),
m_newValueHasBeenSet(false),
m_statusHasBeenSet(false),
m_modifyTimeHasBeenSet(false)
{
}
CoreInternalOutcome InstanceParamHistory::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("ParamName") && !value["ParamName"].IsNull())
{
if (!value["ParamName"].IsString())
{
return CoreInternalOutcome(Core::Error("response `InstanceParamHistory.ParamName` IsString=false incorrectly").SetRequestId(requestId));
}
m_paramName = string(value["ParamName"].GetString());
m_paramNameHasBeenSet = true;
}
if (value.HasMember("PreValue") && !value["PreValue"].IsNull())
{
if (!value["PreValue"].IsString())
{
return CoreInternalOutcome(Core::Error("response `InstanceParamHistory.PreValue` IsString=false incorrectly").SetRequestId(requestId));
}
m_preValue = string(value["PreValue"].GetString());
m_preValueHasBeenSet = true;
}
if (value.HasMember("NewValue") && !value["NewValue"].IsNull())
{
if (!value["NewValue"].IsString())
{
return CoreInternalOutcome(Core::Error("response `InstanceParamHistory.NewValue` IsString=false incorrectly").SetRequestId(requestId));
}
m_newValue = string(value["NewValue"].GetString());
m_newValueHasBeenSet = true;
}
if (value.HasMember("Status") && !value["Status"].IsNull())
{
if (!value["Status"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `InstanceParamHistory.Status` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_status = value["Status"].GetInt64();
m_statusHasBeenSet = true;
}
if (value.HasMember("ModifyTime") && !value["ModifyTime"].IsNull())
{
if (!value["ModifyTime"].IsString())
{
return CoreInternalOutcome(Core::Error("response `InstanceParamHistory.ModifyTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_modifyTime = string(value["ModifyTime"].GetString());
m_modifyTimeHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void InstanceParamHistory::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_paramNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ParamName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_paramName.c_str(), allocator).Move(), allocator);
}
if (m_preValueHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PreValue";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_preValue.c_str(), allocator).Move(), allocator);
}
if (m_newValueHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "NewValue";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_newValue.c_str(), allocator).Move(), allocator);
}
if (m_statusHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Status";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_status, allocator);
}
if (m_modifyTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ModifyTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_modifyTime.c_str(), allocator).Move(), allocator);
}
}
string InstanceParamHistory::GetParamName() const
{
return m_paramName;
}
void InstanceParamHistory::SetParamName(const string& _paramName)
{
m_paramName = _paramName;
m_paramNameHasBeenSet = true;
}
bool InstanceParamHistory::ParamNameHasBeenSet() const
{
return m_paramNameHasBeenSet;
}
string InstanceParamHistory::GetPreValue() const
{
return m_preValue;
}
void InstanceParamHistory::SetPreValue(const string& _preValue)
{
m_preValue = _preValue;
m_preValueHasBeenSet = true;
}
bool InstanceParamHistory::PreValueHasBeenSet() const
{
return m_preValueHasBeenSet;
}
string InstanceParamHistory::GetNewValue() const
{
return m_newValue;
}
void InstanceParamHistory::SetNewValue(const string& _newValue)
{
m_newValue = _newValue;
m_newValueHasBeenSet = true;
}
bool InstanceParamHistory::NewValueHasBeenSet() const
{
return m_newValueHasBeenSet;
}
int64_t InstanceParamHistory::GetStatus() const
{
return m_status;
}
void InstanceParamHistory::SetStatus(const int64_t& _status)
{
m_status = _status;
m_statusHasBeenSet = true;
}
bool InstanceParamHistory::StatusHasBeenSet() const
{
return m_statusHasBeenSet;
}
string InstanceParamHistory::GetModifyTime() const
{
return m_modifyTime;
}
void InstanceParamHistory::SetModifyTime(const string& _modifyTime)
{
m_modifyTime = _modifyTime;
m_modifyTimeHasBeenSet = true;
}
bool InstanceParamHistory::ModifyTimeHasBeenSet() const
{
return m_modifyTimeHasBeenSet;
}
| 28.239631 | 149 | 0.691743 | suluner |
dc18858c7b4de0402fd268f26309f7d6c9c6a182 | 24,089 | cpp | C++ | OpenCLMocker/src/API.cpp | DrizztDoUrden/OpenCLMocker | f3382ce780483f2af9c44b112ee76a2d374f097c | [
"MIT"
] | null | null | null | OpenCLMocker/src/API.cpp | DrizztDoUrden/OpenCLMocker | f3382ce780483f2af9c44b112ee76a2d374f097c | [
"MIT"
] | null | null | null | OpenCLMocker/src/API.cpp | DrizztDoUrden/OpenCLMocker | f3382ce780483f2af9c44b112ee76a2d374f097c | [
"MIT"
] | null | null | null | #include <OpenCLMocker/Buffer.hpp>
#include <OpenCLMocker/Context.hpp>
#include <OpenCLMocker/Device.hpp>
#include <OpenCLMocker/Event.hpp>
#include <OpenCLMocker/Kernel.hpp>
#include <OpenCLMocker/Platform.hpp>
#include <OpenCLMocker/Program.hpp>
#include <OpenCLMocker/Queue.hpp>
#include <CL/cl.h>
#include <algorithm>
#include <array>
#include <chrono>
#include <cstring>
#include <iostream>
#include <limits>
#include <string>
#include <thread>
namespace OpenCL
{
constexpr bool ExtensiveLogging = false;
}
namespace
{
template <class TElement>
bool FillArrayProperty(const TElement* arr, std::size_t size, size_t param_value_size, void* param_value, size_t* param_value_size_ret, const char* description = "")
{
const auto memory = size * sizeof(TElement);
const auto fullDescription = strlen(description) > 0
? std::string{" ("} + description + ")"
: description;
if (param_value != nullptr && param_value_size != 0)
{
if (OpenCL::ExtensiveLogging)
std::cerr << "CL Mocker" << fullDescription << ": Writing " << memory << " bytes to 0x" << std::ios::hex << reinterpret_cast<std::ptrdiff_t>(param_value) << std::ios::dec << "." << std::endl;
if (param_value_size < memory)
{
std::cerr << "CL Mocker" << fullDescription << ": Not enough memory to store value: " << param_value_size << " < " << memory << "." << std::endl;
return false;
}
std::memcpy(param_value, arr, memory);
}
if (param_value_size_ret != nullptr)
*param_value_size_ret = memory;
return true;
}
template <class TValue>
bool FillProperty(TValue value, size_t param_value_size, void* param_value, size_t* param_value_size_ret, const char* description = "")
{
const auto fullDescription = strlen(description) > 0
? std::string{ " (" } + description + ")"
: description;
if (param_value != nullptr && param_value_size != 0)
{
if (OpenCL::ExtensiveLogging)
std::cerr << "CL Mocker" << fullDescription << ": Writing " << sizeof(TValue) << " bytes to 0x" << std::ios::hex << reinterpret_cast<std::ptrdiff_t>(param_value) << std::ios::dec << ": " << value << std::endl;
if (param_value_size < sizeof(TValue))
{
std::cerr << "CL Mocker" << fullDescription << ": Not enough memory to store value: " << param_value_size << " < " << sizeof(TValue) << "." << std::endl;
return false;
}
*reinterpret_cast<TValue*>(param_value) = value;
}
if (param_value_size_ret != nullptr)
*param_value_size_ret = sizeof(TValue);
return true;
}
bool FillStringProperty(const std::string& value, size_t param_value_size, void* param_value, size_t* param_value_size_ret)
{
const auto memory = (value.length() + 1) * sizeof(char);
if (param_value != nullptr && param_value_size != 0)
{
if (param_value_size < memory)
return false;
std::strcpy(reinterpret_cast<char*>(param_value), value.c_str());
}
if (param_value_size_ret != nullptr)
*param_value_size_ret = memory;
return true;
}
template<class TProperty, class THandler>
cl_int IterateOverProperties(const TProperty* properties, const THandler& handler)
{
auto curPtr = properties;
while (curPtr != nullptr && *curPtr != 0)
{
const auto& name = *curPtr;
if (++curPtr == nullptr)
return CL_INVALID_PROPERTY;
const auto tret = handler(name, *curPtr);
if (tret != CL_SUCCESS)
return tret;
++curPtr;
}
return CL_SUCCESS;
}
OpenCL::Platform* GetPlatformByDeviceType(cl_device_type device_type)
{
for (auto& platform : OpenCL::Platform::Get())
for (auto& device : platform->devices)
if (device.type == device_type)
return platform;
return nullptr;
}
}
cl_int CL_API_CALL clGetPlatformIDs(cl_uint num_entries, cl_platform_id* platforms, cl_uint* num_platforms) CL_API_SUFFIX__VERSION_1_0
{
auto& existingPlatforms = OpenCL::Platform::Get();
if (num_platforms != nullptr)
* num_platforms = existingPlatforms.size();
if (platforms != nullptr && num_entries > 0)
for (auto i = 0; i < std::min(num_entries, static_cast<cl_uint>(existingPlatforms.size())); ++i)
platforms[i] = MapType(existingPlatforms[i]);
return CL_SUCCESS;
}
cl_int CL_API_CALL clGetPlatformInfo(cl_platform_id platform, cl_platform_info param_name, size_t param_value_size, void* param_value, size_t* param_value_size_ret) CL_API_SUFFIX__VERSION_1_0
{
switch (param_name)
{
case CL_PLATFORM_NAME:
if (!FillStringProperty(MapType(platform).name, param_value_size, param_value, param_value_size_ret))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
case CL_PLATFORM_VENDOR:
if (!FillStringProperty(MapType(platform).vendor, param_value_size, param_value, param_value_size_ret))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
case CL_PLATFORM_PROFILE:
if (!FillStringProperty(MapType(platform).profile, param_value_size, param_value, param_value_size_ret))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
case CL_PLATFORM_VERSION:
if (!FillStringProperty(MapType(platform).version, param_value_size, param_value, param_value_size_ret))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
default:
std::cerr << "Unknown device info: " << std::hex << param_name << std::endl;
return CL_INVALID_ARG_VALUE;
}
}
cl_int CL_API_CALL clGetDeviceIDs(cl_platform_id platform, cl_device_type device_type, cl_uint num_entries, cl_device_id* devices, cl_uint* num_devices) CL_API_SUFFIX__VERSION_1_0
{
auto& mockPlatform = MapType(platform);
if (num_devices != nullptr)
* num_devices = mockPlatform.devices.size();
if (devices != nullptr && num_entries > 0)
for (auto i = 0; i < std::min<cl_uint>(num_entries, mockPlatform.devices.size()); i++)
devices[i] = MapType(mockPlatform.devices[i]);
return CL_SUCCESS;
}
cl_context CL_API_CALL clCreateContext(const cl_context_properties* properties, cl_uint num_devices, const cl_device_id* devices, void (CL_CALLBACK* /* pfn_notify */)(const char*, const void*, size_t, void*), void* /* user_data */, cl_int* errcode_ret) CL_API_SUFFIX__VERSION_1_0
{
if (num_devices <= 0 || devices == nullptr)
{
if (errcode_ret != nullptr)
*errcode_ret = CL_INVALID_ARG_VALUE;
return nullptr;
}
auto ctx = OpenCL::Context{};
const auto propertyHandler = [&ctx](const cl_context_properties& name, const cl_context_properties& value)
{
switch (reinterpret_cast<const cl_int&>(name))
{
default:
return CL_INVALID_PROPERTY;
}
};
const auto errcode = IterateOverProperties(properties, propertyHandler);
if (errcode != CL_SUCCESS)
{
if (errcode_ret != nullptr)
* errcode_ret = errcode;
return nullptr;
}
for (auto i = 0; i < num_devices; ++i)
{
if (devices[i] == nullptr)
{
if (errcode_ret != nullptr)
* errcode_ret = CL_INVALID_ARG_VALUE;
return nullptr;
}
ctx.devices.push_back(&MapType(devices[i]));
}
ctx.platform = ctx.devices.front()->GetPlatform();
if (errcode_ret != nullptr)
* errcode_ret = CL_SUCCESS;
return MapType(new OpenCL::Context{ std::move(ctx) });
}
cl_context CL_API_CALL clCreateContextFromType(const cl_context_properties* properties, cl_device_type device_type, void (CL_CALLBACK* /* pfn_notify */)(const char*, const void*, size_t, void*), void* /* user_data */, cl_int* errcode_ret) CL_API_SUFFIX__VERSION_1_0
{
auto ctx = OpenCL::Context{};
const auto propertyHandler = [&ctx](const cl_context_properties& name, const cl_context_properties& value)
{
switch (reinterpret_cast<const cl_int&>(name))
{
case CL_CONTEXT_PLATFORM:
ctx.platform = &MapType(reinterpret_cast<const cl_platform_id&>(value));
return CL_SUCCESS;
default:
return CL_INVALID_PROPERTY;
}
};
const auto errcode = IterateOverProperties(properties, propertyHandler);
if (errcode != CL_SUCCESS)
{
if (errcode_ret != nullptr)
* errcode_ret = errcode;
return nullptr;
}
ctx.platform = GetPlatformByDeviceType(device_type);
for (auto& device : ctx.platform->devices)
ctx.devices.push_back(&device);
if (errcode_ret != nullptr)
*errcode_ret = CL_SUCCESS;
return MapType(new OpenCL::Context{ std::move(ctx) });
}
cl_int CL_API_CALL clRetainContext(cl_context context) CL_API_SUFFIX__VERSION_1_0
{
MapType(context).Retain();
return CL_SUCCESS;
}
cl_int CL_API_CALL clGetContextInfo(cl_context context, cl_context_info param_name, size_t param_value_size, void* param_value, size_t* param_value_size_ret) CL_API_SUFFIX__VERSION_1_0
{
const auto& ctx = MapType(context);
switch (param_name)
{
case CL_CONTEXT_PLATFORM:
if (!FillProperty(MapType(ctx.platform), param_value_size, param_value, param_value_size_ret, "clGetContextInfo(CL_CONTEXT_PLATFORM)"))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
case CL_CONTEXT_NUM_DEVICES:
if (!FillProperty(static_cast<cl_uint>(ctx.devices.size()), param_value_size, param_value, param_value_size_ret, "clGetContextInfo(CL_CONTEXT_PLATFORM)"))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
case CL_CONTEXT_DEVICES:
if (!FillArrayProperty(ctx.devices.data(), ctx.devices.size(), param_value_size, param_value, param_value_size_ret, "clGetContextInfo(CL_CONTEXT_DEVICES)"))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
default:
std::cerr << "Unknown device info: " << std::hex << param_name << std::endl;
return CL_INVALID_ARG_VALUE;
}
}
cl_int CL_API_CALL clGetDeviceInfo(cl_device_id device, cl_device_info param_name, size_t param_value_size, void* param_value, size_t* param_value_size_ret) CL_API_SUFFIX__VERSION_1_0
{
const auto& dev = MapType(device);
switch (param_name)
{
case CL_DEVICE_NAME:
if (!FillStringProperty("", param_value_size, param_value, param_value_size_ret))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
case CL_DEVICE_VERSION:
if (!FillStringProperty("", param_value_size, param_value, param_value_size_ret))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
case CL_DRIVER_VERSION:
if (!FillStringProperty("", param_value_size, param_value, param_value_size_ret))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
case CL_DEVICE_MAX_MEM_ALLOC_SIZE:
if (!FillProperty(std::numeric_limits<cl_ulong>::max(), param_value_size, param_value, param_value_size_ret, "clGetDeviceInfo(CL_DEVICE_MAX_MEM_ALLOC_SIZE)"))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
case CL_DEVICE_GLOBAL_MEM_SIZE:
if (!FillProperty(std::numeric_limits<cl_ulong>::max(), param_value_size, param_value, param_value_size_ret, "clGetDeviceInfo(CL_DEVICE_GLOBAL_MEM_SIZE)"))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
case CL_DEVICE_LOCAL_MEM_SIZE:
if (!FillProperty(std::numeric_limits<cl_ulong>::max(), param_value_size, param_value, param_value_size_ret, "clGetDeviceInfo(CL_DEVICE_LOCAL_MEM_SIZE)"))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
case CL_DEVICE_MAX_WORK_GROUP_SIZE:
if (!FillProperty(std::numeric_limits<size_t>::max(), param_value_size, param_value, param_value_size_ret, "clGetDeviceInfo(CL_DEVICE_MAX_WORK_GROUP_SIZE)"))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
case CL_DEVICE_MAX_CLOCK_FREQUENCY:
if (!FillProperty(std::numeric_limits<cl_uint>::max(), param_value_size, param_value, param_value_size_ret, "clGetDeviceInfo(CL_DEVICE_MAX_CLOCK_FREQUENCY)"))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
case CL_DEVICE_MAX_COMPUTE_UNITS:
if (!FillProperty(static_cast<cl_uint>(64), param_value_size, param_value, param_value_size_ret, "clGetDeviceInfo(CL_DEVICE_MAX_COMPUTE_UNITS)"))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
case CL_DEVICE_VENDOR_ID:
if (!FillProperty(static_cast<cl_uint>(0x1002), param_value_size, param_value, param_value_size_ret, "clGetDeviceInfo(CL_DEVICE_VENDOR_ID)"))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
case CL_DEVICE_AVAILABLE:
if (!FillProperty(static_cast<cl_bool>(true), param_value_size, param_value, param_value_size_ret, "clGetDeviceInfo(CL_DEVICE_AVAILABLE)"))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
case CL_DEVICE_PLATFORM:
if (!FillProperty(MapType(dev.GetPlatform()), param_value_size, param_value, param_value_size_ret, "clGetDeviceInfo(CL_DEVICE_PLATFORM)"))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
default:
std::cerr << "Unknown device info: " << std::hex << param_name << std::endl;
return CL_INVALID_ARG_VALUE;
}
}
cl_command_queue CL_API_CALL clCreateCommandQueue(cl_context context, cl_device_id device, cl_command_queue_properties /* properties */, cl_int* errcode_ret) CL_API_SUFFIX__VERSION_2_0
{
auto queue = OpenCL::Queue{};
queue.ctx = &MapType(context);
queue.device = &MapType(device);
if (errcode_ret != nullptr)
* errcode_ret = CL_SUCCESS;
return MapType(new OpenCL::Queue{ std::move(queue) });
}
cl_command_queue CL_API_CALL clCreateCommandQueueWithProperties(cl_context context, cl_device_id device, const cl_queue_properties* /* properties */, cl_int* errcode_ret) CL_API_SUFFIX__VERSION_2_0
{
auto queue = OpenCL::Queue{};
queue.ctx = &MapType(context);
queue.device = &MapType(device);
if (errcode_ret != nullptr)
* errcode_ret = CL_SUCCESS;
return MapType(new OpenCL::Queue{ std::move(queue) });
}
cl_int CL_API_CALL clRetainCommandQueue(cl_command_queue command_queue) CL_API_SUFFIX__VERSION_1_0
{
MapType(command_queue).Retain();
return CL_SUCCESS;
}
cl_int CL_API_CALL clFlush(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0 { return CL_SUCCESS; }
cl_int CL_API_CALL clFinish(cl_command_queue command_queue) CL_API_SUFFIX__VERSION_1_0
{
MapType(command_queue).Wait();
return CL_SUCCESS;
}
cl_mem CL_API_CALL clCreateBuffer(cl_context /* context */, cl_mem_flags /* flags */, size_t /* size */, void* /* host_ptr */, cl_int* errcode_ret) CL_API_SUFFIX__VERSION_1_0
{
if (errcode_ret != nullptr)
*errcode_ret = CL_SUCCESS;
return MapType(new OpenCL::Buffer{});
}
cl_mem CL_API_CALL clCreateSubBuffer(cl_mem /* buffer */, cl_mem_flags /* flags */, cl_buffer_create_type /* buffer_create_type */, const void* /* buffer_create_info */, cl_int* errcode_ret) CL_API_SUFFIX__VERSION_1_1
{
if (errcode_ret != nullptr)
*errcode_ret = CL_SUCCESS;
return MapType(new OpenCL::Buffer{});
}
cl_int CL_API_CALL clRetainMemObject(cl_mem memobj) CL_API_SUFFIX__VERSION_1_0
{
MapType(memobj).Retain();
return CL_SUCCESS;
}
cl_int CL_API_CALL clEnqueueWriteBuffer(cl_command_queue command_queue, cl_mem /* buffer */, cl_bool blocking_write, size_t /* offset */, size_t /* size */, const void* /* ptr */, cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* ev) CL_API_SUFFIX__VERSION_1_0
{
const auto mockEvent = new OpenCL::Event{ { event_wait_list, event_wait_list + num_events_in_wait_list }, std::chrono::nanoseconds(1000 + rand() % 1000) };
MapType(command_queue).RegisterEvent(mockEvent);
if (ev != nullptr)
MapType(ev) = mockEvent;
if (blocking_write)
mockEvent->Wait();
return CL_SUCCESS;
}
cl_int CL_API_CALL clGetCommandQueueInfo(cl_command_queue command_queue, cl_command_queue_info param_name, size_t param_value_size, void* param_value, size_t* param_value_size_ret) CL_API_SUFFIX__VERSION_1_0
{
const auto& queue = MapType(command_queue);
switch (param_name)
{
case CL_QUEUE_CONTEXT:
if (!FillProperty(MapType(queue.ctx), param_value_size, param_value, param_value_size_ret, "clGetCommandQueueInfo(CL_QUEUE_CONTEXT)"))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
case CL_QUEUE_DEVICE:
if (!FillProperty(MapType(queue.device), param_value_size, param_value, param_value_size_ret, "clGetCommandQueueInfo(CL_QUEUE_DEVICE)"))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
default:
std::cerr << "Unknown device info: " << std::hex << param_name << std::endl;
return CL_INVALID_ARG_VALUE;
}
}
cl_program CL_API_CALL clCreateProgramWithSource(cl_context /* context */, cl_uint /* count */, const char** /* strings */, const size_t* /* lengths */, cl_int* errcode_ret) CL_API_SUFFIX__VERSION_1_0
{
if (errcode_ret != nullptr)
*errcode_ret = CL_SUCCESS;
return MapType(new OpenCL::Program{});
}
cl_program CL_API_CALL clCreateProgramWithBinary(cl_context /* context */, cl_uint /* num_devices */, const cl_device_id* /* device_list */, const size_t* /* lengths */, const unsigned char** /* binaries */, cl_int* /* binary_status */, cl_int* errcode_ret) CL_API_SUFFIX__VERSION_1_0
{
if (errcode_ret != nullptr)
* errcode_ret = CL_SUCCESS;
return MapType(new OpenCL::Program{});
}
cl_int CL_API_CALL clRetainProgram(cl_program program) CL_API_SUFFIX__VERSION_1_0
{
MapType(program).Retain();
return CL_SUCCESS;
}
cl_int CL_API_CALL clBuildProgram(cl_program /* program */, cl_uint /* num_devices */, const cl_device_id* /* device_list */, const char* /* options */, void (CL_CALLBACK* /* pfn_notify */)(cl_program /* program */, void* /* user_data */), void* /* user_data */) CL_API_SUFFIX__VERSION_1_0
{
std::this_thread::sleep_for(std::chrono::milliseconds{ 10 + rand() % 10 });
return CL_SUCCESS;
}
cl_int CL_API_CALL clGetProgramBuildInfo(cl_program /* program */, cl_device_id /* device */, cl_program_build_info param_name, size_t param_value_size, void* param_value, size_t* param_value_size_ret) CL_API_SUFFIX__VERSION_1_0
{
switch (param_name)
{
case CL_PROGRAM_BUILD_LOG:
if (!FillStringProperty("", param_value_size, param_value, param_value_size_ret))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
default:
return CL_INVALID_ARG_VALUE;
}
}
cl_int CL_API_CALL clGetProgramInfo(cl_program /* program */, cl_program_info param_name, size_t param_value_size, void* param_value, size_t* param_value_size_ret) CL_API_SUFFIX__VERSION_1_0
{
auto binaries = std::array<std::array<char, 1024>, 1>{};
switch (param_name)
{
case CL_PROGRAM_BINARY_SIZES:
{
auto sizes = std::array<std::size_t, std::tuple_size<decltype(binaries)>::value>{};
std::transform(binaries.begin(), binaries.end(), sizes.begin(), [](auto&& arr) { return arr.size(); });
if (!FillArrayProperty(sizes.data(), sizes.size(), param_value_size, param_value, param_value_size_ret, "clGetProgramInfo(CL_PROGRAM_BINARY_SIZES)"))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
}
case CL_PROGRAM_BINARIES:
{
if (OpenCL::ExtensiveLogging)
std::cerr << "CL Mocker(clGetProgramInfo(CL_PROGRAM_BINARIES)): Writing " << binaries.size() << " binaries to 0x" << std::ios::hex << reinterpret_cast<std::ptrdiff_t>(param_value) << std::ios::dec << "." << std::endl;
if (param_value_size / sizeof(std::size_t) != binaries.size() ||
param_value_size % sizeof(std::size_t) != 0)
return CL_INVALID_ARG_SIZE;
const auto resultNum = param_value_size < sizeof(std::size_t);
char** results = reinterpret_cast<char**>(param_value);
for (auto i = 0; i < resultNum; ++i)
strncpy(results[i], binaries[i].data(), binaries[i].size());
return CL_SUCCESS;
}
default:
std::cerr << "Unknown device info: " << std::hex << param_name << std::endl;
return CL_INVALID_VALUE;
}
}
cl_kernel CL_API_CALL clCreateKernel(cl_program /* program */, const char* kernel_name, cl_int* errcode_ret) CL_API_SUFFIX__VERSION_1_0
{
auto kernel = OpenCL::Kernel{};
kernel.name = kernel_name;
if (errcode_ret != nullptr)
* errcode_ret = CL_SUCCESS;
return MapType(new OpenCL::Kernel{ std::move(kernel) });
}
cl_int CL_API_CALL clRetainKernel(cl_kernel kernel) CL_API_SUFFIX__VERSION_1_0
{
MapType(kernel).Retain();
return CL_SUCCESS;
}
cl_int CL_API_CALL clGetKernelInfo(cl_kernel kernel, cl_kernel_info param_name, size_t param_value_size, void* param_value, size_t* param_value_size_ret) CL_API_SUFFIX__VERSION_1_0
{
const auto& k = MapType(kernel);
switch (param_name)
{
case CL_KERNEL_FUNCTION_NAME:
if (!FillStringProperty(k.name, param_value_size, param_value, param_value_size_ret))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
default:
std::cerr << "Unknown device info: " << std::hex << param_name << std::endl;
return CL_INVALID_ARG_VALUE;
}
}
cl_int CL_API_CALL clSetKernelArg(cl_kernel /* kernel */, cl_uint /* arg_index */, size_t /* arg_size */, const void* /* arg_value */) CL_API_SUFFIX__VERSION_1_0
{
return CL_SUCCESS;
}
cl_int CL_API_CALL clEnqueueNDRangeKernel(cl_command_queue command_queue, cl_kernel /* kernel */, cl_uint /* work_dim */, const size_t* /* global_work_offset */, const size_t* /* global_work_size */, const size_t* /* local_work_size */, cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* ev) CL_API_SUFFIX__VERSION_1_0
{
const auto mockEvent = new OpenCL::Event{ { event_wait_list, event_wait_list + num_events_in_wait_list }, std::chrono::nanoseconds(3000 + rand() % 3000) };
MapType(command_queue).RegisterEvent(mockEvent);
if (ev != nullptr)
MapType(ev) = mockEvent;
return CL_SUCCESS;
}
cl_int CL_API_CALL clWaitForEvents(cl_uint num_events, const cl_event* event_list) CL_API_SUFFIX__VERSION_1_0
{
for (auto i = 0; i < num_events; ++i)
{
auto& mockEvent = MapType(event_list[i]);
if (!mockEvent.IsFinished())
mockEvent.Wait();
}
return CL_SUCCESS;
}
cl_int CL_API_CALL clGetEventProfilingInfo(cl_event ev, cl_profiling_info param_name, size_t param_value_size, void* param_value, size_t* param_value_size_ret) CL_API_SUFFIX__VERSION_1_0
{
auto& mockEvent = MapType(ev);
switch (param_name)
{
case CL_PROFILING_COMMAND_START:
if (!FillProperty<cl_ulong>(mockEvent.GetStart().time_since_epoch().count(), param_value_size, param_value, param_value_size_ret, "clGetEventProfilingInfo(CL_PROFILING_COMMAND_START)"))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
case CL_PROFILING_COMMAND_END:
if (!FillProperty<cl_ulong>(mockEvent.GetEnd().time_since_epoch().count(), param_value_size, param_value, param_value_size_ret, "clGetEventProfilingInfo(CL_PROFILING_COMMAND_END)"))
return CL_INVALID_ARG_SIZE;
return CL_SUCCESS;
default:
std::cerr << "Unknown device info: " << std::hex << param_name << std::endl;
return CL_INVALID_ARG_VALUE;
}
}
cl_int CL_API_CALL clEnqueueCopyBuffer(cl_command_queue command_queue, cl_mem /* src_buffer */, cl_mem /* dst_buffer */, size_t /* src_offset */, size_t /* dst_offset */, size_t /* size */, cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* ev) CL_API_SUFFIX__VERSION_1_0
{
const auto mockEvent = new OpenCL::Event{ { event_wait_list, event_wait_list + num_events_in_wait_list }, std::chrono::nanoseconds(1000 + rand() % 1000) };
MapType(command_queue).RegisterEvent(mockEvent);
if (ev != nullptr)
MapType(ev) = mockEvent;
return CL_SUCCESS;
}
cl_int CL_API_CALL clEnqueueReadBuffer(cl_command_queue command_queue, cl_mem /* buffer */, cl_bool blocking_read, size_t /* offset */, size_t /* size */, void* /* ptr */, cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* ev) CL_API_SUFFIX__VERSION_1_0
{
auto mockEvent = OpenCL::Event{ { event_wait_list, event_wait_list + num_events_in_wait_list }, std::chrono::nanoseconds(1000 + rand() % 1000) };
if (blocking_read)
{
mockEvent.Wait();
return CL_SUCCESS;
}
MapType(command_queue).RegisterEvent(new OpenCL::Event{std::move(mockEvent)});
return CL_SUCCESS;
}
cl_int CL_API_CALL clReleaseMemObject(cl_mem memobj) CL_API_SUFFIX__VERSION_1_0
{
auto& mem = MapType(memobj);
if (mem.Release())
delete& mem;
return CL_SUCCESS;
}
cl_int CL_API_CALL clReleaseKernel(cl_kernel kernel) CL_API_SUFFIX__VERSION_1_0
{
auto& k = MapType(kernel);
if (k.Release())
delete& k;
return CL_SUCCESS;
}
cl_int CL_API_CALL clReleaseProgram(cl_program program) CL_API_SUFFIX__VERSION_1_0
{
auto& p = MapType(program);
if (p.Release())
delete& p;
return CL_SUCCESS;
}
cl_int CL_API_CALL clReleaseCommandQueue(cl_command_queue command_queue) CL_API_SUFFIX__VERSION_1_0
{
auto& queue = MapType(command_queue);
if (queue.Release())
delete& queue;
return CL_SUCCESS;
}
cl_int CL_API_CALL clReleaseContext(cl_context context) CL_API_SUFFIX__VERSION_1_0
{
auto& ctx = MapType(context);
if (ctx.Release())
delete& ctx;
return CL_SUCCESS;
}
cl_int CL_API_CALL clReleaseEvent(cl_event ev) CL_API_SUFFIX__VERSION_1_0
{
auto& event = MapType(ev);
if (event.Release())
delete& event;
return CL_SUCCESS;
}
| 34.911594 | 343 | 0.752916 | DrizztDoUrden |
dc19742bfcb720ab23dcf47060eea87b6feb27b6 | 11,184 | cpp | C++ | src/utils/socket_client_udp.cpp | evaesteban/brainflow | 4310cdd61903992e06f855d65a6f6f42c2970757 | [
"MIT"
] | 1 | 2021-01-26T07:08:00.000Z | 2021-01-26T07:08:00.000Z | src/utils/socket_client_udp.cpp | TimurGolovinov/brainflow | 1199dd38438b32aefb6d91352832f54c306ef687 | [
"MIT"
] | 5 | 2021-02-08T14:35:32.000Z | 2021-04-24T00:37:08.000Z | src/utils/socket_client_udp.cpp | xloem/brainflow | b8faafc84df6eb728f94e3dbf102289633756adb | [
"MIT"
] | 2 | 2021-01-10T18:18:15.000Z | 2022-02-01T16:44:33.000Z | #include <string.h>
#include "socket_client_udp.h"
///////////////////////////////
/////////// WINDOWS ///////////
//////////////////////////////
#ifdef _WIN32
#pragma comment(lib, "Ws2_32.lib")
#pragma comment(lib, "Mswsock.lib")
#pragma comment(lib, "AdvApi32.lib")
int SocketClientUDP::get_local_ip_addr (const char *connect_ip, int port, char *local_ip)
{
WSADATA wsadata;
int return_value = (int)SocketClientUDPReturnCodes::STATUS_OK;
struct sockaddr_in serv;
char buffer[80];
SOCKET sock = INVALID_SOCKET;
struct sockaddr_in name;
int res = WSAStartup (MAKEWORD (2, 2), &wsadata);
if (res != 0)
{
return_value = (int)SocketClientUDPReturnCodes::WSA_STARTUP_ERROR;
}
if (return_value == (int)SocketClientUDPReturnCodes::STATUS_OK)
{
sock = socket (AF_INET, SOCK_DGRAM, 0);
if (sock == INVALID_SOCKET)
{
return_value = (int)SocketClientUDPReturnCodes::CREATE_SOCKET_ERROR;
}
}
if (return_value == (int)SocketClientUDPReturnCodes::STATUS_OK)
{
memset (&serv, 0, sizeof (serv));
serv.sin_family = AF_INET;
if (inet_pton (AF_INET, connect_ip, &serv.sin_addr) == 0)
{
return_value = (int)SocketClientUDPReturnCodes::PTON_ERROR;
}
serv.sin_port = htons (port);
}
if (return_value == (int)SocketClientUDPReturnCodes::STATUS_OK)
{
if (::connect (sock, (const struct sockaddr *)&serv, sizeof (serv)) == SOCKET_ERROR)
{
return_value = (int)SocketClientUDPReturnCodes::CONNECT_ERROR;
}
}
if (return_value == (int)SocketClientUDPReturnCodes::STATUS_OK)
{
int name_len = sizeof (name);
int err = getsockname (sock, (struct sockaddr *)&name, &name_len);
if (err != 0)
{
return_value = (int)SocketClientUDPReturnCodes::CONNECT_ERROR;
}
}
if (return_value == (int)SocketClientUDPReturnCodes::STATUS_OK)
{
const char *p = inet_ntop (AF_INET, &name.sin_addr, buffer, 80);
if (p != NULL)
{
strcpy (local_ip, buffer);
}
else
{
return_value = (int)SocketClientUDPReturnCodes::PTON_ERROR;
}
}
closesocket (sock);
WSACleanup ();
return return_value;
}
SocketClientUDP::SocketClientUDP (const char *ip_addr, int port)
{
strcpy (this->ip_addr, ip_addr);
this->port = port;
connect_socket = INVALID_SOCKET;
memset (&socket_addr, 0, sizeof (socket_addr));
}
int SocketClientUDP::connect ()
{
WSADATA wsadata;
int res = WSAStartup (MAKEWORD (2, 2), &wsadata);
if (res != 0)
{
return (int)SocketClientUDPReturnCodes::WSA_STARTUP_ERROR;
}
socket_addr.sin_family = AF_INET;
socket_addr.sin_port = htons (port);
if (inet_pton (AF_INET, ip_addr, &socket_addr.sin_addr) == 0)
{
return (int)SocketClientUDPReturnCodes::PTON_ERROR;
}
connect_socket = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (connect_socket == INVALID_SOCKET)
{
return (int)SocketClientUDPReturnCodes::CREATE_SOCKET_ERROR;
}
// ensure that library will not hang in blocking recv/send call
DWORD timeout = 5000;
setsockopt (connect_socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof (timeout));
setsockopt (connect_socket, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof (timeout));
if (::connect (connect_socket, (const struct sockaddr *)&socket_addr, sizeof (socket_addr)) ==
SOCKET_ERROR)
{
return (int)SocketClientUDPReturnCodes::CONNECT_ERROR;
}
return (int)SocketClientUDPReturnCodes::STATUS_OK;
}
int SocketClientUDP::set_timeout (int num_seconds)
{
if ((num_seconds < 1) || (num_seconds > 100))
{
return (int)SocketClientUDPReturnCodes::INVALID_ARGUMENT_ERROR;
}
if (connect_socket == INVALID_SOCKET)
{
return (int)SocketClientUDPReturnCodes::CREATE_SOCKET_ERROR;
}
DWORD timeout = 1000 * num_seconds;
setsockopt (connect_socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof (timeout));
setsockopt (connect_socket, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof (timeout));
return (int)SocketClientUDPReturnCodes::STATUS_OK;
}
int SocketClientUDP::bind ()
{
// for socket clients which dont call sendto before recvfrom bind should be called on client
// side
// https://stackoverflow.com/questions/3057029/do-i-have-to-bind-a-udp-socket-in-my-client-program-to-receive-data-i-always-g
if (connect_socket == INVALID_SOCKET)
{
return (int)SocketClientUDPReturnCodes::CREATE_SOCKET_ERROR;
}
if (::bind (connect_socket, (const struct sockaddr *)&socket_addr, sizeof (socket_addr)) != 0)
{
return (int)SocketClientUDPReturnCodes::CONNECT_ERROR;
}
return (int)SocketClientUDPReturnCodes::STATUS_OK;
}
int SocketClientUDP::get_local_port ()
{
if (connect_socket == INVALID_SOCKET)
{
return (int)SocketClientUDPReturnCodes::CREATE_SOCKET_ERROR;
}
struct sockaddr_in sin_local;
memset (&sin_local, 0, sizeof (sin_local));
socklen_t slen = (socklen_t)sizeof (sin_local);
if (getsockname (connect_socket, (struct sockaddr *)&sin_local, &slen) == 0)
{
return ntohs (sin_local.sin_port);
}
else
{
return -1;
}
}
int SocketClientUDP::send (const char *data, int size)
{
int res = sendto (connect_socket, data, size, 0, NULL, NULL);
if (res == SOCKET_ERROR)
{
return -1;
}
return res;
}
int SocketClientUDP::recv (void *data, int size)
{
int res = recvfrom (connect_socket, (char *)data, size, 0, NULL, NULL);
if (res == SOCKET_ERROR)
{
return -1;
}
return res;
}
void SocketClientUDP::close ()
{
closesocket (connect_socket);
connect_socket = INVALID_SOCKET;
WSACleanup ();
}
///////////////////////////////
//////////// UNIX /////////////
///////////////////////////////
#else
#include <netinet/in.h>
#include <netinet/tcp.h>
int SocketClientUDP::get_local_ip_addr (const char *connect_ip, int port, char *local_ip)
{
int return_value = (int)SocketClientUDPReturnCodes::STATUS_OK;
struct sockaddr_in serv;
char buffer[80];
int sock = -1;
struct sockaddr_in name;
if (return_value == (int)SocketClientUDPReturnCodes::STATUS_OK)
{
sock = socket (AF_INET, SOCK_DGRAM, 0);
if (sock < 0)
{
return_value = (int)SocketClientUDPReturnCodes::CREATE_SOCKET_ERROR;
}
}
if (return_value == (int)SocketClientUDPReturnCodes::STATUS_OK)
{
memset (&serv, 0, sizeof (serv));
serv.sin_family = AF_INET;
if (inet_pton (AF_INET, connect_ip, &serv.sin_addr) == 0)
{
return_value = (int)SocketClientUDPReturnCodes::PTON_ERROR;
}
serv.sin_port = htons (port);
}
if (return_value == (int)SocketClientUDPReturnCodes::STATUS_OK)
{
if (::connect (sock, (const struct sockaddr *)&serv, sizeof (serv)) == -1)
{
return_value = (int)SocketClientUDPReturnCodes::CONNECT_ERROR;
}
}
if (return_value == (int)SocketClientUDPReturnCodes::STATUS_OK)
{
socklen_t namelen = (socklen_t)sizeof (name);
int err = getsockname (sock, (struct sockaddr *)&name, &namelen);
if (err != 0)
{
return_value = (int)SocketClientUDPReturnCodes::CONNECT_ERROR;
}
}
if (return_value == (int)SocketClientUDPReturnCodes::STATUS_OK)
{
const char *p = inet_ntop (AF_INET, &name.sin_addr, buffer, 80);
if (p != NULL)
{
strcpy (local_ip, buffer);
}
else
{
return_value = (int)SocketClientUDPReturnCodes::PTON_ERROR;
}
}
::close (sock);
return return_value;
}
SocketClientUDP::SocketClientUDP (const char *ip_addr, int port)
{
strcpy (this->ip_addr, ip_addr);
this->port = port;
connect_socket = -1;
memset (&socket_addr, 0, sizeof (socket_addr));
}
int SocketClientUDP::connect ()
{
connect_socket = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (connect_socket < 0)
{
return (int)SocketClientUDPReturnCodes::CREATE_SOCKET_ERROR;
}
socket_addr.sin_family = AF_INET;
socket_addr.sin_port = htons (port);
if (inet_pton (AF_INET, ip_addr, &socket_addr.sin_addr) == 0)
{
return (int)SocketClientUDPReturnCodes::PTON_ERROR;
}
// ensure that library will not hang in blocking recv/send call
struct timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;
setsockopt (connect_socket, SOL_SOCKET, SO_RCVTIMEO, (const char *)&tv, sizeof (tv));
setsockopt (connect_socket, SOL_SOCKET, SO_SNDTIMEO, (const char *)&tv, sizeof (tv));
if (::connect (connect_socket, (const struct sockaddr *)&socket_addr, sizeof (socket_addr)) ==
-1)
{
return (int)SocketClientUDPReturnCodes::CONNECT_ERROR;
}
return (int)SocketClientUDPReturnCodes::STATUS_OK;
}
int SocketClientUDP::set_timeout (int num_seconds)
{
if ((num_seconds < 1) || (num_seconds > 100))
{
return (int)SocketClientUDPReturnCodes::INVALID_ARGUMENT_ERROR;
}
if (connect_socket < 0)
{
return (int)SocketClientUDPReturnCodes::CREATE_SOCKET_ERROR;
}
struct timeval tv;
tv.tv_sec = num_seconds;
tv.tv_usec = 0;
setsockopt (connect_socket, SOL_SOCKET, SO_RCVTIMEO, (const char *)&tv, sizeof (tv));
setsockopt (connect_socket, SOL_SOCKET, SO_SNDTIMEO, (const char *)&tv, sizeof (tv));
return (int)SocketClientUDPReturnCodes::STATUS_OK;
}
int SocketClientUDP::bind ()
{
// for socket clients which dont call sendto before recvfrom bind should be called on client
// side
// https://stackoverflow.com/questions/3057029/do-i-have-to-bind-a-udp-socket-in-my-client-program-to-receive-data-i-always-g
if (connect_socket < 0)
{
return (int)SocketClientUDPReturnCodes::CREATE_SOCKET_ERROR;
}
if (::bind (connect_socket, (const struct sockaddr *)&socket_addr, sizeof (socket_addr)) != 0)
{
return (int)SocketClientUDPReturnCodes::CONNECT_ERROR;
}
return (int)SocketClientUDPReturnCodes::STATUS_OK;
}
int SocketClientUDP::get_local_port ()
{
if (connect_socket < 0)
{
return (int)SocketClientUDPReturnCodes::CREATE_SOCKET_ERROR;
}
struct sockaddr_in sin_local;
memset (&sin_local, 0, sizeof (sin_local));
socklen_t slen = (socklen_t)sizeof (sin_local);
if (getsockname (connect_socket, (struct sockaddr *)&sin_local, &slen) == 0)
{
return ntohs (sin_local.sin_port);
}
else
{
return -1;
}
}
int SocketClientUDP::send (const char *data, int size)
{
int res = sendto (connect_socket, data, size, 0, NULL, 0);
return res;
}
int SocketClientUDP::recv (void *data, int size)
{
int res = recvfrom (connect_socket, (char *)data, size, 0, NULL, NULL);
return res;
}
void SocketClientUDP::close ()
{
::close (connect_socket);
connect_socket = -1;
}
#endif
| 28.676923 | 129 | 0.638501 | evaesteban |
dc1c7e66b98a377fb74b1dfa4e498861406b3717 | 1,258 | cpp | C++ | Firmware/commonSrc/Commands.cpp | usatiuk/EggbotWireless | 4b46fc080c91d4d2b4c5d9c5d559a33500e68c56 | [
"MIT"
] | 1 | 2021-09-24T14:39:28.000Z | 2021-09-24T14:39:28.000Z | Firmware/commonSrc/Commands.cpp | usatiuk/EggbotWireless | 4b46fc080c91d4d2b4c5d9c5d559a33500e68c56 | [
"MIT"
] | 4 | 2020-12-06T14:25:52.000Z | 2021-11-15T19:50:37.000Z | Firmware/commonSrc/Commands.cpp | usatiuk/EggbotWireless | 4b46fc080c91d4d2b4c5d9c5d559a33500e68c56 | [
"MIT"
] | null | null | null | #include <Arduino.h>
#include "common/Commands.h"
Command::Command(CommandType type, float arg1, float arg2, float arg3,
float arg4, float arg5, float arg6)
: type(type),
arg1(arg1),
arg2(arg2),
arg3(arg3),
arg4(arg4),
arg5(arg5),
arg6(arg6){};
Command::Command(float *floats) { fromFloats(floats); }
void Command::fromFloats(float *floats) {
type = static_cast<CommandType>(floats[0]);
arg1 = floats[1];
arg2 = floats[2];
arg3 = floats[3];
arg4 = floats[4];
arg5 = floats[5];
arg6 = floats[6];
}
void Command::toFloats(float *floats) {
floats[0] = static_cast<float>(type);
floats[1] = arg1;
floats[2] = arg2;
floats[3] = arg3;
floats[4] = arg4;
floats[5] = arg5;
floats[6] = arg6;
}
Command::Command(byte *bytes) { fromBytes(bytes); }
void Command::fromBytes(byte *bytes) {
float floats[i2cCmdFloats];
for (int i = 0; i < i2cCmdFloats; i++) {
bytesToFloat(&floats[i], &bytes[i * i2cFloatSize]);
}
fromFloats(floats);
}
void Command::toBytes(byte *bytes) {
float floats[i2cCmdFloats];
toFloats(floats);
for (int i = 0; i < 7; i++) {
floatToBytes(&bytes[i * i2cFloatSize], floats[i]);
}
}
| 23.296296 | 70 | 0.5938 | usatiuk |
dc1f0e9af2e01b39ad6e826398f23288e833e54e | 62,420 | cpp | C++ | test/test.cpp | calzakk/CyoArguments | 85e572a4648793ede087162fe3c13869ebb28d5d | [
"MIT"
] | 3 | 2015-11-16T15:54:17.000Z | 2021-08-18T22:14:09.000Z | test/test.cpp | calzakk/CyoArguments | 85e572a4648793ede087162fe3c13869ebb28d5d | [
"MIT"
] | null | null | null | test/test.cpp | calzakk/CyoArguments | 85e572a4648793ede087162fe3c13869ebb28d5d | [
"MIT"
] | null | null | null | /*
[CyoArguments] test.cpp
The MIT License (MIT)
Copyright (c) 2015-2016 Graham Bull
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 "cyoarguments.hpp"
#include <algorithm>
#include <iostream>
#include <list>
#include <stdexcept>
#include <string>
#include <vector>
using namespace cyoarguments;
///////////////////////////////////////////////////////////////////////////////
#define CHECK(value) \
if (!value) \
{ \
std::cout << "\nline " << __LINE__ << ": value=" << value; \
throw std::runtime_error("Unexpected value"); \
}
#define CHECK_EQUAL(expected, actual) \
if (expected != actual) \
{ \
std::cout << "\nline " << __LINE__ << ": value=" << actual << " expected=" << expected; \
throw std::runtime_error("Unexpected value"); \
}
#define CHECK_THROW(expected, func) \
try \
{ \
func; \
throw std::runtime_error("Exception not caught"); \
} \
catch (const std::exception& ex) \
{ \
if (std::string(expected) != ex.what()) \
{ \
std::cout << "\nline " << __LINE__ << ": exception=" << ex.what() << " expected=" << expected; \
throw std::runtime_error("Exception not caught"); \
} \
} \
catch (...) \
{ \
}
#define TEST(name, index, setup) \
class Test##name##index : public setup \
{ \
public: \
static Test##name##index instance; \
Test##name##index() \
{ \
TestRunner::instance().AddTest(this); \
} \
private: \
std::string getNameImpl() const override \
{ \
return "Test" #name #index; \
} \
void RunImpl() override; \
}; \
Test##name##index Test##name##index::instance; \
void Test##name##index::RunImpl()
namespace
{
class Test
{
public:
std::string getName() const { return getNameImpl(); }
void Run() { RunImpl(); }
protected:
Arguments arguments;
void ProcessArgs(const std::vector<const char*>& args, bool expectedResult, const char* expectedError)
{
std::vector<const char*> fullArgs{ "exe_pathname" };
std::copy(begin(args), end(args), std::back_inserter(fullArgs));
std::string actualError;
bool actualResult = arguments.Process((int)fullArgs.size(), (char**)&fullArgs[0], actualError);
if (actualResult != expectedResult)
{
std::cout << "\nresult=" << actualResult << " expected=" << expectedResult;
throw std::runtime_error("Unexpected result");
}
if (actualError.compare(expectedError) != 0)
{
std::cout << "\nerror=\"" << actualError << "\" expected=\"" << expectedError << "\"";
throw std::runtime_error("Unexpected error");
}
}
private:
virtual std::string getNameImpl() const = 0;
virtual void RunImpl() = 0;
};
class TestRunner
{
public:
static TestRunner& instance()
{
static TestRunner testRunner;
return testRunner;
}
void AddTest(Test* test)
{
tests_.push_back(test);
}
void RunAllTests()
{
int testNum = 0;
int failures = 0;
for (auto& test : tests_)
{
try
{
std::cout << "TEST " << ++testNum << ": " << test->getName() << ":";
test->Run();
std::cout << " success" << std::endl;
}
catch (...)
{
++failures;
std::cout << "\n*** FAILED ***" << std::endl;
}
}
std::cout << '\n' << failures << " failure(s)" << std::endl;
}
private:
std::list<Test*> tests_;
};
///////////////////////////////////////////////////////////////////////////
// bool
namespace
{
// Letter
namespace
{
class LetterBoolBase : public Test
{
public:
LetterBoolBase()
{
arguments.AddOption('a', "description", a);
arguments.AddOption('b', "description", b);
}
bool a = false;
bool b = false;
};
TEST(LetterBool, 1, LetterBoolBase)
{
ProcessArgs({ "-a1" }, false, "Invalid argument: -a1");
CHECK_EQUAL(true, a);
CHECK_EQUAL(false, b);
}
TEST(LetterBool, 2, LetterBoolBase)
{
ProcessArgs({ "-a=2" }, false, "Invalid argument: -a=2");
CHECK_EQUAL(false, a);
CHECK_EQUAL(false, b);
}
TEST(LetterBool, 3, LetterBoolBase)
{
ProcessArgs({ "-a", "3" }, false, "Invalid argument: 3");
CHECK_EQUAL(true, a);
CHECK_EQUAL(false, b);
}
TEST(LetterBool, 4, LetterBoolBase)
{
ProcessArgs({ "-a=", "4" }, false, "Invalid argument: -a=");
CHECK_EQUAL(false, a);
CHECK_EQUAL(false, b);
}
TEST(LetterBool, 5, LetterBoolBase)
{
ProcessArgs({ "-a" }, true, "");
CHECK_EQUAL(true, a);
CHECK_EQUAL(false, b);
}
TEST(LetterBool, 6, LetterBoolBase)
{
ProcessArgs({ "-a=" }, false, "Invalid argument: -a=");
CHECK_EQUAL(false, a);
CHECK_EQUAL(false, b);
}
}
// Letters
namespace
{
class LettersBoolBase : public Test
{
public:
LettersBoolBase()
{
arguments.AddOption('x', "description", x);
arguments.AddOption('y', "description", y);
}
bool x = false;
bool y = false;
};
TEST(LettersBool, 1, LettersBoolBase)
{
ProcessArgs({ "-x1y2" }, false, "Invalid argument: -x1y2");
CHECK_EQUAL(true, x);
CHECK_EQUAL(false, y);
}
TEST(LettersBool, 2, LettersBoolBase)
{
ProcessArgs({ "-x3", "-y4" }, false, "Invalid argument: -x3");
CHECK_EQUAL(true, x);
CHECK_EQUAL(false, y);
}
TEST(LettersBool, 3, LettersBoolBase)
{
ProcessArgs({ "-x", "5", "-y", "6" }, false, "Invalid argument: 5");
CHECK_EQUAL(true, x);
CHECK_EQUAL(false, y);
}
TEST(LettersBool, 4, LettersBoolBase)
{
ProcessArgs({ "-xy" }, true, "");
CHECK_EQUAL(true, x);
CHECK_EQUAL(true, y);
}
}
// Word
namespace
{
class WordBoolBase : public Test
{
public:
WordBoolBase()
{
arguments.AddOption("num", "description", num);
}
bool num = false;
};
TEST(WordBool, 1, WordBoolBase)
{
ProcessArgs({ "--num1" }, false, "Invalid argument: --num1");
CHECK_EQUAL(false, num);
}
TEST(WordBool, 2, WordBoolBase)
{
ProcessArgs({ "--num=2" }, false, "Invalid argument: --num=2");
CHECK_EQUAL(false, num);
}
TEST(WordBool, 3, WordBoolBase)
{
ProcessArgs({ "--num", "3" }, false, "Invalid argument: 3");
CHECK_EQUAL(true, num);
}
TEST(WordBool, 4, WordBoolBase)
{
ProcessArgs({ "--num=", "4" }, false, "Invalid argument: --num=");
CHECK_EQUAL(false, num);
}
TEST(WordBool, 5, WordBoolBase)
{
ProcessArgs({ "--num" }, true, "");
CHECK_EQUAL(true, num);
}
TEST(WordBool, 6, WordBoolBase)
{
ProcessArgs({ "--num=" }, false, "Invalid argument: --num=");
CHECK_EQUAL(false, num);
}
}
// Words
namespace
{
class WordsBoolBase : public Test
{
public:
WordsBoolBase()
{
arguments.AddOption("num", "description", num);
arguments.AddOption("val", "description", val);
}
bool num = false;
bool val = false;
};
TEST(WordsBool, 1, WordsBoolBase)
{
ProcessArgs({ "--num1", "--val2" }, false, "Invalid argument: --num1");
CHECK_EQUAL(false, num);
CHECK_EQUAL(false, val);
}
TEST(WordsBool, 2, WordsBoolBase)
{
ProcessArgs({ "--num=3", "--val=4" }, false, "Invalid argument: --num=3");
CHECK_EQUAL(false, num);
CHECK_EQUAL(false, val);
}
TEST(WordsBool, 3, WordsBoolBase)
{
ProcessArgs({ "--num", "5", "--val", "6" }, false, "Invalid argument: 5");
CHECK_EQUAL(true, num);
CHECK_EQUAL(false, val);
}
TEST(WordsBool, 4, WordsBoolBase)
{
ProcessArgs({ "--num=", "7", "--val=", "8" }, false, "Invalid argument: --num=");
CHECK_EQUAL(false, num);
CHECK_EQUAL(false, val);
}
TEST(WordsBool, 5, WordsBoolBase)
{
ProcessArgs({ "--num", "--val" }, true, "");
CHECK_EQUAL(true, num);
CHECK_EQUAL(true, val);
}
TEST(WordsBool, 6, WordsBoolBase)
{
ProcessArgs({ "--num=", "--val=" }, false, "Invalid argument: --num=");
CHECK_EQUAL(false, num);
CHECK_EQUAL(false, val);
}
TEST(WordsBool, 7, WordsBoolBase)
{
ProcessArgs({ "--num9val10" }, false, "Invalid argument: --num9val10");
CHECK_EQUAL(false, num);
CHECK_EQUAL(false, val);
}
}
}
///////////////////////////////////////////////////////////////////////////
// Argument<bool>
namespace
{
// Letter
namespace
{
class LetterArgumentBoolBase : public Test
{
public:
LetterArgumentBoolBase()
{
arguments.AddOption('a', "description", a);
arguments.AddOption('b', "description", b);
}
Argument<bool> a;
Argument<bool> b;
};
TEST(LetterArgumentBool, 1, LetterArgumentBoolBase)
{
ProcessArgs({ "-a1" }, false, "Invalid argument: -a1");
CHECK(a() && a.get());
CHECK(!b());
}
TEST(LetterArgumentBool, 2, LetterArgumentBoolBase)
{
ProcessArgs({ "-a=2" }, false, "Invalid argument: -a=2");
CHECK(!a());
CHECK(!b());
}
TEST(LetterArgumentBool, 3, LetterArgumentBoolBase)
{
ProcessArgs({ "-a", "3" }, false, "Invalid argument: 3");
CHECK(a() && a.get());
CHECK(!b());
}
TEST(LetterArgumentBool, 4, LetterArgumentBoolBase)
{
ProcessArgs({ "-a=", "4" }, false, "Invalid argument: -a=");
CHECK(!a());
CHECK(!b());
}
TEST(LetterArgumentBool, 5, LetterArgumentBoolBase)
{
ProcessArgs({ "-a" }, true, "");
CHECK(a() && a.get());
CHECK(!b());
}
TEST(LetterArgumentBool, 6, LetterArgumentBoolBase)
{
ProcessArgs({ "-a=" }, false, "Invalid argument: -a=");
CHECK(!a());
CHECK(!b());
}
}
// Letters
namespace
{
class LettersArgumentBoolBase : public Test
{
public:
LettersArgumentBoolBase()
{
arguments.AddOption('x', "description", x);
arguments.AddOption('y', "description", y);
}
Argument<bool> x;
Argument<bool> y;
};
TEST(LettersArgumentBool, 1, LettersArgumentBoolBase)
{
ProcessArgs({ "-x1y2" }, false, "Invalid argument: -x1y2");
CHECK(x() && x.get());
CHECK(!y());
}
TEST(LettersArgumentBool, 2, LettersArgumentBoolBase)
{
ProcessArgs({ "-x3", "-y4" }, false, "Invalid argument: -x3");
CHECK(x() && x.get());
CHECK(!y());
}
TEST(LettersArgumentBool, 3, LettersArgumentBoolBase)
{
ProcessArgs({ "-x", "5", "-y", "6" }, false, "Invalid argument: 5");
CHECK(x() && x.get());
CHECK(!y());
}
TEST(LettersArgumentBool, 4, LettersArgumentBoolBase)
{
ProcessArgs({ "-xy" }, true, "");
CHECK(x() && x.get());
CHECK(y() && y.get());
}
}
// Word
namespace
{
class WordArgumentBoolBase : public Test
{
public:
WordArgumentBoolBase()
{
arguments.AddOption("num", "description", num);
}
Argument<bool> num;
};
TEST(WordArgumentBool, 1, WordArgumentBoolBase)
{
ProcessArgs({ "--num1" }, false, "Invalid argument: --num1");
CHECK(!num());
}
TEST(WordArgumentBool, 2, WordArgumentBoolBase)
{
ProcessArgs({ "--num=2" }, false, "Invalid argument: --num=2");
CHECK(!num());
}
TEST(WordArgumentBool, 3, WordArgumentBoolBase)
{
ProcessArgs({ "--num", "3" }, false, "Invalid argument: 3");
CHECK(num() && num.get());
}
TEST(WordArgumentBool, 4, WordArgumentBoolBase)
{
ProcessArgs({ "--num=", "4" }, false, "Invalid argument: --num=");
CHECK(!num());
}
TEST(WordArgumentBool, 5, WordArgumentBoolBase)
{
ProcessArgs({ "--num" }, true, "");
CHECK(num() && num.get());
}
TEST(WordArgumentBool, 6, WordArgumentBoolBase)
{
ProcessArgs({ "--num=" }, false, "Invalid argument: --num=");
CHECK(!num());
}
}
// Words
namespace
{
class WordsArgumentBoolBase : public Test
{
public:
WordsArgumentBoolBase()
{
arguments.AddOption("num", "description", num);
arguments.AddOption("val", "description", val);
}
Argument<bool> num;
Argument<bool> val;
};
TEST(WordsArgumentBool, 1, WordsArgumentBoolBase)
{
ProcessArgs({ "--num1", "--val2" }, false, "Invalid argument: --num1");
CHECK(!num());
CHECK(!val());
}
TEST(WordsArgumentBool, 2, WordsArgumentBoolBase)
{
ProcessArgs({ "--num=3", "--val=4" }, false, "Invalid argument: --num=3");
CHECK(!num());
CHECK(!val());
}
TEST(WordsArgumentBool, 3, WordsArgumentBoolBase)
{
ProcessArgs({ "--num", "5", "--val", "6" }, false, "Invalid argument: 5");
CHECK(num() && num.get());
CHECK(!val());
}
TEST(WordsArgumentBool, 4, WordsArgumentBoolBase)
{
ProcessArgs({ "--num=", "7", "--val=", "8" }, false, "Invalid argument: --num=");
CHECK(!num());
CHECK(!val());
}
TEST(WordsArgumentBool, 5, WordsArgumentBoolBase)
{
ProcessArgs({ "--num", "--val" }, true, "");
CHECK(num() && num.get());
CHECK(val() && val.get());
}
TEST(WordsArgumentBool, 6, WordsArgumentBoolBase)
{
ProcessArgs({ "--num=", "--val=" }, false, "Invalid argument: --num=");
CHECK(!num());
CHECK(!val());
}
TEST(WordsArgumentBool, 7, WordsArgumentBoolBase)
{
ProcessArgs({ "--num9val10" }, false, "Invalid argument: --num9val10");
CHECK(!num());
CHECK(!val());
}
}
}
///////////////////////////////////////////////////////////////////////////
// int
namespace
{
// Required
namespace
{
class RequiredIntBase : public Test
{
public:
RequiredIntBase()
{
arguments.AddRequired("first", "description", first);
arguments.AddRequired("second", "description", second);
}
int first = 0;
int second = 0;
};
TEST(RequiredInt, 1, RequiredIntBase)
{
ProcessArgs({}, false, "Missing argument: first");
CHECK_EQUAL(0, first);
CHECK_EQUAL(0, second);
}
TEST(RequiredInt, 2, RequiredIntBase)
{
ProcessArgs({ "123" }, false, "Missing argument: second");
CHECK_EQUAL(123, first);
CHECK_EQUAL(0, second);
}
TEST(RequiredInt, 3, RequiredIntBase)
{
ProcessArgs({ "123", "456" }, true, "");
CHECK_EQUAL(123, first);
CHECK_EQUAL(456, second);
}
TEST(RequiredInt, 4, RequiredIntBase)
{
ProcessArgs({ "123", "456", "789" }, false, "Invalid argument: 789");
CHECK_EQUAL(123, first);
CHECK_EQUAL(456, second);
}
TEST(RequiredInt, 5, RequiredIntBase)
{
ProcessArgs({ "NotAnInteger" }, false, "Invalid argument: NotAnInteger");
CHECK_EQUAL(0, first);
CHECK_EQUAL(0, second);
}
TEST(RequiredInt, 6, RequiredIntBase)
{
ProcessArgs({ "123", "NotAnInteger" }, false, "Invalid argument: NotAnInteger");
CHECK_EQUAL(123, first);
CHECK_EQUAL(0, second);
}
TEST(RequiredInt, 7, RequiredIntBase)
{
ProcessArgs({ "123", "456BadInteger" }, false, "Invalid argument: 456BadInteger");
CHECK_EQUAL(123, first);
CHECK_EQUAL(0, second);
}
}
// List
namespace
{
class ListIntBase : public Test
{
public:
ListIntBase()
{
arguments.AddList("numbers", "description", numbers);
}
std::vector<int> numbers;
};
TEST(ListInt, 1, ListIntBase)
{
ProcessArgs({}, true, "");
CHECK(numbers.empty());
}
TEST(ListInt, 2, ListIntBase)
{
ProcessArgs({ "123" }, true, "");
CHECK_EQUAL(1, numbers.size());
CHECK_EQUAL(123, numbers[0]);
}
TEST(ListInt, 3, ListIntBase)
{
ProcessArgs({ "123", "456" }, true, "");
CHECK_EQUAL(2, numbers.size());
CHECK_EQUAL(123, numbers[0]);
CHECK_EQUAL(456, numbers[1]);
}
TEST(ListInt, 4, ListIntBase)
{
ProcessArgs({ "a" }, false, "Invalid argument: a");
CHECK(numbers.empty());
}
TEST(ListInt, 5, ListIntBase)
{
ProcessArgs({ "1a" }, false, "Invalid argument: 1a");
CHECK(numbers.empty());
}
TEST(ListInt, 6, ListIntBase)
{
ProcessArgs({ "a1" }, false, "Invalid argument: a1");
CHECK(numbers.empty());
}
}
// Letter
namespace
{
class LetterIntBase : public Test
{
public:
LetterIntBase()
{
arguments.AddOption('a', "description", a);
arguments.AddOption('b', "description", b);
}
int a = 0;
int b = 0;
};
TEST(LetterInt, 1, LetterIntBase)
{
ProcessArgs({ "-a1" }, true, "");
CHECK_EQUAL(1, a);
CHECK_EQUAL(0, b);
}
TEST(LetterInt, 2, LetterIntBase)
{
ProcessArgs({ "-a=2" }, true, "");
CHECK_EQUAL(2, a);
CHECK_EQUAL(0, b);
}
TEST(LetterInt, 3, LetterIntBase)
{
ProcessArgs({ "-a", "3" }, true, "");
CHECK_EQUAL(3, a);
CHECK_EQUAL(0, b);
}
TEST(LetterInt, 4, LetterIntBase)
{
ProcessArgs({ "-a=", "4" }, true, "");
CHECK_EQUAL(4, a);
CHECK_EQUAL(0, b);
}
TEST(LetterInt, 5, LetterIntBase)
{
ProcessArgs({ "-a" }, false, "Invalid argument: -a");
CHECK_EQUAL(0, a);
CHECK_EQUAL(0, b);
}
TEST(LetterInt, 6, LetterIntBase)
{
ProcessArgs({ "-a=" }, false, "Invalid argument: -a=");
CHECK_EQUAL(0, a);
CHECK_EQUAL(0, b);
}
}
// Letters
namespace
{
class LettersIntBase : public Test
{
public:
LettersIntBase()
{
arguments.AddOption('x', "description", x);
arguments.AddOption('y', "description", y);
}
int x = 0;
int y = 0;
};
TEST(LettersInt, 1, LettersIntBase)
{
ProcessArgs({ "-x1y2" }, true, "");
CHECK_EQUAL(1, x);
CHECK_EQUAL(2, y);
}
TEST(LettersInt, 2, LettersIntBase)
{
ProcessArgs({ "-x3", "-y4" }, true, "");
CHECK_EQUAL(3, x);
CHECK_EQUAL(4, y);
}
TEST(LettersInt, 3, LettersIntBase)
{
ProcessArgs({ "-x", "5", "-y", "6" }, true, "");
CHECK_EQUAL(5, x);
CHECK_EQUAL(6, y);
}
TEST(LettersInt, 4, LettersIntBase)
{
ProcessArgs({ "-xy" }, false, "Invalid argument: -xy");
CHECK_EQUAL(0, x);
CHECK_EQUAL(0, y);
}
}
// Word
namespace
{
class WordIntBase : public Test
{
public:
WordIntBase()
{
arguments.AddOption("num", "description", num);
}
int num = 0;
};
TEST(WordInt, 1, WordIntBase)
{
ProcessArgs({ "--num1" }, true, "");
CHECK_EQUAL(1, num);
}
TEST(WordInt, 2, WordIntBase)
{
ProcessArgs({ "--num=2" }, true, "");
CHECK_EQUAL(2, num);
}
TEST(WordInt, 3, WordIntBase)
{
ProcessArgs({ "--num", "3" }, true, "");
CHECK_EQUAL(3, num);
}
TEST(WordInt, 4, WordIntBase)
{
ProcessArgs({ "--num=", "4" }, true, "");
CHECK_EQUAL(4, num);
}
TEST(WordInt, 5, WordIntBase)
{
ProcessArgs({ "--num" }, false, "Invalid argument: --num");
CHECK_EQUAL(0, num);
}
TEST(WordInt, 6, WordIntBase)
{
ProcessArgs({ "--num=" }, false, "Invalid argument: --num=");
CHECK_EQUAL(0, num);
}
}
// Words
namespace
{
class WordsIntBase : public Test
{
public:
WordsIntBase()
{
arguments.AddOption("num", "description", num);
arguments.AddOption("val", "description", val);
}
int num = 0;
int val = 0;
};
TEST(WordsInt, 1, WordsIntBase)
{
ProcessArgs({ "--num1", "--val2" }, true, "");
CHECK_EQUAL(1, num);
CHECK_EQUAL(2, val);
}
TEST(WordsInt, 2, WordsIntBase)
{
ProcessArgs({ "--num=3", "--val=4" }, true, "");
CHECK_EQUAL(3, num);
CHECK_EQUAL(4, val);
}
TEST(WordsInt, 3, WordsIntBase)
{
ProcessArgs({ "--num", "5", "--val", "6" }, true, "");
CHECK_EQUAL(5, num);
CHECK_EQUAL(6, val);
}
TEST(WordsInt, 4, WordsIntBase)
{
ProcessArgs({ "--num=", "7", "--val=", "8" }, true, "");
CHECK_EQUAL(7, num);
CHECK_EQUAL(8, val);
}
TEST(WordsInt, 5, WordsIntBase)
{
ProcessArgs({ "--num", "--val" }, false, "Invalid argument: --num");
CHECK_EQUAL(0, num);
CHECK_EQUAL(0, val);
}
TEST(WordsInt, 6, WordsIntBase)
{
ProcessArgs({ "--num=", "--val=" }, false, "Invalid argument: --num=");
CHECK_EQUAL(0, num);
CHECK_EQUAL(0, val);
}
TEST(WordsInt, 7, WordsIntBase)
{
ProcessArgs({ "--num9val10" }, false, "Invalid argument: --num9val10");
CHECK_EQUAL(0, num);
CHECK_EQUAL(0, val);
}
}
}
///////////////////////////////////////////////////////////////////////////
// Argument<int>
namespace
{
// Letter
namespace
{
class LetterArgumentIntBase : public Test
{
public:
LetterArgumentIntBase()
{
arguments.AddOption('a', "description", a);
arguments.AddOption('b', "description", b);
}
Argument<int> a;
Argument<int> b;
};
TEST(LetterArgumentInt, 1, LetterArgumentIntBase)
{
ProcessArgs({ "-a1" }, true, "");
CHECK(a() && a.get() == 1);
CHECK(!b());
}
TEST(LetterArgumentInt, 2, LetterArgumentIntBase)
{
ProcessArgs({ "-a=2" }, true, "");
CHECK(a() && a.get() == 2);
CHECK(!b());
}
TEST(LetterArgumentInt, 3, LetterArgumentIntBase)
{
ProcessArgs({ "-a", "3" }, true, "");
CHECK(a() && a.get() == 3);
CHECK(!b());
}
TEST(LetterArgumentInt, 4, LetterArgumentIntBase)
{
ProcessArgs({ "-a=", "4" }, true, "");
CHECK(a() && a.get() == 5);
CHECK(!b());
}
TEST(LetterArgumentInt, 5, LetterArgumentIntBase)
{
ProcessArgs({ "-a" }, false, "Invalid argument: -a");
CHECK(!a());
CHECK(!b());
}
TEST(LetterArgumentInt, 6, LetterArgumentIntBase)
{
ProcessArgs({ "-a=" }, false, "Invalid argument: -a=");
CHECK(!a());
CHECK(!b());
}
}
// Letters
namespace
{
class LettersArgumentIntBase : public Test
{
public:
LettersArgumentIntBase()
{
arguments.AddOption('x', "description", x);
arguments.AddOption('y', "description", y);
}
Argument<int> x;
Argument<int> y;
};
TEST(LettersArgumentInt, 1, LettersArgumentIntBase)
{
ProcessArgs({ "-x1y2" }, true, "");
CHECK(x() && x.get() == 1);
CHECK(y() && y.get() == 2);
}
TEST(LettersArgumentInt, 2, LettersArgumentIntBase)
{
ProcessArgs({ "-x3", "-y4" }, true, "");
CHECK(x() && x.get() == 3);
CHECK(y() && y.get() == 4);
}
TEST(LettersArgumentInt, 3, LettersArgumentIntBase)
{
ProcessArgs({ "-x", "5", "-y", "6" }, true, "");
CHECK(x() && x.get() == 5);
CHECK(y() && y.get() == 6);
}
TEST(LettersArgumentInt, 4, LettersArgumentIntBase)
{
ProcessArgs({ "-xy" }, false, "Invalid argument: -xy");
CHECK(!x());
CHECK(!y());
}
}
// Word
namespace
{
class WordArgumentIntBase : public Test
{
public:
WordArgumentIntBase()
{
arguments.AddOption("num", "description", num);
}
Argument<int> num;
};
TEST(WordArgumentInt, 1, WordArgumentIntBase)
{
ProcessArgs({ "--num1" }, true, "");
CHECK(num() && num.get() == 1);
}
TEST(WordArgumentInt, 2, WordArgumentIntBase)
{
ProcessArgs({ "--num=2" }, true, "");
CHECK(num() && num.get() == 2);
}
TEST(WordArgumentInt, 3, WordArgumentIntBase)
{
ProcessArgs({ "--num", "3" }, true, "");
CHECK(num() && num.get() == 3);
}
TEST(WordArgumentInt, 4, WordArgumentIntBase)
{
ProcessArgs({ "--num=", "4" }, true, "");
CHECK(num() && num.get() == 4);
}
TEST(WordArgumentInt, 5, WordArgumentIntBase)
{
ProcessArgs({ "--num" }, false, "Invalid argument: --num");
CHECK(!num());
}
TEST(WordArgumentInt, 6, WordArgumentIntBase)
{
ProcessArgs({ "--num=" }, false, "Invalid argument: --num=");
CHECK(!num());
}
}
// Words
namespace
{
class WordsArgumentIntBase : public Test
{
public:
WordsArgumentIntBase()
{
arguments.AddOption("num", "description", num);
arguments.AddOption("val", "description", val);
}
Argument<int> num;
Argument<int> val;
};
TEST(WordsArgumentInt, 1, WordsArgumentIntBase)
{
ProcessArgs({ "--num1", "--val2" }, true, "");
CHECK(num() && num.get() == 1);
CHECK(val() && val.get() == 2);
}
TEST(WordsArgumentInt, 2, WordsArgumentIntBase)
{
ProcessArgs({ "--num=3", "--val=4" }, true, "");
CHECK(num() && num.get() == 3);
CHECK(val() && val.get() == 4);
}
TEST(WordsArgumentInt, 3, WordsArgumentIntBase)
{
ProcessArgs({ "--num", "5", "--val", "6" }, true, "");
CHECK(num() && num.get() == 5);
CHECK(val() && val.get() == 6);
}
TEST(WordsArgumentInt, 4, WordsArgumentIntBase)
{
ProcessArgs({ "--num=", "7", "--val=", "8" }, true, "");
CHECK(num() && num.get() == 7);
CHECK(val() && val.get() == 8);
}
TEST(WordsArgumentInt, 5, WordsArgumentIntBase)
{
ProcessArgs({ "--num", "--val" }, false, "Invalid argument: --num");
CHECK(!num());
CHECK(!val());
}
TEST(WordsArgumentInt, 6, WordsArgumentIntBase)
{
ProcessArgs({ "--num=", "--val=" }, false, "Invalid argument: --num=");
CHECK(!num());
CHECK(!val());
}
TEST(WordsArgumentInt, 7, WordsArgumentIntBase)
{
ProcessArgs({ "--num9val10" }, false, "Invalid argument: --num9val10");
CHECK(!num());
CHECK(!val());
}
}
}
///////////////////////////////////////////////////////////////////////////
// std::string
namespace
{
// Required
namespace
{
class RequiredStringBase : public Test
{
public:
RequiredStringBase()
{
arguments.AddRequired("first", "description", first);
arguments.AddRequired("second", "description", second);
}
std::string first;
std::string second;
};
TEST(RequiredString, 1, RequiredStringBase)
{
ProcessArgs({}, false, "Missing argument: first");
CHECK_EQUAL("", first);
CHECK_EQUAL("", second);
}
TEST(RequiredString, 2, RequiredStringBase)
{
ProcessArgs({ "alpha" }, false, "Missing argument: second");
CHECK_EQUAL("alpha", first);
CHECK_EQUAL("", second);
}
TEST(RequiredString, 3, RequiredStringBase)
{
ProcessArgs({ "alpha", "beta" }, true, "");
CHECK_EQUAL("alpha", first);
CHECK_EQUAL("beta", second);
}
TEST(RequiredString, 4, RequiredStringBase)
{
ProcessArgs({ "alpha", "beta", "gamma" }, false, "Invalid argument: gamma");
CHECK_EQUAL("alpha", first);
CHECK_EQUAL("beta", second);
}
}
// List
namespace
{
class ListStringBase : public Test
{
public:
ListStringBase()
{
arguments.AddList("words", "description", words);
}
std::vector<std::string> words;
};
TEST(ListString, 1, ListStringBase)
{
ProcessArgs({}, true, "");
CHECK(words.empty());
}
TEST(ListString, 2, ListStringBase)
{
ProcessArgs({ "alpha" }, true, "");
CHECK_EQUAL(1, words.size());
CHECK_EQUAL("alpha", words[0]);
}
TEST(ListString, 3, ListStringBase)
{
ProcessArgs({ "alpha", "beta" }, true, "");
CHECK_EQUAL(2, words.size());
CHECK_EQUAL("alpha", words[0]);
CHECK_EQUAL("beta", words[1]);
}
}
// Letter
namespace
{
class LetterStringBase : public Test
{
public:
LetterStringBase()
{
arguments.AddOption('a', "description", a);
arguments.AddOption('b', "description", b);
}
std::string a;
std::string b;
};
TEST(LetterString, 1, LetterStringBase)
{
ProcessArgs({ "-a1" }, false, "Invalid argument: -a1");
CHECK_EQUAL("", a);
CHECK_EQUAL("", b);
}
TEST(LetterString, 2, LetterStringBase)
{
ProcessArgs({ "-a=2" }, true, "");
CHECK_EQUAL("2", a);
CHECK_EQUAL("", b);
}
TEST(LetterString, 3, LetterStringBase)
{
ProcessArgs({ "-a", "3" }, true, "");
CHECK_EQUAL("3", a);
CHECK_EQUAL("", b);
}
TEST(LetterString, 4, LetterStringBase)
{
ProcessArgs({ "-a=", "4" }, true, "");
CHECK_EQUAL("4", a);
CHECK_EQUAL("", b);
}
TEST(LetterString, 5, LetterStringBase)
{
ProcessArgs({ "-a" }, false, "Invalid argument: -a");
CHECK_EQUAL("", a);
CHECK_EQUAL("", b);
}
TEST(LetterString, 6, LetterStringBase)
{
ProcessArgs({ "-a=" }, false, "Invalid argument: -a=");
CHECK_EQUAL("", a);
CHECK_EQUAL("", b);
}
}
// Letters
namespace
{
class LettersStringBase : public Test
{
public:
LettersStringBase()
{
arguments.AddOption('x', "description", x);
arguments.AddOption('y', "description", y);
}
std::string x;
std::string y;
};
TEST(LettersString, 1, LettersStringBase)
{
ProcessArgs({ "-x1y2" }, false, "Invalid argument: -x1y2");
CHECK_EQUAL("", x);
CHECK_EQUAL("", y);
}
TEST(LettersString, 2, LettersStringBase)
{
ProcessArgs({ "-x3", "-y4" }, false, "Invalid argument: -x3");
CHECK_EQUAL("", x);
CHECK_EQUAL("", y);
}
TEST(LettersString, 3, LettersStringBase)
{
ProcessArgs({ "-x", "5", "-y", "6" }, true, "");
CHECK_EQUAL("5", x);
CHECK_EQUAL("6", y);
}
TEST(LettersString, 4, LettersStringBase)
{
ProcessArgs({ "-xy" }, false, "Invalid argument: -xy");
CHECK_EQUAL("", x);
CHECK_EQUAL("", y);
}
}
// Word
namespace
{
class WordStringBase : public Test
{
public:
WordStringBase()
{
arguments.AddOption("val", "description", val);
}
std::string val;
};
TEST(WordString, 1, WordStringBase)
{
ProcessArgs({ "--val1" }, false, "Invalid argument: --val1");
CHECK_EQUAL("", val);
}
TEST(WordString, 2, WordStringBase)
{
ProcessArgs({ "--val=2" }, true, "");
CHECK_EQUAL("2", val);
}
TEST(WordString, 3, WordStringBase)
{
ProcessArgs({ "--val", "3" }, true, "");
CHECK_EQUAL("3", val);
}
TEST(WordString, 4, WordStringBase)
{
ProcessArgs({ "--val=", "4" }, true, "");
CHECK_EQUAL("4", val);
}
TEST(WordString, 5, WordStringBase)
{
ProcessArgs({ "--val" }, false, "Invalid argument: --val");
CHECK_EQUAL("", val);
}
TEST(WordString, 6, WordStringBase)
{
ProcessArgs({ "--val=" }, false, "Invalid argument: --val=");
CHECK_EQUAL("", val);
}
}
// Words
namespace
{
class WordsStringBase : public Test
{
public:
WordsStringBase()
{
arguments.AddOption("name", "description", name);
arguments.AddOption("val", "description", val);
}
std::string name;
std::string val;
};
TEST(WordsString, 1, WordsStringBase)
{
ProcessArgs({ "--name1", "--val2" }, false, "Invalid argument: --name1");
CHECK_EQUAL("", name);
CHECK_EQUAL("", val);
}
TEST(WordsString, 2, WordsStringBase)
{
ProcessArgs({ "--name=3", "--val=4" }, true, "");
CHECK_EQUAL("3", name);
CHECK_EQUAL("4", val);
}
TEST(WordsString, 3, WordsStringBase)
{
ProcessArgs({ "--name", "5", "--val", "6" }, true, "");
CHECK_EQUAL("5", name);
CHECK_EQUAL("6", val);
}
TEST(WordsString, 4, WordsStringBase)
{
ProcessArgs({ "--name=", "7", "--val=", "8" }, true, "");
CHECK_EQUAL("7", name);
CHECK_EQUAL("8", val);
}
TEST(WordsString, 5, WordsStringBase)
{
ProcessArgs({ "--name", "--val" }, false, "Invalid argument: --name");
CHECK_EQUAL("", name);
CHECK_EQUAL("", val);
}
TEST(WordsString, 6, WordsStringBase)
{
ProcessArgs({ "--name=", "--val=" }, false, "Invalid argument: --name=");
CHECK_EQUAL("", name);
CHECK_EQUAL("", val);
}
TEST(WordsString, 7, WordsStringBase)
{
ProcessArgs({ "--name9val10" }, false, "Invalid argument: --name9val10");
CHECK_EQUAL("", name);
CHECK_EQUAL("", val);
}
}
}
///////////////////////////////////////////////////////////////////////////
// Argument<std::string>
namespace
{
// Letter
namespace
{
class LetterArgumentStringBase : public Test
{
public:
LetterArgumentStringBase()
{
arguments.AddOption('a', "description", a);
arguments.AddOption('b', "description", b);
}
Argument<std::string> a;
Argument<std::string> b;
};
TEST(LetterArgumentString, 1, LetterArgumentStringBase)
{
ProcessArgs({ "-a1" }, false, "Invalid argument: -a1");
CHECK(!a());
CHECK(!b());
}
TEST(LetterArgumentString, 2, LetterArgumentStringBase)
{
ProcessArgs({ "-a=2" }, true, "");
CHECK(a() && a.get() == "2");
CHECK(!b());
}
TEST(LetterArgumentString, 3, LetterArgumentStringBase)
{
ProcessArgs({ "-a", "3" }, true, "");
CHECK(a() && a.get() == "3");
CHECK(!b());
}
TEST(LetterArgumentString, 4, LetterArgumentStringBase)
{
ProcessArgs({ "-a=", "4" }, true, "");
CHECK(a() && a.get() == "4");
CHECK(!b());
}
TEST(LetterArgumentString, 5, LetterArgumentStringBase)
{
ProcessArgs({ "-a" }, false, "Invalid argument: -a");
CHECK(!a());
CHECK(!b());
}
TEST(LetterArgumentString, 6, LetterArgumentStringBase)
{
ProcessArgs({ "-a=" }, false, "Invalid argument: -a=");
CHECK(!a());
CHECK(!b());
}
}
// Letters
namespace
{
class LettersArgumentStringBase : public Test
{
public:
LettersArgumentStringBase()
{
arguments.AddOption('x', "description", x);
arguments.AddOption('y', "description", y);
}
Argument<std::string> x;
Argument<std::string> y;
};
TEST(LettersArgumentString, 1, LettersArgumentStringBase)
{
ProcessArgs({ "-x1y2" }, false, "Invalid argument: -x1y2");
CHECK(!x());
CHECK(!y());
}
TEST(LettersArgumentString, 2, LettersArgumentStringBase)
{
ProcessArgs({ "-x3", "-y4" }, false, "Invalid argument: -x3");
CHECK(!x());
CHECK(!y());
}
TEST(LettersArgumentString, 3, LettersArgumentStringBase)
{
ProcessArgs({ "-x", "5", "-y", "6" }, true, "");
CHECK(x() && x.get() == "5");
CHECK(y() && y.get() == "6");
}
TEST(LettersArgumentString, 4, LettersArgumentStringBase)
{
ProcessArgs({ "-xy" }, false, "Invalid argument: -xy");
CHECK(!x());
CHECK(!y());
}
}
// Word
namespace
{
class WordArgumentStringBase : public Test
{
public:
WordArgumentStringBase()
{
arguments.AddOption("val", "description", val);
}
Argument<std::string> val;
};
TEST(WordArgumentString, 1, WordArgumentStringBase)
{
ProcessArgs({ "--val1" }, false, "Invalid argument: --val1");
CHECK(!val());
}
TEST(WordArgumentString, 2, WordArgumentStringBase)
{
ProcessArgs({ "--val=2" }, true, "");
CHECK(val() && val.get() == "2");
}
TEST(WordArgumentString, 3, WordArgumentStringBase)
{
ProcessArgs({ "--val", "3" }, true, "");
CHECK(val() && val.get() == "3");
}
TEST(WordArgumentString, 4, WordArgumentStringBase)
{
ProcessArgs({ "--val=", "4" }, true, "");
CHECK(val() && val.get() == "4");
}
TEST(WordArgumentString, 5, WordArgumentStringBase)
{
ProcessArgs({ "--val" }, false, "Invalid argument: --val");
CHECK(!val());
}
TEST(WordArgumentString, 6, WordArgumentStringBase)
{
ProcessArgs({ "--val=" }, false, "Invalid argument: --val=");
CHECK(!val());
}
}
// Words
namespace
{
class WordsArgumentStringBase : public Test
{
public:
WordsArgumentStringBase()
{
arguments.AddOption("name", "description", name);
arguments.AddOption("val", "description", val);
}
Argument<std::string> name;
Argument<std::string> val;
};
TEST(WordsArgumentString, 1, WordsArgumentStringBase)
{
ProcessArgs({ "--name1", "--val2" }, false, "Invalid argument: --name1");
CHECK(!name());
CHECK(!val());
}
TEST(WordsArgumentString, 2, WordsArgumentStringBase)
{
ProcessArgs({ "--name=3", "--val=4" }, true, "");
CHECK(name() && name.get() == "3");
CHECK(val() && val.get() == "4");
}
TEST(WordsArgumentString, 3, WordsArgumentStringBase)
{
ProcessArgs({ "--name", "5", "--val", "6" }, true, "");
CHECK(name() && name.get() == "5");
CHECK(val() && val.get() == "6");
}
TEST(WordsArgumentString, 4, WordsArgumentStringBase)
{
ProcessArgs({ "--name=", "7", "--val=", "8" }, true, "");
CHECK(name() && name.get() == "7");
CHECK(val() && val.get() == "8");
}
TEST(WordsArgumentString, 5, WordsArgumentStringBase)
{
ProcessArgs({ "--name", "--val" }, false, "Invalid argument: --name");
CHECK(!name());
CHECK(!val());
}
TEST(WordsArgumentString, 6, WordsArgumentStringBase)
{
ProcessArgs({ "--name=", "--val=" }, false, "Invalid argument: --name=");
CHECK(!name());
CHECK(!val());
}
TEST(WordsArgumentString, 7, WordsArgumentStringBase)
{
ProcessArgs({ "--name9val10" }, false, "Invalid argument: --name9val10");
CHECK(!name());
CHECK(!val());
}
}
}
///////////////////////////////////////////////////////////////////////////
// std::vector<std::string>
namespace
{
// Letter
namespace
{
class LetterStringVectorBase : public Test
{
public:
LetterStringVectorBase()
{
arguments.AddOption('a', "description", a);
}
std::vector<std::string> a;
};
TEST(LetterStringVector, 1, LetterStringVectorBase)
{
ProcessArgs({ "-a1" }, false, "Invalid argument: -a1");
CHECK_EQUAL(0u, a.size());
}
TEST(LetterStringVector, 2, LetterStringVectorBase)
{
ProcessArgs({ "-a=2" }, true, "");
CHECK_EQUAL(1, a.size());
CHECK_EQUAL("2", a[0]);
}
TEST(LetterStringVector, 3, LetterStringVectorBase)
{
ProcessArgs({ "-a", "3" }, true, "");
CHECK_EQUAL(1, a.size());
CHECK_EQUAL("3", a[0]);
}
TEST(LetterStringVector, 4, LetterStringVectorBase)
{
ProcessArgs({ "-a=", "4" }, true, "");
CHECK_EQUAL(1, a.size());
CHECK_EQUAL("4", a[0]);
}
TEST(LetterStringVector, 5, LetterStringVectorBase)
{
ProcessArgs({ "-a" }, false, "Invalid argument: -a");
CHECK_EQUAL(0, a.size());
}
TEST(LetterStringVector, 6, LetterStringVectorBase)
{
ProcessArgs({ "-a=" }, false, "Invalid argument: -a=");
CHECK_EQUAL(0, a.size());
}
TEST(LetterStringVector, 7, LetterStringVectorBase)
{
ProcessArgs({ "-a=1", "-a=2" }, true, "");
CHECK_EQUAL(2, a.size());
CHECK_EQUAL("1", a[0]);
CHECK_EQUAL("2", a[1]);
}
}
// Letters
namespace
{
class LettersStringVectorBase : public Test
{
public:
LettersStringVectorBase()
{
arguments.AddOption('x', "description", x);
arguments.AddOption('y', "description", y);
}
std::vector<std::string> x;
std::vector<std::string> y;
};
TEST(LettersStringVector, 1, LettersStringVectorBase)
{
ProcessArgs({ "-x1y2" }, false, "Invalid argument: -x1y2");
CHECK_EQUAL(0, x.size());
CHECK_EQUAL(0, y.size());
}
TEST(LettersStringVector, 2, LettersStringVectorBase)
{
ProcessArgs({ "-x3", "-y4" }, false, "Invalid argument: -x3");
CHECK_EQUAL(0, x.size());
CHECK_EQUAL(0, y.size());
}
TEST(LettersStringVector, 3, LettersStringVectorBase)
{
ProcessArgs({ "-x", "5", "-y", "6" }, true, "");
CHECK_EQUAL(1, x.size());
CHECK_EQUAL("5", x[0]);
CHECK_EQUAL(1, y.size());
CHECK_EQUAL("6", y[0]);
}
TEST(LettersStringVector, 4, LettersStringVectorBase)
{
ProcessArgs({ "-xy" }, false, "Invalid argument: -xy");
CHECK_EQUAL(0, x.size());
CHECK_EQUAL(0, y.size());
}
TEST(LettersStringVector, 5, LettersStringVectorBase)
{
ProcessArgs({ "-x", "1", "-y", "2", "-x", "3", "-y", "4" }, true, "");
CHECK_EQUAL(2, x.size());
CHECK_EQUAL("1", x[0]);
CHECK_EQUAL("3", x[1]);
CHECK_EQUAL(2, y.size());
CHECK_EQUAL("2", y[0]);
CHECK_EQUAL("4", y[1]);
}
}
// Word
namespace
{
class WordStringVectorBase : public Test
{
public:
WordStringVectorBase()
{
arguments.AddOption("val", "description", val);
}
std::vector<std::string> val;
};
TEST(WordStringVector, 1, WordStringVectorBase)
{
ProcessArgs({ "--val1" }, false, "Invalid argument: --val1");
CHECK_EQUAL(0, val.size());
}
TEST(WordStringVector, 2, WordStringVectorBase)
{
ProcessArgs({ "--val=2" }, true, "");
CHECK_EQUAL(1, val.size());
CHECK_EQUAL("2", val[0]);
}
TEST(WordStringVector, 3, WordStringVectorBase)
{
ProcessArgs({ "--val", "3" }, true, "");
CHECK_EQUAL(1, val.size());
CHECK_EQUAL("3", val[0]);
}
TEST(WordStringVector, 4, WordStringVectorBase)
{
ProcessArgs({ "--val=", "4" }, true, "");
CHECK_EQUAL(1, val.size());
CHECK_EQUAL("4", val[0]);
}
TEST(WordStringVector, 5, WordStringVectorBase)
{
ProcessArgs({ "--val" }, false, "Invalid argument: --val");
CHECK_EQUAL(0, val.size());
}
TEST(WordStringVector, 6, WordStringVectorBase)
{
ProcessArgs({ "--val=" }, false, "Invalid argument: --val=");
CHECK_EQUAL(0, val.size());
}
TEST(WordStringVector, 7, WordStringVectorBase)
{
ProcessArgs({ "--val=1", "--val=2" }, true, "");
CHECK_EQUAL(2, val.size());
CHECK_EQUAL("1", val[0]);
CHECK_EQUAL("2", val[1]);
}
TEST(WordStringVector, 8, WordStringVectorBase)
{
ProcessArgs({ "--val", "3", "--val", "4" }, true, "");
CHECK_EQUAL(2, val.size());
CHECK_EQUAL("3", val[0]);
CHECK_EQUAL("4", val[1]);
}
TEST(WordStringVector, 9, WordStringVectorBase)
{
ProcessArgs({ "--val=", "4", "--val=", "5" }, true, "");
CHECK_EQUAL(2, val.size());
CHECK_EQUAL("4", val[0]);
CHECK_EQUAL("5", val[1]);
}
}
// Words
namespace
{
class WordsStringVectorBase : public Test
{
public:
WordsStringVectorBase()
{
arguments.AddOption("name", "description", name);
arguments.AddOption("val", "description", val);
}
std::vector<std::string> name;
std::vector<std::string> val;
};
TEST(WordsStringVector, 1, WordsStringVectorBase)
{
ProcessArgs({ "--name1", "--val2" }, false, "Invalid argument: --name1");
CHECK_EQUAL(0, name.size());
CHECK_EQUAL(0, val.size());
}
TEST(WordsStringVector, 2, WordsStringVectorBase)
{
ProcessArgs({ "--name=3", "--val=4" }, true, "");
CHECK_EQUAL(1, name.size());
CHECK_EQUAL("3", name[0]);
CHECK_EQUAL(1, val.size());
CHECK_EQUAL("4", val[0]);
}
TEST(WordsStringVector, 3, WordsStringVectorBase)
{
ProcessArgs({ "--name", "5", "--val", "6" }, true, "");
CHECK_EQUAL(1, name.size());
CHECK_EQUAL("5", name[0]);
CHECK_EQUAL(1, val.size());
CHECK_EQUAL("6", val[0]);
}
TEST(WordsStringVector, 4, WordsStringVectorBase)
{
ProcessArgs({ "--name=", "7", "--val=", "8" }, true, "");
CHECK_EQUAL(1, name.size());
CHECK_EQUAL("7", name[0]);
CHECK_EQUAL(1, val.size());
CHECK_EQUAL("8", val[0]);
}
TEST(WordsStringVector, 5, WordsStringVectorBase)
{
ProcessArgs({ "--name", "--val" }, false, "Invalid argument: --name");
CHECK_EQUAL(0, name.size());
CHECK_EQUAL(0, val.size());
}
TEST(WordsStringVector, 6, WordsStringVectorBase)
{
ProcessArgs({ "--name=", "--val=" }, false, "Invalid argument: --name=");
CHECK_EQUAL(0, name.size());
CHECK_EQUAL(0, val.size());
}
TEST(WordsStringVector, 7, WordsStringVectorBase)
{
ProcessArgs({ "--name9val10" }, false, "Invalid argument: --name9val10");
CHECK_EQUAL(0, name.size());
CHECK_EQUAL(0, val.size());
}
TEST(WordsStringVector, 8, WordsStringVectorBase)
{
ProcessArgs({ "--name=1", "--val=2", "--name=3", "--val=4" }, true, "");
CHECK_EQUAL(2, name.size());
CHECK_EQUAL("1", name[0]);
CHECK_EQUAL("3", name[1]);
CHECK_EQUAL(2, val.size());
CHECK_EQUAL("2", val[0]);
CHECK_EQUAL("4", val[1]);
}
TEST(WordsStringVector, 9, WordsStringVectorBase)
{
ProcessArgs({ "--name", "5", "--val", "6", "--name", "7", "--val", "8" }, true, "");
CHECK_EQUAL(2, name.size());
CHECK_EQUAL("5", name[0]);
CHECK_EQUAL("7", name[1]);
CHECK_EQUAL(2, val.size());
CHECK_EQUAL("6", val[0]);
CHECK_EQUAL("8", val[1]);
}
TEST(WordsStringVector, 10, WordsStringVectorBase)
{
ProcessArgs({ "--name=", "A", "--val=", "B", "--name=", "C", "--val=", "D" }, true, "");
CHECK_EQUAL(2, name.size());
CHECK_EQUAL("A", name[0]);
CHECK_EQUAL("C", name[1]);
CHECK_EQUAL(2, val.size());
CHECK_EQUAL("B", val[0]);
CHECK_EQUAL("D", val[1]);
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
int main()
{
TestRunner::instance().RunAllTests();
return 0;
}
| 30.977667 | 110 | 0.409676 | calzakk |
dc210888e9eb81678386ff7528a0a15d8cb4394f | 16,143 | cpp | C++ | Util/SUNDIALS_serial_test/main.cpp | Gosenca/axionyx_1.0 | 7e2a723e00e6287717d6d81b23db32bcf6c3521a | [
"BSD-3-Clause-LBNL"
] | 6 | 2021-02-18T09:13:17.000Z | 2022-03-22T21:27:46.000Z | Util/SUNDIALS_serial_test/main.cpp | Gosenca/axionyx_1.0 | 7e2a723e00e6287717d6d81b23db32bcf6c3521a | [
"BSD-3-Clause-LBNL"
] | 1 | 2020-10-12T08:54:31.000Z | 2020-10-12T08:54:31.000Z | Util/SUNDIALS_serial_test/main.cpp | Gosenca/axionyx_1.0 | 7e2a723e00e6287717d6d81b23db32bcf6c3521a | [
"BSD-3-Clause-LBNL"
] | 3 | 2020-09-04T10:26:25.000Z | 2022-03-14T23:51:51.000Z | #include <fstream>
#include <iomanip>
#include <AMReX_ParmParse.H>
#include <AMReX_Geometry.H>
#include <AMReX_MultiFab.H>
#include <AMReX_Print.H>
#include <AMReX_PlotFileUtil.H>
#include <AMReX_BLFort.H>
#include <cvode/cvode.h> /* prototypes for CVODE fcts., consts. */
#include <sunlinsol/sunlinsol_spgmr.h> /* access to SPGMR SUNLinearSolver */
#include <cvode/cvode_spils.h> /* access to CVSpils interface */
#include <cvode/cvode_diag.h> /* access to CVDiag interface */
#include <sundials/sundials_types.h> /* definition of type realtype */
#include <sundials/sundials_math.h> /* definition of ABS and EXP */
#include <nvector/nvector_cuda.h>
#include <nvector/nvector_serial.h>
#include "myfunc_F.H"
/* Functions Called by the Solver */
static int f(realtype t, N_Vector u, N_Vector udot, void *user_data);
static void PrintFinalStats(void *cvode_mem);
static void PrintOutput(realtype t, realtype umax, long int nst);
/* Private function to check function return values */
static int check_retval(void *flagvalue, const char *funcname, int opt);
int integrate_state_box
(amrex::MultiFab &state,
amrex::MultiFab &diag_eos,
const amrex::Real& a, const amrex::Real& delta_time);
using namespace amrex;
/*
#pragma gpu
void device_ptr_wrapper(N_Vector u, Real* dptr)
dptr=N_VGetDeviceArrayPointer_Cuda(u);
*/
int main (int argc, char* argv[])
{
amrex::Initialize(argc,argv);
// What time is it now? We'll use this to compute total run time.
Real strt_time = ParallelDescriptor::second();
std::cout << std::setprecision(15);
int n_cell, max_grid_size;
int cvode_meth, cvode_itmeth, write_plotfile, nGrow;
bool do_tiling;
int ierr=0;
nGrow=0;
// inputs parameters
{
// ParmParse is way of reading inputs from the inputs file
ParmParse pp;
// We need to get n_cell from the inputs file - this is the number of
// cells on each side of a square (or cubic) domain.
pp.get("n_cell",n_cell);
// Default nsteps to 0, allow us to set it to something else in the
// inputs file
pp.get("max_grid_size",max_grid_size);
// Select CVODE solve method.
// 1 = Adams (for non-stiff problems)
// 2 = BDF (for stiff problems)
pp.get("cvode_meth",cvode_meth);
// Select CVODE solver iteration method.
// 1 = Functional iteration
// 2 = Newton iteration
pp.get("cvode_itmeth",cvode_itmeth);
pp.get("write_plotfile",write_plotfile);
pp.get("do_tiling",do_tiling);
pp.get("nGrow",nGrow);
}
if(do_tiling)
amrex::Abort("Add function argument for tiling bool");
if (cvode_meth < 1)
amrex::Abort("Unknown cvode_meth");
if (cvode_itmeth < 1)
amrex::Abort("Unknown cvode_itmeth");
amrex::Print() << "This is AMReX version " << amrex::Version() << std::endl;
amrex::Print() << "Problem domain size: nx = ny = nz = " << n_cell << std::endl;
amrex::Print() << "Max grid size: " << max_grid_size << std::endl;
amrex::Print() << "CVODE method: ";
if (cvode_meth == 1) {
amrex::Print() << "Adams (non-stiff)";
} else if (cvode_meth == 2) {
amrex::Print() << "BDF (stiff)";
}
amrex::Print() << std::endl;
amrex::Print() << "CVODE iteration method: ";
if (cvode_itmeth == 1) {
amrex::Print() << "Functional";
} else if (cvode_itmeth == 2) {
amrex::Print() << "Newton";
}
amrex::Print() << std::endl;
// make BoxArray and Geometry
BoxArray ba;
Geometry geom;
{
IntVect dom_lo(IntVect(D_DECL(0,0,0)));
IntVect dom_hi(IntVect(D_DECL(n_cell-1, n_cell-1, n_cell-1)));
Box domain(dom_lo, dom_hi);
// Initialize the boxarray "ba" from the single box "bx"
ba.define(domain);
// Break up boxarray "ba" into chunks no larger than "max_grid_size"
// along a direction
ba.maxSize(max_grid_size);
// This defines the physical size of the box. Right now the box is
// [-1,1] in each direction.
RealBox real_box;
for (int n = 0; n < BL_SPACEDIM; n++) {
real_box.setLo(n,-1.0);
real_box.setHi(n, 1.0);
}
// This sets the boundary conditions to be doubly or triply periodic
int is_periodic[BL_SPACEDIM];
for (int i = 0; i < BL_SPACEDIM; i++) {
is_periodic[i] = 1;
}
// This defines a Geometry object
geom.define(domain,&real_box,CoordSys::cartesian,is_periodic);
}
// Ncomp = number of components for each array
int Ncomp = 1;
// time = starting time in the simulation
Real time = 0.0;
DistributionMapping dm(ba);
// Create MultiFab with no ghost cells.
MultiFab mf(ba, dm, Ncomp, nGrow);
// Create MultiFab with no ghost cells.
MultiFab S_old(ba, dm, 6, nGrow);
// Create MultiFab with no ghost cells.
MultiFab D_old(ba, dm, 2, nGrow);
/*
rparh[4*i+0]= 3.255559960937500E+04; //rpar(1)=T_vode
rparh[4*i+1]= 1.076699972152710E+00;// rpar(2)=ne_vode
rparh[4*i+2]= 2.119999946752000E+12; // rpar(3)=rho_vode
rparh[4*i+3]=1/(1.635780036449432E-01)-1; // rpar(4)=z_vode
*/
S_old.setVal(2.119999946752000E+12,0,1,nGrow); // rpar(3)=rho_vode
S_old.setVal(6.226414794921875E+02,5,1,nGrow); // rpar(3)=rho_vode
D_old.setVal(3.255559960937500E+04 ,0,1,nGrow); // rpar(1)=T_vode
D_old.setVal(1.076699972152710E+00 ,1,1,nGrow); // rpar(2)=ne_vode
// MultiFab vode_aux_vars(ba, dm, 4*Ncomp, 0);
/* vode_aux_vars.setVal(3.255559960937500E+04,0);
vode_aux_vars.setVal(1.076699972152710E+00,1);
vode_aux_vars.setVal(2.119999946752000E+12,2);
vode_aux_vars.setVal(1/(1+1.635780036449432E-01),3);*/
//////////////////////////////////////////////////////////////////////
// Allocate data
//////////////////////////////////////////////////////////////////////
double delta_time= 8.839029760565609E-06;
amrex::Real a=1.635780036449432E-01;
fort_init_allocations();
fort_init_tables_eos_params(a);
ierr=integrate_state_box(S_old, D_old, a, delta_time);
if(ierr)
{
amrex::Print()<<"returned nonzero error code"<<std::endl;
return ierr;
}
// Deallocate data
//////////////////////////////////////////////////////////////////////
fort_fin_allocations();
amrex::Print()<<"Maximum of repacked final solution: "<<S_old.max(0,0,0)<<std::endl;
if (write_plotfile)
{
amrex::WriteSingleLevelPlotfile("PLT_OUTPUT",
S_old,
{"rho","U","V","W","Eden","Eint"},
geom,
time,
0);
amrex::WriteSingleLevelPlotfile("PLT_DIAG_OUTPUT",
D_old,
{"Temp","Ne"},
geom,
time,
0);
}
// Call the timer again and compute the maximum difference between the start time and stop time
// over all processors
Real stop_time = ParallelDescriptor::second() - strt_time;
const int IOProc = ParallelDescriptor::IOProcessorNumber();
ParallelDescriptor::ReduceRealMax(stop_time,IOProc);
// Tell the I/O Processor to write out the "run time"
amrex::Print() << "Run time = " << stop_time << std::endl;
amrex::Finalize();
return 0;
}
int integrate_state_box
(amrex::MultiFab &S_old,
amrex::MultiFab &D_old,
const amrex::Real& a, const amrex::Real& delta_time)
{
// time = starting time in the simulation
realtype reltol, abstol, t, tout, umax;
N_Vector u;
// SUNLinearSolver LS;
void *cvode_mem;
int iout, flag;
long int nst;
bool do_tiling=false;
u = NULL;
// LS = NULL;
cvode_mem = NULL;
reltol = 1e-6; /* Set the tolerances */
abstol = 1e-10;
for ( MFIter mfi(S_old, do_tiling); mfi.isValid(); ++mfi )
{
Real* dptr;
t=0.0;
const Box& tbx = mfi.growntilebox(S_old.nGrow());
amrex::IntVect tile_size = tbx.size();
const int* hi = tbx.hiVect();
const int* lo = tbx.loVect();
int long neq1=(hi[0]-lo[0]+1)*(hi[1]-lo[1]+1)*(hi[2]-lo[2]+1);
int long neq2=(hi[0]-lo[0]+1-S_old.nGrow())*(hi[1]-lo[1]+1-S_old.nGrow())*(hi[2]-lo[2]+1-S_old.nGrow());
int long neq=(tile_size[0])*(tile_size[1])*(tile_size[2]);
if(neq>1)
{
amrex::Print()<<"Integrating a box with "<<neq<<" cells"<<std::endl;
amrex::Print()<<"Integrating a box with "<<neq1<<" cells"<<std::endl;
amrex::Print()<<"Integrating a box with "<<neq2<<"real cells"<<std::endl;
}
/* Create a CUDA vector with initial values */
u = N_VNew_Serial(neq); /* Allocate u vector */
if(check_retval((void*)u, "N_VNew_Cuda", 0)) return(1);
/* FSetInternalEnergy_mfab(S_old[mfi].dataPtr(),
tbx.loVect(),
tbx.hiVect()); /* Initialize u vector */
dptr=N_VGetArrayPointer_Serial(u);
S_old[mfi].copyToMem(tbx,5,1,dptr);
/* Call CVodeCreate to create the solver memory and specify the
* Backward Differentiation Formula and the use of a Newton iteration */
#ifdef CV_NEWTON
cvode_mem = CVodeCreate(CV_BDF, CV_NEWTON);
#else
cvode_mem = CVodeCreate(CV_BDF);
#endif
if(check_retval((void *)cvode_mem, "CVodeCreate", 0)) return(1);
/* Call CVodeInit to initialize the integrator memory and specify the
* user's right hand side function in u'=f(t,u), the initial time T0, and
* the initial dependent variable vector u. */
flag = CVodeInit(cvode_mem, f, t, u);
if(check_retval(&flag, "CVodeInit", 1)) return(1);
/* Call CVodeSStolerances to specify the scalar relative tolerance
* and scalar absolute tolerance */
flag = CVodeSStolerances(cvode_mem, reltol, abstol);
if (check_retval(&flag, "CVodeSStolerances", 1)) return(1);
/* Create SPGMR solver structure without preconditioning
* and the maximum Krylov dimension maxl */
// LS = SUNSPGMR(u, PREC_NONE, 0);
// if(check_flag(&flag, "SUNSPGMR", 1)) return(1);
/* Set CVSpils linear solver to LS */
// flag = CVSpilsSetLinearSolver(cvode_mem, LS);
// if(check_flag(&flag, "CVSpilsSetLinearSolver", 1)) return(1);
flag = CVDiag(cvode_mem);
/*Use N_Vector to create userdata, in order to allocate data on device*/
N_Vector Data = N_VNew_Serial(4*neq); // Allocate u vector
N_VConst(0.0,Data);
double* rparh=N_VGetArrayPointer_Serial(Data);
N_Vector rho_tmp = N_VNew_Serial(neq); // Allocate u vector
N_VConst(0.0,rho_tmp);
double* rho_tmp_ptr=N_VGetArrayPointer_Serial(rho_tmp);
S_old[mfi].copyToMem(tbx,0,1,rho_tmp_ptr);
N_Vector T_tmp = N_VNew_Serial(2*neq); // Allocate u vector
N_VConst(0.0,T_tmp);
double* Tne_tmp_ptr=N_VGetArrayPointer_Serial(T_tmp);
D_old[mfi].copyToMem(tbx,0,2,Tne_tmp_ptr);
for(int i=0;i<neq;i++)
{
rparh[4*i+0]= Tne_tmp_ptr[i]; //rpar(1)=T_vode
rparh[4*i+1]= Tne_tmp_ptr[neq+i];// rpar(2)=ne_vode
rparh[4*i+2]= rho_tmp_ptr[i]; // rpar(3)=rho_vode
rparh[4*i+3]=1/a-1; // rpar(4)=z_vode
}
CVodeSetUserData(cvode_mem, &Data);
/* Call CVode using 1 substep */
/* flag = CVode(cvode_mem, tout, u, &t, CV_NORMAL);
if(check_flag(&flag, "CVode", 1)) break;
*/
int n_substeps=1;
for(iout=1, tout= delta_time/n_substeps ; iout <= n_substeps; iout++, tout += delta_time/n_substeps) {
flag = CVode(cvode_mem, tout, u, &t, CV_NORMAL);
umax = N_VMaxNorm(u);
flag = CVodeGetNumSteps(cvode_mem, &nst);
check_retval(&flag, "CVodeGetNumSteps", 1);
PrintOutput(tout, umax, nst);
}
for(int i=0;i<neq;i++)
{
Tne_tmp_ptr[i]=rparh[4*i+0]; //rpar(1)=T_vode
Tne_tmp_ptr[neq+i]=rparh[4*i+1];// rpar(2)=ne_vode
// amrex::Print()<<"Temp"<<Tne_tmp_ptr[i]<<std::endl;
// rho should not change rho_tmp_ptr[i]=rparh[4*i+2]; // rpar(3)=rho_vode
}
D_old[mfi].copyFromMem(tbx,0,2,Tne_tmp_ptr);
S_old[mfi].copyFromMem(tbx,5,1,dptr);
PrintFinalStats(cvode_mem);
N_VDestroy(u); /* Free the u vector */
N_VDestroy(Data); /* Free the userdata vector */
N_VDestroy(T_tmp);
N_VDestroy(rho_tmp);
CVodeFree(&cvode_mem); /* Free the integrator memory */
}
}
static int f(realtype t, N_Vector u, N_Vector udot, void* user_data)
{
Real* udot_ptr=N_VGetArrayPointer_Serial(udot);
Real* u_ptr=N_VGetArrayPointer_Serial(u);
int neq=N_VGetLength_Serial(udot);
double* rpar=N_VGetArrayPointer_Serial(*(static_cast<N_Vector*>(user_data)));
/* fprintf(stdout,"\nt=%g \n\n",t);
fprintf(stdout,"\nrparh[0]=%g \n\n",rpar[0]);
fprintf(stdout,"\nrparh[1]=%g \n\n",rpar[1]);
fprintf(stdout,"\nrparh[2]=%g \n\n",rpar[2]);
fprintf(stdout,"\nrparh[3]=%g \n\n",rpar[3]);*/
for(int tid=0;tid<neq;tid++)
{
// fprintf(stdout,"\nrpar[4*tid+0]=%g\n",rpar[4*tid]);
RhsFnReal(t,&(u_ptr[tid]),&(udot_ptr[tid]),&(rpar[4*tid]),1);
// fprintf(stdout,"\nafter rpar[4*tid+0]=%g\n",rpar[4*tid]);
}
/* fprintf(stdout,"\nafter rparh[0]=%g \n\n",rpar[0]);
fprintf(stdout,"\nafter rparh[1]=%g \n\n",rpar[1]);
fprintf(stdout,"\nafter rparh[2]=%g \n\n",rpar[2]);
fprintf(stdout,"\nafter rparh[3]=%g \n\n",rpar[3]);
fprintf(stdout,"\nafter last rparh[4*(neq-1)+1]=%g \n\n",rpar[4*(neq-1)+1]);*/
return 0;
}
static void PrintOutput(realtype t, realtype umax, long int nst)
{
#if defined(SUNDIALS_EXTENDED_PRECISION)
printf("At t = %4.2Lf max.norm(u) =%14.16Le nst = %4ld\n", t, umax, nst);
#elif defined(SUNDIALS_DOUBLE_PRECISION)
printf("At t = %4.2f max.norm(u) =%14.16e nst = %4ld\n", t, umax, nst);
#else
printf("At t = %4.2f max.norm(u) =%14.16e nst = %4ld\n", t, umax, nst);
#endif
return;
}
/* Get and print some final statistics */
static void PrintFinalStats(void *cvode_mem)
{
long lenrw, leniw ;
long lenrwLS, leniwLS;
long int nst, nfe, nsetups, nni, ncfn, netf;
long int nli, npe, nps, ncfl, nfeLS;
int retval;
retval = CVodeGetWorkSpace(cvode_mem, &lenrw, &leniw);
check_retval(&retval, "CVodeGetWorkSpace", 1);
retval = CVodeGetNumSteps(cvode_mem, &nst);
check_retval(&retval, "CVodeGetNumSteps", 1);
retval = CVodeGetNumRhsEvals(cvode_mem, &nfe);
check_retval(&retval, "CVodeGetNumRhsEvals", 1);
retval = CVodeGetNumLinSolvSetups(cvode_mem, &nsetups);
check_retval(&retval, "CVodeGetNumLinSolvSetups", 1);
retval = CVodeGetNumErrTestFails(cvode_mem, &netf);
check_retval(&retval, "CVodeGetNumErrTestFails", 1);
retval = CVDiagGetNumRhsEvals(cvode_mem, &nfeLS);
printf("\nFinal Statistics.. \n\n");
printf("lenrw = %5ld leniw = %5ld\n" , lenrw, leniw);
printf("nst = %5ld\n" , nst);
printf("nfe = %5ld nfeLS = %5ld\n" , nfe, nfeLS);
printf("nsetups = %5ld netf = %5ld\n" , nsetups, netf);
return;
}
static int check_retval(void *flagvalue, const char *funcname, int opt)
{
int *errflag;
/* Check if SUNDIALS function returned NULL pointer - no memory allocated */
if (opt == 0 && flagvalue == NULL) {
fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n",
funcname);
return(1); }
/* Check if flag < 0 */
else if (opt == 1) {
errflag = (int *) flagvalue;
if (*errflag < 0) {
fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed with flag = %d\n\n",
funcname, *errflag);
return(1); }}
/* Check if function returned NULL pointer - no memory allocated */
else if (opt == 2 && flagvalue == NULL) {
fprintf(stderr, "\nMEMORY_ERROR: %s() failed - returned NULL pointer\n\n",
funcname);
return(1); }
return(0);
}
| 33.842767 | 110 | 0.604782 | Gosenca |
dc24c91937ee39b8eb08090a22fc4d707c98c20e | 13,024 | cpp | C++ | src/ccd_vf.cpp | ricortiz/SCCD | 35ee94736c9337164732591aa8b053bad60a9f09 | [
"BSD-4-Clause-UC"
] | 7 | 2017-04-01T08:09:26.000Z | 2021-08-06T03:29:15.000Z | src/ccd_vf.cpp | deberle2/CD | 35ee94736c9337164732591aa8b053bad60a9f09 | [
"BSD-4-Clause-UC"
] | null | null | null | src/ccd_vf.cpp | deberle2/CD | 35ee94736c9337164732591aa8b053bad60a9f09 | [
"BSD-4-Clause-UC"
] | 2 | 2016-03-03T16:55:50.000Z | 2020-06-16T03:33:16.000Z | /*************************************************************************\
Copyright 2010 The University of North Carolina at Chapel Hill.
All Rights Reserved.
Permission to use, copy, modify and distribute this software and its
documentation for educational, research and non-profit purposes, without
fee, and without a written agreement is hereby granted, provided that the
above copyright notice and the following three paragraphs appear in all
copies.
IN NO EVENT SHALL THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL BE
LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR
CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY
OF NORTH CAROLINA HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
THE UNIVERSITY OF NORTH CAROLINA SPECIFICALLY DISCLAIM ANY
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
NORTH CAROLINA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
The authors may be contacted via:
US Mail: GAMMA Research Group at UNC
Department of Computer Science
Sitterson Hall, CB #3175
University of N. Carolina
Chapel Hill, NC 27599-3175
Phone: (919)962-1749
EMail: geom@cs.unc.edu; tang_m@zju.edu.cn
\**************************************************************************/
#include "vec3f.h"
#define ccdTimeResolution double(10e-8)
#define zeroRes double(10e-8)
#define IsZero(x) ((x) < zeroRes && (x) > -zeroRes ? true : false)
typedef struct {
vec3f ad, bd, cd, pd;
vec3f a0, b0, c0, p0;
} NewtonCheckData;
/*
* Ordinary inside-triangle test for p. The triangle normal is computed from the vertices.
*/
static inline bool _insideTriangle(const vec3f &a, const vec3f &b, const vec3f &c, const vec3f &p, vec3f &baryc)
{
vec3f n, da, db, dc;
float wa, wb, wc;
vec3f ba = b-a;
vec3f ca = c-a;
n = ba.cross(ca);
da = a - p, db = b - p, dc = c - p;
if ((wa = (db.cross(dc)).dot(n)) < 0.0f) return false;
if ((wb = (dc.cross(da)).dot(n)) < 0.0f) return false;
if ((wc = (da.cross(db)).dot(n)) < 0.0f) return false;
//Compute barycentric coordinates
float area2 = n.dot(n);
wa /= area2, wb /= area2, wc /= area2;
baryc = vec3f(wa, wb, wc);
return true;
}
static inline bool _insideLnSeg(const vec3f &a, const vec3f &b, const vec3f &c)
{
return (a-b).dot(a-c)<=0;
}
static inline bool checkRootValidity_VE(float t, NewtonCheckData &data)
{
return _insideLnSeg(
data.ad*t + data.a0,
data.bd*t + data.b0,
data.cd*t + data.c0);
}
static inline bool checkRootValidity_VF(float t, vec3f& baryc, NewtonCheckData &data) {
return _insideTriangle(
data.ad*t + data.a0,
data.bd*t + data.b0,
data.cd*t + data.c0,
data.pd*t + data.p0,
baryc);
}
// http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline3d/
/*
Calculate the line segment PaPb that is the shortest route between
two lines P1P2 and P3P4. Calculate also the values of mua and mub where
Pa = P1 + mua (P2 - P1)
Pb = P3 + mub (P4 - P3)
Return FALSE if no solution exists.
*/
inline bool LineLineIntersect(
const vec3f &p1, const vec3f &p2, const vec3f &p3, const vec3f &p4,
vec3f &pa, vec3f &pb, float &mua, float &mub)
{
vec3f p13,p43,p21;
float d1343,d4321,d1321,d4343,d2121;
float numer,denom;
p13 = p1 - p3;
p43 = p4 - p3;
if (fabs(p43[0]) < std::numeric_limits<float>::epsilon() && fabs(p43[1]) < std::numeric_limits<float>::epsilon() && fabs(p43[2]) < std::numeric_limits<float>::epsilon())
return false;
p21 = p2 - p1;
if (fabs(p21[0]) < std::numeric_limits<float>::epsilon() && fabs(p21[1]) < std::numeric_limits<float>::epsilon() && fabs(p21[2]) < std::numeric_limits<float>::epsilon())
return false;
d1343 = p13.dot(p43);
d4321 = p43.dot(p21);
d1321 = p13.dot(p21);
d4343 = p43.dot(p43);
d2121 = p21.dot(p21);
denom = d2121 * d4343 - d4321 * d4321;
if (fabs(denom) < std::numeric_limits<float>::epsilon())
return false;
numer = d1343 * d4321 - d1321 * d4343;
mua = numer / denom;
if (mua < 0 || mua > 1)
return false;
mub = (d1343 + d4321 * mua) / d4343;
if (mub < 0 || mub > 1)
return false;
pa = p1 + p21*mua;
pb = p3 + p43*mub;
return true;
}
static inline bool checkRootValidity_EE(float t, vec3f &pt, NewtonCheckData &data) {
vec3f a = data.ad*t + data.a0;
vec3f b = data.bd*t + data.b0;
vec3f c = data.cd*t + data.c0;
vec3f d = data.pd*t + data.p0;
vec3f p1, p2;
float tab, tcd;
if (LineLineIntersect(a, b, c, d, p1, p2, tab, tcd)) {
t = tab;
pt = p1;
return true;
}
return false;
}
inline bool solveSquare(float a, float b, float c, NewtonCheckData &data)
{
if (IsZero(a)) {
float t = -c/b;
return (t >= 0 && t <= 1) ? checkRootValidity_VE(t, data) : false;
}
float discriminant = b*b-4*a*c;
if (discriminant < 0)
return false;
float tmp = sqrt(discriminant);
float ta = 0.5f/a;
vec3f baryc;
float r1 = (-b+tmp)*ta;
bool v1 = (r1 >= 0.f && r1 <= 1.f) ? checkRootValidity_VE(r1, data) : false;
if (v1) return true;
float r2 = (-b-tmp)*ta;
bool v2 = (r2 >= 0.f && r2 <= 1.f) ? checkRootValidity_VE(r2, data) : false;
return v2;
}
inline bool solveCubicWithIntervalNewton(double &l, double &r, vec3f& baryc, bool bVF,
NewtonCheckData &data, double coeffs[])
{
double v2[2]={l*l,r*r};
double v[2]={l,r};
double rBkUp;
unsigned char min3, min2, min1, max3, max2, max1;
min3=*((unsigned char*)&coeffs[3]+7)>>7;max3=min3^1;
min2=*((unsigned char*)&coeffs[2]+7)>>7;max2=min2^1;
min1=*((unsigned char*)&coeffs[1]+7)>>7;max1=min1^1;
// bound the cubic
double minor=coeffs[3]*v2[min3]*v[min3]+coeffs[2]*v2[min2]+coeffs[1]*v[min1]+coeffs[0];
double major=coeffs[3]*v2[max3]*v[max3]+coeffs[2]*v2[max2]+coeffs[1]*v[max1]+coeffs[0];
if (major<0) return false;
if (minor>0) return false;
// starting here, the bounds have opposite values
double m=0.5*(r+l);
// bound the derivative
double dminor=3.0*coeffs[3]*v2[min3]+2.0*coeffs[2]*v[min2]+coeffs[1];
double dmajor=3.0*coeffs[3]*v2[max3]+2.0*coeffs[2]*v[max2]+coeffs[1];
if ((dminor>0)||(dmajor<0)) // we can use Newton
{
double m2=m*m;
double fm=coeffs[3]*m2*m+coeffs[2]*m2+coeffs[1]*m+coeffs[0];
double nl=m;
double nu=m;
if (fm>0) {nl-=fm*(1.0/dminor);nu-=fm*(1.0/dmajor);}
else {nu-=fm*(1.0/dminor);nl-=fm*(1.0/dmajor);}
//intersect with [l,r]
if (nl>r) return false; // pas de solution
if (nu<l) return false; // pas de solution
if (nl>l)
{
if (nu<r) {l=nl;r=nu;m=0.5*(l+r);}
else {l=nl;m=0.5*(l+r);}
}
else
{
if (nu<r) {r=nu;m=0.5*(l+r);}
}
}
// sufficient temporal resolution, check root validity
if ((r-l)<ccdTimeResolution)
if (bVF)
return checkRootValidity_VF(r, baryc, data);
else
return checkRootValidity_EE(r, baryc, data);
rBkUp = r, r = m;
if (solveCubicWithIntervalNewton(l,r,baryc, bVF, data, coeffs)) return true;
l = m, r = rBkUp;
return (solveCubicWithIntervalNewton(l,r,baryc, bVF, data, coeffs));
}
/*
* Computes the coefficients of the cubic equations from the geometry data.
*/
inline void _equateCubic_VF(const vec3f &a0, const vec3f &ad, const vec3f &b0, const vec3f &bd,
const vec3f &c0, const vec3f &cd, const vec3f &p0, const vec3f &pd,
float &a, float &b, float &c, float &d)
{
/*
* For definitions & notation refer to the semester thesis doc.
*/
vec3f dab, dac, dap;
vec3f oab, oac, oap;
vec3f dabXdac, dabXoac, oabXdac, oabXoac;
dab = bd - ad, dac = cd - ad, dap = pd - ad;
oab = b0 - a0, oac = c0 - a0, oap = p0 - a0;
dabXdac = dab.cross(dac);
dabXoac = dab.cross(oac);
oabXdac = oab.cross(dac);
oabXoac = oab.cross(oac);
a = dap.dot(dabXdac);
b = oap.dot(dabXdac) + dap.dot(dabXoac + oabXdac);
c = dap.dot(oabXoac) + oap.dot(dabXoac + oabXdac);
d = oap.dot(oabXoac);
}
/*
* Computes the coefficients of the cubic equations from the geometry data.
*/
inline void _equateCubic_VE(
const vec3f &a0, const vec3f &ad, const vec3f &b0, const vec3f &bd,
const vec3f &c0, const vec3f &cd, const vec3f &L,
float &a, float &b, float &c)
{
/*
* For definitions & notation refer to the semester thesis doc.
*/
vec3f dab, dcb;
vec3f oab, ocb;
dab = ad-bd; dcb = cd-bd;
oab = a0-b0; ocb = c0-b0;
vec3f Ldcb = L.cross(dcb);
vec3f Locb = L.cross(ocb);
a = Ldcb.dot(dab);
b = Ldcb.dot(oab) + Locb.dot(dab);
c = Locb.dot(oab);
}
/*
* Computes the coefficients of the cubic equations from the geometry data.
*/
inline void _equateCubic_EE(const vec3f &a0, const vec3f &ad, const vec3f &b0, const vec3f &bd,
const vec3f &c0, const vec3f &cd, const vec3f &d0, const vec3f &dd,
float &a, float &b, float &c, float &d)
{
/*
* For definitions & notation refer to the semester thesis doc.
*/
vec3f dba, ddc, dca;
vec3f odc, oba, oca;
vec3f dbaXddc, dbaXodc, obaXddc, obaXodc;
dba = bd - ad, ddc = dd - cd, dca = cd - ad;
odc = d0 - c0, oba = b0 - a0, oca = c0 - a0;
dbaXddc = dba.cross(ddc);
dbaXodc = dba.cross(odc);
obaXddc = oba.cross(ddc);
obaXodc = oba.cross(odc);
a = dca.dot(dbaXddc);
b = oca.dot(dbaXddc) + dca.dot(dbaXodc + obaXddc);
c = dca.dot(obaXodc) + oca.dot(dbaXodc + obaXddc);
d = oca.dot(obaXodc);
}
bool
Intersect_VE(const vec3f &ta0, const vec3f &tb0, const vec3f &tc0,
const vec3f &ta1, const vec3f &tb1, const vec3f &tc1, const vec3f &L)
{
vec3f ad, bd, cd;
/* diff. vectors for linear interpolation */
ad = ta1 - ta0, bd = tb1 - tb0, cd = tc1 - tc0;
/*
* Compute scalar coefficients by evaluating dot and cross-products.
*/
float a, b, c; /* cubic polynomial coefficients */
_equateCubic_VE(ta0, ad, tb0, bd, tc0, cd, L, a, b, c);
if (IsZero(a) && IsZero(b) && IsZero(c))
return true;
NewtonCheckData data;
data.a0 = ta0, data.b0 = tb0, data.c0 = tc0;
data.ad = ad, data.bd = bd, data.cd = cd;
return solveSquare(a, b, c, data);
}
float
Intersect_VF(const vec3f &ta0, const vec3f &tb0, const vec3f &tc0,
const vec3f &ta1, const vec3f &tb1, const vec3f &tc1,
const vec3f &q0, const vec3f &q1,
vec3f &qi, vec3f &baryc)
{
/* Default value returned if no collision occurs */
float collisionTime = -1.0f;
vec3f qd, ad, bd, cd;
/* diff. vectors for linear interpolation */
qd = q1 - q0, ad = ta1 - ta0, bd = tb1 - tb0, cd = tc1 - tc0;
/*
* Compute scalar coefficients by evaluating dot and cross-products.
*/
float a, b, c, d; /* cubic polynomial coefficients */
_equateCubic_VF(ta0, ad, tb0, bd, tc0, cd, q0, qd, a, b, c, d);
if (IsZero(a) && IsZero(b) && IsZero(c) && IsZero(d))
return collisionTime;
NewtonCheckData data;
data.a0 = ta0, data.b0 = tb0;
data.c0 = tc0, data.p0 = q0;
data.ad = ad, data.bd = bd;
data.cd = cd, data.pd = qd;
/*
* iteratively solve the cubic (scalar) equation and test for validity of the solution.
*/
double l = 0;
double r = 1;
double coeffs[4];
coeffs[3] = a, coeffs[2] = b, coeffs[1] = c, coeffs[0] = d;
if (solveCubicWithIntervalNewton(l, r, baryc, true, data, coeffs)) {
collisionTime = (l+r)*0.5f;
qi = qd*collisionTime + q0;
}
return collisionTime;
}
float
Intersect_EE(const vec3f &ta0, const vec3f &tb0, const vec3f &tc0, const vec3f &td0,
const vec3f &ta1, const vec3f &tb1, const vec3f &tc1, const vec3f &td1,
vec3f &qi)
{
/* Default value returned if no collision occurs */
float collisionTime = -1.0f;
vec3f ad, bd, cd, dd;
/* diff. vectors for linear interpolation */
dd = td1 - td0, ad = ta1 - ta0, bd = tb1 - tb0, cd = tc1 - tc0;
/*
* Compute scalar coefficients by evaluating dot and cross-products.
*/
float a, b, c, d; /* cubic polynomial coefficients */
_equateCubic_EE(ta0, ad, tb0, bd, tc0, cd, td0, dd, a, b, c, d);
if (IsZero(a) && IsZero(b) && IsZero(c) && IsZero(d))
return collisionTime;
NewtonCheckData data;
data.a0 = ta0, data.b0 = tb0;
data.c0 = tc0, data.p0 = td0;
data.ad = ad, data.bd = bd;
data.cd = cd, data.pd = dd;
/*
* iteratively solve the cubic (scalar) equation and test for validity of the solution.
*/
double l = 0;
double r = 1;
double coeffs[4];
coeffs[3] = a, coeffs[2] = b, coeffs[1] = c, coeffs[0] = d;
vec3f pab;
if (solveCubicWithIntervalNewton(l, r, pab, false, data, coeffs)) {
collisionTime = (l+r)*0.5f;
qi = pab;
}
return collisionTime;
} | 28.687225 | 174 | 0.616554 | ricortiz |
dc2cb418923e36b791d69f3f5a94cba588cb6244 | 328 | cpp | C++ | RenderQueuePass.cpp | TheHolyBell/Hardware3D | 1879c498645dfec874ab25497d1c830482bbf0c7 | [
"MIT"
] | null | null | null | RenderQueuePass.cpp | TheHolyBell/Hardware3D | 1879c498645dfec874ab25497d1c830482bbf0c7 | [
"MIT"
] | null | null | null | RenderQueuePass.cpp | TheHolyBell/Hardware3D | 1879c498645dfec874ab25497d1c830482bbf0c7 | [
"MIT"
] | null | null | null | #include "RenderQueuePass.h"
namespace RenderGraph
{
void RenderQueuePass::Accept(Job job) noexcept
{
m_Jobs.push_back(job);
}
void RenderQueuePass::Execute(Graphics& gfx) const noxnd
{
BindAll(gfx);
for (const auto& j : m_Jobs)
j.Execute(gfx);
}
void RenderQueuePass::Reset() noxnd
{
m_Jobs.clear();
}
} | 14.909091 | 57 | 0.692073 | TheHolyBell |
dc328e504f20ad3452b559b3d9e3a0a49da4c2f7 | 3,357 | hpp | C++ | include/instructions/math.hpp | luizschonarth/JVM-8 | b828d1e12072b71cbadeb924b7b13661d300f798 | [
"MIT"
] | null | null | null | include/instructions/math.hpp | luizschonarth/JVM-8 | b828d1e12072b71cbadeb924b7b13661d300f798 | [
"MIT"
] | 24 | 2022-03-12T18:38:22.000Z | 2022-03-28T00:29:03.000Z | include/instructions/math.hpp | luizschonarth/JVM-8 | b828d1e12072b71cbadeb924b7b13661d300f798 | [
"MIT"
] | null | null | null | /**
* @file math.hpp
* @brief Declaration of the instructions of type math
*/
#ifndef _MATH_HPP
#define _MATH_HPP
#include "../frame.hpp"
#include "../constant_pool_info.hpp"
void dadd(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void fadd(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void iadd(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void ladd(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void isub(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void lsub(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void fsub(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void dsub(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void imul(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void lmul(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void fmul(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void dmul(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void idiv(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void ldiv(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void fdiv(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void ddiv(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void irem(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void lrem(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void frem(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void drem(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void ineg(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void lneg(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void fneg(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void dneg(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void ishl(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void lshl(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void ishr(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void lshr(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void iushr(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void lushr(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void iand(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void land(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void ior(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void lor(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void ixor(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void lxor(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
void iinc(cp_info_vector &constant_pool, bytestream &code, stack<frame_t> *stack_f);
#endif // _MATH_HPP | 55.95 | 85 | 0.79148 | luizschonarth |
dc32947e2a1738f32cda886493ed8a21d79216f8 | 1,667 | cpp | C++ | cmdstan/stan/lib/stan_math/test/unit/math/fwd/scal/fun/log1m_exp_test.cpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | cmdstan/stan/lib/stan_math/test/unit/math/fwd/scal/fun/log1m_exp_test.cpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | cmdstan/stan/lib/stan_math/test/unit/math/fwd/scal/fun/log1m_exp_test.cpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | #include <stan/math/fwd/scal.hpp>
#include <gtest/gtest.h>
#include <test/unit/math/fwd/scal/fun/nan_util.hpp>
#include <cmath>
TEST(AgradFwdLog1mExp,Fvar) {
using stan::math::fvar;
using stan::math::log1m_exp;
using std::exp;
using std::log;
fvar<double> x(-0.5);
fvar<double> y(-1.0);
x.d_ = 1.0;
y.d_ = 2.0;
fvar<double> a = log1m_exp(x);
EXPECT_FLOAT_EQ(log1m_exp(-0.5), a.val_);
EXPECT_FLOAT_EQ(-exp(-0.5) / (1 - exp(-0.5)), a.d_);
EXPECT_FLOAT_EQ(-1 / ::expm1(0.5), a.d_);
fvar<double> b = log1m_exp(y);
EXPECT_FLOAT_EQ(log1m_exp(-1.0), b.val_);
EXPECT_FLOAT_EQ(2.0 * -exp(-1.0) / (1 - exp(-1.0)), b.d_);
EXPECT_FLOAT_EQ(2.0 * -1 / ::expm1(1), b.d_);
fvar<double> a2 = log(1-exp(x));
EXPECT_FLOAT_EQ(a.d_, a2.d_);
fvar<double> b2 = log(1-exp(y));
EXPECT_FLOAT_EQ(b.d_, b2.d_);
}
TEST(AgradFwdLog1mExp,Fvar_exception) {
using stan::math::fvar;
using stan::math::log1m_exp;
EXPECT_NO_THROW(log1m_exp(fvar<double>(-3)));
EXPECT_NO_THROW(log1m_exp(fvar<double>(3)));
}
TEST(AgradFwdLog1mExp,FvarFvarDouble) {
using stan::math::fvar;
using stan::math::log1m_exp;
using std::exp;
fvar<fvar<double> > x;
x.val_.val_ = -0.2;
x.val_.d_ = 1.0;
fvar<fvar<double> > a = log1m_exp(x);
EXPECT_FLOAT_EQ(log1m_exp(-0.2), a.val_.val_);
EXPECT_FLOAT_EQ(-exp(-0.2) / (1.0 - exp(-0.2)), a.val_.d_);
EXPECT_FLOAT_EQ(0, a.d_.val_);
EXPECT_FLOAT_EQ(0, a.d_.d_);
}
struct log1m_exp_fun {
template <typename T0>
inline T0
operator()(const T0& arg1) const {
return log1m_exp(arg1);
}
};
TEST(AgradFwdLog1mExp,log1m_exp_NaN) {
log1m_exp_fun log1m_exp_;
test_nan_fwd(log1m_exp_,false);
}
| 23.814286 | 61 | 0.652669 | yizhang-cae |
dc331e0cd220e98a12cdf866a0a6dc3719981b29 | 571 | cpp | C++ | p179/p179.cpp | suzyz/leetcode_practice | e22dc5a81e065dc962e5561b14ac84b9a2302e8a | [
"MIT"
] | 1 | 2019-10-07T05:00:21.000Z | 2019-10-07T05:00:21.000Z | p179/p179.cpp | suzyz/leetcode_practice | e22dc5a81e065dc962e5561b14ac84b9a2302e8a | [
"MIT"
] | null | null | null | p179/p179.cpp | suzyz/leetcode_practice | e22dc5a81e065dc962e5561b14ac84b9a2302e8a | [
"MIT"
] | null | null | null | class Solution {
public:
string largestNumber(vector<int>& nums) {
int n = nums.size();
vector<string> s(n,"");
for (int i = 0; i < n; ++i)
s[i] = to_string(nums[i]);
sort(s.begin(),s.end(),my_cmp);
string res;
for (int i = 0; i < n; ++i)
res += s[i];
while (res.length() > 1 && res[0] == '0')
res.erase(res.begin());
return res;
}
static bool my_cmp(const string &a,const string &b)
{
string c = a + b;
string d = b + a;
return c > d;
}
};
| 21.148148 | 55 | 0.455342 | suzyz |
dc37141e96af6a2ee36af9e126f40f5177e5b62d | 582 | cpp | C++ | task1/source/bvh.cpp | barblin/ray-tracer | c8023fa32f27ca642e1acb0c3052abbb6307da18 | [
"MIT"
] | null | null | null | task1/source/bvh.cpp | barblin/ray-tracer | c8023fa32f27ca642e1acb0c3052abbb6307da18 | [
"MIT"
] | null | null | null | task1/source/bvh.cpp | barblin/ray-tracer | c8023fa32f27ca642e1acb0c3052abbb6307da18 | [
"MIT"
] | null | null | null |
struct BVH {
uint32_t SceneTriangleCount;
uint32_t BVHNodeCount;
BVH()
{
}
void GenerateBVH(Scene* scene) {
SceneTriangleCount = 0;
BVHNodeCount = 0;
}
void
Draw(int maxNodeLevel) {
// maxNodeLevel should restrict the depth of the rendered nodes to a certain level.
// e.g. if maxNodeLevel == 3 only the first 3 levels of the BVH should be drawn.
// You can draw your nodes using the debug renderer, e.g.:
// Debug::DrawBoxMinMax(Min, Max, Debug::RGBAColor(1.0f, 0.0f, 0.0f, 1.0f));
}
}; | 25.304348 | 91 | 0.608247 | barblin |
dc371b9cf565f74dc291e9a1fb0e8f252ee72b8c | 2,319 | cpp | C++ | src/usi-engine/Zobrist.cpp | bleu48/aobazero | c805b80d9ed8d27ce507fc2b74fb7609d75b2426 | [
"Unlicense"
] | 43 | 2019-05-10T05:50:23.000Z | 2022-01-03T02:46:00.000Z | src/usi-engine/Zobrist.cpp | bleu48/aobazero | c805b80d9ed8d27ce507fc2b74fb7609d75b2426 | [
"Unlicense"
] | 34 | 2019-05-07T15:22:44.000Z | 2021-09-21T04:34:39.000Z | src/usi-engine/Zobrist.cpp | kobanium/aoba-zero | dd6eb185e22c57b72663859e678fff79f7f425a5 | [
"Unlicense"
] | 13 | 2019-05-10T02:11:45.000Z | 2021-10-05T12:28:03.000Z | /*
This file is part of Leela Zero.
Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors
Leela Zero 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.
Leela Zero 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 Leela Zero. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with NVIDIA Corporation's libraries from the
NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural
Network library and/or the NVIDIA TensorRT inference library
(or a modified version of those libraries), containing parts covered
by the terms of the respective license agreement, the licensors of
this Program grant you additional permission to convey the resulting
work.
*/
#include "config.h"
#include "Zobrist.h"
#include "Random.h"
std::array<std::array<std::uint64_t, FastBoard::NUM_VERTICES>, 4> Zobrist::zobrist;
std::array<std::uint64_t, FastBoard::NUM_VERTICES> Zobrist::zobrist_ko;
std::array<std::array<std::uint64_t, FastBoard::NUM_VERTICES * 2>, 2> Zobrist::zobrist_pris;
std::array<std::uint64_t, 5> Zobrist::zobrist_pass;
void Zobrist::init_zobrist(Random& rng) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < FastBoard::NUM_VERTICES; j++) {
Zobrist::zobrist[i][j] = rng.randuint64();
}
}
for (int j = 0; j < FastBoard::NUM_VERTICES; j++) {
Zobrist::zobrist_ko[j] = rng.randuint64();
}
for (int i = 0; i < 2; i++) {
for (int j = 0; j < FastBoard::NUM_VERTICES * 2; j++) {
Zobrist::zobrist_pris[i][j] = rng.randuint64();
}
}
for (int i = 0; i < 5; i++) {
Zobrist::zobrist_pass[i] = rng.randuint64();
}
}
| 38.65 | 92 | 0.658905 | bleu48 |
dc3cca350deeffe8ceb4b5401f7e12e77b30f28d | 1,848 | cc | C++ | src/msgpack/rpc/reqtable.cc | shayanalia/msgpack-rpc-cpp | 3fd73f9a58b899774dca13a1c478fad7924dd8fd | [
"Apache-2.0"
] | 28 | 2015-01-15T13:50:05.000Z | 2022-03-01T13:41:33.000Z | src/msgpack/rpc/reqtable.cc | shayanalia/msgpack-rpc-cpp | 3fd73f9a58b899774dca13a1c478fad7924dd8fd | [
"Apache-2.0"
] | 1 | 2016-10-03T22:45:49.000Z | 2016-10-04T01:11:57.000Z | src/msgpack/rpc/reqtable.cc | shayanalia/msgpack-rpc-cpp | 3fd73f9a58b899774dca13a1c478fad7924dd8fd | [
"Apache-2.0"
] | 13 | 2015-11-27T15:30:59.000Z | 2020-09-30T20:43:00.000Z | //
// msgpack::rpc::reqtable - Cluster Communication Framework
//
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "reqtable.h"
#include "future_impl.h"
namespace msgpack {
namespace rpc {
void reqtable::insert(msgid_t msgid, shared_future f)
{
mp::pthread_scoped_lock lk(m_mutex);
m_map.insert( map_t::value_type(msgid, f) );
}
shared_future reqtable::take(msgid_t msgid)
{
mp::pthread_scoped_lock lk(m_mutex);
map_t::iterator found = m_map.find(msgid);
if(found == m_map.end()) {
return shared_future();
} else {
shared_future f = found->second;
m_map.erase(found);
return f;
}
}
void reqtable::take_all(std::vector<shared_future>* all)
{
mp::pthread_scoped_lock lk(m_mutex);
for(map_t::iterator it(m_map.begin()); it != m_map.end(); ) {
shared_future& f = it->second;
all->push_back(f);
m_map.erase(it++);
}
}
void reqtable::step_timeout(std::vector<shared_future>* timedout)
{
mp::pthread_scoped_lock lk(m_mutex);
for(map_t::iterator it(m_map.begin()); it != m_map.end(); ) {
shared_future& f = it->second;
if(f->step_timeout()) {
timedout->push_back(f);
m_map.erase(it++);
} else {
++it;
}
}
}
size_t reqtable::size() const
{
return m_map.size();
}
} // namespace rpc
} // namespace msgpack
| 23.692308 | 78 | 0.688312 | shayanalia |
dc418ffb17fffddc5ffa0a498c5776e56c9f09ad | 1,509 | hpp | C++ | include/game/skirmish/gui/mapeditortoolbar.hpp | namelessvoid/qrwar | bbc4036cd3bab6b0edcaccbc95286379ef51f12b | [
"MIT"
] | 3 | 2015-03-28T02:51:58.000Z | 2018-11-08T16:49:53.000Z | include/game/skirmish/gui/mapeditortoolbar.hpp | namelessvoid/qrwar | bbc4036cd3bab6b0edcaccbc95286379ef51f12b | [
"MIT"
] | 39 | 2015-05-18T08:29:16.000Z | 2020-07-18T21:17:44.000Z | include/game/skirmish/gui/mapeditortoolbar.hpp | namelessvoid/qrwar | bbc4036cd3bab6b0edcaccbc95286379ef51f12b | [
"MIT"
] | null | null | null | #ifndef QRW_MAPEDITORTOOLBAR_HPP
#define QRW_MAPEDITORTOOLBAR_HPP
#include "gui/ng/tabwidget.hpp"
#include "engine/terraintypes.hpp"
#include "game/skirmish/structure.hpp"
namespace namelessgui
{
class Window;
class LineInput;
}
namespace qrw
{
class MapEditorToolBar : public namelessgui::TabWidget
{
public:
MapEditorToolBar(unsigned int initialBoardWidth, unsigned int initialBoardHeight);
~MapEditorToolBar() override = default;
namelessgui::Signal<const std::string> signalSaveClicked;
namelessgui::Signal<const std::string> signalLoadClicked;
namelessgui::Signal<unsigned int> signalBoardWidthChanged;
namelessgui::Signal<unsigned int> signalBoardHeightChanged;
namelessgui::Signal<TERRAINTYPES> signalTerrainTypeClicked;
namelessgui::Signal<> signalEraseTerrainClicked;
namelessgui::Signal<Structure::Type> signalStructureClicked;
namelessgui::Signal<> signalEraseStructureClicked;
namelessgui::Signal<unsigned int> signalDeploymentZoneClicked;
namelessgui::Signal<> signalEraseDeploymentZoneClicked;
private:
namelessgui::Window* createConfigToolsWindow(unsigned int initialBoardWidth, unsigned int initialBoardHeight);
namelessgui::Window* createTerrainToolsWindow();
namelessgui::Window* createStructureToolsWindow();
namelessgui::Window* createDeploymentZoneToolsWindow();
namelessgui::LineInput* mapNameInput_;
const sf::Vector2f BUTTON_SIZE = sf::Vector2f(140.0f, 50.0f);
const float BUTTON_Y_OFFSET = 45;
};
} // namespace qrw
#endif //QRW_MAPEDITORTOOLBAR_HPP
| 27.944444 | 111 | 0.817097 | namelessvoid |
dc41fd851fb3d9a94fbc9c94d5b0b1a240e89e5c | 1,075 | hpp | C++ | include/tone_mapping.hpp | ecarpita93/HPC_projet_1 | a2c00e056c03227711c43cf2ad23d75c6afbe698 | [
"Xnet",
"X11"
] | null | null | null | include/tone_mapping.hpp | ecarpita93/HPC_projet_1 | a2c00e056c03227711c43cf2ad23d75c6afbe698 | [
"Xnet",
"X11"
] | null | null | null | include/tone_mapping.hpp | ecarpita93/HPC_projet_1 | a2c00e056c03227711c43cf2ad23d75c6afbe698 | [
"Xnet",
"X11"
] | null | null | null | /*
PICCANTE
The hottest HDR imaging library!
http://vcg.isti.cnr.it/piccante
Copyright (C) 2014
Visual Computing Laboratory - ISTI CNR
http://vcg.isti.cnr.it
First author: Francesco Banterle
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef PIC_TONE_MAPPING_HPP
#define PIC_TONE_MAPPING_HPP
#include "tone_mapping/get_all_exposures.hpp"
#include "tone_mapping/exposure_fusion.hpp"
#include "tone_mapping/find_best_exposure.hpp"
#include "tone_mapping/hybrid_tmo.hpp"
#include "tone_mapping/lischinski_tmo.hpp"
#include "tone_mapping/reinhard_tmo.hpp"
#include "tone_mapping/drago_tmo.hpp"
#include "tone_mapping/ward_histogram_tmo.hpp"
#include "tone_mapping/durand_tmo.hpp"
#include "tone_mapping/ferwerda_tmo.hpp"
#include "tone_mapping/schlick_tmo.hpp"
#include "tone_mapping/raman_tmo.hpp"
#include "tone_mapping/tumblin_tmo.hpp"
#include "tone_mapping/ward_global_tmo.hpp"
#endif /* PIC_TONE_MAPPING_HPP */
| 27.564103 | 67 | 0.8 | ecarpita93 |
dc47eda91c7feef53ea3f31437a01afb4b2f2e59 | 3,123 | c++ | C++ | chua/chuaHand.c++ | camilleg/vss | 27f1c8f73f8d7ef2d4e5de077e4b2ed7e4f72803 | [
"MIT"
] | null | null | null | chua/chuaHand.c++ | camilleg/vss | 27f1c8f73f8d7ef2d4e5de077e4b2ed7e4f72803 | [
"MIT"
] | null | null | null | chua/chuaHand.c++ | camilleg/vss | 27f1c8f73f8d7ef2d4e5de077e4b2ed7e4f72803 | [
"MIT"
] | null | null | null | #include "chua.h"
//===========================================================================
// construction
//
chuaHand::chuaHand(chuaAlg * alg):
VHandler( alg )
{
setTypeName("chuaHand");
}
//===========================================================================
// receiveMessage
//
int
chuaHand::receiveMessage(const char * Message)
{
CommandFromMessage(Message);
if (CommandIs("ResetChuaState"))
{
ifNil( resetChuaState() );
// Uncatch();
}
if (CommandIs("SetChuaR"))
{
ifFF(freq, when, setR(freq, when));
ifF(freq, setR(freq));
Uncatch();
}
if (CommandIs("SetChuaR0"))
{
ifFF(freq, when, setR0(freq, when));
ifF(freq, setR0(freq));
Uncatch();
}
if (CommandIs("SetChuaC1"))
{
ifFF(freq, when, setC1(freq, when));
ifF(freq, setC1(freq));
Uncatch();
}
if (CommandIs("SetChuaC2"))
{
ifFF(freq, when, setC2(freq, when));
ifF(freq, setC2(freq));
Uncatch();
}
if (CommandIs("SetChuaL"))
{
ifFF(freq, when, setL(freq, when));
ifF(freq, setL(freq));
Uncatch();
}
if (CommandIs("SetChuaBPH1"))
{
ifFF(freq, when, setBPH1(freq, when));
ifF(freq, setBPH1(freq));
Uncatch();
}
if (CommandIs("SetChuaBPH2"))
{
ifFF(freq, when, setBPH2(freq, when));
ifF(freq, setBPH2(freq));
Uncatch();
}
if (CommandIs("SetChuaBP1"))
{
ifFF(freq, when, setBP1(freq, when));
ifF(freq, setBP1(freq));
Uncatch();
}
if (CommandIs("SetChuaBP2"))
{
ifFF(freq, when, setBP2(freq, when));
ifF(freq, setBP2(freq));
Uncatch();
}
if (CommandIs("SetChuaM0"))
{
ifFF(freq, when, setM0(freq, when));
ifF(freq, setM0(freq));
Uncatch();
}
if (CommandIs("SetChuaM1"))
{
ifFF(freq, when, setM1(freq, when));
ifF(freq, setM1(freq));
Uncatch();
}
if (CommandIs("SetChuaM2"))
{
ifFF(freq, when, setM2(freq, when));
ifF(freq, setM2(freq));
Uncatch();
}
if (CommandIs("SetChuaM3"))
{
ifFF(freq, when, setM3(freq, when));
ifF(freq, setM3(freq));
Uncatch();
}
return VHandler::receiveMessage(Message);
}
void chuaHand::SetAttribute(IParam iParam, float z)
{
if (iParam.FOnlyI())
{
switch (iParam.i)
{
case isetR:
getAlg()->setR(R = z);
break;
case isetR0:
getAlg()->setR0(R0 = z);
break;
case isetC1:
getAlg()->setC1(C1 = z * 1e-7);
break;
case isetC2:
getAlg()->setC2(C2 = z * 1e-7);
break;
case isetL:
getAlg()->setL(L = z);
break;
case isetBPH1:
getAlg()->setBPH1(BPH1 = z);
break;
case isetBPH2:
getAlg()->setBPH2(BPH2 = z);
break;
case isetBP1:
getAlg()->setBP1(BP1 = z);
break;
case isetBP2:
getAlg()->setBP2(BP2 = z);
break;
case isetM0:
getAlg()->setM0(M0 = z * 1e-3);
break;
case isetM1:
getAlg()->setM1(M1 = z * 1e-3);
break;
case isetM2:
getAlg()->setM2(M2 = z * 1e-3);
break;
case isetM3:
getAlg()->setM3(M3 = z * 1e-3);
break;
default:
printf("vss error: chuaHandler got bogus float-index %d.\n", iParam.i);
}
}
else
printf("vss error: chuaHandler got bogus element-of-float-array-index %d.\n", iParam.i);
}
void chuaHand::resetChuaState(void)
{
getAlg()->resetVector();
}
| 17.544944 | 90 | 0.574448 | camilleg |
dc4dd1985196010d42575e37e3742f67d91aa056 | 5,615 | hpp | C++ | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32756G_EVAL/Demonstrations/TouchGFX/Gui/gui/include/gui/common/CollapsibleMenu.hpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32756G_EVAL/Demonstrations/TouchGFX/Gui/gui/include/gui/common/CollapsibleMenu.hpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32756G_EVAL/Demonstrations/TouchGFX/Gui/gui/include/gui/common/CollapsibleMenu.hpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | /**
******************************************************************************
* This file is part of the TouchGFX 4.10.0 distribution.
*
* @attention
*
* Copyright (c) 2018 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
#ifndef COLLAPSIBLE_MENU_HPP
#define COLLAPSIBLE_MENU_HPP
#include <touchgfx/widgets/Image.hpp>
#include <touchgfx/containers/ListLayout.hpp>
#include <touchgfx/widgets/Button.hpp>
#include <touchgfx/mixins/MoveAnimator.hpp>
#include <touchgfx/mixins/FadeAnimator.hpp>
using namespace touchgfx;
/**
* @class CollapsibleMenu
*
* This widget is part of the TouchGFX Open Widget Repository.
* https://github.com/draupnergraphics/touchgfx-widgets
*
* A menu that holds a set of elements that is placed on top
* of each other and is faded out. You can activate the menu
* and fade in the selected element and then expand the menu
* so that all elements becomes visible.
*
* @sa CollapsibleMenu
*/
class CollapsibleMenu : public Container
{
public:
enum ExpandDirection
{
LEFT,
RIGHT
};
CollapsibleMenu();
virtual ~CollapsibleMenu();
void addMenuElement(const Bitmap& elementBitmap, const Bitmap& elementPressedBitmap);
void finilizeInitialization();
/**
* @fn void CollapsibleMenu::setElementSpace(uint16_t space);
*
* @brief Sets the size of the space between the menu elements.
*
* @param space The size of the space between the menu elements (in pixels).
*/
void setElementSpace(uint16_t space);
/**
* @fn void CollapsibleMenu::setExpandDirection(ExpandDirection direction);
*
* @brief Sets expand direction.
*
* @param direction The direction.
*/
void setExpandDirection(ExpandDirection direction);
/**
* @fn void CollapsibleMenu::collapseMenu();
*
* @brief Collapses the menu.
*/
void collapseMenu();
/**
* @fn void CollapsibleMenu::expandMenu();
*
* @brief Expands the menu.
*/
void expandMenu();
/**
* @fn void CollapsibleMenu::setTimeout(int newTimeout);
*
* @brief Sets a timeout for automatic collapse.
*
* @param newTimeout The new timeout.
*
* @see collapseMenu
*/
void setTimeout(int newTimeout);
/**
* @fn void CollapsibleMenu::fadeIn(int duration = 14);
*
* @brief Fade in the selected item.
*
* @param duration (Optional) the duration.
*/
void fadeIn(int duration = 14);
/**
* @fn void CollapsibleMenu::fadeInAndExpand(int duration = 14);
*
* @brief Fade in the selected item and expand.
*
* @param duration (Optional) the duration.
*/
void fadeInAndExpand(int duration = 14);
/**
* @fn void CollapsibleMenu::fadeOut(int duration = 14);
*
* @brief Fade out the selected item.
*
* @param duration (Optional) the duration.
*/
void fadeOut(int duration = 14);
/**
* @fn bool CollapsibleMenu::isFadedOut();
*
* @brief Query if the selected item is faded out.
*
* @return true if faded out, false if not.
*/
bool isFadedOut();
/**
* @fn uint8_t CollapsibleMenu::getSelectedElementIndex();
*
* @brief Gets selected element index.
*
* @return The selected element index.
*/
uint8_t getSelectedElementIndex();
/**
* @fn void CollapsibleMenu::setStateChangedCallback(touchgfx::GenericCallback<const CollapsibleMenu&, const bool>& callback)
*
* @brief Associates an action to be performed when the menu changes expanded/collapsed state.
*
* @param callback The callback to be executed. The callback will be given a reference to the
* CollapsibleMenu and a bool that state if the menu is expanded.
*
* @see GenericCallback
*/
void setStateChangedCallback(touchgfx::GenericCallback<const CollapsibleMenu&, const bool>& callback)
{
stateChangedAction = &callback;
}
private:
static const uint8_t MAX_NUMBER_OF_ELEMENTS = 10;
enum AnimationState
{
ANIMATE_TO_EXPANDED,
ANIMATE_TO_COLLAPSED,
FADE_OUT,
FADE_IN,
FADE_IN_AND_EXPAND,
NO_ANIMATION
};
AnimationState currentAnimationState;
uint8_t size;
bool isExpanded;
uint16_t elementSpace;
ExpandDirection expandDirection;
bool fadedOut;
int timeout;
int timeoutCounter;
FadeAnimator<MoveAnimator<Button> > menuElements[MAX_NUMBER_OF_ELEMENTS];
uint8_t selectedElementIndex;
Callback<CollapsibleMenu, const AbstractButton&> onButtonPressed;
Callback<CollapsibleMenu, const MoveAnimator<Button>& > menuElementMoveAnimationEndedCallback;
Callback<CollapsibleMenu, const FadeAnimator<MoveAnimator<Button> >& > menuElementFadeAnimationEndedCallback;
GenericCallback<const CollapsibleMenu&, const bool>* stateChangedAction;
void buttonPressedHandler(const AbstractButton& button);
void menuElementMoveAnimationEndedHandler(const MoveAnimator<Button>& element);
void menuElementFadeAnimationEndedHandler(const FadeAnimator<MoveAnimator<Button> >& element);
bool anyFadeAnimationRunning();
virtual void handleTickEvent();
};
#endif /* COLLAPSIBLE_MENU_HPP */
| 27.52451 | 129 | 0.654853 | ramkumarkoppu |
dc4ee9c7f164aac61a34a7a623e1831aa3b92000 | 3,120 | cpp | C++ | Source/JavaScriptCore/runtime/ProxyRevoke.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | null | null | null | Source/JavaScriptCore/runtime/ProxyRevoke.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | 9 | 2020-04-18T18:47:18.000Z | 2020-04-18T18:52:41.000Z | Source/JavaScriptCore/runtime/ProxyRevoke.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2016 Apple 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:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "ProxyRevoke.h"
#include "JSCInlines.h"
#include "ProxyObject.h"
namespace JSC {
STATIC_ASSERT_IS_TRIVIALLY_DESTRUCTIBLE(ProxyRevoke);
const ClassInfo ProxyRevoke::s_info = { "ProxyRevoke", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(ProxyRevoke) };
ProxyRevoke* ProxyRevoke::create(VM& vm, Structure* structure, ProxyObject* proxy)
{
ProxyRevoke* revoke = new (NotNull, allocateCell<ProxyRevoke>(vm.heap)) ProxyRevoke(vm, structure);
revoke->finishCreation(vm, "revoke", proxy);
return revoke;
}
ProxyRevoke::ProxyRevoke(VM& vm, Structure* structure)
: Base(vm, structure)
{
}
void ProxyRevoke::finishCreation(VM& vm, const char* name, ProxyObject* proxy)
{
Base::finishCreation(vm, String(name));
m_proxy.set(vm, this, proxy);
putDirect(vm, vm.propertyNames->length, jsNumber(0), ReadOnly | DontDelete | DontEnum);
}
static EncodedJSValue JSC_HOST_CALL performProxyRevoke(ExecState* exec)
{
ProxyRevoke* proxyRevoke = jsCast<ProxyRevoke*>(exec->jsCallee());
JSValue proxyValue = proxyRevoke->proxy();
if (proxyValue.isNull())
return JSValue::encode(jsUndefined());
ProxyObject* proxy = jsCast<ProxyObject*>(proxyValue);
VM& vm = exec->vm();
proxy->revoke(vm);
proxyRevoke->setProxyToNull(vm);
return JSValue::encode(jsUndefined());
}
CallType ProxyRevoke::getCallData(JSCell*, CallData& callData)
{
callData.native.function = performProxyRevoke;
return CallType::Host;
}
void ProxyRevoke::visitChildren(JSCell* cell, SlotVisitor& visitor)
{
ProxyRevoke* thisObject = jsCast<ProxyRevoke*>(cell);
ASSERT_GC_OBJECT_INHERITS(thisObject, info());
Base::visitChildren(thisObject, visitor);
visitor.append(thisObject->m_proxy);
}
} // namespace JSC
| 35.454545 | 123 | 0.741346 | ijsf |
dc51289cbdcf103f28b73f64e112d42f76a95bad | 3,521 | cc | C++ | sstmac/software/launch/hostname_task_mapper.cc | jpkenny/sst-macro | bcc1f43034281885104962586d8b104df84b58bd | [
"BSD-Source-Code"
] | 20 | 2017-01-26T09:28:23.000Z | 2022-01-17T11:31:55.000Z | sstmac/software/launch/hostname_task_mapper.cc | jpkenny/sst-macro | bcc1f43034281885104962586d8b104df84b58bd | [
"BSD-Source-Code"
] | 542 | 2016-03-29T22:50:58.000Z | 2022-03-22T20:14:08.000Z | sstmac/software/launch/hostname_task_mapper.cc | jpkenny/sst-macro | bcc1f43034281885104962586d8b104df84b58bd | [
"BSD-Source-Code"
] | 36 | 2016-03-10T21:33:54.000Z | 2021-12-01T07:44:12.000Z | /**
Copyright 2009-2021 National Technology and Engineering Solutions of Sandia,
LLC (NTESS). Under the terms of Contract DE-NA-0003525, the U.S. Government
retains certain rights in this software.
Sandia National Laboratories is a multimission laboratory managed and operated
by National Technology and Engineering Solutions of Sandia, LLC., a wholly
owned subsidiary of Honeywell International, Inc., for the U.S. Department of
Energy's National Nuclear Security Administration under contract DE-NA0003525.
Copyright (c) 2009-2021, NTESS
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 copyright holder nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Questions? Contact sst-macro-help@sandia.gov
*/
#include <fstream>
#include <sstream>
#include <sstmac/backends/common/parallel_runtime.h>
#include <sstmac/software/launch/hostname_task_mapper.h>
#include <sstmac/software/launch/hostname_allocation.h>
#include <sstmac/software/process/operating_system.h>
#include <sstmac/common/runtime.h>
#include <sprockit/fileio.h>
#include <sprockit/errors.h>
#include <sprockit/sim_parameters.h>
#include <sprockit/keyword_registration.h>
RegisterKeywords(
{ "hostmap", "a line-by-line list of hostnames to map each task to" },
);
namespace sstmac {
namespace sw {
HostnameTaskMapper::HostnameTaskMapper(SST::Params& params) :
TaskMapper(params)
{
listfile_ = params.find<std::string>("hostmap");
}
void
HostnameTaskMapper::mapRanks(
const ordered_node_set& /*nodes*/,
int /*ppn*/,
std::vector<NodeId> &result,
int nproc)
{
int nrank = nproc;
result.resize(nrank);
std::ifstream nodelist(listfile_);
std::stringstream sstr;
for (int i = 0; i < nrank; i++) {
std::string hostname;
nodelist >> hostname;
sstr << hostname << "\n";
NodeId nid;
if (!topology_) {
spkt_throw_printf(sprockit::ValueError, "hostname_task_mapper: null topology");
}
nid = topology_->nodeNameToId(hostname);
debug_printf(sprockit::dbg::indexing,
"hostname_task_mapper: rank %d is on hostname %s at nid=%d",
i, hostname.c_str(), int(nid));
result[i] = nid;
}
}
}
}
| 32.906542 | 85 | 0.753763 | jpkenny |
dc5261caa2a7fd200bbd53025794ad1ab7d34039 | 4,916 | cc | C++ | src/OpenVolumeMesh/Mesh/TetrahedralMeshIterators.cc | Rupemgera/VtkMeshFrame | abcaf84639d186756c06de73f1d6b4664566da14 | [
"MIT"
] | null | null | null | src/OpenVolumeMesh/Mesh/TetrahedralMeshIterators.cc | Rupemgera/VtkMeshFrame | abcaf84639d186756c06de73f1d6b4664566da14 | [
"MIT"
] | null | null | null | src/OpenVolumeMesh/Mesh/TetrahedralMeshIterators.cc | Rupemgera/VtkMeshFrame | abcaf84639d186756c06de73f1d6b4664566da14 | [
"MIT"
] | null | null | null | /*===========================================================================*\
* *
* OpenVolumeMesh *
* Copyright (C) 2011 by Computer Graphics Group, RWTH Aachen *
* www.openvolumemesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenVolumeMesh. *
* *
* OpenVolumeMesh is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenVolumeMesh is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU LesserGeneral Public *
* License along with OpenVolumeMesh. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
#include <set>
#include "TetrahedralMeshIterators.hh"
#include "TetrahedralMeshTopologyKernel.hh"
#include "../Core/Iterators.hh"
namespace OpenVolumeMesh {
//================================================================================================
// TetVertexIter
//================================================================================================
TetVertexIter::TetVertexIter(const CellHandle& _ref_h,
const TetrahedralMeshTopologyKernel* _mesh, int _max_laps) :
BaseIter(_mesh, _ref_h, _max_laps) {
assert(_ref_h.is_valid());
TetrahedralMeshTopologyKernel::Cell cell = _mesh->cell(_ref_h);
assert(cell.halffaces().size() == 4);
// Get first half-face
HalfFaceHandle curHF = *cell.halffaces().begin();
assert(curHF.is_valid());
// Get first half-edge
assert(_mesh->halfface(curHF).halfedges().size() == 3);
HalfEdgeHandle curHE = *_mesh->halfface(curHF).halfedges().begin();
assert(curHE.is_valid());
vertices_.push_back(_mesh->halfedge(curHE).to_vertex());
curHE = _mesh->next_halfedge_in_halfface(curHE, curHF);
vertices_.push_back(_mesh->halfedge(curHE).to_vertex());
curHE = _mesh->next_halfedge_in_halfface(curHE, curHF);
vertices_.push_back(_mesh->halfedge(curHE).to_vertex());
curHF = _mesh->adjacent_halfface_in_cell(curHF, curHE);
curHE = _mesh->opposite_halfedge_handle(curHE);
curHE = _mesh->next_halfedge_in_halfface(curHE, curHF);
vertices_.push_back(_mesh->halfedge(curHE).to_vertex());
cur_index_ = 0;
BaseIter::valid(vertices_.size() > 0);
if(BaseIter::valid()) {
BaseIter::cur_handle(vertices_[cur_index_]);
}
}
TetVertexIter& TetVertexIter::operator--() {
if (cur_index_ == 0) {
cur_index_ = vertices_.size() - 1;
--lap_;
if (lap_ < 0)
BaseIter::valid(false);
} else {
--cur_index_;
}
BaseIter::cur_handle(vertices_[cur_index_]);
return *this;
}
TetVertexIter& TetVertexIter::operator++() {
++cur_index_;
if(cur_index_ == vertices_.size()) {
cur_index_ = 0;
++lap_;
if (lap_ >= max_laps_)
BaseIter::valid(false);
}
BaseIter::cur_handle(vertices_[cur_index_]);
return *this;
}
} // Namespace OpenVolumeMesh
| 39.645161 | 98 | 0.487185 | Rupemgera |
dc56e9942a39babd11a255c4802fd9ce4388af59 | 744 | cpp | C++ | 10339 Watching Watches.cpp | zihadboss/UVA-Solutions | 020fdcb09da79dc0a0411b04026ce3617c09cd27 | [
"Apache-2.0"
] | 86 | 2016-01-20T11:36:50.000Z | 2022-03-06T19:43:14.000Z | 10339 Watching Watches.cpp | Mehedishihab/UVA-Solutions | 474fe3d9d9ba574b97fd40ca5abb22ada95654a1 | [
"Apache-2.0"
] | null | null | null | 10339 Watching Watches.cpp | Mehedishihab/UVA-Solutions | 474fe3d9d9ba574b97fd40ca5abb22ada95654a1 | [
"Apache-2.0"
] | 113 | 2015-12-04T06:40:57.000Z | 2022-02-11T02:14:28.000Z | #include <cstdio>
const unsigned int FullDaySeconds = 86400;
const unsigned int HalfDaySeconds = 43200;
const unsigned int SecondsInMin = 60;
const unsigned int SecondsInHour = 3600;
const unsigned int HalfDayMin = HalfDaySeconds / SecondsInMin;
int main()
{
int k, m;
while (scanf("%d%d", &k, &m) == 2)
{
unsigned int diff = k > m ? k - m : m - k;
// The 30 seconds makes it round automatically
unsigned int numSeconds = (HalfDaySeconds * (FullDaySeconds - k) / diff) % 43200 + 30;
unsigned int hour = numSeconds / SecondsInHour % 12;
unsigned int min = numSeconds / SecondsInMin % 60;
printf("%d %d %02d:%02d\n", k, m, hour == 0 ? 12 : hour, min);
}
}
| 28.615385 | 94 | 0.608871 | zihadboss |
dc58114319770ef4ff7ceeea772ad9ecac01e37a | 72 | cpp | C++ | tests/Issue223.cpp | galorojo/cppinsights | 52ecab4ddd8e36fb99893551cf0fb8b5d58589f2 | [
"MIT"
] | 1,853 | 2018-05-13T21:49:17.000Z | 2022-03-30T10:34:45.000Z | tests/Issue223.cpp | tiandaoafei/cppinsights | af78ac299121354101a5e506dafccaac95d27a77 | [
"MIT"
] | 398 | 2018-05-15T14:48:51.000Z | 2022-03-24T12:14:33.000Z | tests/Issue223.cpp | SammyEnigma/cppinsights | c984b8e68139bbcc244c094fd2463eeced8fd997 | [
"MIT"
] | 104 | 2018-05-15T04:00:59.000Z | 2022-03-17T02:04:15.000Z | #include <cstdio>
int main()
{
float f = (float)(3.0);
return f;
}
| 9 | 25 | 0.555556 | galorojo |
dc58bf4b426ca4640685fbcc690bb6970943c3db | 3,922 | cpp | C++ | Userland/Libraries/LibWeb/WebAssembly/WebAssemblyTableConstructor.cpp | dykatz/serenity | 3ad6d87a4518732c8e181c0cf1edfab35716b92f | [
"BSD-2-Clause"
] | null | null | null | Userland/Libraries/LibWeb/WebAssembly/WebAssemblyTableConstructor.cpp | dykatz/serenity | 3ad6d87a4518732c8e181c0cf1edfab35716b92f | [
"BSD-2-Clause"
] | 1 | 2020-06-21T23:22:11.000Z | 2020-06-21T23:22:11.000Z | Userland/Libraries/LibWeb/WebAssembly/WebAssemblyTableConstructor.cpp | dykatz/serenity | 3ad6d87a4518732c8e181c0cf1edfab35716b92f | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibJS/Runtime/GlobalObject.h>
#include <LibJS/Runtime/TypedArray.h>
#include <LibWeb/Bindings/WindowObject.h>
#include <LibWeb/WebAssembly/WebAssemblyObject.h>
#include <LibWeb/WebAssembly/WebAssemblyTableConstructor.h>
#include <LibWeb/WebAssembly/WebAssemblyTableObject.h>
#include <LibWeb/WebAssembly/WebAssemblyTablePrototype.h>
namespace Web::Bindings {
WebAssemblyTableConstructor::WebAssemblyTableConstructor(JS::GlobalObject& global_object)
: NativeFunction(*global_object.function_prototype())
{
}
WebAssemblyTableConstructor::~WebAssemblyTableConstructor()
{
}
JS::Value WebAssemblyTableConstructor::call()
{
vm().throw_exception<JS::TypeError>(global_object(), JS::ErrorType::ConstructorWithoutNew, "WebAssembly.Table");
return {};
}
JS::Value WebAssemblyTableConstructor::construct(FunctionObject&)
{
auto& vm = this->vm();
auto& global_object = this->global_object();
auto descriptor = TRY_OR_DISCARD(vm.argument(0).to_object(global_object));
auto element_value = TRY_OR_DISCARD(descriptor->get("element"));
if (!element_value.is_string()) {
vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::InvalidHint, element_value.to_string_without_side_effects());
return {};
}
auto& element = element_value.as_string().string();
Optional<Wasm::ValueType> reference_type;
if (element == "anyfunc"sv)
reference_type = Wasm::ValueType(Wasm::ValueType::FunctionReference);
else if (element == "externref"sv)
reference_type = Wasm::ValueType(Wasm::ValueType::ExternReference);
if (!reference_type.has_value()) {
vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::InvalidHint, element);
return {};
}
auto initial_value = TRY_OR_DISCARD(descriptor->get("initial"));
auto maximum_value = TRY_OR_DISCARD(descriptor->get("maximum"));
auto initial = initial_value.to_u32(global_object);
if (vm.exception())
return {};
Optional<u32> maximum;
if (!maximum_value.is_undefined()) {
maximum = maximum_value.to_u32(global_object);
if (vm.exception())
return {};
}
if (maximum.has_value() && maximum.value() < initial) {
vm.throw_exception<JS::RangeError>(global_object, "maximum should be larger than or equal to initial");
return {};
}
auto value_value = TRY_OR_DISCARD(descriptor->get("value"));
auto reference_value = [&]() -> Optional<Wasm::Value> {
if (value_value.is_undefined())
return Wasm::Value(*reference_type, 0ull);
return to_webassembly_value(value_value, *reference_type, global_object);
}();
if (!reference_value.has_value())
return {};
auto& reference = reference_value->value().get<Wasm::Reference>();
auto address = WebAssemblyObject::s_abstract_machine.store().allocate(Wasm::TableType { *reference_type, Wasm::Limits { initial, maximum } });
if (!address.has_value()) {
vm.throw_exception<JS::TypeError>(global_object, "Wasm Table allocation failed");
return {};
}
auto& table = *WebAssemblyObject::s_abstract_machine.store().get(*address);
for (auto& element : table.elements())
element = reference;
return vm.heap().allocate<WebAssemblyTableObject>(global_object, global_object, *address);
}
void WebAssemblyTableConstructor::initialize(JS::GlobalObject& global_object)
{
auto& vm = this->vm();
auto& window = static_cast<WindowObject&>(global_object);
NativeFunction::initialize(global_object);
define_direct_property(vm.names.prototype, &window.ensure_web_prototype<WebAssemblyTablePrototype>("WebAssemblyTablePrototype"), 0);
define_direct_property(vm.names.length, JS::Value(1), JS::Attribute::Configurable);
}
}
| 34.707965 | 146 | 0.708312 | dykatz |
dc594676001d1b5a27d58df6d29f5079a28d674a | 6,145 | cc | C++ | mediapipe/calculators/tensor/image_to_tensor_utils.cc | Ensteinjun/mediapipe | 38be2ec58f2a1687f4ffca287094c7bbd7791f58 | [
"Apache-2.0"
] | 2 | 2021-12-02T02:14:31.000Z | 2021-12-02T02:16:24.000Z | mediapipe/calculators/tensor/image_to_tensor_utils.cc | Ensteinjun/mediapipe | 38be2ec58f2a1687f4ffca287094c7bbd7791f58 | [
"Apache-2.0"
] | null | null | null | mediapipe/calculators/tensor/image_to_tensor_utils.cc | Ensteinjun/mediapipe | 38be2ec58f2a1687f4ffca287094c7bbd7791f58 | [
"Apache-2.0"
] | 3 | 2021-01-19T14:40:59.000Z | 2021-06-09T13:43:49.000Z | // Copyright 2020 The MediaPipe Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "mediapipe/calculators/tensor/image_to_tensor_utils.h"
#include <array>
#include "absl/types/optional.h"
#include "mediapipe/framework/port/ret_check.h"
#include "mediapipe/framework/port/statusor.h"
namespace mediapipe {
RotatedRect GetRoi(int input_width, int input_height,
absl::optional<mediapipe::NormalizedRect> norm_rect) {
if (norm_rect) {
return {/*center_x=*/norm_rect->x_center() * input_width,
/*center_y =*/norm_rect->y_center() * input_height,
/*width =*/norm_rect->width() * input_width,
/*height =*/norm_rect->height() * input_height,
/*rotation =*/norm_rect->rotation()};
}
return {/*center_x=*/0.5f * input_width,
/*center_y =*/0.5f * input_height,
/*width =*/static_cast<float>(input_width),
/*height =*/static_cast<float>(input_height),
/*rotation =*/0};
}
mediapipe::StatusOr<std::array<float, 4>> PadRoi(int input_tensor_width,
int input_tensor_height,
bool keep_aspect_ratio,
RotatedRect* roi) {
if (!keep_aspect_ratio) {
return std::array<float, 4>{0.0f, 0.0f, 0.0f, 0.0f};
}
RET_CHECK(input_tensor_width > 0 && input_tensor_height > 0)
<< "Input tensor width and height must be > 0.";
const float tensor_aspect_ratio =
static_cast<float>(input_tensor_height) / input_tensor_width;
RET_CHECK(roi->width > 0 && roi->height > 0)
<< "ROI width and height must be > 0.";
const float roi_aspect_ratio = roi->height / roi->width;
float vertical_padding = 0.0f;
float horizontal_padding = 0.0f;
float new_width;
float new_height;
if (tensor_aspect_ratio > roi_aspect_ratio) {
new_width = roi->width;
new_height = roi->width * tensor_aspect_ratio;
vertical_padding = (1.0f - roi_aspect_ratio / tensor_aspect_ratio) / 2.0f;
} else {
new_width = roi->height / tensor_aspect_ratio;
new_height = roi->height;
horizontal_padding = (1.0f - tensor_aspect_ratio / roi_aspect_ratio) / 2.0f;
}
roi->width = new_width;
roi->height = new_height;
return std::array<float, 4>{horizontal_padding, vertical_padding,
horizontal_padding, vertical_padding};
}
mediapipe::StatusOr<ValueTransformation> GetValueRangeTransformation(
float from_range_min, float from_range_max, float to_range_min,
float to_range_max) {
RET_CHECK_LT(from_range_min, from_range_max)
<< "Invalid FROM range: min >= max.";
RET_CHECK_LT(to_range_min, to_range_max) << "Invalid TO range: min >= max.";
const float scale =
(to_range_max - to_range_min) / (from_range_max - from_range_min);
const float offset = to_range_min - from_range_min * scale;
return ValueTransformation{scale, offset};
}
void GetRotatedSubRectToRectTransformMatrix(const RotatedRect& sub_rect,
int rect_width, int rect_height,
bool flip_horizontaly,
std::array<float, 16>* matrix_ptr) {
std::array<float, 16>& matrix = *matrix_ptr;
// The resulting matrix is multiplication of below commented out matrices:
// post_scale_matrix
// * translate_matrix
// * rotate_matrix
// * flip_matrix
// * scale_matrix
// * initial_translate_matrix
// Matrix to convert X,Y to [-0.5, 0.5] range "initial_translate_matrix"
// { 1.0f, 0.0f, 0.0f, -0.5f}
// { 0.0f, 1.0f, 0.0f, -0.5f}
// { 0.0f, 0.0f, 1.0f, 0.0f}
// { 0.0f, 0.0f, 0.0f, 1.0f}
const float a = sub_rect.width;
const float b = sub_rect.height;
// Matrix to scale X,Y,Z to sub rect "scale_matrix"
// Z has the same scale as X.
// { a, 0.0f, 0.0f, 0.0f}
// {0.0f, b, 0.0f, 0.0f}
// {0.0f, 0.0f, a, 0.0f}
// {0.0f, 0.0f, 0.0f, 1.0f}
const float flip = flip_horizontaly ? -1 : 1;
// Matrix for optional horizontal flip around middle of output image.
// { fl , 0.0f, 0.0f, 0.0f}
// { 0.0f, 1.0f, 0.0f, 0.0f}
// { 0.0f, 0.0f, 1.0f, 0.0f}
// { 0.0f, 0.0f, 0.0f, 1.0f}
const float c = std::cos(sub_rect.rotation);
const float d = std::sin(sub_rect.rotation);
// Matrix to do rotation around Z axis "rotate_matrix"
// { c, -d, 0.0f, 0.0f}
// { d, c, 0.0f, 0.0f}
// { 0.0f, 0.0f, 1.0f, 0.0f}
// { 0.0f, 0.0f, 0.0f, 1.0f}
const float e = sub_rect.center_x;
const float f = sub_rect.center_y;
// Matrix to do X,Y translation of sub rect within parent rect
// "translate_matrix"
// {1.0f, 0.0f, 0.0f, e }
// {0.0f, 1.0f, 0.0f, f }
// {0.0f, 0.0f, 1.0f, 0.0f}
// {0.0f, 0.0f, 0.0f, 1.0f}
const float g = 1.0f / rect_width;
const float h = 1.0f / rect_height;
// Matrix to scale X,Y,Z to [0.0, 1.0] range "post_scale_matrix"
// {g, 0.0f, 0.0f, 0.0f}
// {0.0f, h, 0.0f, 0.0f}
// {0.0f, 0.0f, g, 0.0f}
// {0.0f, 0.0f, 0.0f, 1.0f}
// row 1
matrix[0] = a * c * flip * g;
matrix[1] = -b * d * g;
matrix[2] = 0.0f;
matrix[3] = (-0.5f * a * c * flip + 0.5f * b * d + e) * g;
// row 2
matrix[4] = a * d * flip * h;
matrix[5] = b * c * h;
matrix[6] = 0.0f;
matrix[7] = (-0.5f * b * c - 0.5f * a * d * flip + f) * h;
// row 3
matrix[8] = 0.0f;
matrix[9] = 0.0f;
matrix[10] = a * g;
matrix[11] = 0.0f;
// row 4
matrix[12] = 0.0f;
matrix[13] = 0.0f;
matrix[14] = 0.0f;
matrix[15] = 1.0f;
}
} // namespace mediapipe
| 34.717514 | 80 | 0.603417 | Ensteinjun |
dc5b279e90390b6256d859ceabe114a2e22cfbb3 | 4,562 | cpp | C++ | src/libtrio/tabix_streamer.cpp | StephenTanner/gvcftools | 5702a67fe5e744065b5462760b6c0bba38d8d9ea | [
"BSL-1.0"
] | 26 | 2015-11-30T18:53:11.000Z | 2021-11-12T07:48:37.000Z | src/libtrio/tabix_streamer.cpp | StephenTanner/gvcftools | 5702a67fe5e744065b5462760b6c0bba38d8d9ea | [
"BSL-1.0"
] | 5 | 2015-08-06T18:32:55.000Z | 2020-03-08T18:13:22.000Z | src/libtrio/tabix_streamer.cpp | ctsa/gvcftools | 7e854392c94c63410a846d29a97b95a6f1435576 | [
"BSL-1.0"
] | 8 | 2015-07-20T09:53:07.000Z | 2018-06-10T09:55:31.000Z | // -*- mode: c++; indent-tabs-mode: nil; -*-
//
// Copyright (c) 2009-2012 Illumina, Inc.
//
// 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.
//
//
/// \file
/// \author Chris Saunders
///
#include "tabix_streamer.hh"
#include "tabix_util.hh"
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <set>
#include <string>
namespace {
std::ostream& log_os(std::cerr);
}
tabix_header_streamer::
tabix_header_streamer(const char* filename)
: _is_record_set(false)
, _is_stream_end(false)
, _tfp(NULL)
, _titer(NULL)
, _linebuf(NULL)
{
if (NULL == filename) {
throw blt_exception("vcf filename is null ptr");
}
if ('\0' == *filename) {
throw blt_exception("vcf filename is empty string");
}
_tfp = ti_open(filename, 0);
if (NULL == _tfp) {
log_os << "ERROR: Failed to open VCF file: '" << filename << "'\n";
exit(EXIT_FAILURE);
}
_titer = ti_query(_tfp, 0, 0, 0);
}
tabix_header_streamer::
~tabix_header_streamer() {
if (NULL != _titer) ti_iter_destroy(_titer);
if (NULL != _tfp) ti_close(_tfp);
}
bool
tabix_header_streamer::
next() {
if (_is_stream_end || (NULL==_tfp) || (NULL==_titer)) return false;
int len;
_linebuf = (char*) ti_read(_tfp, _titer, &len);
if (NULL == _linebuf) {
_is_stream_end=true;
} else {
if ((strlen(_linebuf)<1) || (_linebuf[0] != '#')) {
_is_stream_end=true;
}
}
_is_record_set=(! _is_stream_end);
return _is_record_set;
}
tabix_streamer::
tabix_streamer(const char* filename,
const char* region)
: _is_record_set(false)
, _is_stream_end(false)
, _record_no(0)
, _stream_name(filename)
, _tfp(NULL)
, _titer(NULL)
, _linebuf(NULL)
{
if (NULL == filename) {
throw blt_exception("vcf filename is null ptr");
}
if ('\0' == *filename) {
throw blt_exception("vcf filename is empty string");
}
_tfp = ti_open(filename, 0);
if (NULL == _tfp) {
log_os << "ERROR: Failed to open VCF file: '" << filename << "'\n";
exit(EXIT_FAILURE);
}
// read from a specific region:
if (ti_lazy_index_load(_tfp) < 0) {
log_os << "ERROR: Failed to load index for vcf file: '" << filename << "'\n";
exit(EXIT_FAILURE);
}
if (NULL == region) {
// read the whole VCF file:
_titer = ti_query(_tfp, 0, 0, 0);
return;
}
enforce_tabix_index(filename);
int tid,beg,end;
if (ti_parse_region(_tfp->idx, region, &tid, &beg, &end) == 0) {
_titer = ti_queryi(_tfp, tid, beg, end);
} else {
_is_stream_end=true;
}
}
tabix_streamer::
~tabix_streamer() {
if (NULL != _titer) ti_iter_destroy(_titer);
if (NULL != _tfp) ti_close(_tfp);
}
bool
tabix_streamer::
next() {
if (_is_stream_end || (NULL==_tfp) || (NULL==_titer)) return false;
int len;
_linebuf = (char*) ti_read(_tfp, _titer, &len);
_is_stream_end=(NULL == _linebuf);
_is_record_set=(! _is_stream_end);
if (_is_record_set) _record_no++;
return _is_record_set;
}
void
tabix_streamer::
report_state(std::ostream& os) const {
const char* line(getline());
os << "\tvcf_stream_label: " << name() << "\n";
if (NULL != line) {
os << "\tvcf_stream_record_no: " << record_no() << "\n"
<< "\tvcf_record: '" << line << "'\n";
} else {
os << "\tno vcf record currently set\n";
}
}
| 23.040404 | 85 | 0.62363 | StephenTanner |
dc5baa217b6b6c04b298f8ca44a665c410516f71 | 1,893 | cpp | C++ | OsakaEngine/RPGFactory.cpp | osakahq/OsakaEngine | 47dd0ec5b67a176c552441a25168ecb48b52e14b | [
"Zlib",
"MIT"
] | 2 | 2016-04-04T06:00:28.000Z | 2016-04-18T15:39:38.000Z | OsakaEngine/RPGFactory.cpp | osakahq/OsakaEngine | 47dd0ec5b67a176c552441a25168ecb48b52e14b | [
"Zlib",
"MIT"
] | null | null | null | OsakaEngine/RPGFactory.cpp | osakahq/OsakaEngine | 47dd0ec5b67a176c552441a25168ecb48b52e14b | [
"Zlib",
"MIT"
] | null | null | null | #include "stdafx.h"
#include "GameData.h"
#include "GameDataParams.h"
#include "GameSession.h"
#include "GameSessionManager.h"
#include "RPGApplication.h"
#include "SDLLib.h"
#include "Debug.h"
#include "TextureManager.h"
#include "Factory.h"
#include "Image.h"
#include "FadeInFadeOutEffect.h"
#include "FloatingEffect.h"
#include "FadeInEffect.h"
#include "Square.h"
#include "rpglib_include.h"
#include "RPGFactory.h"
#include "osaka_forward.h"
namespace Osaka{
namespace RPGLib{
RPGFactory::RPGFactory(Debug::Debug* debug, GameData* data, GameDataParams* gdp, Factory* factory){
this->debug = debug;
this->data = data;
this->factory = factory;
this->gamedataparams = gdp;
}
RPGFactory::~RPGFactory(){
raw_renderer = NULL;
debug = NULL;
data = NULL;
factory = NULL;
gamedataparams = NULL;
}
void RPGFactory::Init(){
//Be careful. This function is called BEFORE `app->Init()`
raw_renderer = factory->app->sdl->GetRAWSDLRenderer();
}
Image* RPGFactory::CreateImage(const std::string& id_sprite){
sprite_info& info = factory->texturem->CreateSprite(id_sprite);
return new Image(raw_renderer, info.raw_texture, info.clip);
}
Square* RPGFactory::CreateSquare(int x, int y, int h, int w){
Square* square = new Square(raw_renderer);
square->quad.x = x;
square->quad.y = y;
square->quad.h = h;
square->quad.w = w;
return square;
}
Square* RPGFactory::CreateSquare(){
return new Square(raw_renderer);
}
FadeInFadeOutEffect* RPGFactory::CreateFadeInFadeOutEffect(){
return new FadeInFadeOutEffect(factory->CreateTimer());
}
FloatingEffect* RPGFactory::CreateFloatingEffect(){
return new FloatingEffect(factory->timem);
}
FadeInEffect* RPGFactory::CreateFadeInEffect(){
return new FadeInEffect(factory->CreateTimer());
}
}
} | 28.681818 | 102 | 0.684099 | osakahq |
dc622070c2647bf6b946adf8810e8776cca90a3e | 7,592 | cpp | C++ | core/CU/CodeDiscovery.cpp | RL-Bin/RLBin | 621305a1c8149728e8b5d6ded75dbd81e00d7037 | [
"BSD-3-Clause"
] | null | null | null | core/CU/CodeDiscovery.cpp | RL-Bin/RLBin | 621305a1c8149728e8b5d6ded75dbd81e00d7037 | [
"BSD-3-Clause"
] | null | null | null | core/CU/CodeDiscovery.cpp | RL-Bin/RLBin | 621305a1c8149728e8b5d6ded75dbd81e00d7037 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file CodeDiscovery.cpp
* @brief Defines the functions used to handle discovery of new code.
*/
#include "..\include\CU\CU.h"
#include "..\include\TMU\TMU.h"
#include "..\include\IMU\IMU.h"
#include "..\include\SubUnits\Modules\Modules.h"
#include "..\include\DataStructs\DisTable\DisTable.h"
#include "..\include\SubUnits\Disassembler\Disassembler.h"
void CU::HandleNewDC(ADDRESS _address)
{
// Add next to pretype 2
RLBinUtils::RLBin_Debug("STATUS : DC1", __FILENAME__, __LINE__);
// Check Call Dest Discovered
RLBinUtils::RLBin_Debug("STATUS : DC2", __FILENAME__, __LINE__);
ADDRESS call_dest;
Disassembler::Get()->GetDirectCTIDest(_address, &call_dest);
if(DisTable::Get()->GetEntry(call_dest) == LOC_UNDISCOVERD)
{
// Check Call Dest Middle of function
RLBinUtils::RLBin_Debug("STATUS : DC3", __FILENAME__, __LINE__);
// Register function
RLBinUtils::RLBin_Debug("STATUS : DC4", __FILENAME__, __LINE__);
// Put trap to be discovered
TMU::Get()->InsertTrampoline(call_dest);
RLBinUtils::RLBin_Debug("STATUS : DC51", __FILENAME__, __LINE__);
}
else
{
// Check Call Dest Middle of function
RLBinUtils::RLBin_Debug("STATUS : DC3", __FILENAME__, __LINE__);
// Register function
RLBinUtils::RLBin_Debug("STATUS : DC4", __FILENAME__, __LINE__);
}
return;
}
void CU::HandleNewNC(ADDRESS _address)
{
// Check Next Inst Discovered
RLBinUtils::RLBin_Debug("STATUS : NC1", __FILENAME__, __LINE__);
Inst current;
Disassembler::Get()->GetOneInst(_address, ¤t);
ADDRESS next_inst = _address + current.size;
if(DisTable::Get()->GetEntry(next_inst) == LOC_UNDISCOVERD)
{
// Check Next Inst Middle of function
RLBinUtils::RLBin_Debug("STATUS : NC21", __FILENAME__, __LINE__);
// Register function
RLBinUtils::RLBin_Debug("STATUS : NC32", __FILENAME__, __LINE__);
// Put trap to be discovered
TMU::Get()->InsertTrampoline(next_inst);
RLBinUtils::RLBin_Debug("STATUS : NC41", __FILENAME__, __LINE__);
}
else
{
}
return;
}
void CU::HandleNewDJ(ADDRESS _address)
{
// Target of conditional or unconditional jump
ADDRESS jump_target;
if(Disassembler::Get()->IsInstConditionalJump(_address))
{
Inst current;
Disassembler::Get()->GetOneInst(_address, ¤t);
ADDRESS next_inst = _address + current.size;
ADDRESS targets[2];
Disassembler::Get()->GetConditionalCTIDest(_address, targets);
jump_target = targets[0];
// Check Next Inst Discovered
RLBinUtils::RLBin_Debug("STATUS : DJ1_F", __FILENAME__, __LINE__);
if(DisTable::Get()->GetEntry(next_inst) == LOC_UNDISCOVERD)
{
// Check Next Inst Within Current Function
RLBinUtils::RLBin_Debug("STATUS : DJ22_F", __FILENAME__, __LINE__);
// Add to pre type 1
RLBinUtils::RLBin_Debug("STATUS : DJ33_F", __FILENAME__, __LINE__);
// Put trap to be discovered
TMU::Get()->InsertTrampoline(next_inst);
RLBinUtils::RLBin_Debug("STATUS : DJ43_F", __FILENAME__, __LINE__);
}
else
{
}
}
else
{
Disassembler::Get()->GetDirectCTIDest(_address, &jump_target);
}
RLBinUtils::RLBin_Debug("jump target is " + RLBinUtils::ConvertHexToString(jump_target), __FILENAME__, __LINE__);
// Now we handle the target
// Check Next Inst Discovered
RLBinUtils::RLBin_Debug("STATUS : DJ1_T", __FILENAME__, __LINE__);
if(DisTable::Get()->GetEntry(jump_target) == LOC_UNDISCOVERD)
{
// Check Next Inst Within Current Function
RLBinUtils::RLBin_Debug("STATUS : DJ22_T", __FILENAME__, __LINE__);
// Add to pre type 1
RLBinUtils::RLBin_Debug("STATUS : DJ33_T", __FILENAME__, __LINE__);
// Put trap to be discovered
TMU::Get()->InsertTrampoline(jump_target);
RLBinUtils::RLBin_Debug("STATUS : DJ43_T", __FILENAME__, __LINE__);
}
else
{
}
return;
}
void CU::HandleNewR(ADDRESS _address, ADDRESS _return_address)
{
if(!(*(byte *)_address == 0xC3))
{
if(!(*(byte *)_address == 0xC2))
{
if(!(*(byte *)_address == 0xF2))
{
Disassembler::Get()->PrintInst(_address, T_OPTSTAT);
}
}
}
// Check against type 2 and pre type 2
RLBinUtils::RLBin_Debug("STATUS : R1", __FILENAME__, __LINE__);
// Analyze safety and modify disassembly table
RLBinUtils::RLBin_Debug("STATUS : R2", __FILENAME__, __LINE__);
// Check External Dest
RLBinUtils::RLBin_Debug("STATUS : R3", __FILENAME__, __LINE__);
if(!Modules::Get()->IsInsideMainCode(_return_address))
{
// Create instrumentation and check external
RLBinUtils::RLBin_Debug("STATUS : R63", __FILENAME__, __LINE__);
// Insert Trampoline to instrumentation
RLBinUtils::RLBin_Debug("STATUS : R71", __FILENAME__, __LINE__);
}
else
{
// Check return address discovered
RLBinUtils::RLBin_Debug("STATUS : R4", __FILENAME__, __LINE__);
if(DisTable::Get()->GetEntry(_return_address) == LOC_UNDISCOVERD)
{
// Put trap to be discovered
TMU::Get()->InsertTrampoline(_return_address);
RLBinUtils::RLBin_Debug("STATUS : R5", __FILENAME__, __LINE__);
// Create Instrumentation to checkDest against type 1
RLBinUtils::RLBin_Debug("STATUS : R62", __FILENAME__, __LINE__);
// Insert Trampoline and Bypass
RLBinUtils::RLBin_Debug("STATUS : R72", __FILENAME__, __LINE__);
}
else
{
// Create Instrumentation to checkDest against type 2
RLBinUtils::RLBin_Debug("STATUS : R61", __FILENAME__, __LINE__);
// Insert Trampoline to instrumentation
RLBinUtils::RLBin_Debug("STATUS : R71", __FILENAME__, __LINE__);
}
}
return;
}
void CU::HandleNewICJ(ADDRESS _address, ADDRESS _cj_address, ADDRESS _next_inst)
{
if(!((*(byte *)_address == 0xFF) && (((*((byte *)_address+1)&0xF0) == 0xD0)||(*((byte *)_address+1) == 0x15)||((*((byte *)_address+1)&0xF0) == 0x50)||(*((byte *)_address+1) == 0x25))))
{
if(!((*(byte *)_address == 0x3E) && ((*((byte *)_address+1)) == 0xFF) && ((*((byte *)_address+2)&0xF0) == 0xE0)))
{
if(!((*(byte *)_address == 0xFF) && ((*((byte *)_address+1)) == 0x24) && ((*((byte *)_address+2)&0xC7) == 0x85)))
{
Disassembler::Get()->PrintInst(_address, T_OPTSTAT);
}
}
}
// Check External Dest
RLBinUtils::RLBin_Debug("STATUS : ICJ2", __FILENAME__, __LINE__);
if(!Modules::Get()->IsInsideMainCode(_cj_address))
{
// Check Call Back
RLBinUtils::RLBin_Debug("STATUS : ICJ32", __FILENAME__, __LINE__);
// Check next inst discovered?
RLBinUtils::RLBin_Debug("STATUS : ICJ53", __FILENAME__, __LINE__);
if(DisTable::Get()->GetEntry(_next_inst) == LOC_UNDISCOVERD)
{
// Put trap to be discovered
RLBinUtils::RLBin_Debug("STATUS : ICJ82", __FILENAME__, __LINE__);
// Create instrumentation to check for external dest
RLBinUtils::RLBin_Debug("STATUS : ICJ93", __FILENAME__, __LINE__);
// Insert trampoline and bypass (trap to be discovered)
TMU::Get()->InsertTrampoline(_next_inst);
RLBinUtils::RLBin_Debug("STATUS : ICJA3", __FILENAME__, __LINE__);
}
}
else
{
// Check target discovered?
RLBinUtils::RLBin_Debug("STATUS : ICJ31", __FILENAME__, __LINE__);
if(DisTable::Get()->GetEntry(_cj_address) == LOC_UNDISCOVERD)
{
// Create instrumentation to check against type 1
RLBinUtils::RLBin_Debug("STATUS : ICJ91", __FILENAME__, __LINE__);
// Insert trampoline and bypass (trap to be discovered)
TMU::Get()->InsertTrampoline(_cj_address);
RLBinUtils::RLBin_Debug("STATUS : ICJA1", __FILENAME__, __LINE__);
}
}
} | 31.242798 | 185 | 0.674262 | RL-Bin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.