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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b96fa4218254fcd123333390248c0237f05fac70 | 4,521 | hpp | C++ | NostraEngine/src/header/nostraengine/core/resource_mngt/ResourceMetadata.hpp | Lehks/NostraEngine | 0d610dcd97ba482fd8f183795140c38728c3a6b3 | [
"MIT"
] | 1 | 2020-11-23T16:46:28.000Z | 2020-11-23T16:46:28.000Z | NostraEngine/src/header/nostraengine/core/resource_mngt/ResourceMetadata.hpp | Lehks/NostraEngine | 0d610dcd97ba482fd8f183795140c38728c3a6b3 | [
"MIT"
] | 107 | 2018-04-06T10:15:47.000Z | 2018-09-28T07:13:46.000Z | NostraEngine/src/header/nostraengine/core/resource_mngt/ResourceMetadata.hpp | Lehks/NostraEngine | 0d610dcd97ba482fd8f183795140c38728c3a6b3 | [
"MIT"
] | null | null | null | #ifndef NOE_CORE_RESOURCE_METADATA_HPP
#define NOE_CORE_RESOURCE_METADATA_HPP
#include "nostraengine/core/StdIncludes.hpp"
#include "nostraengine/core/resource_mngt/ResourceType.hpp"
/**
\file core/resource_mngt/ResourceMetadata.hpp
\author Lukas Reichmann
\version 1.0.0
\since 0.0.1
\brief A file that contains the class ResourceMetadata.
*/
namespace NOE::NOE_CORE
{
/**
\brief A class that can be used to read the meta data of a single resource.
\details
A class that can be used to read the meta data of a single resource. For a full tutorial on how to use the
resource management system, see \link resourceManagementSys this page\endlink.
*/
class ResourceMetadata
{
public:
/**
\brief The type of a resource ID.
*/
using ID = NOU::int32;
/**
\brief An ID that is invalid. An ID with this type must never be stored in a database.
*/
static constexpr ID INVALID_ID = 0;
/**
\brief A generic SQL command that gathers the value of an attribute of an object with a specified ID.
The attribute's name and the object's ID can be modified.
*/
static const NOU::NOU_DAT_ALG::StringView8 SQL_GENERIC;
/**
\brief The name of the "type" attribute in the Resources database.
*/
static const NOU::NOU_DAT_ALG::StringView8 SQL_TYPE_NAME;
/**
\brief The name of the "path" attribute in the Resources database.
*/
static const NOU::NOU_DAT_ALG::StringView8 SQL_PATH_NAME;
/**
\brief The name of the "cached" attribute in the Resources database.
*/
static const NOU::NOU_DAT_ALG::StringView8 SQL_CACHED_PATH_NAME;
/**
\brief A SQL statement that is able to check whether a resource with a specified ID exists. (Or to be
more precise, the statement returns the amount of resources with the specified ID, which will either
be one or zero).
*/
static const NOU::NOU_DAT_ALG::StringView8 SQL_EXISTS_RESOURCE;
private:
/**
\brief The ID of the resource.
*/
mutable ID m_id; //mutable for isValid()
/**
\brief The value of ResourceManager::getResourceRemoveUpdates() from the last validity check.
\details
The value of ResourceManager::getResourceRemoveUpdates() from the last validity check. See
ResourceManager::m_resourceRemoveUpdates for further information.
*/
mutable NOU::int32 m_removeUpdate; //mutable for isValid()
/**
\param attribute The name of the attribute to get the value from.
\return The value of the attribute.
\brief Queries the value of the attribute \p attribute of the resource that is associated with this
meta data.
*/
NOU::NOU_DAT_ALG::String8 getAttribute(const NOU::NOU_DAT_ALG::StringView8 &attribute) const;
/**
\return True, if the resource exists, false if not.
\brief Checks whether the resource still exists in the database.
*/
NOU::boolean checkIfExsists() const;
public:
/**
\param id The ID.
\brief Constructs a new instance and initialized the member attributes with the passed ID.
\note
If the passed ID does not exist in the database, the ID will be set to INVALID_ID. If a resource with
the original ID is created afterwards, the instances of this class that were before that will NOT be
updated.
*/
NOE_FUNC explicit ResourceMetadata(ID id = INVALID_ID);
/**
\return The ID of the resource.
\brief Returns the ID of the resource. If the resource is invalid (it does not exist), INVALID_ID is
returned.
*/
NOE_FUNC ID getID() const;
/**
\return The type of the resource.
\brief Returns the type of the resource.
*/
NOE_FUNC ResourceType getType() const;
/**
\return The path to the source file of the resource.
\brief Returns the path to the source file of the resource.
*/
NOE_FUNC NOU::NOU_FILE_MNGT::Path getPath() const;
/**
\return True, if the resource is cached and false if not.
\brief Returns whether the resource is cached or not.
*/
NOE_FUNC NOU::boolean isCached() const;
/**
\return The path the cache file.
\brief Returns the path to the cache file.
\warning
The result of this method is only valid if <tt>isCached()</tt> returns true.
*/
NOE_FUNC NOU::NOU_FILE_MNGT::Path getCachePath() const;
/**
\return True, if the meta data is valid, false if not.
\brief Returns whether the meta data is valid or not.
*/
NOE_FUNC NOU::boolean isValid() const;
/**
\return isValid()
\brief Same as isValid()
*/
NOE_FUNC operator NOU::boolean() const;
};
constexpr ResourceMetadata::ID ResourceMetadata::INVALID_ID;
}
#endif | 26.910714 | 107 | 0.721301 | Lehks |
b9700bc4e1f26d30772f71aed7db2d101aa91a5e | 11,414 | cpp | C++ | OkvisSLAMSystem.cpp | lidiawu/OpenARK | e98e29a3f1f7d5db7067d7ae6943f1775a936fc9 | [
"Apache-2.0"
] | null | null | null | OkvisSLAMSystem.cpp | lidiawu/OpenARK | e98e29a3f1f7d5db7067d7ae6943f1775a936fc9 | [
"Apache-2.0"
] | null | null | null | OkvisSLAMSystem.cpp | lidiawu/OpenARK | e98e29a3f1f7d5db7067d7ae6943f1775a936fc9 | [
"Apache-2.0"
] | null | null | null | #include "stdafx.h"
#include "OkvisSLAMSystem.h"
namespace ark {
OkvisSLAMSystem::OkvisSLAMSystem(const std::string & strVocFile, const std::string & strSettingsFile) :
start_(0.0), t_imu_(0.0), deltaT_(1.0), num_frames_(0), kill(false),
sparseMap_(){
okvis::VioParametersReader vio_parameters_reader;
try {
vio_parameters_reader.readConfigFile(strSettingsFile);
}
catch (okvis::VioParametersReader::Exception ex) {
std::cerr << ex.what() << "\n";
return;
}
//okvis::VioParameters parameters;
vio_parameters_reader.getParameters(parameters_);
sparseMap_.setEnableLoopClosure(parameters_.loopClosureParameters.enabled,strVocFile,true, new brisk::BruteForceMatcher());
//initialize Visual odometry
okvis_estimator_ = std::make_shared<okvis::ThreadedKFVio>(parameters_);
okvis_estimator_->setBlocking(true);
//Okvis's outframe is our inframe
auto frame_callback = [this](const okvis::Time& timestamp, okvis::OutFrameData::Ptr frame_data) {
frame_data_queue_.enqueue({ frame_data,timestamp });
};
okvis_estimator_->setFrameCallback(frame_callback);
//at thread to pull from queue and call our own callbacks
frameConsumerThread_ = std::thread(&OkvisSLAMSystem::FrameConsumerLoop, this);
frame_data_queue_.clear();
frame_queue_.clear();
std::cout << "SLAM Initialized\n";
}
void OkvisSLAMSystem::Start() {
//Do nothing, starts automatically
}
void OkvisSLAMSystem::FrameConsumerLoop() {
while (!kill) {
//Get processed frame data from OKVIS
StampedFrameData frame_data;
while (!frame_data_queue_.try_dequeue(&frame_data)) {
if(kill)
return;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
//Get the corresponding frame from queue
WrappedMultiCameraFrame wrapped_frame;
bool frame_found = false;
do {
if (!(frame_found = frame_queue_.try_dequeue(&wrapped_frame))) {
break;
}
} while (okvis::Time(wrapped_frame.frame->timestamp_) < frame_data.timestamp);
if (!frame_found){
std::cout << "ERROR, FRAME NOT FOUND, THIS SHOULDN'T HAPPEN\n";
continue;
}
//construct output frame
MultiCameraFrame::Ptr out_frame = wrapped_frame.frame;
out_frame->frameId_ = frame_data.data->id;
out_frame->T_KS_ = frame_data.data->T_KS.T();
out_frame->keyframeId_ = frame_data.data->keyframe_id;
//add sensor transforms
//Note: this could potentially just be done once for the system
//Including here for now in case we switch to optimized results
for (size_t i = 0; i < wrapped_frame.frame->images_.size(); i++) {
okvis::kinematics::Transformation T_SC;
if (i < parameters_.nCameraSystem.numCameras()) {
T_SC = (*parameters_.nCameraSystem.T_SC(i));
}
else if (i - parameters_.nCameraSystem.numCameras() < parameters_.secondaryCameraSystem.numCameras()) {
T_SC = (*parameters_.secondaryCameraSystem.T_SC(i - parameters_.nCameraSystem.numCameras()));
} else {
//no relationship data to imu
//TODO: throw errror
T_SC = okvis::kinematics::Transformation::Identity();
}
out_frame->T_SC_.push_back(T_SC.T());
}
//check if keyframe
if(frame_data.data->is_keyframe){
if(out_frame->keyframeId_!=out_frame->frameId_){
std::cout << "ERROR, KEYFRAME ID INCORRECT, THIS SHOULDN'T HAPPEN\n";
continue;
}
MapKeyFrame::Ptr keyframe = MapKeyFrame::Ptr(new MapKeyFrame);
keyframe->frameId_=out_frame->frameId_;
keyframe->T_WS_ = frame_data.data->T_WS.T();
keyframe->T_SC_ = out_frame->T_SC_;
keyframe->timestamp_ = out_frame->timestamp_;
//copy keypoints and descriptors to output
keyframe->keypoints_.resize(frame_data.data->keypoints.size());
keyframe->keypoints3dh_C.resize(frame_data.data->keypoints.size());
keyframe->descriptors_.resize(frame_data.data->descriptors.size());
for(size_t cam_idx=0 ; cam_idx<frame_data.data->keypoints.size() ; cam_idx++){
keyframe->keypoints_[cam_idx].resize(frame_data.data->keypoints[cam_idx].size());
keyframe->keypoints3dh_C[cam_idx].resize(frame_data.data->keypoints[cam_idx].size());
//get transform of the camera
for(int i=0; i<frame_data.data->keypoints[cam_idx].size(); i++){
//copy keypoint
keyframe->keypoints_[cam_idx][i] = frame_data.data->keypoints[cam_idx][i];
//get estimated 3d position of keypoint in current camera frame
cv::Vec3f pt3d = out_frame->images_[2].at<cv::Vec3f>(
std::round(keyframe->keypoints_[cam_idx][i].pt.y),
std::round(keyframe->keypoints_[cam_idx][i].pt.x));
if(pt3d[2] >0)
keyframe->keypoints3dh_C[cam_idx][i] = Eigen::Vector4d(pt3d[0],pt3d[1],pt3d[2],1);
else
keyframe->keypoints3dh_C[cam_idx][i] = Eigen::Vector4d(0,0,0,0);
}
keyframe->descriptors_[cam_idx]=frame_data.data->descriptors[cam_idx];
}
// push to map
if(sparseMap_.addKeyframe(keyframe)){ //add keyframe returns true if a loop closure was detected
for (MapLoopClosureDetectedHandler::const_iterator callback_iter = mMapLoopClosureHandler.begin();
callback_iter != mMapLoopClosureHandler.end(); ++callback_iter) {
const MapLoopClosureDetectedHandler::value_type& pair = *callback_iter;
pair.second();
}
}
}
out_frame->keyframe_ = sparseMap_.getKeyframe(out_frame->keyframeId_);
//Notify callbacks
if(frame_data.data->is_keyframe){
for (MapKeyFrameAvailableHandler::const_iterator callback_iter = mMapKeyFrameAvailableHandler.begin();
callback_iter != mMapKeyFrameAvailableHandler.end(); ++callback_iter) {
const MapKeyFrameAvailableHandler::value_type& pair = *callback_iter;
pair.second(out_frame);
}
}
for (MapFrameAvailableHandler::const_iterator callback_iter = mMapFrameAvailableHandler.begin();
callback_iter != mMapFrameAvailableHandler.end(); ++callback_iter) {
const MapFrameAvailableHandler::value_type& pair = *callback_iter;
pair.second(out_frame);
}
}
}
/*void OkvisSLAMSystem::PushFrame(const std::vector<cv::Mat>& images, const double ×tamp) {
if (okvis_estimator_ == nullptr)
return;
okvis::Time t_image(timestamp / 1e9);
if (start_ == okvis::Time(0.0)) {
start_ = t_image;
}
if (t_image - start_ > deltaT_) {
if(mMapFrameAvailableHandler.size()>0){
frame_queue_.enqueue({ images,t_image,num_frames_ });
}
num_frames_++;
for (size_t i = 0; i < images.size(); i++) {
if (i < parameters_.nCameraSystem.numCameras()){
//printf("add image: %i\n", i);
okvis_estimator_->addImage(t_image, i, images[i]);
}
}
}
}
void OkvisSLAMSystem::PushFrame(const cv::Mat image, const double ×tamp) {
if (okvis_estimator_ == nullptr)
return;
okvis::Time t_image(timestamp / 1e9);
if (start_ == okvis::Time(0.0)) {
start_ = t_image;
}
if (t_image - start_ > deltaT_) {
std::vector<cv::Mat> images;
images.push_back(image);
if(mMapFrameAvailableHandler.size()>0){
frame_queue_.enqueue({ images,t_image,num_frames_ });
}
num_frames_++;
okvis_estimator_->addImage(t_image, 0, image);
}
}*/
void OkvisSLAMSystem::PushFrame(MultiCameraFrame::Ptr frame){
if (okvis_estimator_ == nullptr)
return;
okvis::Time t_image(frame->timestamp_ / 1e9);
if (start_ == okvis::Time(0.0)) {
start_ = t_image;
}
if (t_image - start_ > deltaT_) {
if(mMapFrameAvailableHandler.size()>0){
frame_queue_.enqueue({ frame});
}
num_frames_++;
for (size_t i = 0; i < frame->images_.size(); i++) {
if (i < parameters_.nCameraSystem.numCameras()){
//printf("add image: %i\n", i);
okvis_estimator_->addImage(t_image, i, frame->images_[i]);
}
}
}
}
void OkvisSLAMSystem::PushIMU(const std::vector<ImuPair>& imu) {
if (okvis_estimator_ == nullptr) return;
for (size_t i = 0; i < imu.size(); i++) {
PushIMU(imu[i]);
}
}
void OkvisSLAMSystem::PushIMU(const ImuPair& imu) {
if (okvis_estimator_ == nullptr) return;
t_imu_ = okvis::Time(imu.timestamp / 1e9);
if (t_imu_ - start_ + okvis::Duration(1.0) > deltaT_) {
//std::cout << imu.timestamp / 1e9 << " , " << imu.accel.transpose() << " , " << imu.gyro.transpose() << std::endl;
okvis_estimator_->addImuMeasurement(t_imu_, imu.accel, imu.gyro);
}
}
void OkvisSLAMSystem::PushIMU(double timestamp, const Eigen::Vector3d& accel, const Eigen::Vector3d gyro) {
if (okvis_estimator_ == nullptr) return;
t_imu_ = okvis::Time(timestamp / 1e9);
if (t_imu_ - start_ + okvis::Duration(1.0) > deltaT_) {
okvis_estimator_->addImuMeasurement(t_imu_, accel, gyro);
}
}
void OkvisSLAMSystem::display() {
if (okvis_estimator_ == nullptr)
return;
okvis_estimator_->display();
}
void OkvisSLAMSystem::ShutDown()
{
frame_queue_.clear();
frame_data_queue_.clear();
kill=true;
frameConsumerThread_.join();
okvis_estimator_.reset();
}
OkvisSLAMSystem::~OkvisSLAMSystem() {
frame_queue_.clear();
frame_data_queue_.clear();
kill=true;
}
void OkvisSLAMSystem::RequestStop()
{
okvis_estimator_ = nullptr;
}
bool OkvisSLAMSystem::IsRunning()
{
return okvis_estimator_ == nullptr;
}
void OkvisSLAMSystem::getTrajectory(std::vector<Eigen::Matrix4d>& trajOut){
sparseMap_.getTrajectory(trajOut);
}
} //ark | 40.619217 | 131 | 0.562642 | lidiawu |
b9747b086d51ef0518d0d36f26edf5ea4c850a22 | 13,486 | cpp | C++ | Village Cycle/OpenGL/Cube.cpp | jSplunk/Village-Cycle | 540b06d85feff0d831e8247473e5cf4d8beccbc8 | [
"Apache-2.0"
] | null | null | null | Village Cycle/OpenGL/Cube.cpp | jSplunk/Village-Cycle | 540b06d85feff0d831e8247473e5cf4d8beccbc8 | [
"Apache-2.0"
] | null | null | null | Village Cycle/OpenGL/Cube.cpp | jSplunk/Village-Cycle | 540b06d85feff0d831e8247473e5cf4d8beccbc8 | [
"Apache-2.0"
] | null | null | null | #include "Cube.h"
Cube::Cube()
{
this->cubeVAO = 0;
this->NormalVBO = 0;
this->PositionVBO = 0;
this->ColourVBO = 0;
this->TexCoordVBO = 0;
this->numElements = 0;
this->IndexVBO = 0;
this->VertexOffsetVBO = 0;
}
//size = size of the cube
Cube::Cube(float size)
{
if (size <= 0) size = 1.0f;
// Per-vertex position vectors
float cubeVertices[32] =
{
-1.0f * size, 1.0f * size, -1.0f * size, 1.0f,
-1.0f* size, 1.0f * size, 1.0f * size, 1.0f,
1.0f * size, 1.0f * size, 1.0f * size, 1.0f,
1.0f * size, 1.0f * size, -1.0f * size, 1.0f,
-1.0f * size, -1.0f * size, -1.0f * size, 1.0f,
-1.0f * size, -1.0f * size, 1.0f * size, 1.0f,
1.0f * size, -1.0f * size, 1.0f * size, 1.0f,
1.0f * size, -1.0f * size, -1.0f * size, 1.0f
};
float cubeNormals[24] =
{
-1.0f , 1.0f , -1.0f,
-1.0f, 1.0f , 1.0f,
1.0f , 1.0f, 1.0f,
1.0f, 1.0f , -1.0f,
-1.0f , -1.0f, -1.0f,
-1.0f , -1.0f, 1.0f,
1.0f , -1.0f , 1.0f,
1.0f , -1.0f , -1.0f
};
// Per-vertex position vectors
float cubeTexCoord[16] =
{
1.0f,0.0f,
1.0f,1.0f,
0.0f,1.0f,
0.0f,0.0f,
0.0f,0.0f,
1.0f,0.0f,
1.0f,1.0f,
0.0f,1.0f
};
// Per-vertex colours (RGBA) floating point values
float cubeColours[32];
int rows = 0;
for (int i = 1; i < 33; i++)
{
if (i % 4 == 0)
{
cubeColours[i-1] = 1.0f; //Every fourth element is 1.0f
rows++;
}
else
{
cubeColours[rows * 4 + ((i % 4) - 1)] = 0.5f; //RGB values are grey colour
}
}
// 12 faces each with 3 vertices (each face forms a triangle) (36 indices total)
unsigned short cubeVertexIndices[36] =
{
0, 1, 2, // top (+y)
0, 2, 3,
4, 7, 5, // bottom (-y)
5, 7, 6,
0, 4, 1, // -x
1, 4, 5,
2, 7, 3, // +x
2, 6, 7,
0, 3, 4, // -z
3, 7, 4,
1, 5, 2, // +z
2, 5, 6
};
// Setup VAO for cube object
glGenVertexArrays(1, &cubeVAO);
glBindVertexArray(cubeVAO);
// Setup VBO for vertex position data
glGenBuffers(1, &PositionVBO);
glBindBuffer(GL_ARRAY_BUFFER, PositionVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), cubeVertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, nullptr); // attribute 0 gets data from bound VBO (so assign vertex position buffer to attribute 0)
//// Setup VBO for vertex colour data
glGenBuffers(1, &ColourVBO);
glBindBuffer(GL_ARRAY_BUFFER, ColourVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(cubeColours), cubeColours, GL_STATIC_DRAW);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, nullptr); // attribute 1 gets colour data
//// Setup VBO for vertex normal data
glGenBuffers(1, &NormalVBO);
glBindBuffer(GL_ARRAY_BUFFER, NormalVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(cubeNormals), cubeNormals, GL_STATIC_DRAW);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, nullptr); // attribute 2 gets normal data
// // Setup VBO for vertex texture data
glGenBuffers(1, &TexCoordVBO);
glBindBuffer(GL_ARRAY_BUFFER, TexCoordVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(cubeTexCoord), cubeTexCoord, GL_STATIC_DRAW);
glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, 0, nullptr); // attribute 1 gets texture data
// Enable vertex position and colour attribute arrays
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
// Setup VBO for face index array
glGenBuffers(1, &IndexVBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexVBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cubeVertexIndices), cubeVertexIndices, GL_STATIC_DRAW);
// Unbind pyramid VAO (or bind another VAO for another object / effect)
// If we didn't do this, we may alter the bindings created above.
glBindVertexArray(0);
//Setting number of indices
numElements = 36;
}
//size = size of the cube, radius = spawn area
Cube::Cube(float size, float radius)
{
//Setting the amount of cubes to render
Amount = radius / size;
//Setting the offsets of the amount of cubes we want to render
std::vector<glm::vec3> offsets;
if (Amount > 1)
{
offsets.resize(Amount*Amount);
float posX = radius - (size * 2);
float posZ = radius - (size * 2);
for (int i = 0; i < Amount; i++)
{
for (int j = 0; j < Amount; j++)
{
offsets[i * Amount + j].x = posX;
offsets[i * Amount + j].z = posZ;
posX -= (size * 2);
}
posZ -= (size * 2);
posX = radius - (size * 2);
}
if (size <= 0) size = 1.0f;
}
else
{
offsets.resize(1);
offsets[0].x = 0;
offsets[0].z = 0;
offsets[0].y = 0;
}
// Per-vertex position vectors
float cubeVertices[32] =
{
-1.0f * size, 1.0f, -1.0f * size, 1.0f,
-1.0f* size, 1.0f, 1.0f * size, 1.0f,
1.0f * size, 1.0f , 1.0f * size, 1.0f,
1.0f * size, 1.0f, -1.0f * size, 1.0f,
-1.0f * size, -1.0f, -1.0f * size, 1.0f,
-1.0f * size, -1.0f, 1.0f * size, 1.0f,
1.0f * size, -1.0f, 1.0f * size, 1.0f,
1.0f * size, -1.0f, -1.0f * size, 1.0f
};
float cubeNormals[24] =
{
-1.0f , 1.0f , -1.0f,
-1.0f, 1.0f , 1.0f,
1.0f , 1.0f, 1.0f,
1.0f, 1.0f , -1.0f,
-1.0f , -1.0f, -1.0f,
-1.0f , -1.0f, 1.0f,
1.0f , -1.0f , 1.0f,
1.0f , -1.0f , -1.0f
};
// Per-vertex position vectors
float cubeTexCoord[16] =
{
1.0f * size,0.0f,
0.0f,0.0f,
0.0f,1.0f * size,
1.0f * size,1.0f * size,
1.0f * size,0.0f,
0.0f,0.0f,
0.0f,1.0f * size,
1.0f * size,1.0f * size,
};
// Per-vertex colours (RGBA) floating point values
float cubeColours[32];
int rows = 0;
for (int i = 1; i < 33; i++)
{
if (i % 4 == 0)
{
cubeColours[i - 1] = 1.0f; //Every fourth element is 1.0f
rows++;
}
else
{
cubeColours[rows * 4 + ((i % 4) - 1)] = 0.1f; //RGB values are grey colour
}
}
// 12 faces each with 3 vertices (each face forms a triangle) (36 indices total)
unsigned short cubeVertexIndices[36] =
{
0, 1, 2, // top (+y)
0, 2, 3,
4, 7, 5, // bottom (-y)
5, 7, 6,
0, 4, 1, // -x
1, 4, 5,
2, 7, 3, // +x
2, 6, 7,
0, 3, 4, // -z
3, 7, 4,
1, 5, 2, // +z
2, 5, 6
};
// Setup VAO for cube object
glGenVertexArrays(1, &cubeVAO);
glBindVertexArray(cubeVAO);
// Setup VBO for vertex position data
glGenBuffers(1, &PositionVBO);
glBindBuffer(GL_ARRAY_BUFFER, PositionVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), cubeVertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, nullptr); // attribute 0 gets data from bound VBO (so assign vertex position buffer to attribute 0)
//// Setup VBO for vertex colour data
glGenBuffers(1, &ColourVBO);
glBindBuffer(GL_ARRAY_BUFFER, ColourVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(cubeColours), cubeColours, GL_STATIC_DRAW);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, nullptr); // attribute 1 gets colour data
//// Setup VBO for vertex normal data
glGenBuffers(1, &NormalVBO);
glBindBuffer(GL_ARRAY_BUFFER, NormalVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(cubeNormals), cubeNormals, GL_STATIC_DRAW);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, nullptr); // attribute 2 gets normal data
// // Setup VBO for vertex texture data
glGenBuffers(1, &TexCoordVBO);
glBindBuffer(GL_ARRAY_BUFFER, TexCoordVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(cubeTexCoord), cubeTexCoord, GL_STATIC_DRAW);
glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, 0, nullptr); // attribute 1 gets texture data
// Setup VBO for vertex instanced array
glGenBuffers(1, &VertexOffsetVBO);
glBindBuffer(GL_ARRAY_BUFFER, VertexOffsetVBO);
if(Amount > 1)
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * Amount * Amount, glm::value_ptr(offsets[0]), GL_STREAM_DRAW);
else
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3), glm::value_ptr(offsets[0]), GL_STREAM_DRAW);
glVertexAttribPointer(6, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
glVertexAttribDivisor(6, 1);
// Enable vertex position and colour attribute arrays
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glEnableVertexAttribArray(6);
// Setup VBO for face index array
glGenBuffers(1, &IndexVBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexVBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cubeVertexIndices), cubeVertexIndices, GL_STATIC_DRAW);
// Unbind pyramid VAO (or bind another VAO for another object / effect)
// If we didn't do this, we may alter the bindings created above.
glBindVertexArray(0);
//Setting number of indices
numElements = 36;
}
Cube::Cube(float width, float breadth, float radius)
{
float size = (width*breadth);
//Setting how many cubes we are rendering
Amount = radius / size;
//Setting the offsets for the amount cube we are rendering
std::vector<glm::vec3> offsets;
if (Amount > 1)
{
offsets.resize(Amount*Amount);
float posX = radius - (width * 2);
float posZ = radius - (breadth * 2);
for (int i = 0; i < Amount; i++)
{
for (int j = 0; j < Amount; j++)
{
offsets[i * Amount + j].x = posX;
offsets[i * Amount + j].z = posZ;
posX -= (width * 2);
}
posZ -= (breadth * 2);
posX = radius - (width * 2);
}
if (width <= 0) width = 1.0f;
if (breadth <= 0) breadth = 1.0f;
}
else
{
offsets.resize(1);
offsets[0].x = 0;
offsets[0].z = 0;
offsets[0].y = 0;
}
// Per-vertex position vectors
float cubeVertices[32] =
{
-1.0f * width, 1.0f, -1.0f * breadth, 1.0f,
-1.0f* width, 1.0f, 1.0f * breadth, 1.0f,
1.0f * width, 1.0f, 1.0f * breadth, 1.0f,
1.0f * width, 1.0f, -1.0f * breadth, 1.0f,
-1.0f * width, -1.0f, -1.0f * breadth, 1.0f,
-1.0f * width, -1.0f, 1.0f * breadth, 1.0f,
1.0f * width, -1.0f, 1.0f * breadth, 1.0f,
1.0f * width, -1.0f, -1.0f * breadth, 1.0f
};
float cubeNormals[24] =
{
-1.0f , 1.0f , -1.0f,
-1.0f, 1.0f , 1.0f,
1.0f , 1.0f, 1.0f,
1.0f, 1.0f , -1.0f,
-1.0f , -1.0f, -1.0f,
-1.0f , -1.0f, 1.0f,
1.0f , -1.0f , 1.0f,
1.0f , -1.0f , -1.0f
};
// Per-vertex position vectors
float cubeTexCoord[16] =
{
1.0f * width,0.0f,
0.0f,0.0f,
0.0f,1.0f * breadth,
1.0f * width,1.0f * breadth,
1.0f * width,0.0f,
0.0f,0.0f,
0.0f,1.0f * breadth,
1.0f * width,1.0f * breadth,
};
// Per-vertex colours (RGBA) floating point values
float cubeColours[32];
//Setting colours
int rows = 0;
for (int i = 1; i < 33; i++)
{
if (i % 4 == 0)
{
cubeColours[i - 1] = 1.0f; //Every fourth element is 1.0f
rows++;
}
else
{
cubeColours[rows * 4 + ((i % 4) - 1)] = 0.1f; //RGB values are grey colour
}
}
// 12 faces each with 3 vertices (each face forms a triangle) (36 indices total)
unsigned short cubeVertexIndices[36] =
{
0, 1, 2, // top (+y)
0, 2, 3,
4, 7, 5, // bottom (-y)
5, 7, 6,
0, 4, 1, // -x
1, 4, 5,
2, 7, 3, // +x
2, 6, 7,
0, 3, 4, // -z
3, 7, 4,
1, 5, 2, // +z
2, 5, 6
};
// Setup VAO for cube object
glGenVertexArrays(1, &cubeVAO);
glBindVertexArray(cubeVAO);
// Setup VBO for vertex position data
glGenBuffers(1, &PositionVBO);
glBindBuffer(GL_ARRAY_BUFFER, PositionVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), cubeVertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, nullptr); // attribute 0 gets data from bound VBO (so assign vertex position buffer to attribute 0)
//// Setup VBO for vertex colour data
glGenBuffers(1, &ColourVBO);
glBindBuffer(GL_ARRAY_BUFFER, ColourVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(cubeColours), cubeColours, GL_STATIC_DRAW);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, nullptr); // attribute 1 gets colour data
//// Setup VBO for vertex normal data
glGenBuffers(1, &NormalVBO);
glBindBuffer(GL_ARRAY_BUFFER, NormalVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(cubeNormals), cubeNormals, GL_STATIC_DRAW);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, nullptr); // attribute 2 gets normal data
// // Setup VBO for vertex texture data
glGenBuffers(1, &TexCoordVBO);
glBindBuffer(GL_ARRAY_BUFFER, TexCoordVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(cubeTexCoord), cubeTexCoord, GL_STATIC_DRAW);
glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, 0, nullptr); // attribute 1 gets texture data
// Setup VBO for vertex instanced array
glGenBuffers(1, &VertexOffsetVBO);
glBindBuffer(GL_ARRAY_BUFFER, VertexOffsetVBO);
if (Amount > 1)
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * Amount * Amount, glm::value_ptr(offsets[0]), GL_STREAM_DRAW);
else
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3), glm::value_ptr(offsets[0]), GL_STREAM_DRAW);
glVertexAttribPointer(6, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
glVertexAttribDivisor(6, 1);
// Enable vertex position and colour attribute arrays
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glEnableVertexAttribArray(6);
// Setup VBO for face index array
glGenBuffers(1, &IndexVBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexVBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cubeVertexIndices), cubeVertexIndices, GL_STREAM_DRAW);
// Unbind VAO (or bind another VAO for another object / effect)
// If we didn't do this, we may alter the bindings created above.
glBindVertexArray(0);
//Setting number of indices
numElements = 36;
}
void Cube::render()
{
glBindVertexArray(cubeVAO);
//Checking to see if we are rendering more than one cube
if(Amount > 1)
glDrawElementsInstanced(GL_TRIANGLES, numElements, GL_UNSIGNED_SHORT, (const GLvoid*)0, Amount*Amount);
else
glDrawElementsInstanced(GL_TRIANGLES, numElements, GL_UNSIGNED_SHORT, (const GLvoid*)0, 1);
glBindVertexArray(0);
}
Cube::~Cube()
{
}
| 26.186408 | 151 | 0.658164 | jSplunk |
b97ad8f3e03aaaa4c8e66d0f620fd46561f428c8 | 971 | cpp | C++ | tests/dev/node-server-mono/node_account.cpp | bryllite/bcp-concept-prototype | 3ded79a85ee4c876fbbd0c1ee51680346874494e | [
"MIT"
] | null | null | null | tests/dev/node-server-mono/node_account.cpp | bryllite/bcp-concept-prototype | 3ded79a85ee4c876fbbd0c1ee51680346874494e | [
"MIT"
] | null | null | null | tests/dev/node-server-mono/node_account.cpp | bryllite/bcp-concept-prototype | 3ded79a85ee4c876fbbd0c1ee51680346874494e | [
"MIT"
] | null | null | null | #include "stdafx.hpp"
#include "node_account.hpp"
node_account::node_account()
{
};
// account address
std::string node_account::address( void )
{
return _key_pair._public.address();
};
uint264 node_account::public_key( void )
{
return _key_pair.get_public_key();
};
uint256 node_account::private_key( void )
{
return _key_pair.get_private_key();
};
bryllite::key_pair node_account::keyPair( void )
{
return _key_pair;
}
void node_account::generate_new_key( void )
{
_key_pair.generate_new();
}
bool node_account::load_key_file( std::string keyFile )
{
return _key_pair.read( keyFile );
}
bool node_account::save_key_file( std::string keyFile )
{
return _key_pair.write( keyFile );
}
std::string node_account::to_string( void )
{
std::stringstream ss;
ss << "{ address=" << _key_pair.address()
<< ", public_key=" << _key_pair.get_public_key().GetHex()
<< ", private_key=" << _key_pair.get_private_key().GetHex()
<< " }";
return ss.str();
}
| 17.654545 | 61 | 0.704428 | bryllite |
b988e737a032c0668c8b213d86a95f21b7d33a53 | 1,876 | hpp | C++ | src/canaries/include/canaries/Loops.hpp | guoyr/genny | f1164927916163824885e019c2498b1ee2042069 | [
"Apache-2.0"
] | null | null | null | src/canaries/include/canaries/Loops.hpp | guoyr/genny | f1164927916163824885e019c2498b1ee2042069 | [
"Apache-2.0"
] | null | null | null | src/canaries/include/canaries/Loops.hpp | guoyr/genny | f1164927916163824885e019c2498b1ee2042069 | [
"Apache-2.0"
] | null | null | null | // Copyright 2019-present MongoDB Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef HEADER_C8D12C92_7C08_4B7F_9857_8B25F7258BB9_INCLUDED
#define HEADER_C8D12C92_7C08_4B7F_9857_8B25F7258BB9_INCLUDED
#include <cstdint>
namespace genny::canaries {
using Nanosecond = int64_t;
/**
* Class for benchmarking Genny internals. It's recommended to run
* these benchmarks as canaries before running Genny workloads.
*
* @tparam WithPing whether to issue db.ping() to a mongo cluster or just
* do a simple increment. The former is useful for gauging
* the overhead of Genny and the latter is useful for seeing
* how this overhead changes over time.
*/
template <bool WithPing>
class Loops {
public:
explicit Loops(int64_t iterations) : _iterations(iterations){};
/**
* Run a basic for-loop, used as the baseline.
*/
Nanosecond simpleLoop();
/**
* Run just the phase loop.
*/
Nanosecond phaseLoop();
/**
* Run a basic for-loop and record one timer metric per loop.
*/
Nanosecond metricsLoop();
/**
* Run the phase loop and record one timer metric per loop.
*/
Nanosecond metricsPhaseLoop();
private:
int64_t _iterations;
};
} // namespace genny::canaries
#endif // HEADER_C8D12C92_7C08_4B7F_9857_8B25F7258BB9_INCLUDED
| 28.861538 | 77 | 0.704691 | guoyr |
b98d91736ad23bcb5f5920b856056a05fabd759b | 1,788 | hpp | C++ | succinct_data_structure/louds.hpp | fumiphys/programming_contest | b9466e646045e1c64571af2a1e64813908e70841 | [
"MIT"
] | 7 | 2019-04-30T14:25:40.000Z | 2020-12-19T17:38:11.000Z | succinct_data_structure/louds.hpp | fumiphys/programming_contest | b9466e646045e1c64571af2a1e64813908e70841 | [
"MIT"
] | 46 | 2018-09-19T16:42:09.000Z | 2020-05-07T09:05:08.000Z | succinct_data_structure/louds.hpp | fumiphys/programming_contest | b9466e646045e1c64571af2a1e64813908e70841 | [
"MIT"
] | null | null | null | /*
* succinct tree by LOUDS
* all notes are 1-based
*/
#ifndef _LOUDS_H_
#define _LOUDS_H_
#include <iostream>
#include <queue>
#include <utility>
#include "fully_indexable_dictionary.hpp"
#include "../graph/dijkstra.hpp"
using namespace std;
typedef struct LOUDS_: SuccinctBitVector{
LOUDS_(int n): SuccinctBitVector(2 * n + 2){}
int select0(int x){
// binary search for L
int lld = 0, lrd = L.size();
while(lrd - lld > 1){
int md = (lld + lrd) / 2;
if(md * l - L[md] <= x)lld = md;
else lrd = md;
}
// binary search for S
int sld = lld * l / block;
int srd = min((lld + 1) * l / block, (int)S.size());
while(srd - sld > 1){
int md = (sld + srd) / 2;
if(md * block - L[lld] - S[md] <= x)sld = md;
else srd = md;
}
int tcount = sld * block - L[lld] - S[sld];
for(int i = 0; i < block; i++){
if(((B[sld] >> i) & 1U) == 0)tcount++;
if(tcount == x + 1)return sld * block + i;
}
return -1;
}
int par(int x){
int zero_x = select0(x);
return rank(zero_x) - 1;
}
pair<int, int> child(int x){
if(select(x) + 1 == select(x + 1))return make_pair(-1, -1);
int ld = select(x) + 1;
int rd = select(x + 1);
return make_pair(ld - rank(ld), rd - 1 - rank(rd));
}
} LOUDS;
LOUDS construct_louds(GraphI graph){
LOUDS louds(graph.n);
int curr = 2;
louds.set_bit(1);
queue<int> q;
q.push(0);
vector<bool> used = vector<bool>(graph.n, false);
used[0] = true;
while(!q.empty()){
int p = q.front(); q.pop();
for(pair<int, int> c: graph.edge[p]){
if(!used[c.first]){
used[c.first] = true;
q.push(c.first);
curr++;
}
}
louds.set_bit(curr);
curr++;
}
louds.build();
return louds;
}
#endif
| 22.632911 | 63 | 0.540268 | fumiphys |
b98dbe53a5dfb6b50c522a13fbd2fcfa7d9e048e | 313 | cpp | C++ | test/module/module_test.cpp | przestaw/Cpp-CMake-template | ce71db7b9635bd57e51ec812e0bfe04dac2355be | [
"MIT"
] | null | null | null | test/module/module_test.cpp | przestaw/Cpp-CMake-template | ce71db7b9635bd57e51ec812e0bfe04dac2355be | [
"MIT"
] | null | null | null | test/module/module_test.cpp | przestaw/Cpp-CMake-template | ce71db7b9635bd57e51ec812e0bfe04dac2355be | [
"MIT"
] | null | null | null | #include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(Project_Test_Suite)
BOOST_AUTO_TEST_SUITE(Module_Test_Suite)
BOOST_AUTO_TEST_CASE(DummyTest_Passes) {
BOOST_CHECK_EQUAL(1,1);
BOOST_CHECK(true);
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END() | 22.357143 | 48 | 0.71885 | przestaw |
b98ec11ee2bba10a6c5c6238f913ab9cc6d64ff8 | 2,666 | cxx | C++ | MITK/Modules/ICPRegService/Internal/niftkICPRegService.cxx | NifTK/NifTK | 2358b333c89ff1bba1c232eecbbcdc8003305dfe | [
"BSD-3-Clause"
] | 13 | 2018-07-28T13:36:38.000Z | 2021-11-01T19:17:39.000Z | MITK/Modules/ICPRegService/Internal/niftkICPRegService.cxx | NifTK/NifTK | 2358b333c89ff1bba1c232eecbbcdc8003305dfe | [
"BSD-3-Clause"
] | null | null | null | MITK/Modules/ICPRegService/Internal/niftkICPRegService.cxx | NifTK/NifTK | 2358b333c89ff1bba1c232eecbbcdc8003305dfe | [
"BSD-3-Clause"
] | 10 | 2018-08-20T07:06:00.000Z | 2021-07-07T07:55:27.000Z | /*=============================================================================
NifTK: A software platform for medical image computing.
Copyright (c) University College London (UCL). All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See LICENSE.txt in the top level directory for details.
=============================================================================*/
#include "niftkICPRegService.h"
#include <mitkDataNode.h>
#include <vtkMatrix4x4.h>
namespace niftk
{
//-----------------------------------------------------------------------------
ICPRegService::ICPRegService()
{
m_Registerer = niftk::ICPBasedRegistration::New();
}
//-----------------------------------------------------------------------------
ICPRegService::~ICPRegService()
{
}
//-----------------------------------------------------------------------------
void ICPRegService::Configure(const us::ServiceProperties& properties)
{
if (properties.size() == 0)
{
return;
}
if (properties.find("MaxLandmarks") != properties.end())
{
int maxLandmarks = us::any_cast<int>((*(properties.find("MaxLandmarks"))).second);
m_Registerer->SetMaximumNumberOfLandmarkPointsToUse(maxLandmarks);
MITK_INFO << "Configured ICPRegService[MaxLandmarks]=" << maxLandmarks;
}
if (properties.find("MaxIterations") != properties.end())
{
int maxIterations = us::any_cast<int>((*(properties.find("MaxIterations"))).second);
m_Registerer->SetMaximumIterations(maxIterations);
MITK_INFO << "Configured ICPRegService[MaxIterations]=" << maxIterations;
}
if (properties.find("TLSIterations") != properties.end())
{
int tlsIterations = us::any_cast<unsigned int>((*(properties.find("TLSIterations"))).second);
m_Registerer->SetTLSIterations(tlsIterations);
MITK_INFO << "Configured ICPRegService[TLSIterations]=" << tlsIterations;
}
if (properties.find("TLSPercentage") != properties.end())
{
int tlsPercentage = us::any_cast<unsigned int>((*(properties.find("TLSPercentage"))).second);
m_Registerer->SetTLSPercentage(tlsPercentage);
MITK_INFO << "Configured ICPRegService[TLSPercentage]=" << tlsPercentage;
}
}
//-----------------------------------------------------------------------------
double ICPRegService::Register(const mitk::DataNode::Pointer fixedDataSet,
const mitk::DataNode::Pointer movingDataSet,
vtkMatrix4x4& matrix) const
{
return m_Registerer->Update(fixedDataSet, movingDataSet, matrix);
}
} // end namespace
| 32.120482 | 97 | 0.583271 | NifTK |
b99366029f4bc1532402d0bdb199e275fadfea08 | 4,547 | cpp | C++ | src/libtsduck/dtv/descriptors/tsTimeShiftedEventDescriptor.cpp | cedinu/tsduck | dc693912b1fda85bcac3fcb830d7753bd8112552 | [
"BSD-2-Clause"
] | 1 | 2019-04-23T21:16:00.000Z | 2019-04-23T21:16:00.000Z | src/libtsduck/dtv/descriptors/tsTimeShiftedEventDescriptor.cpp | cedinu/tsduck | dc693912b1fda85bcac3fcb830d7753bd8112552 | [
"BSD-2-Clause"
] | null | null | null | src/libtsduck/dtv/descriptors/tsTimeShiftedEventDescriptor.cpp | cedinu/tsduck | dc693912b1fda85bcac3fcb830d7753bd8112552 | [
"BSD-2-Clause"
] | null | null | null | //----------------------------------------------------------------------------
//
// TSDuck - The MPEG Transport Stream Toolkit
// Copyright (c) 2005-2021, Thierry Lelegard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL 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 "tsTimeShiftedEventDescriptor.h"
#include "tsDescriptor.h"
#include "tsTablesDisplay.h"
#include "tsPSIRepository.h"
#include "tsPSIBuffer.h"
#include "tsDuckContext.h"
#include "tsxmlElement.h"
TSDUCK_SOURCE;
#define MY_XML_NAME u"time_shifted_event_descriptor"
#define MY_CLASS ts::TimeShiftedEventDescriptor
#define MY_DID ts::DID_TIME_SHIFT_EVENT
#define MY_STD ts::Standards::DVB
TS_REGISTER_DESCRIPTOR(MY_CLASS, ts::EDID::Standard(MY_DID), MY_XML_NAME, MY_CLASS::DisplayDescriptor);
//----------------------------------------------------------------------------
// Constructors
//----------------------------------------------------------------------------
ts::TimeShiftedEventDescriptor::TimeShiftedEventDescriptor() :
AbstractDescriptor(MY_DID, MY_XML_NAME, MY_STD, 0),
reference_service_id(0),
reference_event_id(0)
{
}
ts::TimeShiftedEventDescriptor::TimeShiftedEventDescriptor(DuckContext& duck, const Descriptor& desc) :
TimeShiftedEventDescriptor()
{
deserialize(duck, desc);
}
void ts::TimeShiftedEventDescriptor::clearContent()
{
reference_service_id = 0;
reference_event_id = 0;
}
//----------------------------------------------------------------------------
// Serialization
//----------------------------------------------------------------------------
void ts::TimeShiftedEventDescriptor::serializePayload(PSIBuffer& buf) const
{
buf.putUInt16(reference_service_id);
buf.putUInt16(reference_event_id);
}
void ts::TimeShiftedEventDescriptor::deserializePayload(PSIBuffer& buf)
{
reference_service_id = buf.getUInt16();
reference_event_id = buf.getUInt16();
}
//----------------------------------------------------------------------------
// Static method to display a descriptor.
//----------------------------------------------------------------------------
void ts::TimeShiftedEventDescriptor::DisplayDescriptor(TablesDisplay& disp, PSIBuffer& buf, const UString& margin, DID did, TID tid, PDS pds)
{
if (buf.canReadBytes(4)) {
disp << margin << UString::Format(u"Reference service id: 0x%X (%<d)", {buf.getUInt16()}) << std::endl;
disp << margin << UString::Format(u"Reference event id: 0x%X (%<d)", {buf.getUInt16()}) << std::endl;
}
}
//----------------------------------------------------------------------------
// XML serialization
//----------------------------------------------------------------------------
void ts::TimeShiftedEventDescriptor::buildXML(DuckContext& duck, xml::Element* root) const
{
root->setIntAttribute(u"reference_service_id", reference_service_id, true);
root->setIntAttribute(u"reference_event_id", reference_event_id, true);
}
bool ts::TimeShiftedEventDescriptor::analyzeXML(DuckContext& duck, const xml::Element* element)
{
return element->getIntAttribute(reference_service_id, u"reference_service_id", true) &&
element->getIntAttribute(reference_event_id, u"reference_event_id", true);
}
| 38.863248 | 141 | 0.628106 | cedinu |
b9949e2762d03da2884fa4c1cdcc481ee7c22073 | 2,392 | cpp | C++ | Project2D/newGame.cpp | lodisperkins/Towerapp2 | 342db1a5e2a0c6ce3de68c1bd337c428b8d83ea3 | [
"MIT"
] | null | null | null | Project2D/newGame.cpp | lodisperkins/Towerapp2 | 342db1a5e2a0c6ce3de68c1bd337c428b8d83ea3 | [
"MIT"
] | null | null | null | Project2D/newGame.cpp | lodisperkins/Towerapp2 | 342db1a5e2a0c6ce3de68c1bd337c428b8d83ea3 | [
"MIT"
] | null | null | null | #include "newGame.h"
newGameClass::newGameClass()
{
}
void newGameClass::draw(aie::Renderer2D* renderer, int timer, aie::Font* font)
{
renderer->drawSprite(startTexture, 600, 400, 736, 336);
renderer->drawSprite(spriteTexture, 600, 295, 97, 129);
drawText(renderer, font);
}
void newGameClass::drawText(aie::Renderer2D* renderer, aie::Font* font)
{
renderer->drawText(font, speak(talknum), 220, 200, 0);
if (count == 0)
{
renderer->drawText(font, "2 Items left to take.", 220, 100, 0);
}
if (count == 1)
{
renderer->drawText(font, "1 item left to take.", 220, 100, 0);
}
}
void newGameClass::refresh()
{
count = 0;
startstate = talk;
talknum = 1;
}
const char * newGameClass::speak(int num)
{
const char*say;
switch (num)
{
case 1:
{
return say = "Algernon: Looks like we've finally made it to the tower captain!";
}
case 2:
{
return say = "Algernon: Aargh! I guess I may have taken more damage than I thought huh?";
}
case 3:
{
return say = "Algernon: I don't think I'll be able to make it up the tower with you captain. Not in this condition.";
}
case 4:
{
return say = "Algernon: Here, take something of mine to aid you on your journey. Just leave something for me okay?";
}
case 5:
{
return say = "Algernon: There you go. Ill keep the rest to defend myself. Good luck captain!";
}
}
}
Hero newGameClass::StartGame(int& state,Hero*&Player)
{
switch (startstate)
{
case talk:
{
if (ImGui::Button("Continue", ImVec2(200, 100)))
{
talknum++;
break;
}
if (talknum == 4)
{
startstate = assignpoints;
break;
}
break;
}
case assignpoints:
{
if (count != 2)
{
if (ImGui::Button("Take Nothing", ImVec2(200, 100)))
{
Player->AssignStartingPoints(0);
count++;
}
if (ImGui::Button("Take Health Potion", ImVec2(200, 100)))
{
Player->AssignStartingPoints(1);
count++;
}
if (ImGui::Button("Take Armor Piece", ImVec2(200, 100)))
{
Player->AssignStartingPoints(2);
count++;
}
if (ImGui::Button("Take Accuracy Elixer", ImVec2(200, 100)))
{
Player->AssignStartingPoints(3);
count++;
}
if (ImGui::Button("Take Strength Elixer", ImVec2(200, 100)))
{
Player->AssignStartingPoints(4);
count++;
}
break;
}
else if(count == 2)
{
state = 2;
}
}
}
return *Player;
}
| 18.834646 | 119 | 0.615803 | lodisperkins |
b996183b6a5101e45dbf7c637c1a25b5c0031841 | 1,077 | tpp | C++ | ScatterDraw/src.tpp/PolynomialEquation_en-us.tpp | XOULID/Anboto | 2743b066f23bf2db9cc062d3adedfd044bc69ec1 | [
"Apache-2.0"
] | 8 | 2021-02-28T12:07:43.000Z | 2021-11-14T19:40:45.000Z | ScatterDraw/src.tpp/PolynomialEquation_en-us.tpp | XOULID/Anboto | 2743b066f23bf2db9cc062d3adedfd044bc69ec1 | [
"Apache-2.0"
] | 8 | 2021-03-20T10:46:58.000Z | 2022-01-27T19:50:32.000Z | ScatterDraw/src.tpp/PolynomialEquation_en-us.tpp | XOULID/Anboto | 2743b066f23bf2db9cc062d3adedfd044bc69ec1 | [
"Apache-2.0"
] | 1 | 2021-08-20T09:15:18.000Z | 2021-08-20T09:15:18.000Z | topic "2.1.1 PolynomialEquation";
[0 $$1,0#96390100711032703541132217272105:end]
[i448;a25;kKO9;2 $$2,0#37138531426314131252341829483380:class]
[H6;0 $$3,0#05600065144404261032431302351956:begin]
[i448;a25;kKO9;2 $$4,0#37138531426314131252341829483370:codeitem]
[l288;2 $$5,5#27521748481378242620020725143825:desc]
[ $$0,0#00000000000000000000000000000000:Default]
[{_}%EN-US
[ {{10000@3 [s0; [*@(229)4 PolynomialEquation]]}}&]
[s1; &]
[s2;:PolynomialEquation`:`:class:%- [@(0.0.255)3 class][3 _][*3 PolynomialEquation
: ][@(0.0.255)3 public][3 _][*3 ExplicitEquation]&]
[s0;2 &]
[s0; [2 PolynomialEquation represents a nth degree polynomial like
y `= 3`*x`^2 `+ 2`*x `- 1]&]
[s0;2 &]
[s1; &]
[ {{10000F(128)G(128)@1 [s0; [*2 Public Member List]]}}&]
[s3;%- &]
[s4;:ExplicitEquation`:`:SetDegree`(int`):%- [@(0.0.255) virtual] [@(0.0.255) void]_[* SetD
egree]([@(0.0.255) int]_[*@3 num])&]
[s5; Sets [%-*@3 num] as the exponent of the highest power of the independent
variables.&]
[s5; A polynomial of degree [%-*@3 num] has [%-*@3 num] `+ 1 coefficients.&]
[s1; &]
[s0; ]] | 41.423077 | 91 | 0.662024 | XOULID |
b99986c9d1ab81d012abceb649c071714e4a5b83 | 4,801 | cpp | C++ | src/RIMACS/Functors/GraphCachingFunctor.cpp | rareylab/RIMACS | 938790acc58191b3a6ece2feb82b5bb873224841 | [
"BSD-3-Clause"
] | 2 | 2021-10-18T08:51:13.000Z | 2022-02-08T12:56:12.000Z | src/RIMACS/Functors/GraphCachingFunctor.cpp | rareylab/RIMACS | 938790acc58191b3a6ece2feb82b5bb873224841 | [
"BSD-3-Clause"
] | null | null | null | src/RIMACS/Functors/GraphCachingFunctor.cpp | rareylab/RIMACS | 938790acc58191b3a6ece2feb82b5bb873224841 | [
"BSD-3-Clause"
] | 1 | 2021-05-29T13:07:11.000Z | 2021-05-29T13:07:11.000Z |
#include <Eigen/SparseCore>
#include <RIMACS/Forward.hpp>
#include <RIMACS/Functors/LineGraph.hpp>
#include <RIMACS/Functors/GraphCachingFunctor.hpp>
namespace RIMACS {
// Experimental evaluation for optimal node order suggestion as performed by
// Schmidt et.al.: Disconnected Maximum Common Substructures Under Constraints
// https://dx.doi.org/10.1021/acs.jcim.0c00741
static constexpr double NODE_ORDER_RELATIVE_POSITION = 1.0;
static constexpr double EDGE_ORDER_RELATIVE_POSITION = 0.75;
// Con- Destructors have to be defined in cpp because the SparseMatrixCache struct is undefined in the
// hpp. But the unique_ptr con- destructors require, that the struct is defined.
CachingAdjacencyFunctor::CachingAdjacencyFunctor(
const CachingRequiredMinimalAdjacencyFunctor& realInstance)
: m_instance(realInstance)
{}
CachingAdjacencyFunctor::~CachingAdjacencyFunctor() = default;
CachingAdjacencyFunctor::CachingAdjacencyFunctor(
CachingAdjacencyFunctor&& other,
const CachingRequiredMinimalAdjacencyFunctor& newBaseRef) noexcept
: m_instance(newBaseRef)
, m_cache(std::move(other.m_cache))
, m_nodeOrder(std::move(other.m_nodeOrder))
{}
struct SparseMatrixCache {
SparseMatrixCache(
ComponentIndex nofNodes)
: m_matrix(nofNodes, nofNodes)
{}
Eigen::SparseMatrix<MappingIndex> m_matrix;
};
void CachingAdjacencyFunctor::doInitialize()
{
m_cache = std::make_unique<SparseMatrixCache>(m_instance.getNofNodes());
auto& mat = m_cache->m_matrix;
std::vector<Eigen::Triplet<unsigned>> edges;
edges.reserve(2 * m_instance.getNofEdges());
for(MappingIndex i = 0, last = m_instance.getNofEdges(); i < last; ++i) {
MappingIndex from = m_instance.edgeGetFromId(i);
MappingIndex to = m_instance.edgeGetToId(i);
edges.emplace_back(from, to, i + 1);
edges.emplace_back(to, from, i + 1);
}
std::sort(edges.begin(), edges.end(),
[](const Eigen::Triplet<unsigned>& t1, const Eigen::Triplet<unsigned>& t2) {
if(t1.col() != t2.col()) {
return t1.col() < t2.col();
}
return t1.row() < t2.row();
});
mat.setFromTriplets(edges.begin(), edges.end());
mat.makeCompressed();
if(dynamic_cast<const BasicLineGraph*>(&m_instance)) {
m_nodeOrder = this->getNodeOrderSuggestionVector(EDGE_ORDER_RELATIVE_POSITION);
} else {
m_nodeOrder = this->getNodeOrderSuggestionVector(NODE_ORDER_RELATIVE_POSITION);
}
}
bool CachingAdjacencyFunctor::adjacent(
MappingIndex node1,
MappingIndex node2) const
{
const auto& mat = m_cache->m_matrix;
// perform a linear search on the neighbour indices.
// On such low degree graphs (usually <= 4), linear searches outperform binary searches
auto begin = mat.innerIndexPtr() + mat.outerIndexPtr()[node1];
auto end = mat.innerIndexPtr() + mat.outerIndexPtr()[node1 + 1];
return std::find(begin, end, node2) != end;
}
MappingIndex CachingAdjacencyFunctor::getEdgeId(
MappingIndex nodeFromId,
MappingIndex nodeToId) const
{
static_assert(NO_EDGE == std::numeric_limits<MappingIndex>::max(),
"No edge indicator must be the -1 value");
MappingIndex edgeId = m_cache->m_matrix.coeff(nodeFromId, nodeToId);
return edgeId - 1;
}
MappingIndex CachingAdjacencyFunctor::edgeGetFromId(
MappingIndex edgeId) const
{
return m_instance.edgeGetFromId(edgeId);
}
MappingIndex CachingAdjacencyFunctor::edgeGetToId(
MappingIndex edgeId) const
{
return m_instance.edgeGetToId(edgeId);
}
std::vector<MappingIndex> CachingAdjacencyFunctor::nodeGetEdges(
MappingIndex nodeIdx) const
{
const Eigen::SparseMatrix<unsigned>& mat = m_cache->m_matrix;
Eigen::SparseMatrix<unsigned>::InnerIterator it(mat, nodeIdx);
std::vector<MappingIndex> result;
result.reserve(mat.outerIndexPtr()[nodeIdx + 1] - mat.outerIndexPtr()[nodeIdx]);
for(; it; ++it) {
result.push_back(it.value() - 1);
}
return result;
}
std::vector<MappingIndex> CachingAdjacencyFunctor::nodeGetNeighbours(
MappingIndex nodeIdx) const
{
const Eigen::SparseMatrix<unsigned>& mat = m_cache->m_matrix;
Eigen::SparseMatrix<unsigned>::InnerIterator it(mat, nodeIdx);
std::vector<MappingIndex> result;
result.reserve(mat.outerIndexPtr()[nodeIdx + 1] - mat.outerIndexPtr()[nodeIdx]);
for(; it; ++it) {
result.push_back(it.row());
}
return result;
}
MappingIndex CachingAdjacencyFunctor::getNofNodes() const
{
return m_cache->m_matrix.rows();
}
MappingIndex CachingAdjacencyFunctor::nodeGetNofEdges(
MappingIndex nodeIdx) const
{
return m_cache->m_matrix.outerIndexPtr()[nodeIdx + 1]
- m_cache->m_matrix.outerIndexPtr()[nodeIdx];
}
MappingIndex CachingAdjacencyFunctor::getNofEdges() const
{
return m_instance.getNofEdges();
}
} // namespace RIMACS
| 30.194969 | 102 | 0.729431 | rareylab |
b9a6481cccf6d5f265378690dcecf8af69d7f09e | 20,150 | hpp | C++ | inc/rasters/entities/Grid/vector_calculus_test.hpp | davidson16807/libtectonics | aa0ae2b8a4a1d2a9a346bbdeb334be876ad75646 | [
"CC-BY-4.0"
] | 7 | 2020-06-09T19:56:55.000Z | 2021-02-17T01:53:30.000Z | inc/rasters/entities/Grid/vector_calculus_test.hpp | davidson16807/tectonics.cpp | c40278dba14260c598764467c7abf23b190e676b | [
"CC-BY-4.0"
] | null | null | null | inc/rasters/entities/Grid/vector_calculus_test.hpp | davidson16807/tectonics.cpp | c40278dba14260c598764467c7abf23b190e676b | [
"CC-BY-4.0"
] | null | null | null |
// std libraries
#include <sstream> //std::stringstream
#include <iostream> //std::cout
// 3rd party libraries
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch/catch.hpp"
#define GLM_FORCE_PURE // disable anonymous structs so we can build with ISO C++
#include <glm/vec3.hpp> // *vec3
#include <glm/mat3x2.hpp> // *mat3x2
// in-house libraries
#include <series/types.hpp>
#include <series/relational.hpp>
#include <series/arithmetic.hpp>
#include <series/string_cast.hpp> // to_string
#include <series/glm/glm.hpp> // *vec*s
#include <series/glm/random.hpp> // get_elias_noise
#include <series/glm/convenience.hpp> // get_elias_noise
#include <series/glm/string_cast.hpp> // to_string
#include <meshes/mesh.hpp>
#include "vector_calculus.hpp"
#include "../Grid/convenience.hpp"
#include "../Grid/operators.hpp"
#include "../Grid/Grid_test_utils.hpp" // nonspheroid_icosahedron_grid
using namespace rasters;
TEST_CASE( "Raster gradient determinism", "[rasters]" ) {
auto a= make_Raster<float>(nonspheroid_icosahedron_grid, {1,2,3,4,5,6,7,8,9,10,11,12});
SECTION("gradient(grid, a) must generate the same output when called repeatedly"){
CHECK(series::equal(gradient(a), gradient(a)));
}
}
// TEST_CASE( "gradient translation invariance", "[rasters]" ) {
// meshes::mesh icosphere_mesh(meshes::icosahedron.vertices, meshes::icosahedron.faces);
// icosphere_mesh = meshes::subdivide(icosphere_mesh); series::normalize(icosphere_mesh.vertices, icosphere_mesh.vertices);
// icosphere_mesh = meshes::subdivide(icosphere_mesh); series::normalize(icosphere_mesh.vertices, icosphere_mesh.vertices);
// icosphere_mesh = meshes::subdivide(icosphere_mesh); series::normalize(icosphere_mesh.vertices, icosphere_mesh.vertices);
// icosphere_mesh = meshes::subdivide(icosphere_mesh); series::normalize(icosphere_mesh.vertices, icosphere_mesh.vertices);
// icosphere_mesh = meshes::subdivide(icosphere_mesh); series::normalize(icosphere_mesh.vertices, icosphere_mesh.vertices);
// auto a = make_Raster<float>(icosphere_grid);
// auto A_ids = make_Raster<uint>(icosphere_grid);
// auto Ai_ids = make_Raster<uint>(icosphere_grid);
// auto A_pos = make_Raster<glm::vec3>(icosphere_grid);
// auto Ai_pos = make_Raster<glm::vec3>(icosphere_grid);
// auto A_a = make_Raster<float>(icosphere_grid);
// auto grad_A_a = make_Raster<glm::vec3>(icosphere_grid);
// auto Ai_grad_A_a = make_Raster<glm::vec3>(icosphere_grid);
// auto grad_a = make_Raster<glm::vec3>(icosphere_grid);
// std::mt19937 generator(2);
// series::get_elias_noise(icosphere_grid.metrics->vertex_positions, generator, a);
// mat4 A = glm::rotate(mat4(1.f), 3.14f/3.f, glm::glm::vec3(1,1,1));
// mult(A, icosphere.vertex_positions, A_pos);
// icosphere.get_ids(A_pos, A_ids);
// mat4 Ai = glm::inverse(A);
// mult(Ai, icosphere.vertex_positions, Ai_pos);
// icosphere.get_ids(Ai_pos, Ai_ids);
// SECTION("gradient(a) must generate the same output as unshift(gradient(shift(a)))"){
// gradient ( a, grad_a );
// get ( a, A_ids, A_a );
// gradient ( A_a, grad_A_a );
// get ( grad_A_a, Ai_ids, Ai_grad_A_a );
// CHECK(series::equal(grad_a, Ai_grad_A_a, 0.7f, 0.1f));
// }
// }
// TEST_CASE( "gradient resolution invariance", "[rasters]" ) {
// meshes::mesh icosphere_mesh1(meshes::icosahedron.vertices, meshes::icosahedron.faces);
// icosphere_mesh1 = meshes::subdivide(icosphere_mesh1); series::normalize(icosphere_mesh1.vertices, icosphere_mesh1.vertices);
// MeshCache icosphere1(icosphere_mesh1.vertices, icosphere_mesh1.faces);
// meshes::mesh icosphere_mesh2(icosphere_mesh1);
// icosphere_mesh2 = meshes::subdivide(icosphere_mesh2); series::normalize(icosphere_mesh2.vertices, icosphere_mesh2.vertices);
// MeshCache icosphere2(icosphere_mesh2.vertices, icosphere_mesh2.faces);
// auto a = make_Raster<float>(icosphere1.vertex_count);
// auto A_ids = make_Raster<uint>(icosphere2.vertex_count);
// auto Ai_ids = make_Raster<uint>(icosphere1.vertex_count);
// auto A_a = make_Raster<float>(icosphere2.vertex_count);
// auto grad_A_a = make_Raster<glm::vec3>(icosphere2.vertex_count);
// auto Ai_grad_A_a = make_Raster<glm::vec3>(icosphere1.vertex_count);
// auto grad_a = make_Raster<glm::vec3>(icosphere1.vertex_count);
// std::mt19937 generator(2);
// series::get_elias_noise(icosphere1.vertex_positions, generator, a);
// icosphere1.get_ids(icosphere2.vertex_positions, A_ids);
// icosphere2.get_ids(icosphere1.vertex_positions, Ai_ids);
// SECTION("gradient(a) must generate the same output as unshift(gradient(shift(a)))"){
// gradient ( icosphere1,a, grad_a );
// get ( a, A_ids, A_a );
// gradient ( icosphere2,A_a, grad_A_a );
// get ( grad_A_a, Ai_ids, Ai_grad_A_a );
// CHECK(series::equal(grad_a, Ai_grad_A_a, 0.7f, 0.1f));
// }
// }
TEST_CASE( "Raster gradient distributive over addition", "[rasters]" ) {
meshes::mesh icosphere_mesh(meshes::icosahedron.vertices, meshes::icosahedron.faces);
icosphere_mesh = meshes::subdivide(icosphere_mesh); series::normalize(icosphere_mesh.vertices, icosphere_mesh.vertices);
rasters::Grid icosphere_grid(icosphere_mesh.vertices, icosphere_mesh.faces);
auto a = make_Raster<float>(icosphere_grid);
auto b = make_Raster<float>(icosphere_grid);
std::mt19937 generator(2);
series::get_elias_noise(icosphere_grid.metrics->vertex_positions, generator, a);
series::get_elias_noise(icosphere_grid.metrics->vertex_positions, generator, b);
SECTION("gradient(a+b) must generate the same output as gradient(a)+gradient(b)"){
CHECK(series::equal( gradient(a+b), gradient(a) + gradient(b), 0.01f ));
}
}
TEST_CASE( "Raster gradient multiplication relation", "[rasters]" ) {
meshes::mesh icosphere_mesh(meshes::icosahedron.vertices, meshes::icosahedron.faces);
icosphere_mesh = meshes::subdivide(icosphere_mesh); series::normalize(icosphere_mesh.vertices, icosphere_mesh.vertices);
rasters::Grid icosphere_grid(icosphere_mesh.vertices, icosphere_mesh.faces);
auto a = make_Raster<float>(icosphere_grid);
auto b = make_Raster<float>(icosphere_grid);
std::mt19937 generator(2);
series::get_elias_noise(icosphere_grid.metrics->vertex_positions, generator, a);
a /= std::max(-series::min(a), series::max(a));
series::get_elias_noise(icosphere_grid.metrics->vertex_positions, generator, b);
b /= std::max(-series::min(b), series::max(b));
// glm::mat3x2 basis = glm::mat3x2(1,0,0,
// 0,1,0);
// std::cout << to_string(gradient(a*b), basis) << std::endl;
// std::cout << to_string(gradient(b)*a + gradient(a)*b, basis) << std::endl;
SECTION("gradient(a*b) must generate the same output as a*gradient(b) + b*gradient(a)"){
CHECK(series::equal( gradient(a*b), gradient(b)*a + gradient(a)*b, 0.1f ));
}
}
TEST_CASE( "Raster divergence determinism", "[rasters]" ) {
auto a = make_Raster<glm::vec3>(nonspheroid_icosahedron_grid, {
glm::vec3(1, 2, 3 ),
glm::vec3(4, 5, 6 ),
glm::vec3(7, 8, 9 ),
glm::vec3(10,11,12),
glm::vec3(13,14,15),
glm::vec3(16,17,18),
glm::vec3(19,20,21),
glm::vec3(22,23,24),
glm::vec3(25,26,27),
glm::vec3(28,29,30),
glm::vec3(31,32,33),
glm::vec3(34,35,36)
});
auto out1 = make_Raster<float>(nonspheroid_icosahedron_grid);
auto out2 = make_Raster<float>(nonspheroid_icosahedron_grid);
SECTION("divergence(grid, a) must generate the same output when called repeatedly"){
CHECK(series::equal(divergence(a),divergence(a)));
}
}
// TEST_CASE( "divergence translation invariance", "[rasters]" ) {
// meshes::mesh icosphere_mesh(meshes::icosahedron.vertices, meshes::icosahedron.faces);
// icosphere_mesh = meshes::subdivide(icosphere_mesh); series::normalize(icosphere_mesh.vertices, icosphere_mesh.vertices);
// icosphere_mesh = meshes::subdivide(icosphere_mesh); series::normalize(icosphere_mesh.vertices, icosphere_mesh.vertices);
// icosphere_mesh = meshes::subdivide(icosphere_mesh); series::normalize(icosphere_mesh.vertices, icosphere_mesh.vertices);
// icosphere_mesh = meshes::subdivide(icosphere_mesh); series::normalize(icosphere_mesh.vertices, icosphere_mesh.vertices);
// icosphere_mesh = meshes::subdivide(icosphere_mesh); series::normalize(icosphere_mesh.vertices, icosphere_mesh.vertices);
// auto scalar = make_Raster<float>(icosphere_grid);
// auto a = make_Raster<glm::vec3>(icosphere_grid);
// auto A_ids = make_Raster<uint>(icosphere_grid);
// auto Ai_ids = make_Raster<uint>(icosphere_grid);
// auto A_pos = make_Raster<glm::vec3>(icosphere_grid);
// auto Ai_pos = make_Raster<glm::vec3>(icosphere_grid);
// auto A_a = make_Raster<glm::vec3>(icosphere_grid);
// auto div_A_a = make_Raster<float>(icosphere_grid);
// auto Ai_div_A_a = make_Raster<float>(icosphere_grid);
// auto div_a = make_Raster<float>(icosphere_grid);
// std::mt19937 generator(2);
// series::get_elias_noise ( generator, scalar );
// a = gradient( scalar);
// mat4 A = glm::rotate(mat4(1.f), 3.14f/3.f, glm::glm::vec3(1,1,1));
// mult(A, icosphere.vertex_positions, A_pos);
// icosphere.get_ids(A_pos, A_ids);
// mat4 Ai = glm::inverse(A);
// mult(Ai, icosphere.vertex_positions, Ai_pos);
// icosphere.get_ids(Ai_pos, Ai_ids);
// SECTION("divergence(a) must generate the same output as unshift(divergence(shift(a)))"){
// divergence ( a, div_a );
// get ( a, A_ids, A_a );
// divergence ( A_a, div_A_a );
// get ( div_A_a, Ai_ids, Ai_div_A_a );
// CHECK(series::equal(div_a, Ai_div_A_a, 1e-0f));
// }
// }
// TEST_CASE( "divergence resolution invariance", "[rasters]" ) {
// meshes::mesh icosphere_mesh1(meshes::icosahedron.vertices, meshes::icosahedron.faces);
// icosphere_mesh1 = meshes::subdivide(icosphere_mesh1); series::normalize(icosphere_mesh1.vertices, icosphere_mesh1.vertices);
// MeshCache icosphere1(icosphere_mesh1.vertices, icosphere_mesh1.faces);
// meshes::mesh icosphere_mesh2(icosphere_mesh1);
// icosphere_mesh2 = meshes::subdivide(icosphere_mesh2); series::normalize(icosphere_mesh2.vertices, icosphere_mesh2.vertices);
// MeshCache icosphere2(icosphere_mesh2.vertices, icosphere_mesh2.faces);
// auto scalar = make_Raster<float>(icosphere1.vertex_count);
// auto a = make_Raster<glm::vec3>(icosphere1.vertex_count);
// auto A_ids = make_Raster<uint>(icosphere2.vertex_count);
// auto Ai_ids = make_Raster<uint>(icosphere1.vertex_count);
// auto A_a = make_Raster<glm::vec3>(icosphere2.vertex_count);
// auto div_A_a = make_Raster<float>(icosphere2.vertex_count);
// auto Ai_div_A_a = make_Raster<float>(icosphere1.vertex_count);
// auto div_a = make_Raster<float>(icosphere1.vertex_count);
// std::mt19937 generator(2);
// series::get_elias_noise ( icosphere1, generator, scalar );
// a = gradient( icosphere1, scalar);
// icosphere1.get_ids(icosphere2.vertex_positions, A_ids);
// icosphere2.get_ids(icosphere1.vertex_positions, Ai_ids);
// SECTION("divergence(a) must generate the same output as unshift(divergence(shift(a)))"){
// divergence ( icosphere1,a, div_a );
// get ( a, A_ids, A_a );
// divergence ( icosphere2,A_a, div_A_a );
// get ( div_A_a, Ai_ids, Ai_div_A_a );
// CHECK(series::equal(div_a, Ai_div_A_a, 1e-0f));
// }
// }
TEST_CASE( "Raster divergence distributive over addition", "[rasters]" ) {
meshes::mesh icosphere_mesh(meshes::icosahedron.vertices, meshes::icosahedron.faces);
icosphere_mesh = meshes::subdivide(icosphere_mesh); series::normalize(icosphere_mesh.vertices, icosphere_mesh.vertices);
rasters::Grid icosphere_grid(icosphere_mesh.vertices, icosphere_mesh.faces);
auto scalar = make_Raster<float>(icosphere_grid);
auto a = make_Raster<glm::vec3>(icosphere_grid);
auto b = make_Raster<glm::vec3>(icosphere_grid);
auto div_a = make_Raster<float>(icosphere_grid);
auto div_b = make_Raster<float>(icosphere_grid);
auto div_a_b = make_Raster<float>(icosphere_grid);
std::mt19937 generator(2);
series::get_elias_noise(icosphere_grid.metrics->vertex_positions, generator, scalar);
a = gradient(scalar);
series::get_elias_noise(icosphere_grid.metrics->vertex_positions, generator, scalar);
b = gradient(scalar);
SECTION("divergence(a+b) must generate the same output as divergence(a)+divergence(b)"){
CHECK(series::equal(divergence(a) + divergence( b), divergence(a+b), 0.1f));
}
}
// TEST_CASE( "divergence multiplication relation", "[rasters]" ) {
// meshes::mesh icosphere_mesh(meshes::icosahedron.vertices, meshes::icosahedron.faces);
// icosphere_mesh = meshes::subdivide(icosphere_mesh); series::normalize(icosphere_mesh.vertices, icosphere_mesh.vertices);
// auto scalar = make_Raster<float>(icosphere_grid);
// auto a = make_Raster<float>(icosphere_grid);
// auto b = make_Raster<glm::vec3>(icosphere_grid);
// auto grad_a = make_Raster<glm::vec3>(icosphere_grid);
// auto div_b = make_Raster<float>(icosphere_grid);
// auto div_a_b = make_Raster<float>(icosphere_grid);
// std::mt19937 generator(2);
// series::get_elias_noise(icosphere_grid.metrics->vertex_positions, generator, a);
// series::get_elias_noise(icosphere_grid.metrics->vertex_positions, generator, scalar);
// b = gradient( scalar);
// grad_a = gradient( a );
// SECTION("divergence(a+b) must generate the same output as a*divergence(b) + b*divergence(a)"){
// divergence ( b, div_b );
// divergence ( b*a, div_a_b );
// CHECK(series::equal( div_a_b, div_b*a + dot(b, grad_a), 1e-0f));
// }
// }
TEST_CASE( "Raster curl determinism", "[rasters]" ) {
auto a = make_Raster<glm::vec3>(nonspheroid_icosahedron_grid, {
glm::vec3(1, 2, 3 ),
glm::vec3(4, 5, 6 ),
glm::vec3(7, 8, 9 ),
glm::vec3(10,11,12),
glm::vec3(13,14,15),
glm::vec3(16,17,18),
glm::vec3(19,20,21),
glm::vec3(22,23,24),
glm::vec3(25,26,27),
glm::vec3(28,29,30),
glm::vec3(31,32,33),
glm::vec3(34,35,36)
});
// auto b = make_Raster<float>( {1,1,2,3,5,8,13,21,34,55,89,144});
auto out1= make_Raster<glm::vec3>(nonspheroid_icosahedron_grid);
auto out2= make_Raster<glm::vec3>(nonspheroid_icosahedron_grid);
SECTION("curl(grid, a) must generate the same output when called repeatedly"){
CHECK(series::equal(curl(a),curl(a), 0.1f));
}
}
TEST_CASE( "Raster curl distributive over addition", "[rasters]" ) {
meshes::mesh icosphere_mesh(meshes::icosahedron.vertices, meshes::icosahedron.faces);
icosphere_mesh = meshes::subdivide(icosphere_mesh); series::normalize(icosphere_mesh.vertices, icosphere_mesh.vertices);
rasters::Grid icosphere_grid(icosphere_mesh.vertices, icosphere_mesh.faces);
auto scalar = make_Raster<float>(icosphere_grid);
auto a = make_Raster<glm::vec3>(icosphere_grid);
auto b = make_Raster<glm::vec3>(icosphere_grid);
auto curl_a = make_Raster<glm::vec3>(icosphere_grid);
auto curl_b = make_Raster<glm::vec3>(icosphere_grid);
auto curl_a_b = make_Raster<glm::vec3>(icosphere_grid);
std::mt19937 generator(2);
series::get_elias_noise(icosphere_grid.metrics->vertex_positions, generator, scalar);
a = gradient(scalar);
series::get_elias_noise(icosphere_grid.metrics->vertex_positions, generator, scalar);
b = gradient(scalar);
SECTION("curl(a+b) must generate the same output as curl(a)+curl(b)"){
CHECK(series::equal(curl(a) + curl(b), curl(a+b), 0.1f));
}
}
// TEST_CASE( "curl of gradient is zero", "[rasters]" ) {
// meshes::mesh icosphere_mesh(meshes::icosahedron.vertices, meshes::icosahedron.faces);
// icosphere_mesh = meshes::subdivide(icosphere_mesh); series::normalize(icosphere_mesh.vertices, icosphere_mesh.vertices);
// auto a = make_Raster<float>(icosphere_grid);
// auto grad_a = make_Raster<glm::vec3>(icosphere_grid);
// auto curl_grad_a= make_Raster<glm::vec3>(icosphere_grid);
// auto zeros = make_Raster<glm::vec3>(icosphere_grid);
// std::mt19937 generator(2);
// series::get_elias_noise(icosphere_grid.metrics->vertex_positions, generator, a);
// fill (zeros, glm::vec3(0));
// grad_a = gradient (a);
// curl (grad_a, curl_grad_a );
// SECTION("curl(gradient(a)) must generate the zero vector"){
// // CHECK(curl_grad_a == zeros);
// CHECK(series::equal(curl_grad_a, zeros));
// }
// }
// TEST_CASE( "divergence of curl is zero", "[rasters]" ) {
// meshes::mesh icosphere_mesh(meshes::icosahedron.vertices, meshes::icosahedron.faces);
// icosphere_mesh = meshes::subdivide(icosphere_mesh); series::normalize(icosphere_mesh.vertices, icosphere_mesh.vertices);
// auto scalar = make_Raster<float>(icosphere_grid);
// auto a = make_Raster<glm::vec3>(icosphere_grid);
// auto curl_a = make_Raster<glm::vec3>(icosphere_grid);
// auto div_curl_a = make_Raster<float>(icosphere_grid);
// auto zeros = make_Raster<float>(icosphere_grid);
// std::mt19937 generator(2);
// series::get_elias_noise(icosphere_grid.metrics->vertex_positions, generator, scalar);
// a = gradient(scalar);
// fill (zeros, 0.f);
// curl (a, curl_a );
// divergence (curl_a, div_curl_a );
// SECTION("curl(gradient(a)) must generate the zero vector"){
// CHECK(div_curl_a == zeros);
// // CHECK(series::equal(div_curl_a, zeros));
// }
// }
TEST_CASE( "Raster laplacian determinism", "[rasters]" ) {
auto a = make_Raster<float>(nonspheroid_icosahedron_grid, {1,2,3,4,5,6,7,8,9,10,11,12});
// auto b = make_Raster<float>(nonspheroid_icosahedron_grid, {1,1,2,3,5,8,13,21,34,55,89,144});
auto out1 = make_Raster<float>(nonspheroid_icosahedron_grid);
auto out2 = make_Raster<float>(nonspheroid_icosahedron_grid);
SECTION("laplacian(grid, a) must generate the same output when called repeatedly"){
CHECK(series::equal(laplacian(a), laplacian(a), 0.1f));
}
}
// TEST_CASE( "laplacian is divergence of gradient", "[rasters]" ) {
// meshes::mesh icosphere_mesh(meshes::icosahedron.vertices, meshes::icosahedron.faces);
// icosphere_mesh = meshes::subdivide(icosphere_mesh); series::normalize(icosphere_mesh.vertices, icosphere_mesh.vertices);
// auto a = make_Raster<float>(icosphere_grid);
// auto grad_a = make_Raster<glm::vec3>(icosphere_grid);
// auto div_grad_a = make_Raster<float>(icosphere_grid);
// auto laplacian_a= make_Raster<float>(icosphere_grid);
// std::mt19937 generator(2);
// series::get_elias_noise(generator, a);
// laplacian (a, laplacian_a);
// grad_a = gradient(a);
// divergence(grad_a, div_grad_a );
// SECTION("laplacian(a) must generate the same output as div(grad(a))"){
// CHECK(series::equal(laplacian_a, div_grad_a));
// }
// } | 48.090692 | 131 | 0.662035 | davidson16807 |
b9a6fb408ab243587d3afc819a8090e899fd7de9 | 2,240 | cpp | C++ | src/Rendering/Vulkan/Objects/Instance/Instance.cpp | Frostie314159/FrostEngine | bb7781c5c90baf77ca836d69d6c38a4a5381e27f | [
"MIT"
] | null | null | null | src/Rendering/Vulkan/Objects/Instance/Instance.cpp | Frostie314159/FrostEngine | bb7781c5c90baf77ca836d69d6c38a4a5381e27f | [
"MIT"
] | null | null | null | src/Rendering/Vulkan/Objects/Instance/Instance.cpp | Frostie314159/FrostEngine | bb7781c5c90baf77ca836d69d6c38a4a5381e27f | [
"MIT"
] | null | null | null | #include "Instance.hpp"
void Instance::createApplicationInfo(Config t_config) {
this->m_appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
this->m_appInfo.pNext = nullptr;
this->m_appInfo.pApplicationName = t_config.getConfigEntry("ApplicationName").value.c_str();
this->m_appInfo.applicationVersion = 0;
this->m_appInfo.pEngineName = "FrostEngine";
this->m_appInfo.engineVersion = 0;
this->m_appInfo.apiVersion = VkVersionChecker::getVulkanVersion();
}
void Instance::createInstanceCreateInfo(Config t_config) {
this->createApplicationInfo(t_config);
this->m_instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
this->m_instanceCreateInfo.pNext = nullptr;
this->m_instanceCreateInfo.flags = 0x0;
this->m_instanceCreateInfo.pApplicationInfo = &this->m_appInfo;
this->m_instanceCreateInfo.enabledLayerCount = static_cast<uint32_t>(this->m_enabledLayers.size());
this->m_instanceCreateInfo.ppEnabledLayerNames = this->m_enabledLayers.data();
this->m_instanceCreateInfo.enabledExtensionCount = static_cast<uint32_t>(this->m_enabledExtensions.size());
this->m_instanceCreateInfo.ppEnabledExtensionNames = this->m_enabledExtensions.data();
}
Instance::Instance(Config t_config) {
createInstance(t_config);
}
Instance::Instance(const Instance&) {
this->m_appInfo = VkApplicationInfo();
}
Instance::Instance() {
}
Instance::~Instance() {
if(!this->m_destroyed)
this->destroy();
}
void Instance::destroy(VkInstance t_instance, VkDevice t_logicalDevice) {
vkDestroyInstance(this->m_instance, nullptr);
this->m_instanceLayers.clear();
this->m_instanceExtensions.clear();
this->m_enabledLayers.clear();
this->m_enabledExtensions.clear();
this->m_destroyed = true;
}
const std::type_info& Instance::getUnderlyingType() {
return typeid(VkInstance);
}
void Instance::createInstance(Config t_engineConfig) {
this->m_instanceLayers = Layer::enumerateLayers();
this->m_instanceExtensions = Extension::enumerateExtensions();
createInstanceCreateInfo(t_engineConfig);
ErrorHandler::handleVulkanErrorCode(vkCreateInstance(&m_instanceCreateInfo, nullptr, &this->m_instance));
}
const VkInstance& Instance::getInstance() {
return this->m_instance;
}
const std::string getObjectName() {
return "Instance";
} | 35.555556 | 108 | 0.791518 | Frostie314159 |
b9ac401f2c25d7c30961a4ec5ccb6f6c4f425f91 | 22,399 | cpp | C++ | src/classes/parameterised.cpp | allison-group/indigox | 22657cb3ceb888049cc231e73d18fb2eac099604 | [
"MIT"
] | 7 | 2019-11-24T15:51:37.000Z | 2021-10-02T05:18:42.000Z | src/classes/parameterised.cpp | allison-group/indigox | 22657cb3ceb888049cc231e73d18fb2eac099604 | [
"MIT"
] | 2 | 2018-12-17T00:55:32.000Z | 2019-10-11T01:47:04.000Z | src/classes/parameterised.cpp | allison-group/indigox | 22657cb3ceb888049cc231e73d18fb2eac099604 | [
"MIT"
] | 2 | 2019-10-21T01:26:56.000Z | 2019-12-02T00:00:42.000Z | #include <indigox/classes/angle.hpp>
#include <indigox/classes/atom.hpp>
#include <indigox/classes/bond.hpp>
#include <indigox/classes/dihedral.hpp>
#include <indigox/classes/forcefield.hpp>
#include <indigox/classes/molecule.hpp>
#include <indigox/classes/parameterised.hpp>
namespace indigox {
// ===========================================================================
// == ParamAtom Data Implementation ==========================================
// ===========================================================================
struct ParamAtom::ParamAtomImpl {
Atom atom;
TypeCounts types;
MappedCharge charges;
bool applied;
double added_charge = 0.;
ParamAtomImpl(const Atom &atm) : atom(atm), applied(false) {}
};
// ===========================================================================
// == ParamAtom Construction/Assignment ======================================
// ===========================================================================
ParamAtom::ParamAtom(const Atom &atm)
: m_data(std::make_shared<ParamAtomImpl>(atm)) {}
// ===========================================================================
// == ParamAtom Data Modification ============================================
// ===========================================================================
void ParamAtom::MappedWith(const Atom &mapped) {
if (m_data->applied) return;
if (!mapped.HasType())
throw std::runtime_error("Needs a parameterised atom");
FFAtom t = mapped.GetType();
auto t_pos = m_data->types.find(t);
if (t_pos == m_data->types.end())
m_data->types.emplace(t, 1);
else
++t_pos->second;
m_data->charges.push_back(mapped.GetPartialCharge());
}
int64_t ParamMolecule::charge_rounding = 0;
bool ParamAtom::ApplyParameterisation(bool self_consistent) {
if (m_data->applied) return false;
if (m_data->charges.empty()) return false;
if (self_consistent) {
if (m_data->types.size() > 1)
throw std::runtime_error("Types not self-consistent");
auto min_max =
std::minmax_element(m_data->charges.begin(), m_data->charges.end());
if ((*min_max.second - *min_max.first) > 1e-10)
throw std::runtime_error("Charges not self-consistent");
}
if (!m_data->atom) throw std::runtime_error("Mapped atom missing");
m_data->atom.SetType(GetMostCommonType());
if (!self_consistent) {
double charge = MeanCharge();
if (ParamMolecule::charge_rounding > 0) {
charge = round(charge * ParamMolecule::charge_rounding) / ParamMolecule::charge_rounding;
}
m_data->atom.SetPartialCharge(charge);
}
else
m_data->atom.SetPartialCharge(MeadianCharge());
m_data->applied = true;
return true;
}
void ParamAtom::AddRedistributedCharge(double amount) {
m_data->atom.SetPartialCharge(m_data->atom.GetPartialCharge() + amount);
m_data->added_charge += amount;
}
// ===========================================================================
// == ParamAtom Data Retrevial ===============================================
// ===========================================================================
int64_t ParamAtom::NumSourceAtoms() const { return m_data->charges.size(); }
const Atom &ParamAtom::GetAtom() const { return m_data->atom; }
double ParamAtom::MeanCharge() const {
return CalculateMean(m_data->charges.begin(), m_data->charges.end());
}
double ParamAtom::MeadianCharge() {
return CalculateMedian(m_data->charges.begin(), m_data->charges.end());
}
double ParamAtom::StandardDeviationCharge() const {
return CalculateStandardDeviation(m_data->charges.begin(),
m_data->charges.end());
}
double ParamAtom::RedistributedChargeAdded() const {
return m_data->added_charge;
}
const FFAtom &ParamAtom::GetMostCommonType() const {
using T = TypeCounts::value_type;
return std::max_element(m_data->types.begin(), m_data->types.end(),
[](T &a, T &b) { return a.second < b.second; })
->first;
}
const ParamAtom::TypeCounts &ParamAtom::GetMappedTypeCounts() const {
return m_data->types;
}
const ParamAtom::MappedCharge &ParamAtom::GetMappedCharges() const {
return m_data->charges;
}
// ===========================================================================
// == ParamAtom Operators ====================================================
// ===========================================================================
bool ParamAtom::operator==(const ParamAtom &atm) const {
return m_data->atom == atm.m_data->atom;
}
bool ParamAtom::operator<(const ParamAtom &atm) const {
return (m_data->atom.GetIndex() < atm.m_data->atom.GetIndex());
}
bool ParamAtom::operator>(const ParamAtom &atm) const {
return (m_data->atom.GetIndex() > atm.m_data->atom.GetIndex());
}
std::ostream &operator<<(std::ostream &os, const ParamAtom &atm) {
if (atm) os << "Param[" << atm.GetAtom() << "]";
return os;
}
// ===========================================================================
// == ParamBond Data Implementation ==========================================
// ===========================================================================
struct ParamBond::ParamBondImpl {
BondAtoms atoms;
Bond bond;
TypeCounts types;
bool applied;
ParamBondImpl(BondAtoms atms, const Bond &bnd)
: atoms(atms), bond(bnd), applied(false) {}
};
// ===========================================================================
// == ParamBond Construction/Assignment ======================================
// ===========================================================================
ParamBond::ParamBond(BondAtoms atms, const Bond &bnd)
: m_data(std::make_shared<ParamBondImpl>(atms, bnd)) {}
// ===========================================================================
// == ParamBond Data Modification ============================================
// ===========================================================================
void ParamBond::MappedWith(const Bond &mapped) {
if (m_data->applied) return;
if (!mapped.HasType())
throw std::runtime_error("Needs a parameterised bond");
FFBond t = mapped.GetType();
FFBond t2 = t.GetLinkedType();
auto t_pos = m_data->types.find(t);
auto t2_pos = m_data->types.find(t2);
auto end = m_data->types.end();
if (t_pos == end && t2_pos == end)
m_data->types.emplace(t, 1);
else if (t2 && t2_pos != end)
++t2_pos->second;
else
++t_pos->second;
}
bool ParamBond::ApplyParameterisation(bool self_consistent) {
if (m_data->applied) return false;
if (m_data->types.empty()) return false;
if (self_consistent && m_data->types.size() > 1)
throw std::runtime_error("Types not self-consistent");
if (!m_data->bond) throw std::runtime_error("Mapped bond missing");
m_data->bond.SetType(GetMostCommonType());
m_data->applied = true;
return true;
}
// ===========================================================================
// == ParamBond Data Retrevial ===============================================
// ===========================================================================
int64_t ParamBond::NumSourceBonds() const {
int64_t count = 0;
for (auto &countable : m_data->types) count += countable.second;
return count;
}
const ParamBond::BondAtoms &ParamBond::GetAtoms() const {
return m_data->atoms;
}
const Bond &ParamBond::GetBond() const { return m_data->bond; }
const FFBond &ParamBond::GetMostCommonType() const {
using T = TypeCounts::value_type;
return std::max_element(m_data->types.begin(), m_data->types.end(),
[](T &a, T &b) { return a.second < b.second; })
->first;
}
const ParamBond::TypeCounts &ParamBond::GetMappedTypeCounts() const {
return m_data->types;
}
// ===========================================================================
// == ParamBond Operators ====================================================
// ===========================================================================
bool ParamBond::operator==(const ParamBond &bnd) const {
return m_data->bond == bnd.m_data->bond;
}
bool ParamBond::operator<(const ParamBond &bnd) const {
return (m_data->bond.GetIndex() < bnd.m_data->bond.GetIndex());
}
bool ParamBond::operator>(const ParamBond &bnd) const {
return (m_data->bond.GetIndex() > bnd.m_data->bond.GetIndex());
}
std::ostream &operator<<(std::ostream &os, const ParamBond &bnd) {
if (bnd) os << "Param[" << bnd.GetBond() << "]";
return os;
}
// ===========================================================================
// == ParamAngle Data Implementation =========================================
// ===========================================================================
struct ParamAngle::ParamAngleImpl {
AngleAtoms atoms;
Angle angle;
TypeCounts types;
bool applied;
ParamAngleImpl(AngleAtoms atms, const Angle &ang)
: atoms(atms), angle(ang), applied(false) {}
};
// ===========================================================================
// == ParamAngle Construction/Assignment =====================================
// ===========================================================================
ParamAngle::ParamAngle(AngleAtoms atms, const Angle &ang)
: m_data(std::make_shared<ParamAngleImpl>(atms, ang)) {}
// ===========================================================================
// == ParamAngle Data Modification ===========================================
// ===========================================================================
void ParamAngle::MappedWith(const Angle &mapped) {
if (m_data->applied) return;
if (!mapped.HasType())
throw std::runtime_error("Needs a parameterised angle");
FFAngle t = mapped.GetType();
FFAngle t2 = t.GetLinkedType();
auto t_pos = m_data->types.find(t);
auto t2_pos = m_data->types.find(t2);
auto end = m_data->types.end();
if (t_pos == end && t2_pos == end)
m_data->types.emplace(t, 1);
else if (t2 && t2_pos != end)
++t2_pos->second;
else
++t_pos->second;
}
bool ParamAngle::ApplyParameterisation(bool self_consistent) {
if (m_data->types.empty()) return false;
if (m_data->applied) return false;
if (self_consistent && m_data->types.size() > 1)
throw std::runtime_error("Types not self-consistent");
if (!m_data->angle) throw std::runtime_error("Mapped angle missing");
m_data->angle.SetType(GetMostCommonType());
m_data->applied = true;
return true;
}
// ===========================================================================
// == ParamAngle Data Retrevial ==============================================
// ===========================================================================
int64_t ParamAngle::NumSourceAngles() const {
int64_t count = 0;
for (auto &countable : m_data->types) count += countable.second;
return count;
}
const ParamAngle::AngleAtoms &ParamAngle::GetAtoms() const {
return m_data->atoms;
}
const Angle &ParamAngle::GetAngle() const { return m_data->angle; }
const FFAngle &ParamAngle::GetMostCommonType() const {
using T = TypeCounts::value_type;
return std::max_element(m_data->types.begin(), m_data->types.end(),
[](T &a, T &b) { return a.second < b.second; })
->first;
}
const ParamAngle::TypeCounts &ParamAngle::GetMappedTypeCounts() const {
return m_data->types;
}
// ===========================================================================
// == ParamAngle Operators ===================================================
// ===========================================================================
bool ParamAngle::operator==(const ParamAngle &ang) const {
return m_data->angle == ang.m_data->angle;
}
bool ParamAngle::operator<(const ParamAngle &ang) const {
return (m_data->angle.GetIndex() < ang.m_data->angle.GetIndex());
}
bool ParamAngle::operator>(const ParamAngle &ang) const {
return (m_data->angle.GetIndex() > ang.m_data->angle.GetIndex());
}
std::ostream &operator<<(std::ostream &os, const ParamAngle &ang) {
if (ang) os << "Param[" << ang.GetAngle() << "]";
return os;
}
// ===========================================================================
// == ParamDihedral Data Implementation ======================================
// ===========================================================================
struct ParamDihedral::ParamDihedralImpl {
DihedralAtoms atoms;
Dihedral dihedral;
TypeCounts types;
bool applied;
ParamDihedralImpl(DihedralAtoms atms, const Dihedral &dhd)
: atoms(atms), dihedral(dhd), applied(false) {}
};
// ===========================================================================
// == ParamDihedral Construction/Assignment ==================================
// ===========================================================================
ParamDihedral::ParamDihedral(DihedralAtoms atms, const Dihedral &dhd)
: m_data(std::make_shared<ParamDihedralImpl>(atms, dhd)) {}
// ===========================================================================
// == ParamDihedral Data Modification ========================================
// ===========================================================================
void ParamDihedral::MappedWith(const Dihedral &mapped) {
if (m_data->applied) return;
// Can't throw with dihedrals as they can have no types assigned
if (!mapped.HasType()) return;
// Only map with same priority dihedrals.
// To avoid GROMOS duplication in eg NH3 group.
if (mapped.GetPriority() >= 0 &&
mapped.GetPriority() != m_data->dihedral.GetPriority())
return;
TypeGroup t = mapped.GetTypes();
auto t_pos = m_data->types.emplace(t, 1);
if (!t_pos.second) ++(t_pos.first->second);
}
bool ParamDihedral::ApplyParameterisation(bool self_consistent) {
if (m_data->types.empty()) return false;
if (m_data->applied) return false;
if (self_consistent && m_data->types.size() > 1)
throw std::runtime_error("Types not self-consistent");
if (!m_data->dihedral) throw std::runtime_error("Mapped dihedral missing");
m_data->dihedral.SetTypes(GetMostCommonType());
m_data->applied = true;
return true;
}
// ===========================================================================
// == ParamDihedral Data Retrevial ===========================================
// ===========================================================================
int64_t ParamDihedral::NumSourceDihedral() const {
int64_t count = 0;
for (auto &countable : m_data->types) count += countable.second;
return count;
}
const ParamDihedral::DihedralAtoms &ParamDihedral::GetAtoms() const {
return m_data->atoms;
}
const Dihedral &ParamDihedral::GetDihedral() const {
return m_data->dihedral;
}
const ParamDihedral::TypeGroup &ParamDihedral::GetMostCommonType() const {
using T = TypeCounts::value_type;
return std::max_element(m_data->types.begin(), m_data->types.end(),
[](T &a, T &b) { return a.second < b.second; })
->first;
}
const ParamDihedral::TypeCounts &ParamDihedral::GetMappedTypeCounts() const {
return m_data->types;
}
// ===========================================================================
// == ParamDihedral Operators ================================================
// ===========================================================================
bool ParamDihedral::operator==(const ParamDihedral &ang) const {
return m_data->dihedral == ang.m_data->dihedral;
}
bool ParamDihedral::operator<(const ParamDihedral &ang) const {
return (m_data->dihedral.GetIndex() < ang.m_data->dihedral.GetIndex());
}
bool ParamDihedral::operator>(const ParamDihedral &ang) const {
return (m_data->dihedral.GetIndex() > ang.m_data->dihedral.GetIndex());
}
std::ostream &operator<<(std::ostream &os, const ParamDihedral &ang) {
if (ang) os << "Param[" << ang.GetDihedral() << "]";
return os;
}
// ===========================================================================
// == ParamMolecule Data Implementation ======================================
// ===========================================================================
struct ParamMolecule::ParamMoleculeImpl {
Molecule mol;
std::vector<ParamAtom> atoms;
std::vector<ParamBond> bonds;
std::vector<ParamAngle> angles;
std::vector<ParamDihedral> dihedrals;
ParamAtoms atom_indices;
ParamBonds bond_indices;
ParamAngles angle_indices;
ParamDihedrals dihedral_indices;
std::vector<ParamAtom> nonsc_atoms;
explicit ParamMoleculeImpl(const Molecule &m) : mol(m) {
for (const Atom &atm : mol.GetAtoms()) {
atoms.emplace_back(atm);
atom_indices.emplace(atm, atom_indices.size());
}
for (const Bond &bnd : mol.GetBonds()) {
Atom a = bnd.GetAtoms()[0];
Atom b = bnd.GetAtoms()[1];
if (a > b) { std::swap(a, b); }
bonds.emplace_back(std::make_pair(a, b), bnd);
bond_indices.emplace(std::make_pair(a, b), bond_indices.size());
}
for (const Angle &ang : mol.GetAngles()) {
Atom a = ang.GetAtoms()[0];
Atom b = ang.GetAtoms()[1];
Atom c = ang.GetAtoms()[2];
if (a > c) { std::swap(a, c); }
angles.emplace_back(stdx::make_triple(a, b, c), ang);
angle_indices.emplace(stdx::make_triple(a, b, c), angle_indices.size());
}
for (const Dihedral &dhd : mol.GetDihedrals()) {
Atom a = dhd.GetAtoms()[0];
Atom b = dhd.GetAtoms()[1];
Atom c = dhd.GetAtoms()[2];
Atom d = dhd.GetAtoms()[3];
if (a > d) {
std::swap(a, d);
std::swap(b, c);
}
dihedrals.emplace_back(stdx::make_quad(a, b, c, d), dhd);
dihedral_indices.emplace(stdx::make_quad(a, b, c, d),
dihedral_indices.size());
}
}
};
// ===========================================================================
// == ParamMolecule Construction/Assignment ==================================
// ===========================================================================
ParamMolecule::ParamMolecule(const Molecule &mol)
: m_data(std::make_shared<ParamMoleculeImpl>(mol)) {}
// ===========================================================================
// == ParamMolecule Data Modification ========================================
// ===========================================================================
void ParamMolecule::ApplyParameteristion(bool sc) {
for (ParamAtom atm : m_data->atoms) {
bool param = atm.ApplyParameterisation(sc);
if (!sc && param) m_data->nonsc_atoms.emplace_back(atm);
}
for (ParamBond bnd : m_data->bonds) bnd.ApplyParameterisation(sc);
for (ParamAngle ang : m_data->angles) ang.ApplyParameterisation(sc);
for (ParamDihedral dhd : m_data->dihedrals) dhd.ApplyParameterisation(sc);
}
// ===========================================================================
// == ParamMolecule Data Retrieval ===========================================
// ===========================================================================
const ParamAtom &ParamMolecule::GetAtom(const Atom &atm) const {
return m_data->atoms[m_data->atom_indices.find(atm)->second];
}
const ParamBond &ParamMolecule::GetBond(const Bond &bnd) const {
return GetBond(bnd.GetAtoms()[0], bnd.GetAtoms()[1]);
}
const ParamBond &ParamMolecule::GetBond(const Atom &a, const Atom &b) const {
PBond dat = (a > b) ? std::make_pair(b, a) : std::make_pair(a, b);
return m_data->bonds[m_data->bond_indices.find(dat)->second];
}
const ParamAngle &ParamMolecule::GetAngle(const Angle &ang) const {
return GetAngle(ang.GetAtoms()[0], ang.GetAtoms()[1], ang.GetAtoms()[2]);
}
const ParamAngle &ParamMolecule::GetAngle(const Atom &a, const Atom &b,
const Atom &c) const {
PAngle dat =
(a > c) ? stdx::make_triple(c, b, a) : stdx::make_triple(a, b, c);
return m_data->angles[m_data->angle_indices.find(dat)->second];
}
const ParamDihedral &ParamMolecule::GetDihedral(const Dihedral &dhd) {
return GetDihedral(dhd.GetAtoms()[0], dhd.GetAtoms()[1], dhd.GetAtoms()[2],
dhd.GetAtoms()[3]);
}
const ParamDihedral &ParamMolecule::GetDihedral(const Atom &a, const Atom &b,
const Atom &c,
const Atom &d) {
PDihedral dat =
(a > d) ? stdx::make_quad(d, c, b, a) : stdx::make_quad(a, b, c, d);
auto pos = m_data->dihedral_indices.find(dat);
if (pos != m_data->dihedral_indices.end())
return m_data->dihedrals[pos->second];
Dihedral newD = m_data->mol.NewDihedral(a, b, c, d);
m_data->dihedrals.emplace_back(dat, newD);
m_data->dihedral_indices.emplace(dat, m_data->dihedral_indices.size());
return m_data->dihedrals.back();
}
const std::vector<ParamAtom> &ParamMolecule::GetAtoms() const {
return m_data->atoms;
}
const std::vector<ParamBond> &ParamMolecule::GetBonds() const {
return m_data->bonds;
}
const std::vector<ParamAngle> &ParamMolecule::GetAngles() const {
return m_data->angles;
}
const std::vector<ParamDihedral> &ParamMolecule::GetDihedrals() const {
return m_data->dihedrals;
}
const std::vector<ParamAtom>& ParamMolecule::GetChargeAddableAtoms() const {
return m_data->nonsc_atoms;
}
// ===========================================================================
// == ParamMolecule Operators ================================================
// ===========================================================================
} // namespace indigox
| 38.552496 | 97 | 0.498951 | allison-group |
b9af7ebf77969a0940361311bcdb56ce457a11e2 | 3,190 | hpp | C++ | climate-change/src/VS-Project/Libraries/godot-cpp-bindings/include/gen/OptionButton.hpp | jerry871002/CSE201-project | c42cc0e51d0c8367e4d06fc33756ab2ec4118ff4 | [
"MIT"
] | 5 | 2021-05-27T21:50:33.000Z | 2022-01-28T11:54:32.000Z | climate-change/src/VS-Project/Libraries/godot-cpp-bindings/include/gen/OptionButton.hpp | jerry871002/CSE201-project | c42cc0e51d0c8367e4d06fc33756ab2ec4118ff4 | [
"MIT"
] | null | null | null | climate-change/src/VS-Project/Libraries/godot-cpp-bindings/include/gen/OptionButton.hpp | jerry871002/CSE201-project | c42cc0e51d0c8367e4d06fc33756ab2ec4118ff4 | [
"MIT"
] | 1 | 2021-01-04T21:12:05.000Z | 2021-01-04T21:12:05.000Z | #ifndef GODOT_CPP_OPTIONBUTTON_HPP
#define GODOT_CPP_OPTIONBUTTON_HPP
#include <gdnative_api_struct.gen.h>
#include <stdint.h>
#include <core/CoreTypes.hpp>
#include <core/Ref.hpp>
#include "Button.hpp"
namespace godot {
class Texture;
class PopupMenu;
class OptionButton : public Button {
struct ___method_bindings {
godot_method_bind *mb__focused;
godot_method_bind *mb__get_items;
godot_method_bind *mb__select_int;
godot_method_bind *mb__selected;
godot_method_bind *mb__set_items;
godot_method_bind *mb_add_icon_item;
godot_method_bind *mb_add_item;
godot_method_bind *mb_add_separator;
godot_method_bind *mb_clear;
godot_method_bind *mb_get_item_count;
godot_method_bind *mb_get_item_icon;
godot_method_bind *mb_get_item_id;
godot_method_bind *mb_get_item_index;
godot_method_bind *mb_get_item_metadata;
godot_method_bind *mb_get_item_text;
godot_method_bind *mb_get_popup;
godot_method_bind *mb_get_selected;
godot_method_bind *mb_get_selected_id;
godot_method_bind *mb_get_selected_metadata;
godot_method_bind *mb_is_item_disabled;
godot_method_bind *mb_remove_item;
godot_method_bind *mb_select;
godot_method_bind *mb_set_item_disabled;
godot_method_bind *mb_set_item_icon;
godot_method_bind *mb_set_item_id;
godot_method_bind *mb_set_item_metadata;
godot_method_bind *mb_set_item_text;
};
static ___method_bindings ___mb;
static void *_detail_class_tag;
public:
static void ___init_method_bindings();
inline static size_t ___get_id() { return (size_t)_detail_class_tag; }
static inline const char *___get_class_name() { return (const char *) "OptionButton"; }
static inline Object *___get_from_variant(Variant a) { godot_object *o = (godot_object*) a; return (o) ? (Object *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, o) : nullptr; }
// enums
// constants
static OptionButton *_new();
// methods
void _focused(const int64_t arg0);
Array _get_items() const;
void _select_int(const int64_t arg0);
void _selected(const int64_t arg0);
void _set_items(const Array arg0);
void add_icon_item(const Ref<Texture> texture, const String label, const int64_t id = -1);
void add_item(const String label, const int64_t id = -1);
void add_separator();
void clear();
int64_t get_item_count() const;
Ref<Texture> get_item_icon(const int64_t idx) const;
int64_t get_item_id(const int64_t idx) const;
int64_t get_item_index(const int64_t id) const;
Variant get_item_metadata(const int64_t idx) const;
String get_item_text(const int64_t idx) const;
PopupMenu *get_popup() const;
int64_t get_selected() const;
int64_t get_selected_id() const;
Variant get_selected_metadata() const;
bool is_item_disabled(const int64_t idx) const;
void remove_item(const int64_t idx);
void select(const int64_t idx);
void set_item_disabled(const int64_t idx, const bool disabled);
void set_item_icon(const int64_t idx, const Ref<Texture> texture);
void set_item_id(const int64_t idx, const int64_t id);
void set_item_metadata(const int64_t idx, const Variant metadata);
void set_item_text(const int64_t idx, const String text);
};
}
#endif | 32.886598 | 245 | 0.798119 | jerry871002 |
b9b0d9a7302bf9c5304848f4461f56a89ecad02b | 317 | cpp | C++ | System/rootCommand.cpp | aaly/MPF | c07b28a8b110e404ceb599eb8c40df71e6daa85f | [
"BSD-3-Clause"
] | null | null | null | System/rootCommand.cpp | aaly/MPF | c07b28a8b110e404ceb599eb8c40df71e6daa85f | [
"BSD-3-Clause"
] | null | null | null | System/rootCommand.cpp | aaly/MPF | c07b28a8b110e404ceb599eb8c40df71e6daa85f | [
"BSD-3-Clause"
] | null | null | null | /******************************************************
* copyright 2011, 2012, 2013 AbdAllah Aly Saad , aaly90[@]gmail.com
* Part of Mesk Page Framework (MPF)
******************************************************/
#include "rootCommand.hpp"
Shell::Shell(QObject *parent, QString rootpw) :
QObject(parent)
{
}
| 26.416667 | 67 | 0.460568 | aaly |
b9b61fc225e18060beca4427373b944a981b3474 | 1,433 | cpp | C++ | options/glibc/generic/stdio_ext-stubs.cpp | Dennisbonke/mlibc | 4ac29d952e27f8aefc6def6dfcd113c427eeb391 | [
"MIT"
] | 480 | 2018-06-02T06:50:12.000Z | 2022-03-31T11:38:56.000Z | options/glibc/generic/stdio_ext-stubs.cpp | Dennisbonke/mlibc | 4ac29d952e27f8aefc6def6dfcd113c427eeb391 | [
"MIT"
] | 227 | 2018-12-23T17:07:38.000Z | 2022-03-30T22:49:11.000Z | options/glibc/generic/stdio_ext-stubs.cpp | Dennisbonke/mlibc | 4ac29d952e27f8aefc6def6dfcd113c427eeb391 | [
"MIT"
] | 99 | 2018-06-02T16:19:27.000Z | 2022-03-26T02:08:12.000Z |
#include <stdio_ext.h>
#include <bits/ensure.h>
#include <mlibc/debug.hpp>
size_t __fbufsize(FILE *) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
size_t __fpending(FILE *file_base) {
__ensure(file_base->__dirty_end >= file_base->__dirty_begin);
return file_base->__dirty_end - file_base->__dirty_begin;
}
int __flbf(FILE *) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
int __freadable(FILE *) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
int __fwritable(FILE *) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
int __freading(FILE *file_base) {
return file_base->__io_mode == 0;
}
int __fwriting(FILE *file_base) {
return file_base->__io_mode == 1;
}
int __fsetlocking(FILE *, int) {
mlibc::infoLogger() << "mlibc: __fsetlocking() is a no-op" << frg::endlog;
return FSETLOCKING_INTERNAL;
}
void _flushlbf(void) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
// The following functions are defined by musl.
size_t __freadahead(FILE *file_base) {
if(file_base->__io_mode != 0) {
mlibc::infoLogger() << "mlibc: __freadahead() called but file is not open for reading" << frg::endlog;
return 0;
}
return file_base->__valid_limit - file_base->__offset;
}
const char *__freadptr(FILE *, size_t *) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
void __fseterr(FILE *) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
| 22.046154 | 104 | 0.718074 | Dennisbonke |
b9b733c59d3a981467040dbdbfb3f438c53e673d | 3,210 | cpp | C++ | jobs/source/JobStatus.cpp | gregbreen/aws-iot-device-sdk-cpp-v2 | 57ded0046d1cda3b35fbe9298eed308392961435 | [
"Apache-2.0"
] | 88 | 2019-11-29T19:30:29.000Z | 2022-03-28T02:29:51.000Z | jobs/source/JobStatus.cpp | gregbreen/aws-iot-device-sdk-cpp-v2 | 57ded0046d1cda3b35fbe9298eed308392961435 | [
"Apache-2.0"
] | 194 | 2019-12-01T15:54:42.000Z | 2022-03-31T22:06:11.000Z | jobs/source/JobStatus.cpp | gregbreen/aws-iot-device-sdk-cpp-v2 | 57ded0046d1cda3b35fbe9298eed308392961435 | [
"Apache-2.0"
] | 64 | 2019-12-17T14:13:40.000Z | 2022-03-12T07:43:13.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/iotjobs/JobStatus.h>
#include <aws/crt/StlAllocator.h>
#include <aws/crt/StringUtils.h>
#include <assert.h>
static const size_t QUEUED_HASH = Aws::Crt::HashString("QUEUED");
static const size_t IN_PROGRESS_HASH = Aws::Crt::HashString("IN_PROGRESS");
static const size_t TIMED_OUT_HASH = Aws::Crt::HashString("TIMED_OUT");
static const size_t FAILED_HASH = Aws::Crt::HashString("FAILED");
static const size_t SUCCEEDED_HASH = Aws::Crt::HashString("SUCCEEDED");
static const size_t CANCELED_HASH = Aws::Crt::HashString("CANCELED");
static const size_t REJECTED_HASH = Aws::Crt::HashString("REJECTED");
static const size_t REMOVED_HASH = Aws::Crt::HashString("REMOVED");
namespace Aws
{
namespace Iotjobs
{
namespace JobStatusMarshaller
{
const char *ToString(JobStatus status)
{
switch (status)
{
case JobStatus::QUEUED:
return "QUEUED";
case JobStatus::IN_PROGRESS:
return "IN_PROGRESS";
case JobStatus::TIMED_OUT:
return "TIMED_OUT";
case JobStatus::FAILED:
return "FAILED";
case JobStatus::SUCCEEDED:
return "SUCCEEDED";
case JobStatus::CANCELED:
return "CANCELED";
case JobStatus::REJECTED:
return "REJECTED";
case JobStatus::REMOVED:
return "REMOVED";
default:
assert(0);
return "UNKNOWN_VALUE";
}
}
JobStatus FromString(const Crt::String &str)
{
size_t hash = Crt::HashString(str.c_str());
if (hash == QUEUED_HASH)
{
return JobStatus::QUEUED;
}
if (hash == IN_PROGRESS_HASH)
{
return JobStatus::IN_PROGRESS;
}
if (hash == TIMED_OUT_HASH)
{
return JobStatus::TIMED_OUT;
}
if (hash == FAILED_HASH)
{
return JobStatus::FAILED;
}
if (hash == SUCCEEDED_HASH)
{
return JobStatus::SUCCEEDED;
}
if (hash == CANCELED_HASH)
{
return JobStatus::CANCELED;
}
if (hash == REJECTED_HASH)
{
return JobStatus::REJECTED;
}
if (hash == REMOVED_HASH)
{
return JobStatus::REMOVED;
}
assert(0);
return static_cast<JobStatus>(-1);
}
} // namespace JobStatusMarshaller
} // namespace Iotjobs
} // namespace Aws
| 30.865385 | 75 | 0.471028 | gregbreen |
b9b9c9eefbfc15a990acd5caa5bc9b4c5d507a79 | 11,089 | cc | C++ | tools/macpo/inst/inst.cc | roystgnr/perfexpert | a03b13db9ac83e992e1c5cc3b6e45e52c266fe30 | [
"BSD-4-Clause-UC"
] | 28 | 2015-05-05T15:54:25.000Z | 2021-09-27T16:23:36.000Z | tools/macpo/inst/inst.cc | roystgnr/perfexpert | a03b13db9ac83e992e1c5cc3b6e45e52c266fe30 | [
"BSD-4-Clause-UC"
] | 15 | 2015-10-07T20:52:05.000Z | 2018-04-18T16:08:41.000Z | tools/macpo/inst/inst.cc | roystgnr/perfexpert | a03b13db9ac83e992e1c5cc3b6e45e52c266fe30 | [
"BSD-4-Clause-UC"
] | 11 | 2015-01-23T15:41:40.000Z | 2020-08-18T03:53:19.000Z | /*
* Copyright (c) 2011-2013 University of Texas at Austin. All rights reserved.
*
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* This file is part of PerfExpert.
*
* PerfExpert is free software: you can redistribute it and/or modify it under
* the terms of the The University of Texas at Austin Research License
*
* PerfExpert 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.
*
* Authors: Leonardo Fialho and Ashay Rane
*
* $HEADER$
*/
#include <cstdio>
#include <string>
#include "libmacpo.h"
#include "generic_defs.h"
bool parse_location(const std::string& argument, location_t& location) {
const std::string str_argument = argument;
// Initialize
size_t pos = 0;
location.function_name = "";
location.line_number = 0;
do {
// Find the separating ':' character.
pos = str_argument.find(":", pos);
// We couldn't find a line number component.
if (pos == std::string::npos) {
location.function_name = str_argument;
break;
}
// We did find a line number component.
// Make sure that this ':' isn't a part of the '::',
// which is the separator between the class name and the method name.
if (pos < str_argument.length() - 1 && isdigit(str_argument[pos+1])) {
location.function_name = str_argument.substr(0, pos);
location.line_number = atoi(str_argument.substr(pos+1).c_str());
break;
} else {
// Push pos by one character so that we keep making progress.
pos += 1;
}
} while (true);
return true;
}
int parse_argument(char* arg, macpo_options_t& macpo_options) {
std::string argument = arg, option, value;
if (argument.compare(0, 8, "--macpo:") != 0)
return -1;
size_t start_position = -1, end_position;
if ((start_position = argument.find(":")) == std::string::npos)
return -1;
end_position = argument.find("=", start_position + 1);
if (end_position == std::string::npos) {
option = argument.substr(start_position + 1);
value = "";
} else {
option = argument.substr(start_position + 1,
end_position - start_position - 1);
value = argument.substr(end_position + 1);
}
location_t location;
if (option == "instrument") {
if (!value.size())
return -1;
name_list_t list;
split(value, ',', list);
for (name_list_t::iterator it = list.begin(); it != list.end(); it++) {
if ((*it).empty()) {
continue; //In case there's a problem with the location
}
parse_location(*it, location);
void* alloc = malloc(sizeof(char) * location.function_name.size() + 1);
char* name = reinterpret_cast<char*>(alloc);
snprintf(name, location.function_name.size() + 1, "%s",
location.function_name.c_str());
instrument_block(&macpo_options, ACTION_INSTRUMENT, name,
location.line_number);
}
} else if (option == "check-alignment") {
if (!value.size())
return -1;
name_list_t list;
split(value, ',', list);
for (name_list_t::iterator it = list.begin(); it != list.end() ; it++) {
parse_location(*it, location);
if ((*it).empty()) {
continue;
}
void* alloc = malloc(sizeof(char) * location.function_name.size() + 1);
char* name = reinterpret_cast<char*>(alloc);
snprintf(name, location.function_name.size() + 1, "%s",
location.function_name.c_str());
instrument_block(&macpo_options, ACTION_ALIGNCHECK, name,
location.line_number);
}
} else if (option == "record-tripcount") {
if (!value.size())
return -1;
name_list_t list;
split(value, ',', list);
for (name_list_t::iterator it = list.begin(); it != list.end() ; it++) {
if ((*it).empty()) {
continue;
}
parse_location(*it, location);
void* alloc = malloc(sizeof(char) * location.function_name.size() + 1);
char* name = reinterpret_cast<char*>(alloc);
snprintf(name, location.function_name.size() + 1, "%s",
location.function_name.c_str());
instrument_block(&macpo_options, ACTION_TRIPCOUNT, name,
location.line_number);
}
} else if (option == "record-branchpath") {
if (!value.size())
return -1;
name_list_t list;
split(value, ',', list);
for (name_list_t::iterator it = list.begin(); it != list.end(); it++) {
if ((*it).empty()) {
continue;
}
parse_location(*it, location);
void* alloc = malloc(sizeof(char) * location.function_name.size() + 1);
char* name = reinterpret_cast<char*>(alloc);
snprintf(name, location.function_name.size() + 1, "%s",
location.function_name.c_str());
instrument_block(&macpo_options, ACTION_BRANCHPATH, name,
location.line_number);
}
} else if (option == "gen-trace") {
if (!value.size())
return -1;
parse_location(value, location);
void* alloc = malloc(sizeof(char) * location.function_name.size() + 1);
char* name = reinterpret_cast<char*>(alloc);
snprintf(name, location.function_name.size() + 1, "%s",
location.function_name.c_str());
instrument_block(&macpo_options, ACTION_GENTRACE, name,
location.line_number);
} else if (option == "vector-strides") {
if (!value.size())
return -1;
name_list_t list;
split(value, ',', list);
for (name_list_t::iterator it = list.begin(); it != list.end(); it++) {
if ((*it).empty()) {
continue;
}
parse_location(*it, location);
void* alloc = malloc(sizeof(char) * location.function_name.size() + 1);
char* name = reinterpret_cast<char*>(alloc);
snprintf(name, location.function_name.size() + 1, "%s",
location.function_name.c_str());
instrument_block(&macpo_options, ACTION_VECTORSTRIDES, name,
location.line_number);
}
} else if (option == "overlap-check") {
if (!value.size())
return -1;
name_list_t list;
split(value, ',', list);
for (name_list_t::iterator it = list.begin(); it != list.end(); it++) {
if ((*it).empty()){
continue;
}
parse_location(*it, location);
void* alloc = malloc(sizeof(char) * location.function_name.size() + 1);
char* name = reinterpret_cast<char*>(alloc);
snprintf(name, location.function_name.size() + 1, "%s",
location.function_name.c_str());
instrument_block(&macpo_options, ACTION_OVERLAPCHECK, name,
location.line_number);
}
} else if (option == "stride-check") {
if (!value.size())
return -1;
name_list_t list;
split(value, ',', list);
for (name_list_t::iterator it = list.begin(); it != list.end(); it++) {
if ((*it).empty()){
continue;
}
parse_location(*it, location);
void* alloc = malloc(sizeof(char) * location.function_name.size() + 1);
char* name = reinterpret_cast<char*>(alloc);
snprintf(name, location.function_name.size() + 1, "%s",
location.function_name.c_str());
instrument_block(&macpo_options, ACTION_STRIDECHECK, name,
location.line_number);
}
} else if (option == "reuse-distance") {
if (!value.size())
return -1;
name_list_t list;
split(value, ',', list);
for (name_list_t::iterator it = list.begin(); it != list.end(); it++) {
if ((*it).empty()){
continue;
}
parse_location(*it, location);
void* alloc = malloc(sizeof(char) * location.function_name.size() + 1);
char* name = reinterpret_cast<char*>(alloc);
snprintf(name, location.function_name.size() + 1, "%s",
location.function_name.c_str());
instrument_block(&macpo_options, ACTION_REUSEDISTANCE, name,
location.line_number);
}
} else if (option == "backup-filename") {
if (!value.size())
return -1;
void* alloc = malloc(sizeof(char) * value.size() + 1);
char* name = reinterpret_cast<char*>(alloc);
snprintf(name, value.size() + 1, "%s", value.c_str());
macpo_options.backup_filename = name;
} else if (option == "no-compile") {
set_no_compile_flag(&macpo_options, 1);
} else if (option == "enable-sampling") {
set_disable_sampling_flag(&macpo_options, 0);
} else if (option == "disable-sampling") {
set_disable_sampling_flag(&macpo_options, 1);
} else if (option == "profile-analysis") {
set_profiling_flag(&macpo_options, 1);
} else if (option == "compiler") {
// Check if we were passed a valid executable.
if (!value.size()) {
return -1;
}
void* alloc = malloc(sizeof(char) * value.size() + 1);
char* name = reinterpret_cast<char*>(alloc);
snprintf(name, value.size() + 1, "%s", value.c_str());
macpo_options.base_compiler = name;
} else if (option == "dynamic_inst") {
set_dynamic_instrumentation_flag(&macpo_options, 1);
} else {
return -1;
}
return 0;
}
int main(int argc, char* argv[]) {
name_list_t arguments;
arguments.push_back(argv[0]);
macpo_options_t macpo_options={0};
for (int i = 1; i < argc; i++) {
// Check if argv[i] starts with "--macpo:".
if (strstr(argv[i], "--macpo:") == argv[i]) {
if (parse_argument(argv[i], macpo_options) < 0) {
fprintf(stdout, "Unknown parameter: %s, aborting...\n",
argv[i]);
return -1;
}
} else {
arguments.push_back(argv[i]);
}
}
// Convert the arguments vector back into char* for libmacpo functions.
uint32_t size = arguments.size();
const char** args = new const char*[size];
for (int i = 0; i < size; i++) {
args[i] = arguments[i].c_str();
}
int ret = instrument(&macpo_options, args, arguments.size());
destroy_options(&macpo_options);
delete args;
args = NULL;
return ret;
}
| 36.238562 | 83 | 0.548471 | roystgnr |
b9c688aaab8180eb7fad841d6d9e25fd3ecc0ee3 | 7,182 | cpp | C++ | CmnIP/module/codify/src/codify_data.cpp | Khoronus/CmnUniverse | 9cf9b4297f2fcb49330126aa1047b422144045e1 | [
"MIT"
] | null | null | null | CmnIP/module/codify/src/codify_data.cpp | Khoronus/CmnUniverse | 9cf9b4297f2fcb49330126aa1047b422144045e1 | [
"MIT"
] | null | null | null | CmnIP/module/codify/src/codify_data.cpp | Khoronus/CmnUniverse | 9cf9b4297f2fcb49330126aa1047b422144045e1 | [
"MIT"
] | null | null | null | /**
* @file codify_data.cpp
* @brief Body of the classes of the header file.
*
* @section LICENSE
*
* 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 AUTHOR/AUTHORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Alessandro Moro <alessandromoro.italy@gmail.com>
* @bug No known bugs.
* @version 1.0.0.0
*
*/
#include "codify/inc/codify/codify_data.hpp"
namespace CmnIP
{
namespace codify
{
//-----------------------------------------------------------------------------
int CodifyData2Image::data2image(cv::Mat &image, const char *data, int length,
int index_start, int &index_end)
{
if (index_start < 0) return 0;
int s = length;
int cn = image.channels();
index_end = index_start + s + 4;
int max_size = image.cols * image.rows * image.channels();
if (index_start >= max_size) return 0;
if (index_end >= max_size) return 0;
memcpy((image.data + index_start), &s, 4);
memcpy((image.data + index_start + 4), data, s);
return 1;
}
//-----------------------------------------------------------------------------
int CodifyData2Image::image2message(const cv::Mat &image, int index_start,
int &index_end, char *data, int length)
{
if (index_start < 0) return 0;
// convert the image to string
int s = 0;
memcpy(&s, (image.data + index_start), 4);
int max_size = image.cols * image.rows * image.channels();
if (index_start + 4 + s >= max_size) {
index_end = 0;
return 0;
}
if (length > s + 1) {
memcpy(data, (image.data + index_start + 4), s);
data[s] = '\0';
index_end = index_start + s + 4;
}
return 1;
}
//-----------------------------------------------------------------------------
int CodifyData2Image::message2image(cv::Mat &image, const std::string &message,
int index_start, int &index_end)
{
if (index_start < 0) return 0;
int s = message.length();
int cn = image.channels();
index_end = index_start + s + 4;
int max_size = image.cols * image.rows * image.channels();
if (index_start >= max_size) return 0;
if (index_end >= max_size) return 0;
memcpy((image.data + index_start), &s, 4);
memcpy((image.data + index_start + 4), message.c_str(), s);
return 1;
}
//-----------------------------------------------------------------------------
int CodifyData2Image::image2message(const cv::Mat &image, int index_start,
int &index_end, std::string &msg)
{
if (index_start < 0) return 0;
// convert the image to string
int s = 0;
memcpy(&s, (image.data + index_start), 4);
int max_size = image.cols * image.rows * image.channels();
if (index_start + 4 + s >= max_size) {
index_end = 0;
return 0;
}
#if _MSC_VER && !__INTEL_COMPILER && (_MSC_VER > 1600)
std::unique_ptr<char[]> buf(new char[s + 1]);
memcpy(buf.get(), (image.data + index_start + 4), s);
buf[s] = '\0';
msg = buf.get();
#else
char *buf = new char[s + 1];
memcpy(buf, (image.data + index_start + 4), s);
buf[s] = '\0';
msg = buf;
delete buf; buf = NULL;
#endif
index_end = index_start + s + 4;
return 1;
}
//-----------------------------------------------------------------------------
void CodifyData2Image::message2image(cv::Mat &image,
const std::vector< std::string > &msg, int x, int y)
{
int cn = image.channels();
int index = y * image.cols * cn + x * cn; // +0 B, + 1 G, +2 R
int index_start = index + 4;
#if _MSC_VER && !__INTEL_COMPILER && (_MSC_VER > 1600)
for (auto it = msg.begin(); it != msg.end(); it++)
#else
for (std::vector< std::string >::const_iterator it = msg.begin(); it != msg.end(); it++)
#endif
{
int index_end = 0;
if (!data2image(image, it->c_str(), it->length(), index_start,
index_end)) break;
index_start = index_end;
}
// set the memorized byte size to the first 4 bytes
int max_size = image.cols * image.rows * image.channels();
if (index < max_size) {
int size = index_start - index + 4;
memcpy(image.data + index, &size, 4);
}
}
//-----------------------------------------------------------------------------
void CodifyData2Image::image2message(const cv::Mat &image, int x, int y,
std::vector< std::string > &msg)
{
msg.clear();
int cn = image.channels();
int index = y * image.cols * cn + x * cn; // +0 B, + 1 G, +2 R
int max_size = image.cols * image.rows * image.channels();
if (index < max_size) {
// get the memorized byte size to the first 4 bytes
int size = 0;
memcpy(&size, image.data + index, 4);
//std::cout << "size: " << size << std::endl;
// Get the data
int index_start = index + 4;
while (index_start != 0 && index_start - index < size) {
//std::string tmp;
int index_end = 0;
char tmp[1024];
image2message(image, index_start, index_end, tmp, 1024);
//image2message(image, index_start, index_end, tmp);
index_start = index_end;
msg.push_back(tmp);
//std::cout << tmp << std::endl;
//std::cout << index_start - index << " -> " << size << std::endl;
}
}
}
//-----------------------------------------------------------------------------
int CodifyData2Image::expected_size(const std::vector<std::string> &msg) {
int s = 0;
#if _MSC_VER && !__INTEL_COMPILER && (_MSC_VER > 1600)
for (auto it = msg.begin(); it != msg.end(); it++)
#else
for (std::vector<std::string>::const_iterator it = msg.begin();
it != msg.end(); it++)
#endif
{
s += 4 + it->length();
}
return s;
}
//-----------------------------------------------------------------------------
void CodifyData2Image::insert_message(const cv::Mat &src,
const std::vector<std::string> &msg, cv::Mat &out) {
int rows = expected_size(msg) / src.cols + 2;
out = cv::Mat::zeros(cv::Size(src.cols, src.rows + rows), src.type());
src.copyTo(out(cv::Rect(0, 0, src.cols, src.rows)));
int x = 0, y = src.rows;
message2image(out, msg, x, y);
}
//-----------------------------------------------------------------------------
void CodifyData2Image::test()
{
cv::Mat m(512, 512, CV_8UC3, cv::Scalar(0, 255));
std::vector< std::string > vmsg, testmsg;
vmsg.push_back("This is an example");
vmsg.push_back("of how");
vmsg.push_back("a data is codified in an image $%&#?!");
cv::Mat out;
CodifyData2Image::insert_message(m, vmsg, out);
CodifyData2Image::image2message(out, 0, m.rows, testmsg);
std::cout << "<<< CODIFY >>>" << std::endl;
#if _MSC_VER && !__INTEL_COMPILER && (_MSC_VER > 1600)
for (auto it = testmsg.begin(); it != testmsg.end(); it++)
#else
for (std::vector< std::string >::const_iterator it = testmsg.begin();
it != testmsg.end(); it++)
#endif
{
std::cout << *it << std::endl;
}
cv::imshow("out", out);
cv::waitKey();
}
} // namespace codify
} // namespace CmnIP
| 32.351351 | 89 | 0.591618 | Khoronus |
b9c6a1d64840e5b589dfabfaa0ecf917a489b4bc | 159 | cpp | C++ | FileTesting/SampAp/res/src/Run.cpp | Filip-Pesula/MonoEngine | 8aaca13dd49054f4296896661e7ee6cd2c3b5428 | [
"MIT"
] | null | null | null | FileTesting/SampAp/res/src/Run.cpp | Filip-Pesula/MonoEngine | 8aaca13dd49054f4296896661e7ee6cd2c3b5428 | [
"MIT"
] | null | null | null | FileTesting/SampAp/res/src/Run.cpp | Filip-Pesula/MonoEngine | 8aaca13dd49054f4296896661e7ee6cd2c3b5428 | [
"MIT"
] | 1 | 2022-01-12T09:07:37.000Z | 2022-01-12T09:07:37.000Z | #include <Mono/Engine.h>
#include <Mono/Custom.h>
#include <iostream>
int Run(const Engine *engine)
{ std::cout << "Hello World";
std::cin.get();
return 0;
} | 19.875 | 29 | 0.672956 | Filip-Pesula |
b9c9927a0a85f0dc22c9e2b0f3e955f685381e65 | 1,450 | cpp | C++ | next_steps_info_entry.cpp | Jonathan-Harty/Member-Management-System | 65387cd8e786eebccb13b0d1d5da327bb43f7956 | [
"MIT"
] | null | null | null | next_steps_info_entry.cpp | Jonathan-Harty/Member-Management-System | 65387cd8e786eebccb13b0d1d5da327bb43f7956 | [
"MIT"
] | null | null | null | next_steps_info_entry.cpp | Jonathan-Harty/Member-Management-System | 65387cd8e786eebccb13b0d1d5da327bb43f7956 | [
"MIT"
] | null | null | null | #include "next_steps_info_entry.h"
NextStepsInfoEntry::NextStepsInfoEntry(QWidget *parent) : QWidget(parent)
{
nsInputLayout = new QFormLayout;
nsTitle = new QLabel("Next Steps:");
nsOrientationInput = new QLineEdit;
nsPaperworkInput = new QLineEdit;
ns1on1Input = new QLineEdit;
referralNotesLabel = new QLabel("Referral Notes:");
referralNotesInput = new QPlainTextEdit;
nsInputLayout->addRow(tr("&Next Steps Orientation"), nsOrientationInput);
nsInputLayout->addRow(tr("&Next Steps Paperwork"), nsPaperworkInput);
nsInputLayout->addRow(tr("&Next Steps one-on-one"), ns1on1Input);
nsInput = new QWidget;
nsInput->setLayout(nsInputLayout);
layout = new QVBoxLayout;
layout->addWidget(nsTitle);
layout->addWidget(nsInput);
layout->addWidget(referralNotesLabel);
layout->addWidget(referralNotesInput);
this->setLayout(layout);
}
QString NextStepsInfoEntry::getPaperwork()
{
QString nsPaperwork = nsPaperworkInput->text();
return nsPaperwork;
}
QString NextStepsInfoEntry::getOneOnOne()
{
QString ns1on1 = ns1on1Input->text();
return ns1on1;
}
QString NextStepsInfoEntry::getRefNotes()
{
QString nsRefNotes = referralNotesInput->toPlainText();
return nsRefNotes;
}
QString NextStepsInfoEntry::getOrientation()
{
QString nsOrientation = nsOrientationInput->text();
return nsOrientation;
}
| 27.884615 | 78 | 0.705517 | Jonathan-Harty |
844ecc1c635b9952a939b25a6a461f7050160eae | 1,795 | cxx | C++ | STEER/STEERBase/AliVZDC.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | STEER/STEERBase/AliVZDC.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | STEER/STEERBase/AliVZDC.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | /**************************************************************************
* Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//-------------------------------------------------------------------------
// Base class for ESD and AOD ZDC data
// Author: Chiara Oppedisano
// Chiara.Oppedisano@cern.ch
//-------------------------------------------------------------------------
#include "AliVZDC.h"
#include "AliLog.h"
ClassImp(AliVZDC)
//__________________________________________________________________________
AliVZDC::AliVZDC(const AliVZDC& source) :
TObject(source) { } // Copy constructor
//__________________________________________________________________________
AliVZDC& AliVZDC::operator=(const AliVZDC& source)
{
// Assignment operator
//
if (this!=&source) {
TObject::operator=(source);
}
return *this;
}
| 42.738095 | 76 | 0.522563 | AllaMaevskaya |
845447b724e0c1aa8ef80d57f98ebee5c8478263 | 446 | hpp | C++ | src/managers/shaderManager.hpp | starcatter/Udacity-Capstone-Project | 4ac73c0dfb87006fe153a2772d1ec63ccd555bfd | [
"MIT"
] | null | null | null | src/managers/shaderManager.hpp | starcatter/Udacity-Capstone-Project | 4ac73c0dfb87006fe153a2772d1ec63ccd555bfd | [
"MIT"
] | null | null | null | src/managers/shaderManager.hpp | starcatter/Udacity-Capstone-Project | 4ac73c0dfb87006fe153a2772d1ec63ccd555bfd | [
"MIT"
] | null | null | null | //
// Created by superbob on 2020-06-04.
//
#ifndef CAPSTONE_SDL_SHADERMANAGER_HPP
#define CAPSTONE_SDL_SHADERMANAGER_HPP
#include <memory>
#include <gfx/shader.hpp>
#include <gfx/shaderType.hpp>
class ShaderManager
{
std::unique_ptr<Shader> simpleShader;
std::unique_ptr<Shader> lightedShader;
public:
void initShaders();
void cleanupShaders();
Shader * getShader( ShaderType shader );
};
#endif //CAPSTONE_SDL_SHADERMANAGER_HPP
| 15.928571 | 41 | 0.762332 | starcatter |
845caea78fc433160d84d6f89e30624a78c77d17 | 1,691 | cpp | C++ | leetcode/cpp/5-LongestPalindromicSubstring/5-LongestPalindromicSubstring.cpp | davidlunadeleon/leetcode | 3a3d7d3ec9b708982658b154f8e551ae9a9fb8c1 | [
"Unlicense"
] | 1 | 2020-08-20T23:27:13.000Z | 2020-08-20T23:27:13.000Z | leetcode/cpp/5-LongestPalindromicSubstring/5-LongestPalindromicSubstring.cpp | davidlunadeleon/leetcode | 3a3d7d3ec9b708982658b154f8e551ae9a9fb8c1 | [
"Unlicense"
] | null | null | null | leetcode/cpp/5-LongestPalindromicSubstring/5-LongestPalindromicSubstring.cpp | davidlunadeleon/leetcode | 3a3d7d3ec9b708982658b154f8e551ae9a9fb8c1 | [
"Unlicense"
] | null | null | null | // Source: https://leetcode.com/problems/longest-palindromic-substring/
// Date: 18.06.2020
// Solution by: David Luna
// Runtime: 664ms
// Memory usage: 16.7 MB
#include <iostream>
#include <vector>
using namespace std;
// Leetcode solution starts
class Solution {
public:
string longestPalindrome(string s) {
if (s.length() <= 1) {
return s;
}
int size = s.size(), left = 0, right = 0;
vector<vector<bool>> array(size, vector<bool>(size, false));
array[0][0] = true;
for (int i = 1; i < size; i++) {
array[i][i] = true;
array[i][i - 1] = true;
}
for (int diag = 1; diag < size; diag++) {
for (int i = 0; i < size - diag; i++) {
bool temp = s[i] == s[i + diag] && array[i + 1][i + diag - 1];
array[i][i + diag] = temp;
if (temp) {
left = i;
right = i + diag;
}
}
}
return s.substr(left, right - left + 1);
}
};
// Leetcode solution ends
bool checkAns(vector<string> possibleAns, string s) {
string ans = Solution().longestPalindrome(s);
for (int i = 0; i < possibleAns.size(); i++) {
if (ans == possibleAns[i]) {
return true;
}
}
cout << '\n' << s << "\n\n";
return false;
}
void makeTest() {
int numAns;
string s;
vector<string> possibleAns;
// Introduce the string to check
cin >> s;
// Introduce the number of possible answers
cin >> numAns;
// Introduce the possible answers
for (int i = 0; i < numAns; i++) {
string temp;
cin >> temp;
possibleAns.push_back(temp);
}
cout << (checkAns(possibleAns, s) ? "pass\n" : "fail\n");
}
int main() {
int numTests;
// Introduce the number of tests to make.
cin >> numTests;
for (int i = 0; i < numTests; i++) {
makeTest();
}
return 0;
}
| 21.1375 | 71 | 0.591366 | davidlunadeleon |
845fba2ada5405e47f8ae94810de13d167642428 | 7,618 | cpp | C++ | XrsPalm/src/VSTInterface/src/VSTWindow.cpp | bach5000/XRS | 8b9169f8d52a441ddca87415963ea2fcfced1884 | [
"MIT"
] | null | null | null | XrsPalm/src/VSTInterface/src/VSTWindow.cpp | bach5000/XRS | 8b9169f8d52a441ddca87415963ea2fcfced1884 | [
"MIT"
] | null | null | null | XrsPalm/src/VSTInterface/src/VSTWindow.cpp | bach5000/XRS | 8b9169f8d52a441ddca87415963ea2fcfced1884 | [
"MIT"
] | null | null | null | #include "VSTWindow.h"
#include "MyList.h"
#include "MySource.h"
#include "ListItem.h"
#include "ScrollView.h"
#include "Configurator.h"
#include "VSTFilter.h"
#include "stdio.h"
#include "stdlib.h"
#include "strings.h"
#include "Entry.h"
#include "Juice.h"
#include "Box.h"
#include "PlugWindow.h"
#define DRAG_X 1978
#include "TabView.h"
#include "MyItem.h"
BTabView *tab_view;
BTab *tab;
BPath vstpath;
#define WIN_POSX 300
#define WIN_POSY 300
#define GLOBAL_LINE 2
float hs;
VSTWindow::VSTWindow() : PlugWindow()
{
ResizeTo(380,135);
SetTitle("VST Audio Output");
//B_FLOATING_WINDOW, B_ASYNCHRONOUS_CONTROLS|B_OUTLINE_RESIZE|B_WILL_ACCEPT_FIRST_CLICK|B_AVOID_FOCUS)
//SetType(B_FLOATING_WINDOW); //, B_NOT_RESIZABLE)
//SetLook(B_FLOATING_WINDOW_LOOK);
//SetFeel(B_NORMAL_WINDOW_FEEL);
//BWindow(BRect(WIN_POSX,WIN_POSY,WIN_POSX+380,WIN_POSY+135),"VST Audio Output", B_DOCUMENT_WINDOW, |B_ASYNCHRONOUS_CONTROLS
SetFlags(B_AVOID_FOCUS|B_WILL_ACCEPT_FIRST_CLICK|B_NOT_ZOOMABLE|B_NOT_RESIZABLE);
succo=NULL;
list[0]=new MyList(BRect(5,5,105,95));
list[0]->SetInvocationMessage(new BMessage('invk'));
list[1]=new MyList(BRect(5,5,105,95));
list[1]->SetInvocationMessage(new BMessage('invk'));
list[2]=new MyList(BRect(5,5,105,95));
list[2]->SetInvocationMessage(new BMessage('invk'));
BView* empty=new BView(Bounds(),"Pippo",B_FOLLOW_ALL,B_WILL_DRAW);
empty->SetViewColor(216,216,216,0);
//empty->AddChild(new BScrollView("_scroolSource",s,B_FOLLOW_NONE,B_WILL_DRAW|B_FRAME_EVENTS|B_NAVIGABLE_JUMP,false,true,B_FANCY_BORDER));
BRect r = Bounds();
r.InsetBy(5,5);
r.right-=220;
tab_view = new BTabView(r, "tab_view",B_WIDTH_FROM_LABEL,B_FOLLOW_NONE);
tab_view->SetViewColor(216,216,216,0);
r = tab_view->Bounds();
r.InsetBy(5,5);
r.bottom -= tab_view->TabHeight();
tab = new BTab();
tab_view->AddTab(new BScrollView("_scroolView2",list[0],B_FOLLOW_NONE,B_WILL_DRAW|B_FRAME_EVENTS|B_NAVIGABLE_JUMP,false,true,B_FANCY_BORDER), tab);
tab->SetLabel("Fx1");
tab = new BTab();
tab_view->AddTab(new BScrollView("_scroolView3",list[1],B_FOLLOW_NONE,B_WILL_DRAW|B_FRAME_EVENTS|B_NAVIGABLE_JUMP,false,true,B_FANCY_BORDER), tab);
tab->SetLabel("Fx2");
tab = new BTab();
tab_view->AddTab(new BScrollView("_scroolView1",list[2],B_FOLLOW_NONE,B_WILL_DRAW|B_FRAME_EVENTS|B_NAVIGABLE_JUMP,false,true,B_FANCY_BORDER), tab);
tab->SetLabel("Global");
empty->AddChild(tab_view);
//BRect(200,40,280,130)
r=(tab_view->ContainerView())->Frame();
r.top+=10;
r.bottom+=5;
r.left+=200;
r.right+=200;
s=new MySource(r);
empty->AddChild(new BScrollView("_scroolSource",s,B_FOLLOW_NONE,B_WILL_DRAW|B_FRAME_EVENTS|B_NAVIGABLE_JUMP,false,true,B_FANCY_BORDER));
AddChild(empty);
win_vst[0]=(new BList(0));
win_vst[1]=(new BList(0));
win_vst[2]=(new BList(0));
list[0]->AddItem(new MyItem("dump!"));
hs=list[0]->ItemFrame(0).bottom-list[0]->ItemFrame(0).top;
list[0]->RemoveItem((int32)0);
}
void
VSTWindow::getVstName(const char* d,int line,int pos)
{
if(pos >= CountVst(line)) return;
strncpy((char*)d,((BStringItem*)(list[line]->ItemAt(pos)))->Text(),100);
}
int
VSTWindow::CountVst(int i)
{
return list[i]->CountItems();
}
void
VSTWindow::CloseVst()
{
for(int j=0; j<3;j++)
{
for(int i=0;i<win_vst[j]->CountItems();i++)
{
BWindow *dv=(BWindow*)win_vst[j]->ItemAt(i);
if(dv->Lock()) dv->Quit();
}
win_vst[j]->MakeEmpty();
list[j]->MakeEmpty();
}
}
VSTWindow::~VSTWindow()
{
CloseVst();
}
void
VSTWindow::MessageReceived(BMessage* msg)
{
if(msg->what==DRAG_X){
int k=msg->FindInt16("from");
if(k>=0)
{
list[tab_view->Selection()]->RemoveItem(k);
RemoveVst(0,k);
}
}
else
if(msg->what=='invk')
{
int line=tab_view->Selection();
BWindow* nw=(BWindow*)win_vst[line]->ItemAt(list[tab_view->Selection()]->CurrentSelection());
if(nw->Lock())
{
if(nw->IsHidden()) nw->Show();
else
nw->Activate();
nw->Unlock();
}
}
else
BWindow::MessageReceived(msg);
}
void
VSTWindow::Init(Juice* sj)
{
succo=sj;
BEntry e;
entry_ref rif;
status_t err=Ref("vstfolder",&rif,"/boot/xeD/");
if(err==B_OK)
{
printf("found vstfolder : %s\n",rif.name);
e.SetTo(&rif);
e.GetPath(&vstpath);
VSTFilterPlugin::load_plug_ins (vstpath.Path(), (BListView*)s,1);
}
list[0]->Init(hs); list[2]->Init(hs); list[1]->Init(hs); s->Init();
}
bool
VSTWindow::AddVst(BMessage* msg,int line,int pos,bool g=false)
{
//printf("VSTWindow :: AddVst name : %s, line: %d.\n",line);
BPath p(vstpath);
p.Append(msg->FindString("xrsname"));
BEntry e(p.Path());
if(!e.Exists()){return false; }
if(g) line=GLOBAL_LINE; // INSERIMENTO SULLA LINEA GLOBALE!
printf("Line accepted!\n");
if(Lock()){
succo->Pause();
VSTFilterPlugin* vst2=new VSTFilterPlugin(p.Path());
MyItem *st=new MyItem(msg->FindString("xrsname"));
list[line]->AddItem(st,pos);
if(succo->vst[line]->AddItem((void*)vst2,pos))
{
vst2->SetConfig(msg);
st->SetStatus(vst2->GetStatus());
succo->ResetVstTempo(vst2);
}
else
{
Unlock();
return false;
}
vstWindow(vst2,msg->FindString("xrsname"),line,pos,msg);
//((PlugWindow*)win_vst[line]->ItemAt(pos))->LoadPref(msg);
succo->Pause();
Unlock();
}
return true;
}
void
VSTWindow::AddVst(const char* n,int line,int pos)
{
line=tab_view->Selection();
if(succo==NULL || line < 0) return;
BPath p(vstpath);
p.Append(n);
BEntry e(p.Path());
if(!e.Exists()){
return;
}
if(Lock()){
succo->Pause();
VSTFilterPlugin* vst2=new VSTFilterPlugin(p.Path());
vstWindow(vst2,n,line,pos);
if(succo->vst[line]->AddItem((void*)vst2,pos))
succo->ResetVstTempo(vst2);
else
printf("error while putting a vst in line %d\n",line);
succo->Pause();
Unlock();
}
}
void
VSTWindow::SetVstState(int pos,bool s)
{
int line=tab_view->Selection();
if(line < 0 || pos<0) return;
VSTFilterPlugin* vst2=(VSTFilterPlugin*)(succo->vst[line]->ItemAt(pos));
vst2->SetStatus(s);
}
void
VSTWindow::RemoveVst(int line,int pos)
{
line=tab_view->Selection();
if(succo==NULL || line < 0 || pos<0) return;
if(Lock()){
succo->Pause();
BWindow* nw=(BWindow*)(win_vst[line]->ItemAt(pos));
win_vst[line]->RemoveItem(pos);
if(nw->Lock())
{
nw->Quit();
//delete nw;
}
VSTFilterPlugin* vst2=(VSTFilterPlugin*)(succo->vst[line]->ItemAt(pos) );
succo->vst[line]->RemoveItem(pos);
delete vst2;
succo->Pause();
Unlock();
}
}
void
VSTWindow::MoveVst(int from,int to)
{
int line=tab_view->Selection();
if(from==to || line < 0 ||succo==NULL) return;
if(Lock()){
succo->Pause();
BWindow* nw=(BWindow*)(win_vst[line]->ItemAt(from));
VSTFilterPlugin* vst2=(VSTFilterPlugin*)(succo->vst[line]->ItemAt(from));
win_vst[line]->RemoveItem(from);
succo->vst[line]->RemoveItem(from);
win_vst[line]->AddItem((void*)nw,to);
succo->vst[line]->AddItem((void*)vst2,to);
succo->Pause();
Unlock();
}
}
void
VSTWindow::vstWindow(VSTFilterPlugin *vst,const char* name,int line,int pos,BMessage* msg=NULL)
{
//B_ASYNCHRONOUS_CONTROLS
PlugWindow *nw= new PlugWindow();
win_vst[line]->AddItem((void*)nw,pos);
nw->SetControls(vst->Configure(),0);
if(msg!=NULL)
nw->LoadPref(msg);
if(line==0)
nw->SetTitle("Fx1");
else
if(line==1)
nw->SetTitle("Fx2");
else
nw->SetTitle("Global");
nw->Show();
}
void
VSTWindow::AddVstWindowInfo(BMessage* m,int line,int pos)
{
((PlugWindow*)win_vst[line]->ItemAt(pos))->SavePref(m);
} | 20.206897 | 148 | 0.663166 | bach5000 |
8463ca0daea9db36a494b7b14bd2a2300e9ad3ba | 2,733 | cpp | C++ | src/helpers.cpp | MagicAtom/PixelStream | f465bf7d950be298aea1ab5efafaee14ca4140ae | [
"MIT"
] | 9 | 2021-11-19T05:29:41.000Z | 2022-01-27T05:09:20.000Z | src/helpers.cpp | MagicAtom/PixelStream | f465bf7d950be298aea1ab5efafaee14ca4140ae | [
"MIT"
] | null | null | null | src/helpers.cpp | MagicAtom/PixelStream | f465bf7d950be298aea1ab5efafaee14ca4140ae | [
"MIT"
] | 3 | 2021-12-16T08:48:29.000Z | 2022-03-22T17:13:24.000Z | /*
* libdatachannel streamer example
* Copyright (c) 2020 Filip Klembara (in2core)
*
* 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 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; If not, see <http://www.gnu.org/licenses/>.
*/
#include "helpers.hpp"
#include <ctime>
#ifdef _WIN32
// taken from https://stackoverflow.com/questions/10905892/equivalent-of-gettimeday-for-windows
#include <windows.h>
#include <winsock2.h> // for struct timeval
struct timezone {
int tz_minuteswest;
int tz_dsttime;
};
int gettimeofday(struct timeval *tv, struct timezone *tz)
{
if (tv) {
FILETIME filetime; /* 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 00:00 UTC */
ULARGE_INTEGER x;
ULONGLONG usec;
static const ULONGLONG epoch_offset_us = 11644473600000000ULL; /* microseconds betweeen Jan 1,1601 and Jan 1,1970 */
#if _WIN32_WINNT >= _WIN32_WINNT_WIN8
GetSystemTimePreciseAsFileTime(&filetime);
#else
GetSystemTimeAsFileTime(&filetime);
#endif
x.LowPart = filetime.dwLowDateTime;
x.HighPart = filetime.dwHighDateTime;
usec = x.QuadPart / 10 - epoch_offset_us;
tv->tv_sec = (time_t)(usec / 1000000ULL);
tv->tv_usec = (long)(usec % 1000000ULL);
}
if (tz) {
TIME_ZONE_INFORMATION timezone;
GetTimeZoneInformation(&timezone);
tz->tz_minuteswest = timezone.Bias;
tz->tz_dsttime = 0;
}
return 0;
}
#else
#include <sys/time.h>
#endif
using namespace std;
using namespace rtc;
ClientTrackData::ClientTrackData(shared_ptr<Track> track, shared_ptr<RtcpSrReporter> sender) {
this->track = track;
this->sender = sender;
}
void Client::setState(State state) {
std::unique_lock lock(_mutex);
this->state = state;
}
Client::State Client::getState() {
std::shared_lock lock(_mutex);
return state;
}
ClientTrack::ClientTrack(string id, shared_ptr<ClientTrackData> trackData) {
this->id = id;
this->trackData = trackData;
}
uint64_t currentTimeInMicroSeconds() {
struct timeval time;
gettimeofday(&time, NULL);
return uint64_t(time.tv_sec) * 1000 * 1000 + time.tv_usec;
}
| 30.366667 | 143 | 0.69228 | MagicAtom |
84688141f08fabfcb7036a644791e6e981f7b133 | 970 | cpp | C++ | Third party distributions/xlw-5.0.1f0/xlw/examples/MJ - Design Patterns/common_source/Test.cpp | RoelofBerg/QuantFinCode | a0d32b51fb46cf591242cf9981bdd86ea7b37898 | [
"BSD-3-Clause"
] | null | null | null | Third party distributions/xlw-5.0.1f0/xlw/examples/MJ - Design Patterns/common_source/Test.cpp | RoelofBerg/QuantFinCode | a0d32b51fb46cf591242cf9981bdd86ea7b37898 | [
"BSD-3-Clause"
] | null | null | null | Third party distributions/xlw-5.0.1f0/xlw/examples/MJ - Design Patterns/common_source/Test.cpp | RoelofBerg/QuantFinCode | a0d32b51fb46cf591242cf9981bdd86ea7b37898 | [
"BSD-3-Clause"
] | null | null | null |
/*
Copyright (C) 2006 Mark Joshi
This file is part of XLW, a free-software/open-source C++ wrapper of the
Excel C API - http://xlw.sourceforge.net/
XLW is free software: you can redistribute it and/or modify it under the
terms of the XLW license. You should have received a copy of the
license along with this program; if not, please email xlw-users@lists.sf.net
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 license for more details.
*/
#include "Test.h"
#include <ctime>
#include <windows.h>
#include<xlw/XlfExcel.h>
#include<xlw/XlOpenClose.h>
#include<xlw/XlfServices.h>
double // evaluate pay--off
PayOffEvaluation(const Wrapper<PayOff>& OptionPayOff // table for payoff
, double Spot // point for evaluation
)
{
return (*OptionPayOff)(Spot);
}
| 31.290323 | 79 | 0.706186 | RoelofBerg |
84691316a7827b72aab11412e6ee49342c13d09b | 425 | cpp | C++ | Projeto/dialogmatriz.cpp | asilvadev/DCA-Modelador-3D | 5f3b0795be7ca589a05e209d72822862366aa589 | [
"MIT"
] | null | null | null | Projeto/dialogmatriz.cpp | asilvadev/DCA-Modelador-3D | 5f3b0795be7ca589a05e209d72822862366aa589 | [
"MIT"
] | null | null | null | Projeto/dialogmatriz.cpp | asilvadev/DCA-Modelador-3D | 5f3b0795be7ca589a05e209d72822862366aa589 | [
"MIT"
] | null | null | null | #include "dialogmatriz.h"
#include "ui_dialogmatriz.h"
DialogMatriz::DialogMatriz(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogMatriz)
{
ui->setupUi(this);
}
DialogMatriz::~DialogMatriz()
{
delete ui;
}
int DialogMatriz::getX()
{
return ui->spinBox_dX->value();
}
int DialogMatriz::getY()
{
return ui->spinBox_dY->value();
}
int DialogMatriz::getZ()
{
return ui->spinBox_dZ->value();
}
| 15.178571 | 45 | 0.665882 | asilvadev |
846982df22ca99e0573d28f87f60f1a8c9ceae8f | 6,098 | hpp | C++ | Include/LIEF/MachO/DynamicSymbolCommand.hpp | RaniaJarraya/fraudulent_behavior_detection | d1506603fd3468a6c106c73d4880623c5a9b4869 | [
"BSD-3-Clause"
] | 54 | 2020-01-29T18:44:56.000Z | 2022-03-14T11:24:59.000Z | Include/LIEF/MachO/DynamicSymbolCommand.hpp | RaniaJarraya/fraudulent_behavior_detection | d1506603fd3468a6c106c73d4880623c5a9b4869 | [
"BSD-3-Clause"
] | 13 | 2021-03-19T09:25:18.000Z | 2022-02-10T12:15:24.000Z | Include/LIEF/MachO/DynamicSymbolCommand.hpp | RaniaJarraya/fraudulent_behavior_detection | d1506603fd3468a6c106c73d4880623c5a9b4869 | [
"BSD-3-Clause"
] | 8 | 2019-05-19T11:24:28.000Z | 2022-02-16T20:19:30.000Z | /* Copyright 2017 R. Thomas
* Copyright 2017 Quarkslab
*
* 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 LIEF_MACHO_DYNAMIC_SYMBOL_COMMAND_H_
#define LIEF_MACHO_DYNAMIC_SYMBOL_COMMAND_H_
#include <string>
#include <vector>
#include <iostream>
#include <array>
#include "LIEF/visibility.h"
#include "LIEF/types.hpp"
#include "LIEF/MachO/LoadCommand.hpp"
namespace LIEF {
namespace MachO {
class LIEF_API DynamicSymbolCommand : public LoadCommand {
public:
DynamicSymbolCommand(void);
DynamicSymbolCommand(const dysymtab_command *cmd);
DynamicSymbolCommand& operator=(const DynamicSymbolCommand& copy);
DynamicSymbolCommand(const DynamicSymbolCommand& copy);
virtual ~DynamicSymbolCommand(void);
virtual void accept(Visitor& visitor) const override;
bool operator==(const DynamicSymbolCommand& rhs) const;
bool operator!=(const DynamicSymbolCommand& rhs) const;
virtual std::ostream& print(std::ostream& os) const override;
//! Index of the first symbol in the group of local symbols.
uint32_t idx_local_symbol(void) const;
//! Number of symbols in the group of local symbols.
uint32_t nb_local_symbols(void) const;
//! Index of the first symbol in the group of defined external symbols.
uint32_t idx_external_define_symbol(void) const;
//! Number of symbols in the group of defined external symbols.
uint32_t nb_external_define_symbols(void) const;
//! Index of the first symbol in the group of undefined external symbols.
uint32_t idx_undefined_symbol(void) const;
//! Number of symbols in the group of undefined external symbols.
uint32_t nb_undefined_symbols(void) const;
//! Byte offset from the start of the file to the table of contents data
//!
//! Table of content is used by legacy Mach-O loader and this field should be
//! set to 0
uint32_t toc_offset(void) const;
//! Number of entries in the table of contents.
//!
//! Should be set to 0 on recent Mach-O
uint32_t nb_toc(void) const;
//! Byte offset from the start of the file to the module table data.
//!
//! This field seems unused by recent Mach-O loader and should be set to 0
uint32_t module_table_offset(void) const;
//! Number of entries in the module table.
//!
//! This field seems unused by recent Mach-O loader and should be set to 0
uint32_t nb_module_table(void) const;
//! Byte offset from the start of the file to the external reference table data.
//!
//! This field seems unused by recent Mach-O loader and should be set to 0
uint32_t external_reference_symbol_offset(void) const;
//! Number of entries in the external reference table
//!
//! This field seems unused by recent Mach-O loader and should be set to 0
uint32_t nb_external_reference_symbols(void) const;
//! Byte offset from the start of the file to the indirect symbol table data.
//!
//! Indirect symbol table is used by the loader to speed-up symbol resolution during
//! the *lazy binding* process
//!
//! References:
//! * dyld-519.2.1/src/ImageLoaderMachOCompressed.cpp
//! * dyld-519.2.1/src/ImageLoaderMachOClassic.cpp
uint32_t indirect_symbol_offset(void) const;
//! Number of entries in the indirect symbol table.
//!
//! @see indirect_symbol_offset
uint32_t nb_indirect_symbols(void) const;
//! Byte offset from the start of the file to the external relocation table data.
//!
//! This field seems unused by recent Mach-O loader and should be set to 0
uint32_t external_relocation_offset(void) const;
//! Number of entries in the external relocation table.
//!
//! This field seems unused by recent Mach-O loader and should be set to 0
uint32_t nb_external_relocations(void) const;
//! Byte offset from the start of the file to the local relocation table data.
//!
//! This field seems unused by recent Mach-O loader and should be set to 0
uint32_t local_relocation_offset(void) const;
//! Number of entries in the local relocation table.
//!
//! This field seems unused by recent Mach-O loader and should be set to 0
uint32_t nb_local_relocations(void) const;
void idx_local_symbol(uint32_t value);
void nb_local_symbols(uint32_t value);
void idx_external_define_symbol(uint32_t value);
void nb_external_define_symbols(uint32_t value);
void idx_undefined_symbol(uint32_t value);
void nb_undefined_symbols(uint32_t value);
void toc_offset(uint32_t value);
void nb_toc(uint32_t value);
void module_table_offset(uint32_t value);
void nb_module_table(uint32_t value);
void external_reference_symbol_offset(uint32_t value);
void nb_external_reference_symbols(uint32_t value);
void indirect_symbol_offset(uint32_t value);
void nb_indirect_symbols(uint32_t value);
void external_relocation_offset(uint32_t value);
void nb_external_relocations(uint32_t value);
void local_relocation_offset(uint32_t value);
void nb_local_relocations(uint32_t value);
private:
uint32_t idx_local_symbol_;
uint32_t nb_local_symbols_;
uint32_t idx_external_define_symbol_;
uint32_t nb_external_define_symbols_;
uint32_t idx_undefined_symbol_;
uint32_t nb_undefined_symbols_;
uint32_t toc_offset_;
uint32_t nb_toc_;
uint32_t module_table_offset_;
uint32_t nb_module_table_;
uint32_t external_reference_symbol_offset_;
uint32_t nb_external_reference_symbols_;
uint32_t indirect_sym_offset_;
uint32_t nb_indirect_symbols_;
uint32_t external_relocation_offset_;
uint32_t nb_external_relocations_;
uint32_t local_relocation_offset_;
uint32_t nb_local_relocations_;
};
}
}
#endif
| 31.760417 | 86 | 0.760905 | RaniaJarraya |
8470e4b9d2e737a473dcc38b14c757689ff9b46d | 208 | cpp | C++ | src/test_pellets/TestThreadSync.cpp | wohaaitinciu/zpublic | 0e4896b16e774d2f87e1fa80f1b9c5650b85c57e | [
"Unlicense"
] | 50 | 2015-01-07T01:54:54.000Z | 2021-01-15T00:41:48.000Z | src/test_pellets/TestThreadSync.cpp | lib1256/zpublic | 64c2be9ef1abab878288680bb58122dcc25df81d | [
"Unlicense"
] | 1 | 2015-05-26T07:40:19.000Z | 2015-05-26T07:40:19.000Z | src/test_pellets/TestThreadSync.cpp | lib1256/zpublic | 64c2be9ef1abab878288680bb58122dcc25df81d | [
"Unlicense"
] | 39 | 2015-01-07T02:03:15.000Z | 2021-01-15T00:41:50.000Z | #include "TestThreadSync.h"
CTestThreadSync::CTestThreadSync(void)
{
TEST_ADD(CTestThreadSync::testEvent);
TEST_ADD(CTestThreadSync::testSemaphore);
}
CTestThreadSync::~CTestThreadSync(void)
{
}
| 13.866667 | 45 | 0.759615 | wohaaitinciu |
847203679ab30f6f67af41a423b61748d7c065b9 | 2,945 | cpp | C++ | src/settings.cpp | BerryTrucks/NineMensMorris-BB10 | 8d70d55c77e9cda10077f55da3c2a296ca76778a | [
"CC-BY-2.0"
] | 2 | 2021-04-07T18:46:31.000Z | 2021-05-19T03:53:01.000Z | src/settings.cpp | Summeli/NineMensMorris-BB10 | 8d70d55c77e9cda10077f55da3c2a296ca76778a | [
"CC-BY-2.0"
] | 1 | 2021-05-19T12:16:54.000Z | 2021-05-19T12:16:54.000Z | src/settings.cpp | BerryTrucks/NineMensMorris-BB10 | 8d70d55c77e9cda10077f55da3c2a296ca76778a | [
"CC-BY-2.0"
] | 1 | 2021-05-19T12:13:08.000Z | 2021-05-19T12:13:08.000Z | /*
* QMühLe
* Written by Philipp Zabel <philipp.zabel@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "settings.h"
#include <QSettings>
#include <QDebug>
Settings::Settings(QObject *parent) :
QObject(parent),
m_computerWhite(false),
m_computerBlack(true),
m_faceToFace(true),
m_difficulty(1),
m_fullScreen(true)
{
}
void Settings::load()
{
setComputerWhite(m_settings.value("computerWhite", QVariant(false)).toBool());
setComputerBlack(m_settings.value("computerBlack", QVariant(true)).toBool());
setFaceToFace(m_settings.value("faceToFace", QVariant(true)).toBool());
setDifficulty(m_settings.value("difficulty", QVariant(1)).toInt());
setFullScreen(m_settings.value("fullScreen", QVariant(true)).toBool());
}
void Settings::save()
{
m_settings.setValue("computerWhite", m_computerWhite);
m_settings.setValue("computerBlack", m_computerBlack);
m_settings.setValue("faceToFace", m_faceToFace);
m_settings.setValue("difficulty", m_difficulty);
m_settings.setValue("fullScreen", m_fullScreen);
}
void Settings::setComputerWhite(bool computer)
{
if (m_computerWhite != computer) {
m_computerWhite = computer;
emit computerWhiteChanged();
}
}
bool Settings::computerWhite() const
{
return m_computerWhite;
}
void Settings::setComputerBlack(bool computer)
{
if (m_computerBlack != computer) {
m_computerBlack = computer;
emit computerBlackChanged();
}
}
bool Settings::computerBlack() const
{
return m_computerBlack;
}
void Settings::setFaceToFace(bool faceToFace)
{
if (m_faceToFace != faceToFace) {
m_faceToFace = faceToFace;
emit faceToFaceChanged();
}
}
bool Settings::faceToFace() const
{
return m_faceToFace;
}
void Settings::setDifficulty(int difficulty)
{
if (m_difficulty != difficulty) {
m_difficulty = difficulty;
emit difficultyChanged();
}
}
int Settings::difficulty() const
{
return m_difficulty;
}
void Settings::setFullScreen(bool fullScreen)
{
if (m_fullScreen != fullScreen) {
m_fullScreen = fullScreen;
emit fullScreenChanged();
}
}
bool Settings::fullScreen() const
{
return m_fullScreen;
}
| 25.17094 | 82 | 0.701528 | BerryTrucks |
8473b131b75ea06f4636abbfad5f175f85be206d | 4,970 | hpp | C++ | A3_GW_Existence.Altis/Configs/ArmA/CfgRemoteExec.hpp | Hootsir/A3RPGFramework | 9eaa1c285751ee00ba460cb692dcc759eaa1f149 | [
"MIT"
] | 36 | 2018-04-22T19:34:58.000Z | 2021-05-27T20:51:58.000Z | A3_GW_Existence.Altis/Configs/ArmA/CfgRemoteExec.hpp | Hootsir/A3RPGFramework | 9eaa1c285751ee00ba460cb692dcc759eaa1f149 | [
"MIT"
] | 12 | 2018-04-21T14:33:29.000Z | 2020-05-20T18:16:22.000Z | A3_GW_Existence.Altis/Configs/ArmA/CfgRemoteExec.hpp | Hootsir/A3RPGFramework | 9eaa1c285751ee00ba460cb692dcc759eaa1f149 | [
"MIT"
] | 33 | 2018-04-22T15:15:54.000Z | 2020-04-02T23:30:24.000Z | /*
Copyright (C) SimZor, SimZor Studios 2017
All Rights Reserved
Filename: CfgRemoteExec.hpp
*/
// DEFINES
#define HC GW_HC1
#define SERVER 2
#define CLIENT 1
#define ANYONE 0
class CfgRemoteExec {
mode = 1;
jip = 1;
// SCRIPTED FUNCTIONS
class Functions {
// SERVER FUNCTIONS
class GW_server_fnc_log {allowedTargets = SERVER;};
class GW_server_fnc_antiHackInit {allowedTargets = CLIENT;};
class GW_server_fnc_validateAdmin {allowedTargets = SERVER;};
class GW_server_fnc_compile {allowedTargets = ANYONE;};
class GW_server_fnc_compileRequest {allowedTargets = SERVER;};
class GW_server_fnc_getPlayerData {allowedTargets = SERVER;};
class GW_server_fnc_messageSendRequest {allowedTargets = SERVER;};
class GW_server_fnc_vehicleInsert {allowedTargets = SERVER;};
class GW_server_fnc_vehicleDelete {allowedTargets = SERVER;};
class GW_server_fnc_vehicleUpdateStatus {allowedTargets = SERVER;};
class GW_server_fnc_propertyUpdateContainers {allowedTargets = SERVER;};
class GW_server_fnc_vehicleGetInactiveVehicles {allowedTargets = SERVER;};
class GW_server_fnc_logPlayerDeath {allowedTargets = SERVER;};
class GW_server_fnc_warrantsAddWarrant {allowedTargets = SERVER;};
class GW_server_fnc_warrantsQueryWarrants {allowedTargets = SERVER;};
class GW_server_fnc_warrantsDeleteWarrant {allowedTargets = SERVER;};
class GW_server_fnc_worldtrackSpikestrip {allowedTargets = SERVER;};
// CLIENT FUNCTIONS
class GW_client_fnc_syncAnimation {allowedTargets = CLIENT;};
class GW_client_fnc_moveUnitIntoVehicle {allowedTargets = CLIENT;};
class GW_client_fnc_propertySetupClient {allowedTargets = CLIENT;};
class GW_client_fnc_propertyRequestRespond {allowedTargets = CLIENT;};
class GW_client_fnc_receivePlayerData {allowedTargets = CLIENT;};
class GW_client_fnc_organizationsInitPlayerResponse {allowedTargets = CLIENT;};
class GW_client_fnc_notificationsAdd {allowedTargets = CLIENT;};
class GW_client_fnc_broadcast {allowedTargets = CLIENT;};
class GW_client_fnc_retrieveMessage {allowedTargets = CLIENT;};
class GW_client_fnc_organizationsDisbandFromPlayer {allowedTargets = CLIENT;};
class GW_client_fnc_vehicleSetupVehicleEventhandlers {allowedTargets = ANYONE;};
class GW_client_fnc_say3D {allowedTargets = CLIENT;};
class GW_client_fnc_actionRestrainHandler {allowedTargets = CLIENT;};
class GW_client_fnc_bleedoutNotifyRevivers {allowedTargets = CLIENT;};
class GW_client_fnc_arrestWarrantsReceive {allowedTargets = CLIENT;};
class GW_client_fnc_moneyReceive {allowedTargets = CLIENT;};
class GW_client_fnc_ticketSystemIssueTicket {allowedTargets = CLIENT;};
class GW_client_fnc_ticketSystemRewards {allowedTargets = CLIENT;};
class GW_client_fnc_playersHandleMoney {allowedTargets = CLIENT;};
class GW_client_fnc_experienceCategoryAddExperience {allowedTargets = CLIENT;};
class GW_client_fnc_jailOnIncarceration {allowedTargets = CLIENT;};
class GW_client_fnc_jailOnRelease {allowedTargets = CLIENT;};
class GW_client_fnc_moneyPickupResponse {allowedTargets = CLIENT;};
class GW_client_fnc_banksDrill {allowedTargets = CLIENT;};
class GW_client_fnc_banksCollectMoneybag {allowedTargets = CLIENT;};
class GW_client_fnc_organizationsInviteReceived {allowedTargets = CLIENT;};
class GW_client_fnc_holidaysXmasExperienceBoost {allowedTargets = CLIENT;};
class GW_client_fnc_virtualInventoryGiveItemRemote {allowedTargets = CLIENT;};
class GW_client_fnc_vehicleSpikestripEffect {allowedTargets = CLIENT;};
class GW_client_fnc_moneyRobberyRobbed {allowedTargets = CLIENT;};
class GW_client_fnc_moneyRobberyReceive {allowedTargets = CLIENT;};
};
// SCRIPTED COMMANDS
class Commands {
mode = 1;
jip = 1;
class hideObject {allowedTargets = CLIENT;};
class setVelocity {allowedTargets = CLIENT;};
};
};
| 60.609756 | 91 | 0.622133 | Hootsir |
847455f21e94f11aa36cffa1ea5bde3c53ecc754 | 3,901 | hpp | C++ | src/plugin/net/include/AFCNetClientService.hpp | overtalk/ARK | 9d314e99dc13684fc672371a0c3fbaa6b9a46d97 | [
"Apache-2.0"
] | 1 | 2020-02-21T14:32:13.000Z | 2020-02-21T14:32:13.000Z | src/plugin/net/include/AFCNetClientService.hpp | overtalk/ARK | 9d314e99dc13684fc672371a0c3fbaa6b9a46d97 | [
"Apache-2.0"
] | null | null | null | src/plugin/net/include/AFCNetClientService.hpp | overtalk/ARK | 9d314e99dc13684fc672371a0c3fbaa6b9a46d97 | [
"Apache-2.0"
] | null | null | null | /*
* This source file is part of ARK
* For the latest info, see https://github.com/ArkNX
*
* Copyright (c) 2013-2019 ArkNX 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.
*
*/
#pragma once
#include "base/AFMap.hpp"
#include "base/AFCConsistentHash.hpp"
#include "base/AFPluginManager.hpp"
#include "net/interface/AFINetClientService.hpp"
#include "net/interface/AFINetServiceManagerModule.hpp"
#include "bus/interface/AFIBusModule.hpp"
#include "bus/interface/AFIMsgModule.hpp"
#include "log/interface/AFILogModule.hpp"
namespace ark {
class AFCNetClientService final : public AFINetClientService
{
public:
enum EConstDefine
{
EConstDefine_DefaultWeight = 255,
};
AFCNetClientService(AFPluginManager* p);
bool StartClient(const AFHeadLength head_len, const int& target_bus_id, const AFEndpoint& endpoint) override;
void Update() override;
//void Shutdown() override;
bool RegMsgCallback(const int msg_id, const NET_MSG_FUNCTOR&& cb) override;
bool RegForwardMsgCallback(const NET_MSG_FUNCTOR&& cb) override;
bool RegNetEventCallback(const NET_EVENT_FUNCTOR&& cb) override;
std::shared_ptr<AFConnectionData> GetConnectionInfo(const int bus_id) override;
//AFMapEx<int, AFConnectionData>& GetServerList() override;
protected:
void ProcessUpdate();
void ProcessAddConnection();
std::shared_ptr<AFINet> CreateNet(const proto_type proto);
//void RegisterToServer(const AFGUID& session_id, const int bus_id);
int OnConnect(const AFNetEvent* event);
int OnDisconnect(const AFNetEvent* event);
void OnNetMsg(const AFNetMsg* msg, const int64_t session_id);
void OnNetEvent(const AFNetEvent* event);
void KeepReport(std::shared_ptr<AFConnectionData>& connection_data)
{
// TODO
}
void LogServerInfo(const std::string& strServerInfo)
{
// TODO
}
void LogServerInfo();
void KeepAlive(std::shared_ptr<AFConnectionData> pServerData);
//////////////////////////////////////////////////////////////////////////
//bool GetServerMachineData(const std::string& strServerID, AFCMachineNode& xMachineData);
//void AddServerWeightData(std::shared_ptr<AFConnectionData>& xInfo);
//void RemoveServerWeightData(std::shared_ptr<AFConnectionData>& xInfo);
//////////////////////////////////////////////////////////////////////////
bool AddServerNode(std::shared_ptr<AFConnectionData> data);
bool GetServerNode(const std::string& hash_key, AFVNode& vnode);
void RemoveServerNode(std::shared_ptr<AFConnectionData> data);
private:
AFPluginManager* m_pPluginManager;
AFINetServiceManagerModule* m_pNetServiceManagerModule;
AFIBusModule* m_pBusModule;
AFIMsgModule* m_pMsgModule;
AFILogModule* m_pLogModule;
// Connected connections(may the ConnectState is different)
AFSmartPtrMap<int, AFConnectionData> real_connections_;
// TODO: change to AFConsistentHashmap
//AFCConsistentHash consistent_hashmap_;
// the new consistent hash map
AFConsistentHashmapType consistent_hashmap_;
std::list<AFConnectionData> tmp_connections_;
std::map<int, NET_MSG_FUNCTOR> net_msg_callbacks_;
std::list<NET_EVENT_FUNCTOR> net_event_callbacks_;
// [NOT USE now] - forward to other processes
std::list<NET_MSG_FUNCTOR> net_msg_forward_callbacks_;
};
} // namespace ark
| 33.34188 | 113 | 0.716996 | overtalk |
84768d946ef771e9b2021e6d8650bb8af62e9a05 | 7,671 | cpp | C++ | drowaudio-Utility/plugins/Tremolo/Source/PluginEditor.cpp | 34Audiovisual/Progetti_JUCE | d22d91d342939a8463823d7a7ec528bd2228e5f7 | [
"MIT"
] | 92 | 2015-02-25T12:28:58.000Z | 2022-02-15T17:24:24.000Z | drowaudio-Utility/plugins/Tremolo/Source/PluginEditor.cpp | 34Audiovisual/Progetti_JUCE | d22d91d342939a8463823d7a7ec528bd2228e5f7 | [
"MIT"
] | 8 | 2015-05-03T18:36:49.000Z | 2018-02-06T15:50:32.000Z | drowaudio-Utility/plugins/Tremolo/Source/PluginEditor.cpp | 34Audiovisual/Progetti_JUCE | d22d91d342939a8463823d7a7ec528bd2228e5f7 | [
"MIT"
] | 34 | 2015-01-02T13:34:49.000Z | 2021-05-23T20:37:49.000Z | /*
==============================================================================
This file was auto-generated by the Introjucer!
It contains the basic startup code for a Juce application.
==============================================================================
*/
#include "PluginProcessor.h"
#include "PluginEditor.h"
#include "../../Common/PluginLookAndFeel.cpp"
//==============================================================================
TremoloAudioProcessorEditor::TremoloAudioProcessorEditor (TremoloAudioProcessor* ownerFilter_)
: AudioProcessorEditor (ownerFilter_),
ownerFilter (ownerFilter_)
{
Desktop::getInstance().setDefaultLookAndFeel (&customLookAndFeel);
// create the sliders and their labels
for (int i = 0; i < Parameters::numParameters; i++)
{
sliders.add (new Slider ());
addAndMakeVisible (sliders[i]);
String labelName = ownerFilter->getParameterName (i);
labels.add (new Label (String::empty, labelName));
addAndMakeVisible (labels[i]);
labels[i]->setJustificationType (Justification::left);
labels[i]->attachToComponent (sliders[i], false);
sliders[i]->addListener (this);
ownerFilter->getParameterObject (i)->setupSlider (*sliders[i]);
sliders[i]->getValueObject().referTo (ownerFilter->getParameterValueObject (i));
sliders[i]->setTextBoxStyle (Slider::TextBoxRight, false, 60, 18);
// sliders[i]->setColour (Slider::thumbColourId, Colours::grey);
// sliders[i]->setColour (Slider::textBoxTextColourId, Colour (0xff78f4ff));
// sliders[i]->setColour (Slider::textBoxBackgroundColourId, Colours::black);
// sliders[i]->setColour (Slider::textBoxOutlineColourId, Colour (0xff0D2474));
}
sliders[Parameters::rate]->setSliderStyle (Slider::RotaryVerticalDrag);
// sliders[Parameters::rate]->setColour (Slider::rotarySliderFillColourId, Colours::grey);
sliders[Parameters::rate]->setTextBoxStyle (Slider::TextBoxBelow, false, 60, 18);
labels[Parameters::rate]->attachToComponent (sliders[Parameters::rate], false);
labels[Parameters::rate]->setJustificationType (Justification::centred);
sliders[Parameters::depth]->setSliderStyle (Slider::RotaryVerticalDrag);
// sliders[Parameters::depth]->setColour (Slider::rotarySliderFillColourId, Colours::grey);
sliders[Parameters::depth]->setTextBoxStyle (Slider::TextBoxBelow, false, 60, 18);
labels[Parameters::depth]->attachToComponent (sliders[Parameters::depth], false);
labels[Parameters::depth]->setJustificationType (Justification::centred);
// ownerFilter->getParameterValueObject (Parameters::depth).addListener (this);
// ownerFilter->getParameterValueObject (Parameters::shape).addListener (this);
// ownerFilter->getParameterValueObject (Parameters::phase).addListener (this);
// create the buffer views
addAndMakeVisible (bufferViewL = new TremoloBufferView (ownerFilter->getTremoloBuffer (0).getData(),
ownerFilter->getTremoloBuffer (0).getSize()));
bufferViewL->setInterceptsMouseClicks (false, false);
addAndMakeVisible (bufferViewLLabel = new Label ("lLabel", "L:"));
bufferViewLLabel->attachToComponent (bufferViewL, true);
bufferViewLLabel->setFont (Font (30, Font::plain));
// bufferView1Label->setColour(Label::textColourId, Colours::white);
addAndMakeVisible (bufferViewR = new TremoloBufferView (ownerFilter->getTremoloBuffer (1).getData(),
ownerFilter->getTremoloBuffer (1).getSize()));
bufferViewR->setInterceptsMouseClicks (false, false);
addAndMakeVisible (bufferViewRLabel = new Label ("rLabel", "R:"));
bufferViewRLabel->attachToComponent (bufferViewR, true);
bufferViewRLabel->setFont (Font (30, Font::plain));
// bufferView2Label->setColour(Label::textColourId, Colours::white);
if (ownerFilter->getNumInputChannels() == 1)
setSize (360, 170);
else
setSize (360, 210);
// if plugin is mono set up the accordingly
if (ownerFilter->getNumInputChannels() < 2)
{
sliders[Parameters::phase]->setVisible (false);
bufferViewR->setVisible (false);
}
ownerFilter->addChangeListener (this);
}
TremoloAudioProcessorEditor::~TremoloAudioProcessorEditor()
{
ownerFilter->removeChangeListener (this);
for (int i = 0; i < Parameters::numParameters; i++)
{
sliders[i]->removeListener (this);
}
// ownerFilter->getParameterValueObject (Parameters::depth).removeListener (this);
// ownerFilter->getParameterValueObject (Parameters::shape).removeListener (this);
// ownerFilter->getParameterValueObject (Parameters::phase).removeListener (this);
}
//==============================================================================
void TremoloAudioProcessorEditor::paint (Graphics& g)
{
// just clear the window
PluginLookAndFeel::drawPluginBackgroundBase (g, *this);
const int verticalLineX = sliders[Parameters::shape]->getRight() + 10;
PluginLookAndFeel::drawInsetLine (g, 0, 115, verticalLineX, 115, 2);
PluginLookAndFeel::drawInsetLine (g, verticalLineX, 0, verticalLineX, 210, 2);
Rectangle<int> bevel (bufferViewL->getBounds().expanded (2, 2));
g.drawBevel (bevel.getX(), bevel.getY(), bevel.getWidth(), bevel.getHeight(), 2,
Colour (0xFF455769).darker (0.5f), Colour (0xFF455769).brighter (0.3f),
false, true);
if (getAudioProcessor()->getNumInputChannels() > 1)
{
bevel = bufferViewR->getBounds().expanded (2, 2);
g.drawBevel (bevel.getX(), bevel.getY(), bevel.getWidth(), bevel.getHeight(), 2,
Colour (0xFF455769).darker (0.5f), Colour (0xFF455769).brighter (0.3f),
false, true);
}
PluginLookAndFeel::drawPluginBackgroundHighlights (g, *this);
}
void TremoloAudioProcessorEditor::resized()
{
const int w = getWidth();
const int h = getHeight();
sliders[Parameters::rate]->setBounds (20, 35, 70, 70);
sliders[Parameters::depth]->setBounds (105, 35, 70, 70);
sliders[Parameters::shape]->setBounds (5, 140, w - 170, 20);
sliders[Parameters::phase]->setBounds (5, 180, w - 170, 20);
if (getAudioProcessor()->getNumInputChannels() > 1)
{
bufferViewL->setBounds (w - 125, 20,
115, ((h - 15) * 0.5f) - 14);
bufferViewR->setBounds (w - 125, ((h - 15) * 0.5f) + 15 + 2,
115, ((h - 15) * 0.5f) - 14);
}
else if (getAudioProcessor()->getNumInputChannels() == 1)
{
bufferViewL->setBounds (w - 150, 20,
140, (h - 15 - 15));
}
}
//void TremoloAudioProcessorEditor::valueChanged (Value& value)
//{
// bufferViewL->refreshBuffer();
// bufferViewR->refreshBuffer();
//}
void TremoloAudioProcessorEditor::changeListenerCallback (ChangeBroadcaster* /*source*/)
{
bufferViewL->refreshBuffer();
bufferViewR->refreshBuffer();
}
void TremoloAudioProcessorEditor::sliderValueChanged (Slider* /*slider*/)
{
}
void TremoloAudioProcessorEditor::sliderDragStarted (Slider* slider)
{
for (int i = 0; i < Parameters::numParameters; i++)
{
if (slider == sliders[i])
{
getAudioProcessor()->beginParameterChangeGesture (i);
}
}
}
void TremoloAudioProcessorEditor::sliderDragEnded (Slider* slider)
{
for (int i = 0; i < Parameters::numParameters; i++)
{
if (slider == sliders[i])
{
getAudioProcessor()->endParameterChangeGesture (i);
}
}
} | 39.541237 | 107 | 0.637857 | 34Audiovisual |
847b6787ce7e4a476e6e47a767321db6de7eabd5 | 3,798 | cpp | C++ | src/app/clusters/relative-humidity-measurement-server/relative-humidity-measurement-server.cpp | clapre/connectedhomeip | 30732ad8f5a0e5f909a1b27f14946d355db89ec7 | [
"Apache-2.0"
] | 14 | 2021-06-23T19:52:29.000Z | 2022-03-31T14:14:03.000Z | src/app/clusters/relative-humidity-measurement-server/relative-humidity-measurement-server.cpp | clapre/connectedhomeip | 30732ad8f5a0e5f909a1b27f14946d355db89ec7 | [
"Apache-2.0"
] | 40 | 2021-05-04T20:37:25.000Z | 2022-01-25T22:25:40.000Z | src/app/clusters/relative-humidity-measurement-server/relative-humidity-measurement-server.cpp | clapre/connectedhomeip | 30732ad8f5a0e5f909a1b27f14946d355db89ec7 | [
"Apache-2.0"
] | 7 | 2021-08-14T04:36:31.000Z | 2022-03-31T10:39:09.000Z | /*
*
* Copyright (c) 2021 Project CHIP 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 "relative-humidity-measurement-server.h"
#include <app/util/af.h>
#include <app/common/gen/attribute-id.h>
#include <app/common/gen/attribute-type.h>
#include <app/common/gen/cluster-id.h>
#include <app/util/af-event.h>
#include <app/util/attribute-storage.h>
#include <support/logging/CHIPLogging.h>
#ifndef emberAfRelativeHumidityMeasurementClusterPrintln
#define emberAfRelativeHumidityMeasurementClusterPrintln(...) ChipLogProgress(Zcl, __VA_ARGS__);
#endif
EmberAfStatus emberAfRelativeHumidityMeasurementClusterGetMeasuredValue(chip::EndpointId endpoint, uint16_t * measuredValue)
{
return emberAfReadServerAttribute(endpoint, ZCL_RELATIVE_HUMIDITY_MEASUREMENT_CLUSTER_ID,
ZCL_RELATIVE_HUMIDITY_MEASURED_VALUE_ATTRIBUTE_ID, (uint8_t *) measuredValue,
sizeof(*measuredValue));
}
EmberAfStatus emberAfRelativeHumidityMeasurementClusterGetMinMeasuredValue(chip::EndpointId endpoint, uint16_t * minMeasuredValue)
{
return emberAfReadServerAttribute(endpoint, ZCL_RELATIVE_HUMIDITY_MEASUREMENT_CLUSTER_ID,
ZCL_RELATIVE_HUMIDITY_MIN_MEASURED_VALUE_ATTRIBUTE_ID, (uint8_t *) minMeasuredValue,
sizeof(*minMeasuredValue));
}
EmberAfStatus emberAfRelativeHumidityMeasurementClusterGetMaxMeasuredValue(chip::EndpointId endpoint, uint16_t * maxMeasuredValue)
{
return emberAfReadServerAttribute(endpoint, ZCL_RELATIVE_HUMIDITY_MEASUREMENT_CLUSTER_ID,
ZCL_RELATIVE_HUMIDITY_MAX_MEASURED_VALUE_ATTRIBUTE_ID, (uint8_t *) maxMeasuredValue,
sizeof(*maxMeasuredValue));
}
EmberAfStatus emberAfRelativeHumidityMeasurementClusterSetMeasuredValueCallback(chip::EndpointId endpoint, uint16_t measuredValue)
{
return emberAfWriteServerAttribute(endpoint, ZCL_RELATIVE_HUMIDITY_MEASUREMENT_CLUSTER_ID,
ZCL_RELATIVE_HUMIDITY_MEASURED_VALUE_ATTRIBUTE_ID, (uint8_t *) &measuredValue,
ZCL_INT16U_ATTRIBUTE_TYPE);
}
EmberAfStatus emberAfRelativeHumidityMeasurementClusterSetMinMeasuredValueCallback(chip::EndpointId endpoint,
uint16_t minMeasuredValue)
{
return emberAfWriteServerAttribute(endpoint, ZCL_RELATIVE_HUMIDITY_MEASUREMENT_CLUSTER_ID,
ZCL_RELATIVE_HUMIDITY_MIN_MEASURED_VALUE_ATTRIBUTE_ID, (uint8_t *) &minMeasuredValue,
ZCL_INT16U_ATTRIBUTE_TYPE);
}
EmberAfStatus emberAfRelativeHumidityMeasurementClusterSetMaxMeasuredValueCallback(chip::EndpointId endpoint,
uint16_t maxMeasuredValue)
{
return emberAfWriteServerAttribute(endpoint, ZCL_RELATIVE_HUMIDITY_MEASUREMENT_CLUSTER_ID,
ZCL_RELATIVE_HUMIDITY_MAX_MEASURED_VALUE_ATTRIBUTE_ID, (uint8_t *) &maxMeasuredValue,
ZCL_INT16U_ATTRIBUTE_TYPE);
}
| 49.324675 | 130 | 0.695103 | clapre |
847c059447cfbd285063111cf1ddfa41234e043b | 1,234 | cpp | C++ | Src/Gen/Bsw/Common/test_debug.cpp | miaozhendaoren/autosar-framework | abcf11970470c082b2137da16e9b1a460e72fd74 | [
"BSL-1.0"
] | 31 | 2016-04-15T13:47:28.000Z | 2022-01-26T17:40:26.000Z | Src/Gen/Bsw/Common/test_debug.cpp | myGiter/autosar-framework | abcf11970470c082b2137da16e9b1a460e72fd74 | [
"BSL-1.0"
] | null | null | null | Src/Gen/Bsw/Common/test_debug.cpp | myGiter/autosar-framework | abcf11970470c082b2137da16e9b1a460e72fd74 | [
"BSL-1.0"
] | 21 | 2016-03-25T10:52:07.000Z | 2022-03-25T22:58:39.000Z | ///////////////////////////////////////////////////////
// Copyright 2014 Stephan Hage.
// Copyright 2014 Christopher Kormanyos.
// 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 )
//
#include <Bsw/Common/test_debug.h>
EXTERN_C
void test_debug(void)
{
/////////////////////////////////////////////////////
// TEST BEGIN
/////////////////////////////////////////////////////
// ENERGY:
util::dma<std::uint32_t,
std::uint32_t>::reg_or(mcal::reg::rcc_ahb1enr,
UINT32_C(0x08));
// DIRECTION OUTPUT:
util::dma<std::uint32_t,
std::uint32_t>::reg_msk(mcal::reg::gpiod_moder,
UINT32_C(0x55000000), UINT32_C(0xFF000000));
for(;;)
{
// OUTPUT VALUE HIGH:
util::dma<std::uint32_t,
std::uint32_t>::reg_set(mcal::reg::gpiod_bsrr,
UINT32_C(0xF000));
// OUTPUT VALUE LOW:
util::dma<std::uint32_t,
std::uint32_t>::reg_set(mcal::reg::gpiod_bsrr,
UINT32_C(0xF0000000));
}
/////////////////////////////////////////////////////
// TEST END
/////////////////////////////////////////////////////
} | 29.380952 | 64 | 0.47812 | miaozhendaoren |
84808a82387d9a6c56c1fece58b69038efe75ae1 | 3,551 | cpp | C++ | source/libplatform/archive.cpp | Lauvak/ray | 906d3991ddd232a7f78f0e51f29aeead008a139a | [
"BSD-3-Clause"
] | 113 | 2015-06-25T06:24:59.000Z | 2021-09-26T02:46:02.000Z | source/libplatform/archive.cpp | Lauvak/ray | 906d3991ddd232a7f78f0e51f29aeead008a139a | [
"BSD-3-Clause"
] | 2 | 2015-05-03T07:22:49.000Z | 2017-12-11T09:17:20.000Z | source/libplatform/archive.cpp | Lauvak/ray | 906d3991ddd232a7f78f0e51f29aeead008a139a | [
"BSD-3-Clause"
] | 17 | 2015-11-10T15:07:15.000Z | 2021-01-19T15:28:16.000Z | // +----------------------------------------------------------------------
// | Project : ray.
// | All rights reserved.
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017.
// +----------------------------------------------------------------------
// | * Redistribution and use of this software in source and binary forms,
// | with or without modification, are permitted provided that the following
// | conditions are met:
// |
// | * Redistributions of source code must retain the above
// | copyright notice, this list of conditions and the
// | following disclaimer.
// |
// | * Redistributions in binary form must reproduce the above
// | copyright notice, this list of conditions and the
// | following disclaimer in the documentation and/or other
// | materials provided with the distribution.
// |
// | * Neither the name of the ray team, nor the names of its
// | contributors may be used to endorse or promote products
// | derived from this software without specific prior
// | written permission of the ray team.
// |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// +----------------------------------------------------------------------
#include <ray/archive.h>
_NAME_BEGIN
archive::archive() noexcept
{
}
archive::~archive() noexcept
{
}
archivebuf*
archive::rdbuf() const noexcept
{
return _strbuf;
}
void
archive::set_rdbuf(archivebuf* buf) noexcept
{
_strbuf = buf;
}
void
archive::_init(archivebuf* _buf, ios_base::openmode mode) noexcept
{
this->set_rdbuf(_buf);
_mode = mode;
ios_base::_init();
}
void
archive::setOpenMode(ios_base::openmode mode) noexcept
{
_mode = mode;
}
ios_base::openmode
archive::getOpenMode() const noexcept
{
return _mode;
}
std::size_t
archive::size() const noexcept
{
return this->rdbuf()->size();
}
const char*
archive::type_name() const noexcept
{
return this->rdbuf()->type_name();
}
const char*
archive::type_name(type_t type) const noexcept
{
return this->rdbuf()->type_name(type);
}
const archive::type_t
archive::type() const noexcept
{
return this->rdbuf()->type();
}
bool
archive::is_null() const noexcept
{
return this->rdbuf()->is_null();
}
bool
archive::is_boolean() const noexcept
{
return this->rdbuf()->is_boolean();
}
bool
archive::is_integral() const noexcept
{
return this->rdbuf()->is_integral();
}
bool
archive::is_float() const noexcept
{
return this->rdbuf()->is_float();
}
bool
archive::is_string() const noexcept
{
return this->rdbuf()->is_string();
}
bool
archive::is_numeric() const noexcept
{
return this->rdbuf()->is_numeric();
}
bool
archive::is_array() const noexcept
{
return this->rdbuf()->is_array();
}
bool
archive::is_object() const noexcept
{
return this->rdbuf()->is_object();
}
_NAME_END | 23.20915 | 78 | 0.656435 | Lauvak |
8483db579bb4c66af8faaa47b848695c74d1ba31 | 857 | cpp | C++ | Aufgaben/Mehr_Laboraufgaben/loesungen/aufgabe05.cpp | TEL21D/Informatik1 | d9486a64d11e0bf42077b9e9e469157b5371c2ab | [
"MIT"
] | null | null | null | Aufgaben/Mehr_Laboraufgaben/loesungen/aufgabe05.cpp | TEL21D/Informatik1 | d9486a64d11e0bf42077b9e9e469157b5371c2ab | [
"MIT"
] | null | null | null | Aufgaben/Mehr_Laboraufgaben/loesungen/aufgabe05.cpp | TEL21D/Informatik1 | d9486a64d11e0bf42077b9e9e469157b5371c2ab | [
"MIT"
] | 1 | 2022-02-04T08:14:41.000Z | 2022-02-04T08:14:41.000Z | #include "pruefung.h"
/*** AUFGABE: Arrays, 4 Punkte ***/
/*** AUFGABENSTELLUNG:
Schreiben Sie eine Funktion zip, die zwei Strings erwartet.
Die Funktion soll die beiden Strings zusammenmischen, indem Sie
immer abwechselnd ein Zeichen aus dem einen und dem anderen nimmt.
Sie dürfen annehmen, dass die Strings gleich lang sind.
Die Funktion soll das Ergebnis zurückliefern.
***/
string zip(string s1, string s2);
/*** TESTCODE/MAIN ***/
int main() {
cout << zip("abc", "def") << endl; // Soll "adbecf" ausgeben.
cout << zip("bab", "aba") << endl; // Soll "baabba" ausgeben.
cout << zip("", "") << endl; // Soll "" ausgeben.
return 0;
}
/*** LOESUNG ***/
string zip(string s1, string s2)
{
string result;
for (int i=0; i<s1.size(); i++)
{
result += s1[i];
result += s2[i];
}
return result;
}
| 23.162162 | 70 | 0.616103 | TEL21D |
848a113c0effe5216a4319a2eba0e26793bb0fe1 | 1,053 | cpp | C++ | src/service/settings.cpp | pvantonov/energetiK | e4aa0e980274304123009d888353e4ae04eee45c | [
"MIT"
] | 1 | 2020-06-11T14:10:35.000Z | 2020-06-11T14:10:35.000Z | src/service/settings.cpp | pvantonov/energetik | e4aa0e980274304123009d888353e4ae04eee45c | [
"MIT"
] | null | null | null | src/service/settings.cpp | pvantonov/energetik | e4aa0e980274304123009d888353e4ae04eee45c | [
"MIT"
] | null | null | null | #include "settings.hpp"
/*!
* \class Settings
* A singletone object to provide access to service configuration.
*/
Settings::Settings() : KCoreConfigSkeleton("energetikrc")
{
this->setCurrentGroup("General");
this->addItemBool("InspectProcesses", this->inspectProcesses, true);
this->addItemBool("InspectFullscreen", this->inspectFullscreen, true);
this->setCurrentGroup("ProcessInhibition");
this->addItemInt("Interval", this->inspecProcessesInterval, 1000);
this->addItemStringList("Processes", this->wantedProcesses);
}
/*!
* \var QStringList Settings::inspectProcesses
* Show if the process inhibitor should be activated.
*/
/*!
* \var QStringList Settings::inspectFullscreen
* Show if the fullscreen inhibitor should be activated.
*/
/*!
* \var QStringList Settings::wantedProcesses
* List of processes that should cause inhibition of power management.
*/
/*!
* \var int Settings::inspecProcessesInterval
* Interval (in milliseconds) at which the process inhibitor should actualize inhibition list.
*/
| 27.710526 | 94 | 0.739791 | pvantonov |
848ec436eccc31bb7ae89283ff2e55a27fff9f4f | 754 | cpp | C++ | testStats1.cpp | LearnerDroid/cs32lab06 | 36a2cb19b51cc7796a4e9acbd6ac5fd41139e230 | [
"MIT"
] | null | null | null | testStats1.cpp | LearnerDroid/cs32lab06 | 36a2cb19b51cc7796a4e9acbd6ac5fd41139e230 | [
"MIT"
] | null | null | null | testStats1.cpp | LearnerDroid/cs32lab06 | 36a2cb19b51cc7796a4e9acbd6ac5fd41139e230 | [
"MIT"
] | null | null | null | #include "stats.h"
#include "parse.h"
#include <iostream>
#include "tddFuncs.h"
using namespace std;
int main() {
cout << "Testing stats" << endl;
vector<double> x = vector<double>{43.0, 21, 25, 42, 57, 59};
vector<double> y = vector<double>{99.0, 65, 79, 75, 87, 81};
double meanX = stats::computeMean(x);
double stdDevX = stats::computeStdDevSample(x);
double meanY = stats::computeMean(y);
double stdDevY = stats::computeStdDevSample(y);
/*
ASSERT_EQUALS(41.167, meanX);
ASSERT_EQUALS(15.753, stdDevX);
ASSERT_EQUALS(81.0, meanY);
ASSERT_EQUALS(11.454, stdDevY);
*/
ASSERT_EQUALS(meanX, 41.167);
ASSERT_EQUALS(stdDevX, 15.753);
ASSERT_EQUALS(meanY, 81.0);
ASSERT_EQUALS(stdDevY, 11.454);
return 0;
}
| 23.5625 | 63 | 0.668435 | LearnerDroid |
848fe3733ac46892acab29fa4c00533d46bc70f1 | 4,672 | cp | C++ | Win32/Sources/Application/Rules/Action Dialogs/CBounceActionDialog.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2015-04-21T16:10:43.000Z | 2021-11-05T13:41:46.000Z | Win32/Sources/Application/Rules/Action Dialogs/CBounceActionDialog.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2015-11-02T13:32:11.000Z | 2019-07-10T21:11:21.000Z | Win32/Sources/Application/Rules/Action Dialogs/CBounceActionDialog.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2015-01-12T08:49:12.000Z | 2021-03-27T09:11:10.000Z | /*
Copyright (c) 2007 Cyrus Daboo. 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.
*/
// BounceActionDialog.cpp : implementation file
//
#include "CBounceActionDialog.h"
#include "CMulberryCommon.h"
#include "CPreferences.h"
#include "CSDIFrame.h"
#include "CUnicodeUtils.h"
/////////////////////////////////////////////////////////////////////////////
// CBounceActionDialog dialog
CBounceActionDialog::CBounceActionDialog(CWnd* pParent /*=NULL*/)
: CHelpDialog(CBounceActionDialog::IDD, pParent)
{
//{{AFX_DATA_INIT(CBounceActionDialog)
mUseStandard = -1;
mCreateDraft = FALSE;
//}}AFX_DATA_INIT
}
void CBounceActionDialog::DoDataExchange(CDataExchange* pDX)
{
CHelpDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CBounceActionDialog)
DDX_UTF8Text(pDX, IDC_BOUNCEACTION_TO, mTo);
DDX_UTF8Text(pDX, IDC_BOUNCEACTION_CC, mCC);
DDX_UTF8Text(pDX, IDC_BOUNCEACTION_BCC, mBcc);
DDX_Radio(pDX, IDC_BOUNCEACTION_STANDARDIDENTITY, mUseStandard);
DDX_Control(pDX, IDC_BOUNCEACTION_IDENTITY, mIdentityPopup);
DDX_Check(pDX, IDC_BOUNCEACTION_DRAFT, mCreateDraft);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CBounceActionDialog, CHelpDialog)
//{{AFX_MSG_MAP(CBounceActionDialog)
ON_BN_CLICKED(IDC_BOUNCEACTION_STANDARDIDENTITY, OnStandardIdentity)
ON_BN_CLICKED(IDC_BOUNCEACTION_USEIDENTITY, OnUseIdentity)
ON_COMMAND_RANGE(IDM_IDENTITY_NEW, IDM_IDENTITYEnd, OnIdentityPopup)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CBounceActionDialog message handlers
BOOL CBounceActionDialog::OnInitDialog()
{
CHelpDialog::OnInitDialog();
// Subclass items
mIdentityPopup.SubclassDlgItem(IDC_BOUNCEACTION_IDENTITY, this, IDI_POPUPBTN, 0, 0, 0, true, false);
mIdentityPopup.SetMenu(IDR_POPUP_IDENTITY);
mIdentityPopup.Reset(CPreferences::sPrefs->mIdentities.GetValue());
// Set identity items
mIdentityPopup.SetIdentity(CPreferences::sPrefs, mCurrentIdentity);
mIdentityPopup.EnableWindow(mUseStandard == 1);
return true;
}
void CBounceActionDialog::OnStandardIdentity()
{
CButton* cb = static_cast<CButton*>(GetDlgItem(IDC_BOUNCEACTION_STANDARDIDENTITY));
mIdentityPopup.EnableWindow(!cb->GetCheck());
}
void CBounceActionDialog::OnUseIdentity()
{
CButton* cb = static_cast<CButton*>(GetDlgItem(IDC_BOUNCEACTION_USEIDENTITY));
mIdentityPopup.EnableWindow(cb->GetCheck());
}
void CBounceActionDialog::OnIdentityPopup(UINT nID)
{
switch(nID)
{
// New identity wanted
case IDM_IDENTITY_NEW:
mIdentityPopup.DoNewIdentity(CPreferences::sPrefs);
break;
// New identity wanted
case IDM_IDENTITY_EDIT:
mIdentityPopup.DoEditIdentity(CPreferences::sPrefs);
break;
// Delete existing identity
case IDM_IDENTITY_DELETE:
mIdentityPopup.DoDeleteIdentity(CPreferences::sPrefs);
break;
// Select an identity
default:
mIdentityPopup.SetValue(nID);
mCurrentIdentity = CPreferences::sPrefs->mIdentities.Value()[nID - IDM_IDENTITYStart].GetIdentity();
break;
}
}
// Set the details
void CBounceActionDialog::SetDetails(CActionItem::CActionBounce& details)
{
mTo = details.Addrs().mTo;
mCC = details.Addrs().mCC;
mBcc = details.Addrs().mBcc;
mUseStandard = details.UseTiedIdentity() ? 0 : 1;
mCurrentIdentity = details.GetIdentity();
mCreateDraft = details.CreateDraft();
}
// Get the details
void CBounceActionDialog::GetDetails(CActionItem::CActionBounce& details)
{
details.Addrs().mTo = mTo;
details.Addrs().mCC = mCC;
details.Addrs().mBcc = mBcc;
details.SetTiedIdentity(mUseStandard == 0);
details.SetIdentity(mCurrentIdentity);
details.SetCreateDraft(mCreateDraft);
}
bool CBounceActionDialog::PoseDialog(CActionItem::CActionBounce& details)
{
bool result = false;
// Create the dialog
CBounceActionDialog dlog(CSDIFrame::GetAppTopWindow());
dlog.SetDetails(details);
// Let DialogHandler process events
if ((dlog.DoModal() == IDOK))
{
dlog.GetDetails(details);
result = true;
}
return result;
}
| 27.482353 | 103 | 0.715753 | mulberry-mail |
84920b019b61917c8e85ed61db5c325cc6f3b6c4 | 2,913 | cpp | C++ | benchmarks/src/cuda/sdk/4.2/boxFilter/boxFilter_gold.cpp | dounghun22/gpgpu-sim_simulations_UVM | b37827a7d72a024fe958e0137afd3a7c00a2ec88 | [
"BSD-2-Clause"
] | 221 | 2015-03-29T02:05:49.000Z | 2022-03-25T01:45:36.000Z | tests/cuda4.1sdk/tests/boxFilter/boxFilter_gold.cpp | mprevot/gpuocelot | d9277ef05a110e941aef77031382d0260ff115ef | [
"BSD-3-Clause"
] | 106 | 2015-03-29T01:28:42.000Z | 2022-02-15T19:38:23.000Z | tests/cuda4.1sdk/tests/boxFilter/boxFilter_gold.cpp | mprevot/gpuocelot | d9277ef05a110e941aef77031382d0260ff115ef | [
"BSD-3-Clause"
] | 83 | 2015-07-10T23:09:57.000Z | 2022-03-25T03:01:00.000Z | /*
* Copyright 1993-2010 NVIDIA Corporation. All rights reserved.
*
* Please refer to the NVIDIA end user license agreement (EULA) associated
* with this source code for terms and conditions that govern your use of
* this software. Any use, reproduction, disclosure, or distribution of
* this software and related documentation outside the terms of the EULA
* is strictly prohibited.
*
*/
////////////////////////////////////////////////////////////////////////////////
// export C interface
extern "C"
void computeGold(float *id, float *od, int w, int h, int r);
// CPU implementation
void hboxfilter_x(float *id, float *od, int w, int h, int r)
{
float scale = 1.0f / (2*r+1);
for (int y = 0; y < h; y++) {
float t;
// do left edge
t = id[y*w] * r;
for (int x = 0; x < r+1; x++) {
t += id[y*w+x];
}
od[y*w] = t * scale;
for(int x = 1; x < r+1; x++) {
int c = y*w+x;
t += id[c+r];
t -= id[y*w];
od[c] = t * scale;
}
// main loop
for(int x = r+1; x < w-r; x++) {
int c = y*w+x;
t += id[c+r];
t -= id[c-r-1];
od[c] = t * scale;
}
// do right edge
for (int x = w-r; x < w; x++) {
int c = y*w+x;
t += id[(y*w)+w-1];
t -= id[c-r-1];
od[c] = t * scale;
}
}
}
void hboxfilter_y(float *id, float *od, int w, int h, int r)
{
float scale = 1.0f / (2*r+1);
for (int x = 0; x < w; x++) {
float t;
// do left edge
t = id[x] * r;
for (int y = 0; y < r+1; y++) {
t += id[y*w+x];
}
od[x] = t * scale;
for(int y = 1; y < r+1; y++) {
int c = y*w+x;
t += id[c+r*w];
t -= id[x];
od[c] = t * scale;
}
// main loop
for(int y = r+1; y < h-r; y++) {
int c = y*w+x;
t += id[c+r*w];
t -= id[c-(r*w)-w];
od[c] = t * scale;
}
// do right edge
for (int y = h-r; y < h; y++) {
int c = y*w+x;
t += id[(h-1)*w+x];
t -= id[c-(r*w)-w];
od[c] = t * scale;
}
}
}
////////////////////////////////////////////////////////////////////////////////
//! Compute reference data set
//! @param image pointer to input data
//! @param temp pointer to temporary store
//! @param w width of image
//! @param h height of image
//! @param r radius of filter
////////////////////////////////////////////////////////////////////////////////
void computeGold(float *image, float *temp, int w, int h, int r)
{
hboxfilter_x(image, temp, w, h, r);
hboxfilter_y(temp, image, w, h, r);
}
| 26.008929 | 80 | 0.388946 | dounghun22 |
8492877aef82d52c927651d9bab3a463b91ef8e4 | 4,560 | cpp | C++ | VSBellNew/tool/demo-dijkstra.cpp | haskellstudio/belle_old | a5ce86954b61dbacde1d1bf24472d95246be45e5 | [
"BSD-2-Clause"
] | null | null | null | VSBellNew/tool/demo-dijkstra.cpp | haskellstudio/belle_old | a5ce86954b61dbacde1d1bf24472d95246be45e5 | [
"BSD-2-Clause"
] | null | null | null | VSBellNew/tool/demo-dijkstra.cpp | haskellstudio/belle_old | a5ce86954b61dbacde1d1bf24472d95246be45e5 | [
"BSD-2-Clause"
] | null | null | null | /*
==============================================================================
Copyright 2007-2013, 2017 William Andrew Burnson
Copyright 2013-2016 Robert Taub
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL 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.
==============================================================================
*/
#define PRIM_COMPILE_INLINE
#include "prim.h"
using namespace prim;
class CostLabel : public GraphTLabel<String>
{
public:
number Cost() {return Get("Cost").ToNumber();}
bool EdgeEquivalent(const GraphTLabel<String>& L) {(void)L; return true;}
};
typedef GraphT<CostLabel> CostLabeledGraph;
typedef Pointer<GraphT<CostLabel>::Object> CostLabeledEdge;
typedef Pointer<GraphT<CostLabel>::Object> CostLabeledNode;
typedef Pointer<const GraphT<CostLabel>::Object> ConstEdge;
typedef Pointer<const GraphT<CostLabel>::Object> ConstNode;
typedef Array<CostLabeledNode> CostLabeledNodes;
typedef Array<const CostLabeledNode> ConstNodes;
int main()
{
{
CostLabeledGraph G;
CostLabeledNode Start = G.Add(), P = G.Add(), Q = G.Add(), R = G.Add(),
End = G.Add();
Start->Set("Name") = "Start";
P->Set("Name") = "P";
Q->Set("Name") = "Q";
R->Set("Name") = "R";
End->Set("Name") = "End";
G.Connect(Start, P)->Set("Cost") = 5;
G.Connect(P, Q)->Set("Cost") = 5;
G.Connect(Q, R)->Set("Cost") = 5;
G.Connect(R, End)->Set("Cost") = 5;
G.Connect(Start, Q)->Set("Cost") = 1;
G.Connect(Q, End)->Set("Cost") = 1;
C::Out() >> G;
List<ConstNode> ShortestPath = G.ShortestPath(Start, End, CostLabel());
C::Out() >> "Shortest Path:";
for(count i = 0; i < ShortestPath.n(); i++)
C::Out() >> ShortestPath[i]->Get("Name");
}
{
count m = 34, n = 34;
C::Out() >> "Creating Maze...";
Matrix<CostLabeledNode> M(m, n);
CostLabeledGraph G;
Tree<ConstNode, VectorInt> Lookup;
for(count i = 0; i < m; i++)
for(count j = 0; j < n; j++)
M(i, j) = G.Add(), M(i, j)->Set("Name") = String(i) + "," + String(j),
Lookup[M(i, j)] = VectorInt(integer(i), integer(j));
for(count i = 0; i < m; i++)
{
for(count j = 0; j < n; j++)
{
if(i + 1 < m)
G.Connect(M(i, j), M(i + 1, j))->Set("Cost") = 1.f;
if(j + 1 < n)
G.Connect(M(i, j), M(i, j + 1))->Set("Cost") = 1.f;
if(i + 1 < m and j + 1 < n)
G.Connect(M(i, j), M(i + 1, j + 1))->Set("Cost") = Sqrt(2.f);
}
}
for(count i = 0; i < m; i++)
{
for(count j = 0; j < n; j++)
{
number x = i - m / 2;
number y = j - n / 2;
if(Distance(number(0), number(0), x, y) < number(Min(m, n)) / 3.f)
G.Remove(M(i, j)), M(i, j) = CostLabeledNode();
}
}
C::Out() >> "Solving Maze...";
List<ConstNode> ShortestPath = G.ShortestPath(M(0, 0), M(m - 1, n - 1),
CostLabel());
Matrix<ascii> O(m, n);
for(count i = 0; i < m; i++)
for(count j = 0; j < n; j++)
O(i, j) = M(i, j) ? '.' : '*';
for(count i = 0; i < ShortestPath.n(); i++)
{
VectorInt V = Lookup[ShortestPath[i]];
O(count(V.i()), count(V.j())) = 'X';
}
for(count j = 0; j < n; j++)
{
C::Out()++;
for(count i = 0; i < m; i++)
C::Out() << " " << O(i, j);
}
}
return AutoRelease<Console>();
}
| 34.80916 | 80 | 0.576535 | haskellstudio |
8494c59169ea9f8d720347ea9f8bf79ad1abfe1a | 1,427 | hpp | C++ | include/simplecs/components.hpp | iTuMaN4iK/simplesc | 90a8d4b4d885f2de86e1f0a10824ccfb4c726b1c | [
"MIT"
] | null | null | null | include/simplecs/components.hpp | iTuMaN4iK/simplesc | 90a8d4b4d885f2de86e1f0a10824ccfb4c726b1c | [
"MIT"
] | null | null | null | include/simplecs/components.hpp | iTuMaN4iK/simplesc | 90a8d4b4d885f2de86e1f0a10824ccfb4c726b1c | [
"MIT"
] | null | null | null | #pragma once
#include "simplecs/config.hpp"
#include "simplecs/generic/components.h"
// TODO: use only c_api types
#include "simplecs/c_api/relational.hpp"
#include "simplecs/c_api/storage.hpp"
#include <cstddef>
/**
* Component implementation based on C api.
*/
namespace eld
{
namespace impl
{
struct component_traits_c
{
using component_descriptor_type = c_api::component_descriptor;
};
template<typename ClassType>
class component_c
{
public:
using component_descriptor_type = component_traits_c::component_descriptor_type;
using type = ClassType;
SIMPLECS_DECL static component_descriptor_type component_descriptor()
{
static c_context context{};
return context.descriptor();
}
private:
class c_context
{
public:
c_context();
~c_context();
[[nodiscard]] c_api::component_storage_descriptor descriptor() const;
private:
c_api::component_storage_descriptor descriptor_;
};
private:
};
} // namespace impl
template <typename ClassT>
using component_c = impl::component_c<ClassT>;
} // namespace eld
#ifdef SIMPLECS_HEADER_ONLY
# include "simplecs/src/components.ipp"
#endif | 23.016129 | 92 | 0.599159 | iTuMaN4iK |
8498251a256dcc7976011d780e66ef07065b798d | 2,821 | cc | C++ | src/kokkos/plugin-PixelTriplets/kokkos/PixelTrackSoAFromKokkos.cc | asubah/pixeltrack-standalone | 859ffeb0454cc09dc7b1c166fc94548caf5ae02d | [
"Apache-2.0"
] | null | null | null | src/kokkos/plugin-PixelTriplets/kokkos/PixelTrackSoAFromKokkos.cc | asubah/pixeltrack-standalone | 859ffeb0454cc09dc7b1c166fc94548caf5ae02d | [
"Apache-2.0"
] | null | null | null | src/kokkos/plugin-PixelTriplets/kokkos/PixelTrackSoAFromKokkos.cc | asubah/pixeltrack-standalone | 859ffeb0454cc09dc7b1c166fc94548caf5ae02d | [
"Apache-2.0"
] | null | null | null | #include "KokkosCore/kokkosConfig.h"
#include "KokkosCore/Product.h"
#include "KokkosCore/ScopedContext.h"
#include "KokkosCore/deep_copy.h"
#include "KokkosCore/shared_ptr.h"
#include "KokkosDataFormats/PixelTrackKokkos.h"
#include "Framework/EventSetup.h"
#include "Framework/Event.h"
#include "Framework/PluginFactory.h"
#include "Framework/EDProducer.h"
namespace KOKKOS_NAMESPACE {
class PixelTrackSoAFromKokkos : public edm::EDProducerExternalWork {
public:
explicit PixelTrackSoAFromKokkos(edm::ProductRegistry& reg);
~PixelTrackSoAFromKokkos() override = default;
private:
void acquire(edm::Event const& iEvent,
edm::EventSetup const& iSetup,
edm::WaitingTaskWithArenaHolder waitingTaskHolder) override;
void produce(edm::Event& iEvent, edm::EventSetup const& iSetup) override;
using TracksDeviceMemSpace = cms::kokkos::shared_ptr<pixelTrack::TrackSoA, KokkosDeviceMemSpace>;
using TracksHostMemSpace = cms::kokkos::shared_ptr<pixelTrack::TrackSoA, KokkosHostMemSpace>;
edm::EDGetTokenT<cms::kokkos::Product<TracksDeviceMemSpace>> tokenKokkos_;
edm::EDPutTokenT<TracksHostMemSpace> tokenSOA_;
TracksHostMemSpace m_soa;
};
PixelTrackSoAFromKokkos::PixelTrackSoAFromKokkos(edm::ProductRegistry& reg)
: tokenKokkos_(reg.consumes<cms::kokkos::Product<TracksDeviceMemSpace>>()),
tokenSOA_(reg.produces<TracksHostMemSpace>()) {}
void PixelTrackSoAFromKokkos::acquire(edm::Event const& iEvent,
edm::EventSetup const& iSetup,
edm::WaitingTaskWithArenaHolder waitingTaskHolder) {
auto const& inputDataWrapped = iEvent.get(tokenKokkos_);
cms::kokkos::ScopedContextAcquire<KokkosExecSpace> ctx{inputDataWrapped, std::move(waitingTaskHolder)};
auto const& inputData = ctx.get(inputDataWrapped);
m_soa = cms::kokkos::make_shared<pixelTrack::TrackSoA, KokkosHostMemSpace>(ctx.execSpace());
cms::kokkos::deep_copy(ctx.execSpace(), m_soa, inputData);
}
void PixelTrackSoAFromKokkos::produce(edm::Event& iEvent, edm::EventSetup const& iSetup) {
/*
auto const & tsoa = *m_soa;
auto maxTracks = tsoa.stride();
std::cout << "size of SoA" << sizeof(tsoa) << " stride " << maxTracks << std::endl;
int32_t nt = 0;
for (int32_t it = 0; it < maxTracks; ++it) {
auto nHits = tsoa.nHits(it);
assert(nHits==int(tsoa.hitIndices.size(it)));
if (nHits == 0) break; // this is a guard: maybe we need to move to nTracks...
nt++;
}
std::cout << "found " << nt << " tracks in cpu SoA at " << &tsoa << std::endl;
*/
// DO NOT make a copy (actually TWO....)
iEvent.emplace(tokenSOA_, std::move(m_soa));
}
} // namespace KOKKOS_NAMESPACE
DEFINE_FWK_KOKKOS_MODULE(PixelTrackSoAFromKokkos);
| 40.3 | 107 | 0.701524 | asubah |
8499ea746249648b700d7fbdcbcd24a81e759fd6 | 1,319 | hpp | C++ | src/stan/language/generator/generate_program_reader_fun.hpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | 1 | 2019-09-06T15:53:17.000Z | 2019-09-06T15:53:17.000Z | src/stan/language/generator/generate_program_reader_fun.hpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | 8 | 2019-01-17T18:51:16.000Z | 2019-01-17T18:51:39.000Z | src/stan/language/generator/generate_program_reader_fun.hpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_LANG_GENERATOR_GENERATE_PROGRAM_READER_FUN_HPP
#define STAN_LANG_GENERATOR_GENERATE_PROGRAM_READER_FUN_HPP
#include "constants.hpp"
#include <stan/util/io/program_reader.hpp>
#include <ostream>
#include <vector>
namespace stan {
namespace lang {
/**
* Generate a top-level function that returns the program reader
* for the specified history.
*
* <p>Implementation note: Because this is only called when there
* is an error to report, reconstructing on each call has
* acceptable performance.
*
* @param[in] history record of I/O path for lines in compound program
* @param[in, out] o stream to which generated code is written
*/
void generate_program_reader_fun(const std::vector<io::preproc_event>& history,
std::ostream& o) {
o << "static stan::io::program_reader prog_reader__() {" << std::endl;
o << INDENT << "stan::io::program_reader reader;" << std::endl;
for (size_t i = 0; i < history.size(); ++i)
o << INDENT << "reader.add_event(" << history[i].concat_line_num_ << ", "
<< history[i].line_num_ << ", \"" << history[i].action_ << "\""
<< ", \"" << history[i].path_ << "\");" << std::endl;
o << INDENT << "return reader;" << std::endl;
o << "}" << std::endl << std::endl;
}
} // namespace lang
} // namespace stan
#endif
| 34.710526 | 79 | 0.658074 | alashworth |
849a65107e995731e6dafc2b526747c8d5fef702 | 11,401 | cpp | C++ | old/volution.cpp | infoburp/volution | e803f3c66e98943bd7d1263ed9e6220291d49373 | [
"MIT"
] | 2 | 2016-07-15T05:40:19.000Z | 2022-03-13T01:33:55.000Z | old/volution.cpp | infoburp/volution | e803f3c66e98943bd7d1263ed9e6220291d49373 | [
"MIT"
] | null | null | null | old/volution.cpp | infoburp/volution | e803f3c66e98943bd7d1263ed9e6220291d49373 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <QtGui>
#include <QtOpenGL>
#include <boost/compute/command_queue.hpp>
#include <boost/compute/kernel.hpp>
#include <boost/compute/program.hpp>
#include <boost/compute/source.hpp>
#include <boost/compute/system.hpp>
#include <boost/compute/interop/opengl.hpp>
using namespace std;
namespace compute = boost::compute;
int main (int argc, char* argv[])
{
// get the default compute device
compute::device gpu = compute::system::default_device();
// create a compute context and command queue
compute::context ctx(gpu);
compute::command_queue queue(ctx, gpu);
//set some default values for when no commandline arguments are given
//create accuracy variable
int accuracy = 90;
// create vector on device
compute::vector<int> device_accuracy(1);
// copy from host to device
compute::copy(accuracy,
accuracy,
device_accuracy.begin());
//create polygons variable
int polygons = 50;
// create vector on device
compute::vector<int> device_polygons(1);
// copy from host to device
compute::copy(host_data,
host_data + 5,
device_vector.begin());
//create vertices variable
int vertices = 6;
// create vector on device
compute::vector<int> device_vertices(1);
// copy from host to device
compute::copy(host_data,
host_data + 5,
device_vector.begin());
//read input commandline arguments
for (int i = 1; i < argc; ++i)
{
if (std::string(argv[i]) == "-a")
{
//initialise desired accuracy variable according to commandline argument -a
accuracy = argv[i + 1];
// copy from host to device
compute::copy(accuracy,
accuracy,
device_accuracy.begin());
}
if (std::string(argv[i]) == "-p")
{
//initialise maximum polygons variable according to commandline argument -p
polygons = argv[i + 1];
// copy from host to device
compute::copy(accuracy,
accuracy,
device_accuracy.begin());
}
if (std::string(argv[i]) == "-v")
{
//initialise maximum verices per polygon variable according to commandline argument -v
vertices = argv[i + 1];
// copy from host to device
compute::copy(accuracy,
accuracy,
device_accuracy.begin());
}
}
//create leaderDNA variable
// generate random dna vector on the host
std::vector<int> leaderDNA(1000000);
std::generate(leaderDNA.begin(), leaderDNA.end(), rand);
// create vector on the device
compute::vector<int> device_leaderDNA(1000000, ctx);
// copy data to the device
compute::copy(
leaderDNA.begin(),
leaderDNA.end(),
device_leaderDNA.begin(),
queue
);
//create mutatedDNA variable
// create data array on host
int host_data[] = { 1, 3, 5, 7, 9 };
// create vector on device
compute::vector<int> device_vector(5);
// copy from host to device
compute::copy(host_data,
host_data + 5,
device_vector.begin());
//create leaderDNArender variable
// create data array on host
int host_data[] = { 1, 3, 5, 7, 9 };
// create vector on device
compute::vector<int> device_vector(5);
// copy from host to device
compute::copy(host_data,
host_data + 5,
device_vector.begin());
//create mutatedDNArender variable
// create data array on host
int host_data[] = { 1, 3, 5, 7, 9 };
// create vector on device
compute::vector<int> device_vector(5);
// copy from host to device
compute::copy(host_data,
host_data + 5,
device_vector.begin());
//create original image variable + load image into gpu memory
if (std::string(argv[i]) == "")
{
//load file according to commandline argument into gpu vector
//get x(max), y(max). (image dimensions)
//make image vector on device
compute::vector<int> originalimage(ctx, n);
// copy data to the device
compute::copy(
host_vector.begin(),
host_vector.end(),
device_vector.begin(),
queue
);
}
//run render loop until desired accuracy is reached
while (leaderaccuracy<accuracy)
{
//render leader DNA to a raster image in opengl texture
boost::compute::function<int (int)> renderDNA =
boost::compute::make_function_from_source<int (int)>(
"renderDNA",
"int renderDNA(int x)
{ //for each shape in dna
{
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, gl_texture_);
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex2f(0, 0);
glTexCoord2f(0, 1); glVertex2f(0, h);
glTexCoord2f(1, 1); glVertex2f(w, h);
glTexCoord2f(1, 0); glVertex2f(w, 0);
glEnd();
} }"
);
//compute fitness of leader dna image
//compute what % match DNAimage is to original image
boost::compute::function<int (int)> computefitnesspercent =
boost::compute::make_function_from_source<int (int)>(
"computefitnesspercent",
"int computefitnesspercent(int x) { }"
);
while ()
{
//mutate from the leaderDNA
boost::compute::function<int (int)> mutateDNA =
boost::compute::make_function_from_source<int (int)>(
"mutateDNA",
"int mutateDNA(int DNA)
{
//mutate input DNA randomly
mutated_shape = RANDINT(NUM_SHAPES);
double roulette = RANDDOUBLE(3);
//mutate color
//randomly change mutated_shape colour
//change red
//up
//down
//change green
//up
//down
//change blue
//up
//down
//change alpha
//up
//down
//mutate shape
//randomly move one vertex in mutated_shape
//randomly pick vertex
//move up
//move down
//move left
//move right
//mutate stacking
//randomly move one shape up or down stack
//randomly select shape
//move shape up stack
//move shape down stack
//100% mutation (create new random dna)
);
//render mutated DNA to a raster image in opengl texture
boost::compute::function<int (int)> renderDNA =
boost::compute::make_function_from_source<int (int)>(
"renderDNA",
"int renderDNA(int x)
{
//for each shape in dna
{
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, gl_texture_);
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex2f(0, 0);
glTexCoord2f(0, 1); glVertex2f(0, h);
glTexCoord2f(1, 1); glVertex2f(w, h);
glTexCoord2f(1, 0); glVertex2f(w, 0);
glEnd();
} }"
);
//compute what % match mutated dna image is to original image
boost::compute::function<int (int)> computefitnesspercent =
boost::compute::make_function_from_source<int (int)>(
"computefitnesspercent",
"int computefitnesspercent(int x) {
//get x, y size of images to be compared
//for each x,y value
//give % match between leaderDNAimage(x,y) and mutatedDNAimage(x,y)
//calculate average % value and store to mutatedDNAfitness
}"
);
//check if mutated dna image is fitter, if so overwrite leaderDNA
if (mutatedDNAfitness > leaderDNAfitness)
{
//overwrite leaderDNA
leaderDNA = mutatedDNA;
//save dna to disk as filename.dna
pFile = fopen ("%filename.dna","w");
fprintf (pFile, DNA);
fclose (pFile);
}
//perform final render, output svg and raster image
//render final DNA to a raster image in opengl texture
boost::compute::function<int (int)> renderDNA =
boost::compute::make_function_from_source<int (int)>(
"renderDNA",
"int renderDNA(int x)
{
//for each shape in dna
{
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, gl_texture_);
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex2f(0, 0);
glTexCoord2f(0, 1); glVertex2f(0, h);
glTexCoord2f(1, 1); glVertex2f(w, h);
glTexCoord2f(1, 0); glVertex2f(w, 0);
glEnd();
}
}"
);
//copy raster image from gpu to main memory
//save raster image to disk as filename.render.png
pFile = fopen ("%filename.render.png","w");
fprintf (pFile, leaderDNAimage);
fclose (pFile);
//render mutated DNA to a vector image
boost::compute::function<int (int)> renderDNA =
boost::compute::make_function_from_source<int (int)>(
"renderDNAvector",
"int renderDNAvector(DNA)
{
//initialise svg string
//for each shape in dna
{
//add shape to svg
}
}"
//close svg string
);
//copy vector image from gpu to main memory
//save vector image to disk as filename.render.svg
pFile = fopen ("%filename.render.svg","w");
fprintf (pFile, leaderDNAvector);
fclose (pFile);
} | 34.653495 | 102 | 0.485922 | infoburp |
849d5587433c923086f8781322e2fb2721b28d60 | 296 | hpp | C++ | include/Subsets.hpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 43 | 2015-10-10T12:59:52.000Z | 2018-07-11T18:07:00.000Z | include/Subsets.hpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | null | null | null | include/Subsets.hpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 11 | 2015-10-10T14:41:11.000Z | 2018-07-28T06:03:16.000Z | #ifndef SUBSETS_HPP_
#define SUBSETS_HPP_
#include <vector>
using namespace std;
class Subsets {
public:
vector<vector<int>> subsets(vector<int> &nums);
private:
void backtrack(vector<int> &nums, int begin, vector<int> &local, vector<vector<int>> &global);
};
#endif // SUBSETS_HPP_
| 17.411765 | 98 | 0.716216 | yanzhe-chen |
84a1d2dae6e50a6f9b2f00cf1bfe2626624760f6 | 13,047 | cpp | C++ | ass1.cpp | tama0102/competitivesolutions | 3ee67e0adce81fa863110e6f94767c6339738142 | [
"MIT"
] | null | null | null | ass1.cpp | tama0102/competitivesolutions | 3ee67e0adce81fa863110e6f94767c6339738142 | [
"MIT"
] | 1 | 2020-09-27T07:41:04.000Z | 2020-09-27T07:41:04.000Z | ass1.cpp | tama0102/competitivesolutions | 3ee67e0adce81fa863110e6f94767c6339738142 | [
"MIT"
] | 11 | 2020-09-27T07:47:21.000Z | 2020-12-04T12:32:19.000Z | //Assingment-1 First part
//Submitted by Shubham Agrawal
// 19UCS073
#include<bits/stdc++.h>
using namespace std;
struct student
{
int id;
string name;
string branch;
};
struct marks
{
int id;
double dbms,ds,c,total;
double percent;
};
map<int,student>mp;
map<int,marks>mk;
map<int,student>::iterator itr;
student newenrty();
student modifyname(student input);
student modifybranch(student input);
void search_branchwise(string s);
void search_namewise(string s);
student newentry()
{
student input;
int i;
string n,b;
cout<<"Enter student id::";
cin>>i;
while(mp.find(i)!=mp.end())
{
cout<<"\nEntry is already present try whith a new one"<<endl;
cout<<"Enter student id::";
cin>>i;
}
cout<<"\nEnter name of student::";
cin>>n;
cout<<"\nEnter branch of student::";
cin>>b;
cout<<endl;
input.id=i;
input.name=n;
input.branch=b;
return input;
}
student modifyname(student input)
{
cout<<"Enter name to be updated::";
string s;
cin>>s;
cout<<"\n"<<input.name<<" is changed to "<<s;
input.name=s;
return input;
//fwrite(&input,sizeof(student),1,out);
}
student modifybranch(student input)
{
cout<<"Enter branch to be updated::";
string s;
cin>>s;
cout<<"\n"<<input.branch<<" is changed to"<<s;
input.branch=s;
//fwrite(&input,sizeof(student),1,out);
return input;
}
void search_branchwise(string s)
{
int flag=0;
for(auto i:mp)
{
if(i.second.branch==s)
{
if(!flag)
{
cout<<"STUDENT DETAILS::"<<endl;
cout<<"ID\t\tNAME\t\tBRANCH"<<endl;
flag=1;
}
cout<<i.second.id<<"\t\t"<<i.second.name<<"\t\t"<<i.second.branch<<endl;
}
}
}
void search_namewise(string s)
{
int flag=0;
for(auto i:mp)
{
if(i.second.name==s)
{
if(!flag)
{
cout<<"STUDENT DETAILS::"<<endl;
cout<<"ID\t\tNAME\t\tBRANCH"<<endl;
flag=1;
}
cout<<i.second.id<<"\t\t"<<i.second.name<<"\t\t"<<i.second.branch<<endl;
}
}
}
void updatemarks(int id)
{
cout<<"Enter subject of which marks to be updated(all letters in small case)::";
string s;
cin>>s;
int f=0;
if(s=="dbms")
{
f=1;
int marks;
cout<<"\nEnter new marks in DBMS::";
cin>>marks;
while(marks>100)
{
cout<<"\nMarks cannot exceed 100 enter marks again"<<endl;
cin>>marks;
}
mk[id].dbms=marks;
cout<<"\nMarks updated"<<endl;
}
else if(s=="ds")
{
f=1;
int marks;
cout<<"\nEnter new marks in DS::";
cin>>marks;
while(marks>100)
{
cout<<"\nMarks cannot exceed 100 enter marks again"<<endl;
cin>>marks;
}
mk[id].ds=marks;
cout<<"\nMarks updated"<<endl;
}
else if(s=="c")
{
f=1;
int marks;
cout<<"\nEnter new marks in C::";
cin>>marks;
while(marks>100)
{
cout<<"\nMarks cannot exceed 100 enter marks again"<<endl;
cin>>marks;
}
mk[id].c=marks;
cout<<"\nMarks updated"<<endl;
}
mk[id].total=mk[id].c+mk[id].dbms+mk[id].ds;
mk[id].percent=mk[id].total/3;
if(f==0)
{
cout<<"\nEnter correct subject"<<endl;
updatemarks(id);
return;
}
}
int main()
{
//FILE *out;
//out=fopen("data.txt","w");
ifstream indata;
indata.open("students.txt");
if(!indata)
{
cout<<"FILE cannot be opend"<<endl;
return 0;
}
int x;
while(indata>>x)
{
student ind;
ind.id=x;
indata>>ind.name;
indata>>ind.branch;
mp[x]=ind;
}
indata.close();
ofstream outdata;
outdata.open("students.txt");
if(!outdata)
{
cout<<"Students FILE cannot be opend"<<endl;
return 0;
}
int choice;
do
{
cout<<endl;
cout<<"-----------------Entry MENU-----------------\n";
cout<<"For a new entry press 1"<<endl<<"For modification of Name press 2"<<endl;
cout<<"For modification in Branch press 3"<<endl;
cout<<"Delete student data press 4"<<endl;
cout<<"Search branchwise press 5"<<endl;
cout<<"Search by name press 6"<<endl;
cout<<"To Enter marks of given entries press 7\n"<<endl;
cout<<"Enter your choice:: ";
cin>>choice;
cout<<endl;
student input;
student *in;
in=NULL;
switch (choice)
{
case 1:
{
input=newentry();
mp[input.id]=input;
//fwrite(&input,sizeof(student),1,out);
break;
}
case 2:
{
cout<<"Enter student id whose name to be modify::";
int id;
cin>>id;
if(mp.find(id)==mp.end())
{
cout<<"No such id found"<<endl;
break;
}
else
{
input=mp[id];
mp[id]=modifyname(input);
}
break;
}
case 3:
{
cout<<"Enter student id whose branch to be modify::";
int id;
cin>>id;
if(mp.find(id)==mp.end())
{
cout<<"No such id found"<<endl;
break;
}
else
{
input=mp[id];
mp[id]=modifybranch(input);
}
break;
}
case 4:
{
int id;
cout<<"Enter id which has to be deleted::";
cin>>id;
if(mp.find(id)==mp.end())
{
cout<<"No such id found"<<endl;
break;
}
else
{
mp.erase(id);
cout<<"Student id::"<<id<<" has been deleted"<<endl;
}
break;
}
case 5:
{
string s;
cout<<"Enter branch to be searched"<<endl;
cin>>s;
search_branchwise(s);
break;
}
case 6:
{
string s;
cout<<"Enter name to be searched"<<endl;
cin>>s;
search_namewise(s);
break;
}
case 7:
break;
default:
{
cout<<"Incorrect option selected"<<endl;
break;
}
}
}while (choice!=7);
//outdata<<"ID\t\tNAME\t\tBRANCH"<<endl;
for(auto i:mp)
{
outdata<<i.second.id<<"\t\t"<<i.second.name<<"\t\t"<<i.second.branch<<endl;
}
//outdata.close();
ofstream out;
out.open("marks.txt");
if(!out)
{
cout<<" Marks FILE cannot be opend"<<endl;
return 0;
}
cout<<"Insert marks of all students"<<endl;
for(auto i:mp)
{
marks temp;
cout<<"Enter marks of student id:: "<<i.first<<" "<<i.second.name<<endl;
cout<<"Marks in DBMS::";
cin>>temp.dbms;
while(temp.dbms>100)
{
cout<<"\nMarks cannot exceed 100 Please re-enter marks in DBMS::";
cin>>temp.dbms;
}
cout<<"\nMarks in DS::";
cin>>temp.ds;
while(temp.ds>100)
{
cout<<"\nMarks cannot exceed 100 Please re-enter marks in DS::";
cin>>temp.ds;
}
cout<<"\nMarks in C::";
cin>>temp.c;
while(temp.c>100)
{
cout<<"\nMarks cannot exceed 100 Please re-enter marks in C::";
cin>>temp.c;
}
temp.total=temp.dbms+temp.ds+temp.c;
temp.percent=(temp.total*100)/300;
cout<<"Total marks obtained:: "<<temp.total<<" out of 300 \t\tPercentage:: "<<temp.percent*1.0<<"%\n"<<endl;
mk[i.first]=temp;
}
int ch;
do
{
double h;
cout<<"\n----------------Marks MENU----------------\n";
cout<<"Press 1 for upate marks in one of the subject of student"<<endl;
cout<<"Press 2 to delete student record from data\n";
cout<<"Press 3 for list of marks by student ID\n";
cout<<"Press 4 to search the student with above percentage threshold"<<endl;
cout<<"Press 5 to search the students of a particular BRANCH with PERCENTAGE above a threshold"<<endl;
cout<<"Press 6 to exit from program\n";
cout<<"ENTER YOUR OPTION::";
cin>>ch;
cout<<endl;
switch (ch)
{
case 1:
{
int id;
cout<<"Enter student ID of which marks to be updated:: ";
cin>>id;
if(mk.find(id)==mk.end())
{
cout<<"\nNO such ID found\n";
break;
}
updatemarks(id);
break;
}
case 2:
{
cout<<"\nEnter student ID to be deleted::";
int id;
cin>>id;
if(mk.find(id)==mk.end())
{
cout<<"\nNO such ID found\n";
break;
}
mk.erase(id);
mp.erase(id);
cout<<"\nID deleted\n";
break;
}
case 3:
{
cout<<"Enter student ID"<<endl;
int id;
cin>>id;
if(mk.find(id)==mk.end())
{
cout<<"\nNO such ID found\n";
break;
}
cout<<"MARKS OF ::"<<mp[id].name<<endl;
cout<<"DBMS\t\tDS\t\tC\t\tTOTAL\t\tPERCENTAGE"<<endl;
cout<<mk[id].dbms<<"\t\t"<<mk[id].ds<<"\t\t"<<mk[id].c<<"\t\t"<<mk[id].total<<"\t\t"<<mk[id].percent*1.0<<endl;
break;
}
case 4:
{
cout<<"Set a threshold percentage::";
cin>>h;
int f=1;
for(auto i:mk)
{
if(i.second.percent>h)
{
if(f==1)
{
f=0;
cout<<"\nID\t\tNAME\t\tBRANCH\t\tPERCENTAGE"<<endl;
}
cout<<i.first<<"\t\t"<<mp[i.first].name<<"\t\t"<<mp[i.first].branch<<"\t\t"<<i.second.percent<<endl;
}
}
if(f==1)
{
cout<<"\nNo such student found\n";
}
break;
}
case 5:
{
cout<<"Enter branch::";
string s;
cin>>s;
cout<<endl;
cout<<"Set a threshold percentage::";
cin>>h;
int f=1;
for(auto i:mk)
{
int id=i.first;
if(i.second.percent>h&&mp[i.first].branch==s)
{
if(f==1)
{
f=0;
cout<<"\nID\t\tNAME\t\tBRANCH\t\tPERCENTAGE"<<endl;
}
cout<<i.first<<"\t\t"<<mp[id].name<<"\t\t"<<mp[id].branch<<"\t\t"<<i.second.percent*1.0<<"%"<<endl;
}
}
if(f==1)
{
cout<<"\nNo such student found\n";
}
break;
}
case 6:
{
break;
}
default:
cout<<"Choose correct option from menu\n";
break;
}
} while (ch!=6);
for(auto i:mp)
{
outdata<<i.second.id<<"\t\t"<<i.second.name<<"\t\t"<<i.second.branch<<endl;
}
out<<"ID\t\tMARKS IN DBMS\t\tMARKS IN DS\t\tMARKS IN C\t\tTOTAL MARKS\t\tPERCENTAGE\n";
for(auto i:mk)
{
out<<i.first<<"\t\t"<<i.second.dbms<<"\t\t"<<i.second.ds<<"\t\t"<<i.second.c<<"\t\t"<<i.second.total<<"\t\t"<<i.second.percent*1.00<<"%\n";
}
cout<<endl;
return 0;
}
| 26.041916 | 148 | 0.409366 | tama0102 |
84a49269c8bc6c68ed8e67653c13c3d4a7cc2127 | 9,744 | cc | C++ | caffe2/sgd/adagrad_op_hip.cc | ashishfarmer/rocm-caffe2 | 097fe3f71b0e4311340ff7eb797ed6c351073d54 | [
"Apache-2.0"
] | 12 | 2018-04-14T22:00:51.000Z | 2018-07-26T16:44:20.000Z | caffe2/sgd/adagrad_op_hip.cc | ashishfarmer/rocm-caffe2 | 097fe3f71b0e4311340ff7eb797ed6c351073d54 | [
"Apache-2.0"
] | 27 | 2018-04-14T06:44:22.000Z | 2018-08-01T18:02:39.000Z | caffe2/sgd/adagrad_op_hip.cc | ashishfarmer/rocm-caffe2 | 097fe3f71b0e4311340ff7eb797ed6c351073d54 | [
"Apache-2.0"
] | 2 | 2018-04-16T20:46:16.000Z | 2018-06-01T21:00:10.000Z | /**
* Copyright (c) 2016-present, Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <hipcub/hipcub.hpp>
#include "adagrad_op.h"
#include "caffe2/core/common_hip.h"
#include "caffe2/core/context_hip.h"
#include "caffe2/utils/mixed_utils_hip.h"
#include "hip/hip_runtime.h"
namespace caffe2 {
__global__ void AdagradUpdate(int N,
const float* w,
const float* g,
const float* h,
float* nw,
float* nh,
float epsilon,
float decay,
const float* lr)
{
HIP_1D_KERNEL_LOOP(i, N)
{
float gi = g[i];
float hi = nh[i] = decay * h[i] + gi * gi;
nw[i] = w[i] + lr[0] * gi / (sqrtf(hi) + epsilon);
}
}
template <>
void adagrad_update<HIPContext>(int N,
const float* w,
const float* g,
const float* h,
float* nw,
float* nh,
float epsilon,
float decay,
const float* lr,
HIPContext* context)
{
hipLaunchKernelGGL((AdagradUpdate),
dim3(CAFFE_GET_BLOCKS(N)),
dim3(CAFFE_HIP_NUM_THREADS),
0,
context->hip_stream(),
N,
w,
g,
h,
nw,
nh,
epsilon,
decay,
lr);
}
template <typename SIndex, typename THalf>
__global__ void SparseAdagradKernel(const size_t N,
const size_t grad_slice_sz,
const float epsilon,
THalf* param,
THalf* param_mom,
const SIndex* indices,
const float* grad,
const float* lr)
{
const float LR = lr[0];
HIP_1D_KERNEL_LOOP(i, N)
{
const size_t gradIdx = i;
const SIndex index = indices[i / grad_slice_sz];
const size_t paramIdx = index * grad_slice_sz + (i % grad_slice_sz);
float mom_new = mixed_add(grad[gradIdx] * grad[gradIdx], param_mom[paramIdx]);
mixed_store(&mom_new, &(param_mom[paramIdx]));
float param_new =
mixed_add(LR * grad[gradIdx] / (sqrtf(mom_new) + epsilon), param[paramIdx]);
mixed_store(¶m_new, &(param[paramIdx]));
}
}
/**
* Calculate RowwiseSparseAdagrad
* M: gradients.dims[0]
* N: gradients.size_from_dim(1)
* grad: pointer to the gradients
* param: pointer to weights
* param_mom: pointer to the momentum
* indices: keys
*/
template <typename SIndex>
__global__ void RowWiseSparseAdagradKernel(const int M,
const int N,
const float epsilon,
float* param,
float* param_mom,
const SIndex* indices,
const float* grad,
const float* lr)
{
using BlockReduce = hipcub::BlockReduce<float, CAFFE_HIP_NUM_THREADS>;
__shared__ BlockReduce::TempStorage temp_storage;
// in case gridDim is smaller than M
for(int i = hipBlockIdx_x; i < M; i += hipGridDim_x)
{
const SIndex index = indices[i];
float sum_squares = 0.0;
__shared__ float row_sum_squares_avg;
// in case N is bigger than block size which is 512 by default
for(int j = hipThreadIdx_x; j < N; j += hipBlockDim_x)
{
const float x_ij = grad[i * N + j];
sum_squares += x_ij * x_ij;
}
float reduce_result = BlockReduce(temp_storage).Sum(sum_squares);
if(hipThreadIdx_x == 0)
{
row_sum_squares_avg = reduce_result / (float)N;
param_mom[index] += row_sum_squares_avg;
}
__syncthreads();
// update param
float step = lr[0] / (sqrtf(param_mom[index]) + epsilon);
for(int j = hipThreadIdx_x; j < N; j += hipBlockDim_x)
{
param[index * N + j] = param[index * N + j] + grad[i * N + j] * step;
}
}
}
template <typename T, class Context>
class HIPSparseAdagradOp final : public Operator<Context>
{
public:
USE_OPERATOR_CONTEXT_FUNCTIONS;
HIPSparseAdagradOp(const OperatorDef& operator_def, Workspace* ws)
: Operator<Context>(operator_def, ws),
epsilon_(OperatorBase::GetSingleArgument<float>("epsilon", 1e-5f))
{
const T decay = OperatorBase::GetSingleArgument<T>("decay", 1.0f);
CAFFE_ENFORCE_EQ(decay, 1.0, "Decay is not supported for SparseAdagradOp");
}
bool RunOnDevice() override
{
// Enforce shapes
CAFFE_ENFORCE_EQ(Input(PARAM).size(), Input(MOMENT_1).size());
CAFFE_ENFORCE_EQ(Input(LR).size(), 1);
CAFFE_ENFORCE_EQ(Input(PARAM).size_from_dim(1),
Input(GRAD).size_from_dim(Input(INDICES).ndim()));
return DispatchHelper<TensorTypes<int32_t, int64_t>>::call(this, Input(INDICES));
}
template <typename IndexType>
bool DoRunWithType()
{
auto n = Input(INDICES).size();
if(n == 0)
{
return true;
}
return DispatchHelper<TensorTypes2<float, float16>, IndexType>::call(this, Input(PARAM));
}
template <typename IndexType, typename THalf>
bool DoRunWithType2()
{
const auto* lr = Input(LR).template data<T>();
const auto* indices = Input(INDICES).template data<IndexType>();
const auto* gradIn = Input(GRAD).template data<T>();
const auto* paramIn = Input(PARAM).template data<THalf>();
const auto* momentIn = Input(MOMENT_1).template data<THalf>();
auto* paramOut = Output(OUTPUT_PARAM)->template mutable_data<THalf>();
auto* momentOut = Output(OUTPUT_MOMENT_1)->template mutable_data<THalf>();
auto N = Input(GRAD).size();
auto grad_slice_sz = Input(GRAD).size_from_dim(Input(INDICES).ndim());
if(N == 0)
{
// empty grad, nothing to do here, not even launching the kernel
return true;
}
hipLaunchKernelGGL((SparseAdagradKernel<IndexType, THalf>),
dim3(CAFFE_GET_BLOCKS(N)),
dim3(CAFFE_HIP_NUM_THREADS),
0,
context_.hip_stream(),
static_cast<const size_t>(N),
static_cast<const size_t>(grad_slice_sz),
static_cast<const float>(epsilon_),
Output(OUTPUT_PARAM)->template mutable_data<THalf>(),
Output(OUTPUT_MOMENT_1)->template mutable_data<THalf>(),
Input(INDICES).template data<IndexType>(),
Input(GRAD).template data<float>(),
Input(LR).template data<float>());
return true;
}
protected:
T epsilon_;
INPUT_TAGS(PARAM, MOMENT_1, INDICES, GRAD, LR);
OUTPUT_TAGS(OUTPUT_PARAM, OUTPUT_MOMENT_1);
};
template <>
template <typename SIndex>
bool RowWiseSparseAdagradOp<float, HIPContext>::DoRunWithType()
{
auto N = Input(GRAD).size();
if(N == 0)
{
// empty grad, nothing to do here, not even launching the kernel
return true;
}
// size of the 1st dimension of the input gradient
auto GRAD_M = Input(GRAD).dim32(0);
auto GRAD_N = N / GRAD_M;
// each thread block will handle multiple rows of the input and output
hipLaunchKernelGGL((RowWiseSparseAdagradKernel),
dim3(min(GRAD_M, CAFFE_MAXIMUM_NUM_BLOCKS)),
dim3(CAFFE_HIP_NUM_THREADS),
0,
context_.hip_stream(),
static_cast<const int>(GRAD_M),
static_cast<const int>(GRAD_N),
static_cast<const float>(epsilon_),
Output(OUTPUT_PARAM)->template mutable_data<float>(),
Output(OUTPUT_MOMENT_1)->template mutable_data<float>(),
Input(INDICES).template data<SIndex>(),
Input(GRAD).template data<float>(),
Input(LR).template data<float>());
return true;
}
REGISTER_HIP_OPERATOR(Adagrad, AdagradOp<float, HIPContext>);
REGISTER_HIP_OPERATOR(SparseAdagrad, HIPSparseAdagradOp<float, HIPContext>);
REGISTER_HIP_OPERATOR(RowWiseSparseAdagrad, RowWiseSparseAdagradOp<float, HIPContext>);
}
| 37.914397 | 97 | 0.531712 | ashishfarmer |
84add195b701c65c9950aee8cbc7e22938e5fe29 | 1,524 | cpp | C++ | src/onyx/renderer/Texture.cpp | thebigcx/Onyx | e063fc7d1c463907ddd60e48cc82d3e533f1e887 | [
"Apache-2.0"
] | null | null | null | src/onyx/renderer/Texture.cpp | thebigcx/Onyx | e063fc7d1c463907ddd60e48cc82d3e533f1e887 | [
"Apache-2.0"
] | null | null | null | src/onyx/renderer/Texture.cpp | thebigcx/Onyx | e063fc7d1c463907ddd60e48cc82d3e533f1e887 | [
"Apache-2.0"
] | null | null | null | #include <onyx/renderer/Texture.h>
#include <stb_image/stb_image.h>
#include <GL/glew.h>
namespace Onyx
{
Texture::Texture(const std::string& path)
: m_path(path)
{
stbi_set_flip_vertically_on_load(true);
int width, height, channels;
void* data = stbi_load(path.c_str(), &width, &height, &channels, 0);
glCreateTextures(GL_TEXTURE_2D, 1, &m_id);
glBindTextureUnit(0, m_id);
glTextureStorage2D(m_id, 1, GL_RGBA8, width, height);
glTextureSubImage2D(m_id, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, data);
glTextureParameteri(m_id, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
glTextureParameteri(m_id, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTextureParameteri(m_id, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTextureParameteri(m_id, GL_TEXTURE_WRAP_T, GL_REPEAT);
glGenerateTextureMipmap(m_id);
stbi_image_free(data);
m_width = width;
m_height = height;
}
Texture::Texture(uint32_t width, uint32_t height, void* data)
: m_width(width), m_height(height)
{
glCreateTextures(GL_TEXTURE_2D, 1, &m_id);
glBindTextureUnit(0, m_id);
glTextureStorage2D(m_id, 1, GL_RGBA8, width, height);
glTextureSubImage2D(m_id, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, data);
glGenerateTextureMipmap(m_id);
}
Texture::~Texture()
{
glDeleteTextures(1, &m_id);
}
void Texture::bind(uint32_t slot) const
{
glBindTextureUnit(slot, m_id);
}
void Texture::unbind(uint32_t slot) const
{
glBindTextureUnit(slot, 0);
}
} | 24.190476 | 87 | 0.717192 | thebigcx |
84b4b9c94bceda471756e05517754b95163c41ef | 1,384 | hpp | C++ | Versionen/2021_06_15/rmf_ws/install/rmf_task_msgs/include/rmf_task_msgs/msg/detail/dispatch_ack__traits.hpp | flitzmo-hso/flitzmo_agv_control_system | 99e8006920c03afbd93e4c7d38b4efff514c7069 | [
"MIT"
] | null | null | null | Versionen/2021_06_15/rmf_ws/install/rmf_task_msgs/include/rmf_task_msgs/msg/detail/dispatch_ack__traits.hpp | flitzmo-hso/flitzmo_agv_control_system | 99e8006920c03afbd93e4c7d38b4efff514c7069 | [
"MIT"
] | null | null | null | Versionen/2021_06_15/rmf_ws/install/rmf_task_msgs/include/rmf_task_msgs/msg/detail/dispatch_ack__traits.hpp | flitzmo-hso/flitzmo_agv_control_system | 99e8006920c03afbd93e4c7d38b4efff514c7069 | [
"MIT"
] | 2 | 2021-06-21T07:32:09.000Z | 2021-08-17T03:05:38.000Z | // generated from rosidl_generator_cpp/resource/idl__traits.hpp.em
// with input from rmf_task_msgs:msg/DispatchAck.idl
// generated code does not contain a copyright notice
#ifndef RMF_TASK_MSGS__MSG__DETAIL__DISPATCH_ACK__TRAITS_HPP_
#define RMF_TASK_MSGS__MSG__DETAIL__DISPATCH_ACK__TRAITS_HPP_
#include "rmf_task_msgs/msg/detail/dispatch_ack__struct.hpp"
#include <rosidl_runtime_cpp/traits.hpp>
#include <stdint.h>
#include <type_traits>
// Include directives for member types
// Member 'dispatch_request'
#include "rmf_task_msgs/msg/detail/dispatch_request__traits.hpp"
namespace rosidl_generator_traits
{
template<>
inline const char * data_type<rmf_task_msgs::msg::DispatchAck>()
{
return "rmf_task_msgs::msg::DispatchAck";
}
template<>
inline const char * name<rmf_task_msgs::msg::DispatchAck>()
{
return "rmf_task_msgs/msg/DispatchAck";
}
template<>
struct has_fixed_size<rmf_task_msgs::msg::DispatchAck>
: std::integral_constant<bool, has_fixed_size<rmf_task_msgs::msg::DispatchRequest>::value> {};
template<>
struct has_bounded_size<rmf_task_msgs::msg::DispatchAck>
: std::integral_constant<bool, has_bounded_size<rmf_task_msgs::msg::DispatchRequest>::value> {};
template<>
struct is_message<rmf_task_msgs::msg::DispatchAck>
: std::true_type {};
} // namespace rosidl_generator_traits
#endif // RMF_TASK_MSGS__MSG__DETAIL__DISPATCH_ACK__TRAITS_HPP_
| 29.446809 | 98 | 0.804913 | flitzmo-hso |
84b5170b9e50b7fb916bf5b6d01bc9a5b90f0259 | 1,080 | cpp | C++ | src/Units/NonArmyWrappers/LarvaWrapper.cpp | krogenth/AdditionalPylons | 60a2ba5503857de9c6aafa5261e911f39ad0ccf1 | [
"MIT"
] | 1 | 2022-01-22T00:45:45.000Z | 2022-01-22T00:45:45.000Z | src/Units/NonArmyWrappers/LarvaWrapper.cpp | krogenth/AdditionalPylons | 60a2ba5503857de9c6aafa5261e911f39ad0ccf1 | [
"MIT"
] | 39 | 2022-01-10T22:23:20.000Z | 2022-03-31T03:56:21.000Z | src/Units/NonArmyWrappers/LarvaWrapper.cpp | krogenth/AdditionalPylons | 60a2ba5503857de9c6aafa5261e911f39ad0ccf1 | [
"MIT"
] | null | null | null | #include "./LarvaWrapper.h"
#include "../../Strategist/Strategist.h"
void LarvaWrapper::onFrame() {
std::optional<BWAPI::UnitType> order;
if (this->buildOrder == BWAPI::UnitTypes::Unknown) {
order = Strategist::getInstance().getUnitOrder(this->type);
if (order.has_value())
this->buildOrder = order.value();
}
if (this->buildOrder != BWAPI::UnitTypes::Unknown)
this->unit->build(this->buildOrder);
}
void LarvaWrapper::displayInfo() {
if (this->unit->getLastCommand().getTarget()) {
BWAPI::Broodwar->drawLineMap(this->unit->getPosition(), this->unit->getLastCommand().getTarget()->getPosition(), BWAPI::Colors::White);
}
else if (this->unit->getLastCommand().getTargetPosition().isValid()) {
BWAPI::Broodwar->drawLineMap(this->unit->getPosition(), this->unit->getLastCommand().getTargetPosition(), BWAPI::Colors::White);
}
else if (this->unit->getLastCommand().getTargetTilePosition().isValid()) {
BWAPI::Broodwar->drawLineMap(this->unit->getPosition(), BWAPI::Position(this->unit->getLastCommand().getTargetTilePosition()), BWAPI::Colors::White);
}
} | 40 | 151 | 0.712037 | krogenth |
84b5d272b654de6a76aa69b41afcd0084a71694a | 742 | cpp | C++ | _includes/leet487/leet487_1.cpp | mingdaz/leetcode | 64f2e5ad0f0446d307e23e33a480bad5c9e51517 | [
"MIT"
] | null | null | null | _includes/leet487/leet487_1.cpp | mingdaz/leetcode | 64f2e5ad0f0446d307e23e33a480bad5c9e51517 | [
"MIT"
] | 8 | 2019-12-19T04:46:05.000Z | 2022-02-26T03:45:22.000Z | _includes/leet487/leet487_1.cpp | mingdaz/leetcode | 64f2e5ad0f0446d307e23e33a480bad5c9e51517 | [
"MIT"
] | null | null | null | class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int res = 0;
int currContOnes = 0;
int prevContOnes = -1; // set to -1 to handle the case when the vectors starts with 1
for (int num : nums) {
if (num == 1) {
++currContOnes;
}
else {
if (currContOnes == 0) {
prevContOnes = 0; // the two continuous 1's are apart by more than one 0's
}
else {
prevContOnes = currContOnes;
currContOnes = 0;
}
}
res = max(res, currContOnes + prevContOnes + 1);
}
return res;
}
};
| 29.68 | 94 | 0.444744 | mingdaz |
84b914ee09db4ffcbb45ea76850c2061e8000107 | 2,780 | cpp | C++ | src/Converter/Converter.cpp | tanechai/ssl-camera-converter | 0282fc761eb39c491879ae2c84d89094a2602c67 | [
"MIT"
] | null | null | null | src/Converter/Converter.cpp | tanechai/ssl-camera-converter | 0282fc761eb39c491879ae2c84d89094a2602c67 | [
"MIT"
] | null | null | null | src/Converter/Converter.cpp | tanechai/ssl-camera-converter | 0282fc761eb39c491879ae2c84d89094a2602c67 | [
"MIT"
] | null | null | null | #include "Converter.hpp"
#include "../ExtractDifferences/ExtractDifferences.hpp"
void overlayImage(cv::Mat* src, cv::Mat* overlay, const cv::Point& location);
Converter::Converter(Initializer& initializer):initializer_(initializer){}
cv::Mat Converter::imagesToImage(const std::vector<cv::Mat>& images, const cv::Size2d& fieldImageSize){
// 合成後の画像
cv::Mat mixedImage;
std::vector<model::Camera> cameraParameters = initializer_.parameters();
for (int i = 0; i < images.size(); i++) {
cv::Mat undistortedImage = cv::Mat::zeros(fieldImageSize.height, fieldImageSize.width, CV_8UC3);
cv::Mat warpedImage = cv::Mat::zeros(fieldImageSize.height, fieldImageSize.width, CV_8UC3);
ExtractDifferences ext(initializer_.defaultFields().at(i));
cv::Mat leanImage = ext.getDifferences(images.at(i));
cv::undistort(leanImage, undistortedImage, cameraParameters.at(i).cameraMatrix(), cameraParameters.at(i).distCoeffs(), cameraParameters.at(i).cameraMatrix());
cv::warpPerspective(undistortedImage, warpedImage, initializer_.homographyMatrixs().at(i), warpedImage.size());
if(mixedImage.empty()){
mixedImage = warpedImage;
}else{
// 合成割合を決める定数を決める
double alpha = 1 / static_cast<double>(i+1);
double beta = 1 - alpha;
// 合成元をコピー
cv::Mat tmp = mixedImage;
cv::addWeighted(warpedImage, alpha, tmp, beta, 0,mixedImage);
}
}
//cv::Mat affineMat = (cv::Mat_<double>(2,3)<<1,0,0,0,1,0);
//cv::warpAffine(initializer_.field(), mixedImage, affineMat, mixedImage.size(), cv::INTER_LINEAR, cv::BORDER_TRANSPARENT);
cv::Mat field = initializer_.field();
cv::Mat tmp = mixedImage;
cv::addWeighted(field, 0.3, tmp, 0.7, 0,mixedImage);
return mixedImage;
}
void overlayImage(cv::Mat* src, cv::Mat* overlay, const cv::Point& location) {
for (int y = std::max(location.y, 0); y < src->rows; ++y) {
int fY = y - location.y;
if (fY >= overlay->rows)
break;
for (int x = std::max(location.x, 0); x < src->cols; ++x) {
int fX = x - location.x;
if (fX >= overlay->cols)
break;
double opacity = ((double)overlay->data[fY * overlay->step + fX * overlay->channels() + 3])/255;
for (int c = 0; opacity > 0 && c < src->channels(); ++c) {
unsigned char overlayPx = overlay->data[fY * overlay->step + fX * overlay->channels() + c];
unsigned char srcPx = src->data[y * src->step + x * src->channels() + c];
src->data[y * src->step + src->channels() * x + c] = srcPx * (1. - opacity) + overlayPx * opacity;
}
}
}
} | 44.126984 | 166 | 0.6 | tanechai |
84b9e328b45f9c9d28ff794d3931730c9e4fd26c | 11,495 | cpp | C++ | src/goto-symex/memory_model.cpp | dan-blank/yogar-cbmc | 05b4f056b585b65828acf39546c866379dca6549 | [
"MIT"
] | 1 | 2017-07-25T02:44:56.000Z | 2017-07-25T02:44:56.000Z | src/goto-symex/memory_model.cpp | dan-blank/yogar-cbmc | 05b4f056b585b65828acf39546c866379dca6549 | [
"MIT"
] | 1 | 2017-02-22T14:35:19.000Z | 2017-02-27T08:49:58.000Z | src/goto-symex/memory_model.cpp | dan-blank/yogar-cbmc | 05b4f056b585b65828acf39546c866379dca6549 | [
"MIT"
] | 4 | 2019-01-19T03:32:21.000Z | 2021-12-20T14:25:19.000Z | /*******************************************************************\
Module: Memory model for partial order concurrency
Author: Michael Tautschnig, michael.tautschnig@cs.ox.ac.uk
\*******************************************************************/
#include <util/std_expr.h>
#include <util/i2string.h>
#include "memory_model.h"
#include <iostream>
#include <map>
/*******************************************************************\
Function: memory_model_baset::memory_model_baset
Inputs:
Outputs:
Purpose:
\*******************************************************************/
memory_model_baset::memory_model_baset(const namespacet &_ns):
partial_order_concurrencyt(_ns),
var_cnt(0)
{
}
/*******************************************************************\
Function: memory_model_baset::~memory_model_baset
Inputs:
Outputs:
Purpose:
\*******************************************************************/
memory_model_baset::~memory_model_baset()
{
}
/*******************************************************************\
Function: memory_model_baset::nondet_bool_symbol
Inputs:
Outputs:
Purpose:
\*******************************************************************/
symbol_exprt memory_model_baset::nondet_bool_symbol(
const std::string &prefix)
{
return symbol_exprt(
"memory_model::choice_"+prefix+i2string(var_cnt++),
bool_typet());
}
/*******************************************************************\
Function: memory_model_baset::po
Inputs:
Outputs:
Purpose:
\*******************************************************************/
bool memory_model_baset::po(event_it e1, event_it e2)
{
// within same thread
if(e1->source.thread_nr==e2->source.thread_nr)
return numbering[e1]<numbering[e2];
else
{
// in general un-ordered, with exception of thread-spawning
return false;
}
}
/*******************************************************************\
Function: memory_model_baset::read_from
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void memory_model_baset::read_from_backup(symex_target_equationt &equation)
{
// We iterate over all the reads, and
// make them match at least one
// (internal or external) write.
for(address_mapt::const_iterator
a_it=address_map.begin();
a_it!=address_map.end();
a_it++)
{
const a_rect &a_rec=a_it->second;
for(event_listt::const_iterator
r_it=a_rec.reads.begin();
r_it!=a_rec.reads.end();
r_it++)
{
const event_it r=*r_it;
exprt::operandst rf_some_operands;
rf_some_operands.reserve(a_rec.writes.size());
// this is quadratic in #events per address
for(event_listt::const_iterator
w_it=a_rec.writes.begin();
w_it!=a_rec.writes.end();
++w_it)
{
const event_it w=*w_it;
// rf cannot contradict program order
if(po(r, w))
continue; // contradicts po
bool is_rfi=
w->source.thread_nr==r->source.thread_nr;
symbol_exprt s=nondet_bool_symbol("rf");
// record the symbol
choice_symbols[
std::make_pair(r, w)]=s;
// We rely on the fact that there is at least
// one write event that has guard 'true'.
implies_exprt read_from(s,
and_exprt(w->guard,
equal_exprt(r->ssa_lhs, w->ssa_lhs)));
// Uses only the write's guard as precondition, read's guard
// follows from rf_some
add_constraint(equation,
read_from, is_rfi?"rfi":"rf", r->source);
if(!is_rfi)
{
// if r reads from w, then w must have happened before r
exprt cond=implies_exprt(s, before(w, r));
add_constraint(equation,
cond, "rf-order", r->source);
}
// added by ylz
equation.choice_symbol_map[s] = new symex_target_equationt::eq_edge(&(*w), &(*r));
rf_some_operands.push_back(s);
}
// value equals the one of some write
exprt rf_some;
// uninitialised global symbol like symex_dynamic::dynamic_object*
// or *$object
if(rf_some_operands.empty())
continue;
else if(rf_some_operands.size()==1)
rf_some=rf_some_operands.front();
else
{
rf_some=or_exprt();
rf_some.operands().swap(rf_some_operands);
}
// Add the read's guard, each of the writes' guards is implied
// by each entry in rf_some
add_constraint(equation,
implies_exprt(r->guard, rf_some), "rf-some", r->source);
}
}
}
bool memory_model_baset::valid_mutex(symex_target_equationt &equation)
{
int mutex_num = 0;
for(eventst::const_iterator
e_it=equation.SSA_steps.begin();
e_it!=equation.SSA_steps.end();
e_it++)
{
// concurreny-related?
if(e_it->is_verify_atomic_begin())
mutex_num++;
}
return (mutex_num != 1);
}
void memory_model_baset::read_from(symex_target_equationt &equation)
{
per_thread_mapt per_thread_map;
for(eventst::const_iterator e_it=equation.SSA_steps.begin();
e_it!=equation.SSA_steps.end(); e_it++)
{
if((is_shared_read(e_it) ||
is_shared_write(e_it) ||
e_it->is_verify_atomic_begin() ||
e_it->is_verify_atomic_end() ||
e_it->is_thread_create() ||
e_it->is_thread_join()))
{
// if (address(e_it) == "c::__global_lock" || (equation.aux_enable && e_it->is_aux_var() && !equation.thread_malloc))
// continue;
per_thread_map[e_it->source.thread_nr].push_back(e_it);
}
}
int thread_num = per_thread_map.size();
// iterate over threads
for(per_thread_mapt::const_iterator
t_it=per_thread_map.begin();
t_it!=per_thread_map.end();
t_it++)
{
const event_listt &events=t_it->second;
std::map<irep_idt, event_it> event_value_map;
bool atomic_flag = false;
bool single_thread_flag = false;
int curr_threads = (((*(events.begin()))->source.thread_nr == 0) ? 1 : 100);
for(event_listt::const_iterator e_it=events.begin();
e_it!=events.end(); e_it++)
{
event_it e = *e_it;
if (e->is_thread_create() && e->source.thread_nr == 0) {
curr_threads++;
event_value_map.clear();
}
if (e->is_thread_join() && e->source.thread_nr == 0) {
curr_threads--;
event_value_map.clear();
}
single_thread_flag = (curr_threads == 1 ? true : false);
if (e->is_verify_atomic_begin() && valid_mutex(equation)) {
atomic_flag = true;
event_value_map.clear();
}
else if (e->is_verify_atomic_end()) {
atomic_flag = false;
event_value_map.clear();
}
else if (atomic_flag || single_thread_flag) {
if (is_shared_read(e)) {
if (e->rely)
{
if (event_value_map.find(address(e)) == event_value_map.end()) {
read_from_item(e, equation, thread_num);
event_value_map[address(e)] = e;
}
else {
add_constraint(equation, implies_exprt(e->guard, equal_exprt(e->ssa_lhs, event_value_map[address(e)]->ssa_lhs)), "rfi", e->source);
}
}
}
else if (is_shared_write(e)) {
event_value_map[address(e)] = e;
}
}
else {
assert(!atomic_flag);
if (is_shared_read(e) && e->rely) {
read_from_item(e, equation, thread_num);
}
}
}
}
if (!array_map.empty()) {
for (array_mapt::iterator it = array_map.begin(); it != array_map.end(); it++) {
choice_listt& c_list = it->second;
for (choice_listt::iterator mt = c_list.begin(); mt != c_list.end(); mt++) {
for (choice_listt::iterator nt = mt + 1; nt != c_list.end(); nt++) {
add_constraint(equation, implies_exprt((*mt), not_exprt(*nt)), "array_assign", symex_targett::sourcet());
}
}
}
}
}
void memory_model_baset::read_from_item(const event_it& r, symex_target_equationt &equation, int thread_num) {
const a_rect &a_rec=address_map[address(r)];
event_listt rfwrites;
exprt::operandst rf_some_operands;
rf_some_operands.reserve(a_rec.writes.size());
// this is quadratic in #events per address
for(event_listt::const_iterator
w_it=a_rec.writes.begin();
w_it!=a_rec.writes.end();
++w_it)
{
const event_it w=*w_it;
bool is_rfi = (r->source.thread_nr==w->source.thread_nr);
if(po(r, w))
continue; // contradicts po
if (is_rfi && !(equation.aux_enable && w->is_aux_var()))
{
rfwrites.push_back(w);
}
else
{
int symmetry_start = thread_num > 20 ? 2 : 1;
if (thread_num > 10 && r->source.thread_nr >= symmetry_start && r->source.thread_nr < w->source.thread_nr)
continue;
symbol_exprt s=nondet_bool_symbol("rf");
// record the symbol
choice_symbols[std::make_pair(r, w)]=s;
// We rely on the fact that there is at least
// one write event that has guard 'true'.
equal_exprt rw = equal_exprt(r->ssa_lhs, w->ssa_lhs);
or_exprt read_from(not_exprt(s), and_exprt(rw, w->guard));
if (r->array_assign || r->ssa_lhs.get_identifier() == "c::array#2") {
// if (r->array_assign) {
array_map[w->ssa_lhs.get_identifier()].push_back(s);
}
// add the rf relation to the amp
equation.choice_symbol_map[s] = new symex_target_equationt::eq_edge(&(*w), &(*r));
// Uses only the write's guard as precondition, read's guard
// follows from rf_some
add_constraint(equation,
read_from, "rf", r->source);
rf_some_operands.push_back(s);
}
}
event_listt::const_iterator w_it, wt_it;
for(w_it=rfwrites.begin(); w_it!=rfwrites.end(); ++w_it)
{
for(wt_it=rfwrites.begin(); wt_it!=rfwrites.end(); ++wt_it)
{
if (&(*(*w_it)) != &(*(*wt_it)) && po(*w_it, *wt_it))
// if (&(*(*w_it)) != &(*(*wt_it)) && po(*w_it, *wt_it) && ((*w_it)->guard == (*wt_it)->guard))
break;
}
// std::cout << r->ssa_lhs.get_identifier() << ", " << (*w_it)->ssa_lhs.get_identifier() << "\n";
if ((*w_it)->original_lhs_object.get_identifier() != "c::array_index" || wt_it == rfwrites.end())
// if (wt_it == rfwrites.end())
{
const event_it w=*w_it;
symbol_exprt s=nondet_bool_symbol("rf");
// record the symbol
choice_symbols[std::make_pair(r, w)]=s;
// We rely on the fact that there is at least
// one write event that has guard 'true'.
equal_exprt rw = equal_exprt(r->ssa_lhs, w->ssa_lhs);
or_exprt read_from(not_exprt(s), and_exprt(rw, w->guard));
if (r->array_assign || r->ssa_lhs.get_identifier() == "c::array#2") {
// if (r->array_assign) {
array_map[w->ssa_lhs.get_identifier()].push_back(s);
}
// add the rf relation to the amp
equation.choice_symbol_map[s] = new symex_target_equationt::eq_edge(&(*w), &(*r));
// Uses only the write's guard as precondition, read's guard
// follows from rf_some
add_constraint(equation, read_from, "rfi", r->source);
rf_some_operands.push_back(s);
}
}
// value equals the one of some write
exprt rf_some;
// uninitialised global symbol like symex_dynamic::dynamic_object*
// or *$object
if(rf_some_operands.empty())
return;
else if(rf_some_operands.size()==1)
rf_some=rf_some_operands.front();
else
{
rf_some=or_exprt();
rf_some.operands().swap(rf_some_operands);
}
// Add the read's guard, each of the writes' guards is implied
// by each entry in rf_some
add_constraint(equation,
implies_exprt(r->guard, rf_some), "rf-some", r->source);
}
| 27.174941 | 138 | 0.590431 | dan-blank |
84bd0882247e7505722a43a810249b028e733f13 | 1,025 | cpp | C++ | Source/Storm/include/Storm.cpp | SunlayGGX/Storm | 83a34c14cc7d936347b6b8193a64cd13ccbf00a8 | [
"MIT"
] | 3 | 2021-11-27T04:56:12.000Z | 2022-02-14T04:02:10.000Z | Source/Storm/include/Storm.cpp | SunlayGGX/Storm | 83a34c14cc7d936347b6b8193a64cd13ccbf00a8 | [
"MIT"
] | null | null | null | Source/Storm/include/Storm.cpp | SunlayGGX/Storm | 83a34c14cc7d936347b6b8193a64cd13ccbf00a8 | [
"MIT"
] | null | null | null | #include "Application.h"
#include <iostream>
namespace
{
int processEarlyExitAnswer(const Storm::EarlyExitAnswer &earlyExitAnswer)
{
for (const auto &unhandledErrorMsg : earlyExitAnswer._unconsumedErrorMsgs)
{
std::cerr << unhandledErrorMsg << std::endl;
}
return earlyExitAnswer._exitCode;
}
}
int main(const int argc, const char* argv[]) try
{
return static_cast<int>(Storm::Application{ argc, argv }.run());
}
catch (const Storm::Exception &ex)
{
return processEarlyExitAnswer(
Storm::Application::ensureCleanStateAfterException(
"Fatal error (Storm::Exception received) : " + std::string{ ex.what() } + ".\n" + ex.stackTrace(),
true
)
);
}
catch (const std::exception &ex)
{
return processEarlyExitAnswer(Storm::Application::ensureCleanStateAfterException("Fatal error (std::exception received) : " + std::string{ ex.what() }, true));
}
catch (...)
{
return processEarlyExitAnswer(Storm::Application::ensureCleanStateAfterException("Fatal error (unknown exception received)", false));
}
| 25.625 | 160 | 0.725854 | SunlayGGX |
84ca1e1e5ede21401a8d5a1154ba902a3a5b21a1 | 797 | cpp | C++ | QuayLui/e.cpp | daothaison/algorithm-vi | 59ee4046eae2aea97c7f85d7bd64f85f12d84598 | [
"Apache-2.0"
] | null | null | null | QuayLui/e.cpp | daothaison/algorithm-vi | 59ee4046eae2aea97c7f85d7bd64f85f12d84598 | [
"Apache-2.0"
] | null | null | null | QuayLui/e.cpp | daothaison/algorithm-vi | 59ee4046eae2aea97c7f85d7bd64f85f12d84598 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
int a[100][100], n, Min=1000000, start;
int cx[100]={0}, duongDi[100], vet[100];
void input(){
cin>>n;
for(int i=1; i<=n;i++){
for(int j=1; j<=n;j++){
cin>>a[i][j];
}
}
cin>>start;
cx[start]=1;
duongDi[0]=start;
}
void output(int n){
if(n< Min){
Min=n;
for(int i=1;i<n;i++) duongDi[i]=vet[i];
}
}
void duLich(int i,int count, int chiphi){
for(int j=1; j<=n;j++){
if(cx[j]==0 && a[i][j]){
cx[j]=1;
vet[count]=j;
if(count==n-1){
output(chiphi+a[i][j]);
}else{
duLich(j, count+1, chiphi+a[i][j]);
}
cx[j]=0;
}
}
}
main(){
input();
duLich(start, 1, 0);
cout<<"chi phi nho nhat: "<<Min;
cout<<endl<<"duong di: ";
for(int i=0;i<n;i++) cout<<duongDi[i]<<" ";
}
| 17.711111 | 45 | 0.499373 | daothaison |
84cccb50b47ed7845910a88aa8434e1ddef9a1ba | 4,525 | hpp | C++ | modules/core/include/facekit/core/utils/string.hpp | cecabert/FaceKit | 766a32fc7f65ae5deceeba5628c225631986c4d8 | [
"Apache-2.0"
] | null | null | null | modules/core/include/facekit/core/utils/string.hpp | cecabert/FaceKit | 766a32fc7f65ae5deceeba5628c225631986c4d8 | [
"Apache-2.0"
] | null | null | null | modules/core/include/facekit/core/utils/string.hpp | cecabert/FaceKit | 766a32fc7f65ae5deceeba5628c225631986c4d8 | [
"Apache-2.0"
] | 1 | 2017-11-29T12:03:08.000Z | 2017-11-29T12:03:08.000Z | /**
* @file "utils/string.hpp"
* @brief Utility function for string handling
* @ingroup core
*
* @author Christophe Ecabert
* @date 26/08/16
* Copyright © 2016 Christophe Ecabert. All rights reserved.
*/
#ifndef __FACEKIT_STRING_UTIL__
#define __FACEKIT_STRING_UTIL__
#include <string>
#include <vector>
#include "facekit/core/library_export.hpp"
/**
* @namespace FaceKit
* @brief Development space
*/
namespace FaceKit {
/**
* @namespace Path
* @brief Utility functions for processing path
*/
namespace Path {
namespace internal {
std::string JoinImpl(std::initializer_list<std::string> parts);
}
/**
* @name Join
* @fn std::string Join(const T&... parts)
* @tparam T Pack strings to merge together
* @brief Merge filename component into a single valid path. Similar to
* python `os.path.join` method
* @param[in] parts Packed parameters to aggregate together
* @return Appended path
*/
template<typename... T>
std::string Join(const T&... parts) {
return internal::JoinImpl({parts...});
}
/**
* @name IsAbsolute
* @fn bool IsAbsolute(const std::string& path)
* @brief Check if a given `path`is absolute or not (i.e. start with '/').
* @param[in] path Path to check
* @return True if absolute, false otherwise.
*/
bool IsAbsolute(const std::string& path);
/**
* @name Dirname
* @fn std::string Dirname(const std::string& path)
* @brief Return the part in front of the last '/' in `path`. If there is no
* '/' give an empty string.
* Similar to `os.path.dirname`
* @param[in] path Path to file
* @return Complete file's directory or empty string.
*/
std::string Dirname(const std::string& path);
/**
* @name Basename
* @fn std::string Basename(const std::string& path)
* @brief Extract file name from path (i.e. part after last '/'). If there
* is no '/' it returns the same as the input.
* Similar to `os.path.basename`
* @param[in] path Path to file
* @return File name
*/
std::string Basename(const std::string& path);
/**
* @name Extension
* @fn std::string Extension(const std::string& path)
* @brief Extract file's extension (i.e part after the last '.'). If there
* is not '.' return an empty string
* @param[in] path Path to file
* @return File's extension or empty string
*/
std::string Extension(const std::string& path);
/**
* @name Clean
* @fn std::string Clean(const std::string& path)
* @brief Remove duplicate, add ./
* @param[in] path Path to clean
* @return cleaned path
*/
std::string Clean(const std::string& path);
/**
* @name SplitComponent
* @fn void SplitComponent(const std::string& path, std::string* dir,
std::string* file, std::string* ext)
* @brief Split path into directory + file + extension
* @param[in] path Path where to extract data
* @param[out] dir Extracted directory, skipped if nullptr
* @param[out] file Extracted filename, skipped if nullptr
* @param[out] ext Extracted extension, skipped if nullptr
*/
void SplitComponent(const std::string& path, std::string* dir,
std::string* file, std::string* ext);
} // namespace Path
/**
* @namespace String
* @brief Utility functions for processing string
*/
namespace String {
/**
* @name Split
* @fn void Split(const std::string& string, const std::string delimiter,
std::vector<std::string>* parts);
* @brief Split a given \p string into parts for a specific delimiter
* @param[in] string String to split
* @param[in] delimiter Delimiter
* @param[out] parts Splitted parts
*/
void FK_EXPORTS Split(const std::string& string, const std::string delimiter,
std::vector<std::string>* parts);
/**
* @name LeadingZero
* @fn std::string LeadingZero(const T number, const size_t N)
* @brief Convert a number to string and complete it with leading zeros if
* needed
* @param[in] number Number to convert to string
* @param[in] N Number total of char wanted (i.e. N=3, number=12
* -> 012)
* @tparam T Data type
*/
template<typename T>
std::string FK_EXPORTS LeadingZero(const T number, const size_t N) {
std::string num = std::to_string(number);
return std::string(N - num.length(), '0') + num;
}
} // namespace String
} // namespace FaceKit
#endif /* __FACEKIT_STRING_UTIL__ */
| 29.383117 | 78 | 0.638232 | cecabert |
84d36b0aebdf403ad1e3ef8ba90c52d4205cfe52 | 4,664 | cpp | C++ | tutorial_exercises/Heart_rate/FFT.cpp | SijinJohn/OpenVX | 9e6e6cac3679edd85419ca553e678489173068a6 | [
"MIT"
] | null | null | null | tutorial_exercises/Heart_rate/FFT.cpp | SijinJohn/OpenVX | 9e6e6cac3679edd85419ca553e678489173068a6 | [
"MIT"
] | null | null | null | tutorial_exercises/Heart_rate/FFT.cpp | SijinJohn/OpenVX | 9e6e6cac3679edd85419ca553e678489173068a6 | [
"MIT"
] | null | null | null | #include <complex>
#include <cmath>
#include <iterator>
#include "FFT.h"
using namespace std;
unsigned int bitReverse(unsigned int x, int log2n) {
int n = 0;
int mask = 0x1;
for (int i=0; i < log2n; i++) {
n <<= 1;
n |= (x & 1);
x >>= 1;
}
return n;
}
//========================================//
// #include <iostream>
//#include <cmath>
////#include <complex>
//#include <iterator>
//#include "opencv_camera_display.h"
//#include "complex.h"
//#include "FFT.h"
//#include <VX/vx.h>
//#define ERROR_CHECK_STATUS( status ) { \
// vx_status status_ = (status); \
// if(status_ != VX_SUCCESS) { \
// printf("ERROR: failed with status = (%d) at " __FILE__ "#%d\n", status_, __LINE__); \
// exit(1); \
// } \
// }
//#define ERROR_CHECK_OBJECT( obj ) { \
// vx_status status_ = vxGetStatus((vx_reference)(obj)); \
// if(status_ != VX_SUCCESS) { \
// printf("ERROR: failed with status = (%d) at " __FILE__ "#%d\n", status_, __LINE__); \
// exit(1); \
// } \
// }
//enum user_library_e
//{
// USER_LIBRARY_EXAMPLE = 1,
//};
//enum user_kernel_e
//{
// USER_KERNEL_FFT = VX_KERNEL_BASE( VX_ID_DEFAULT, USER_LIBRARY_EXAMPLE ) + 0x001,
//};
//vx_node userfftNode( vx_graph graph,
// vx_image input,
// vx_image fft_output )
//{
// vx_context context = vxGetContext( ( vx_reference ) graph );
// vx_kernel kernel = vxGetKernelByEnum( context, USER_KERNEL_FFT );
// ERROR_CHECK_OBJECT( kernel );
// vx_node node = vxCreateGenericNode( graph, kernel );
// ERROR_CHECK_OBJECT( node );
// ERROR_CHECK_STATUS( vxSetParameterByIndex( node, 0, ( vx_reference ) input ) );
// ERROR_CHECK_STATUS( vxSetParameterByIndex( node, 1, ( vx_reference ) fft_output ) );
// ERROR_CHECK_STATUS( vxReleaseKernel( &kernel ) );
// return node;
//}
//vx_status VX_CALLBACK fft_validator( vx_node node,
// const vx_reference parameters[], vx_uint32 num,
// vx_meta_format metas[] )
//{
// // parameter #0 -- input image of format VX_DF_IMAGE_U8
// vx_df_image format = VX_DF_IMAGE_VIRT;
// ERROR_CHECK_STATUS( vxQueryImage( ( vx_image )parameters[0], VX_IMAGE_FORMAT, &format, sizeof( format ) ) );
// if( format != VX_DF_IMAGE_RGB )
// {
// return VX_ERROR_INVALID_FORMAT;
// }
// // parameter #1 -- output values
// return VX_SUCCESS;
//}
//vx_status VX_CALLBACK fft_host_side_function( vx_node node, const vx_reference * refs, vx_uint32 num )
//{
// vx_image input = ( vx_image ) refs[0];
// vx_scalar fft_freqs = ( vx_scalar ) refs[1];
// /*
// vx_rectangle_t rect = { 0, 0, width, height };
// vx_map_id map_input, map_output;
// vx_imagepatch_addressing_t addr_input, addr_output;
// void * ptr_input, * ptr_output;
// ERROR_CHECK_STATUS( vxMapImagePatch( input, &rect, 0, &map_input, &addr_input, &ptr_input, VX_READ_ONLY, VX_MEMORY_TYPE_HOST, VX_NOGAP_X ) );
// ERROR_CHECK_STATUS( vxMapImagePatch( output, &rect, 0, &map_output, &addr_output, &ptr_output, VX_WRITE_ONLY, VX_MEMORY_TYPE_HOST, VX_NOGAP_X ) );
// cv::Mat mat_input( height, width, CV_8U, ptr_input, addr_input .stride_y );
// cv::Mat mat_output( height, width, CV_8U, ptr_output, addr_output.stride_y );
// cv::medianBlur( mat_input, mat_output, ksize );
// ERROR_CHECK_STATUS( vxUnmapImagePatch( input, map_input ) );
// ERROR_CHECK_STATUS( vxUnmapImagePatch( output, map_output ) );
//*/
// return VX_SUCCESS;
//}
//vx_status registerUserKernel( vx_context context )
//{
// vx_kernel kernel = vxAddUserKernel( context,
// "app.userkernels.fft",
// USER_KERNEL_FFT,
// fft_host_side_function,
// 3, // numParams
// fft_validator,
// NULL,
// NULL );
// ERROR_CHECK_OBJECT( kernel );
// ERROR_CHECK_STATUS( vxAddParameterToKernel( kernel, 0, VX_INPUT, VX_TYPE_IMAGE, VX_PARAMETER_STATE_REQUIRED ) ); // input
// ERROR_CHECK_STATUS( vxAddParameterToKernel( kernel, 1, VX_OUTPUT, VX_TYPE_FLOAT32, VX_PARAMETER_STATE_REQUIRED ) ); // output
// ERROR_CHECK_STATUS( vxReleaseKernel( &kernel ) );
// vxAddLogEntry( ( vx_reference ) context, VX_SUCCESS, "OK: registered user kernel app.userkernels.median_blur\n" );
// return VX_SUCCESS;
//}
| 33.797101 | 152 | 0.59241 | SijinJohn |
84d6133e3c8bc5c9ad0360528aebd6c352bc67f6 | 1,333 | cpp | C++ | anno/FileTreeElement.cpp | urobots-io/anno | 8e240185e6fc0908687b15a39c892814a6bddee6 | [
"MIT"
] | 9 | 2020-07-17T05:28:52.000Z | 2022-03-03T18:26:12.000Z | anno/FileTreeElement.cpp | urobots-io/anno | 8e240185e6fc0908687b15a39c892814a6bddee6 | [
"MIT"
] | null | null | null | anno/FileTreeElement.cpp | urobots-io/anno | 8e240185e6fc0908687b15a39c892814a6bddee6 | [
"MIT"
] | null | null | null | // This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com
//
// Anno Labeling Tool
// 2020-2021 (c) urobots GmbH, https://urobots.io
#include "FileTreeElement.h"
#include "SourcePicturesTreeModel.h"
FileTreeElement::FileTreeElement(SourcePicturesTreeModel* parent) : parent_(parent) {
}
FileTreeElement::~FileTreeElement() {
if (file_model_ && parent_)
parent_->UnregisterFileModel(file_model_.get());
}
std::shared_ptr<FileModel> FileTreeElement::GetFileModel() {
return file_model_;
}
void FileTreeElement::SetFileModel(std::shared_ptr<FileModel> file_model) {
if (file_model_ && parent_)
parent_->UnregisterFileModel(file_model_.get());
file_model_ = file_model;
if (file_model_ && parent_)
parent_->RegisterFileModel(file_model_.get());
}
void FileTreeElement::AddChild(FileTreeElement *child) {
child->parent = this;
child->parent_index = int(children.size());
children.push_back(child);
}
QStringList FileTreeElement::GetPathList() const {
// Traverse up until 2nd level of the tree.
QStringList path;
for (const FileTreeElement* i = this; i->parent && i->parent->parent; i = i->parent)
path.insert(0, i->name);
return path;
}
| 28.361702 | 88 | 0.705926 | urobots-io |
84d65b073afbdb1463f8a716060f7422637c3c9a | 1,441 | hpp | C++ | src/solvers/agent_routing/AgentIntegerAttribute.hpp | tomcreutz/planning-templ | 55e35ede362444df9a7def6046f6df06851fe318 | [
"BSD-3-Clause"
] | 1 | 2022-03-31T12:15:15.000Z | 2022-03-31T12:15:15.000Z | src/solvers/agent_routing/AgentIntegerAttribute.hpp | tomcreutz/planning-templ | 55e35ede362444df9a7def6046f6df06851fe318 | [
"BSD-3-Clause"
] | null | null | null | src/solvers/agent_routing/AgentIntegerAttribute.hpp | tomcreutz/planning-templ | 55e35ede362444df9a7def6046f6df06851fe318 | [
"BSD-3-Clause"
] | 1 | 2021-12-29T10:38:07.000Z | 2021-12-29T10:38:07.000Z | #ifndef TEMPL_AGENT_ROUTING_AGENT_INTEGER_ATTRIBUTE_HPP
#define TEMPL_AGENT_ROUTING_AGENT_INTEGER_ATTRIBUTE_HPP
#include <cstdint>
#include <string>
#include <vector>
namespace templ {
namespace solvers {
namespace agent_routing {
typedef std::string AttributeName;
class AgentIntegerAttribute
{
public:
typedef std::vector<AgentIntegerAttribute> List;
AgentIntegerAttribute();
AgentIntegerAttribute(uint32_t id, const AttributeName& label = "");
bool isValid() const;
void setId(uint32_t id) { mId = id; }
uint32_t getId() const { return mId; }
void setLabel(const AttributeName& label) { mLabel = label; }
const AttributeName& getLabel() const { return mLabel; }
void setValue(uint32_t value) { mValue = value; }
uint32_t getValue() const { return mValue; }
void setMinValue(uint32_t value) { mMinValue = value; }
uint32_t getMinValue() const { return mMinValue; }
void setMaxValue(uint32_t value) { mMaxValue = value; }
uint32_t getMaxValue() const { return mMaxValue; }
std::string toString(uint32_t indent = 0) const;
static std::string toString(const List& list, uint32_t indent = 0);
protected:
uint32_t mId;
AttributeName mLabel;
uint32_t mMinValue;
uint32_t mMaxValue;
uint32_t mValue;
};
} // end namespace agent_routing
} // end namespace solvers
} // end namespace templ
#endif // TEMPL_AGENT_ROUTING_AGENT_INTEGER_ATTRIBUTE_HPP
| 25.732143 | 72 | 0.728661 | tomcreutz |
84dc8aaea1cf098acc1114cf5a575e7c07ab2783 | 11,745 | cpp | C++ | Source/CLI/Help.cpp | g-maxime/MediaConch_SourceCode | 54208791ca0b6eb3f7bffd17f67e236777f69d89 | [
"BSD-2-Clause"
] | null | null | null | Source/CLI/Help.cpp | g-maxime/MediaConch_SourceCode | 54208791ca0b6eb3f7bffd17f67e236777f69d89 | [
"BSD-2-Clause"
] | null | null | null | Source/CLI/Help.cpp | g-maxime/MediaConch_SourceCode | 54208791ca0b6eb3f7bffd17f67e236777f69d89 | [
"BSD-2-Clause"
] | null | null | null | /* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//---------------------------------------------------------------------------
#ifdef __BORLANDC__
#pragma hdrstop
#endif
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "Help.h"
#include "Config.h"
//---------------------------------------------------------------------------
//***************************************************************************
//
//***************************************************************************
//---------------------------------------------------------------------------
int Help()
{
Version();
Help_Usage();
TEXTOUT("");
TEXTOUT("Options:");
TEXTOUT("Help:");
TEXTOUT(" --Help, -h");
TEXTOUT(" Display this help and exit");
TEXTOUT(" --Help=Advanced, -ha");
TEXTOUT(" Display the advanced help and exit");
TEXTOUT(" --Version, -v");
TEXTOUT(" Display the version and exit");
TEXTOUT("");
TEXTOUT(" --User=UserID, -u UserID");
TEXTOUT(" CLI user will be UserID");
TEXTOUT("");
TEXTOUT("Configuration Element:");
TEXTOUT(" --Configuration=ConfigurationFile, -c ConfigurationFile");
TEXTOUT(" Use ConfigurationFile as configuration file");
TEXTOUT(" Default, it uses the one in the user data application file");
TEXTOUT(" --PluginsConfiguration=PluginsConfigurationFile, -pc PluginsConfigurationFile");
TEXTOUT(" Use PluginsConfigurationFile as plugins configuration file");
TEXTOUT(" Default, it uses the struct in the configuration file or");
TEXTOUT(" no plugins configured if not inside.");
TEXTOUT("");
TEXTOUT("Reporting Elements:");
TEXTOUT(" --Mediaconch, -mc");
TEXTOUT(" Output MediaConch report (default)");
TEXTOUT(" (MediaConch contains default verbosity of implementationChecks");
TEXTOUT(" plus any provided policy checks.)");
TEXTOUT(" --Mediainfo, -mi");
TEXTOUT(" Output MediaInfo report");
TEXTOUT(" --Mediatrace, -mt");
TEXTOUT(" Output a trace of the file");
TEXTOUT("");
TEXTOUT("Policy Checker:");
TEXTOUT(" --Policy=PolicyFileName, -p PolicyFileName");
TEXTOUT(" Apply the policy (XSL or Schematron) ");
TEXTOUT(" --CreatePolicy");
TEXTOUT(" Create a policy (XSL) from a file");
TEXTOUT(" --PolicyReferenceFile=VideoFile, -prf VideoFile");
TEXTOUT(" Use the VideoFile as reference to compare in policy");
TEXTOUT("");
TEXTOUT("Output Formats:");
TEXTOUT(" --Format=text, -ft");
TEXTOUT(" Output MediaConch reports in Text format");
TEXTOUT(" --Format=xml, -fx");
TEXTOUT(" Output MediaConch reports in XML format");
TEXTOUT(" (changed to -fa if there are more than 1 tool or more than 1 file)");
TEXTOUT(" --Format=html, -fh");
TEXTOUT(" Output MediaConch reports in HTML format");
TEXTOUT(" --Format=simple, -fs");
TEXTOUT(" Output MediaConch reports in a shorten form");
TEXTOUT(" (>1 line only if there are errors), default format");
TEXTOUT(" --Format=csv, -fc");
TEXTOUT(" Output MediaConch reports in CSV format (only for policies)");
TEXTOUT(" --Format=maxml, -fa");
TEXTOUT(" Output in MediaArea XML format");
TEXTOUT(" --Display=DisplayFileName, -d DisplayFileName");
TEXTOUT(" Apply the display transformation (XSL)");
TEXTOUT("");
TEXTOUT(" --List");
TEXTOUT(" List files analyzed.");
TEXTOUT("");
TEXTOUT("Watch folder:");
TEXTOUT(" --WatchFolders-List, -wfl");
TEXTOUT(" List the folder watched");
TEXTOUT(" --WatchFolder=folder, -wf folder");
TEXTOUT(" Send to the server a folder to watch");
TEXTOUT(" --WatchFolder-Reports=folder, -wfr folder");
TEXTOUT(" Create reports of the selected watch folder to this folder");
TEXTOUT(" --WatchFolder-Not-Recursive");
TEXTOUT(" If watch folder is enabled, do not check recursively the folder");
TEXTOUT(" --WatchFolder-User=userId, -wfu userId");
TEXTOUT(" Create reports of the watch folder for the selected user ID");
TEXTOUT("");
TEXTOUT("Plugins:");
TEXTOUT(" --PluginsList");
TEXTOUT(" Output the plugins information ID");
TEXTOUT(" --UsePlugin=PluginId, -up PluginId");
TEXTOUT(" By default, only format plugin are used.");
TEXTOUT(" With this command, you can give the plugin ID you want to use.");
TEXTOUT(" Plugin ID can be get using the --pluginslist.");
TEXTOUT("");
TEXTOUT("File:");
TEXTOUT(" --FileInformation, -fi");
TEXTOUT(" Print files information and quit");
return CLI_RETURN_FINISH;
}
//---------------------------------------------------------------------------
int Help_Usage()
{
TEXTOUT("Usage: \"MediaConch [-Options...] FileName1 [Filename2...]\"");
return CLI_RETURN_ERROR;
}
//---------------------------------------------------------------------------
int Help_Nothing()
{
Help_Usage();
TEXTOUT("\"MediaConch --Help\" for displaying more information");
return CLI_RETURN_ERROR;
}
//---------------------------------------------------------------------------
int Help_Advanced()
{
TEXTOUT("--LogFile=...");
TEXTOUT(" Save the output in the specified file");
TEXTOUT("--Compression=Mode");
TEXTOUT(" Compress report in database using [Mode]");
TEXTOUT(" [Mode] can be None for no compression");
TEXTOUT(" [Mode] can be ZLib to use zlib");
TEXTOUT("-cz");
TEXTOUT(" Same as --Compression=ZLib");
TEXTOUT("");
TEXTOUT("Implementation Checker:");
TEXTOUT(" --ImplementationSchema=File");
TEXTOUT(" Use the specified File for implementation validation");
TEXTOUT(" --ImplementationVerbosity=V, -iv V");
TEXTOUT(" Select verbosity (V) of the implementation check, default 5");
TEXTOUT(" <= 4, show only fails and N/A");
TEXTOUT(" >= 5, show fails, N/A and pass");
TEXTOUT("");
TEXTOUT("--Force");
TEXTOUT(" Force to parse the file if registered in database");
TEXTOUT("--NoMilAnalyze, -nmil");
TEXTOUT(" Do not analyze with MediaInfoLib");
TEXTOUT("--Async=yes, -as");
TEXTOUT(" Analyze asynchronously the files,");
TEXTOUT(" need to launch again the command to have the result");
TEXTOUT("--Https=0, --no-https");
TEXTOUT(" XML output contains links in HTTP instead of HTTPS");
TEXTOUT("--Help=Ssl");
TEXTOUT(" More details about SSL specific options (e.g. for HTTPS or FTPS)");
TEXTOUT("--Help=Ssh");
TEXTOUT(" More details about SSH specific options (e.g. for SFTP)");
TEXTOUT("");
TEXTOUT("--DefaultValuesForType=Type,Field");
TEXTOUT(" Give the default values for the field of the");
TEXTOUT(" type given (separated by comma)");
return CLI_RETURN_FINISH;
}
//---------------------------------------------------------------------------
int Help_Ssl()
{
TEXTOUT("--Ssl_CertificateFileName=...");
TEXTOUT(" File name of the SSL certificate.");
TEXTOUT(" The default format is \"PEM\" and can be changed");
TEXTOUT(" with --Ssl_CertificateFormat.");
TEXTOUT("--Ssl_CertificateFormat=...");
TEXTOUT(" File format of the SSL certificate.");
TEXTOUT(" Supported formats are \"PEM\" and \"DER\"");
TEXTOUT("--Ssl_PrivateKeyFileName=...");
TEXTOUT(" File name of the SSL private key.");
TEXTOUT(" The default format is \"PEM\" and can be changed");
TEXTOUT(" with --Ssl_PrivateKeyFormat.");
TEXTOUT(" Note: private key with a password is not supported.");
TEXTOUT("--Ssl_PrivateKeyFormat=...");
TEXTOUT(" File format of the SSL private key.");
TEXTOUT(" Supported formats are \"PEM\" and \"DER\"");
TEXTOUT("--Ssl_CertificateAuthorityFileName=...");
TEXTOUT(" File name of the SSL certificate authorities");
TEXTOUT(" to verify the peer with.");
TEXTOUT("--Ssl_CertificateAuthorityPath=...");
TEXTOUT(" Path of the SSL certificate authorities");
TEXTOUT(" to verify the peer with.");
TEXTOUT("--Ssl_CertificateRevocationListFileName=...");
TEXTOUT(" File name of the SSL certificate revocation list.");
TEXTOUT(" The format is \"PEM\"");
TEXTOUT("--Ssl_IgnoreSecurity=...");
TEXTOUT(" Does not verify the authenticity of the peer's certificate");
TEXTOUT(" Use it at your own risks");
return CLI_RETURN_FINISH;
}
//---------------------------------------------------------------------------
int Help_Ssh()
{
TEXTOUT("--Ssh_PublicKeyFileName=...");
TEXTOUT(" File name of the SSH private key.");
TEXTOUT(" Default is $HOME/.ssh/id_rsa.pub or $HOME/.ssh/id_dsa.pub");
TEXTOUT(" if the HOME environment variable is set, and just");
TEXTOUT(" \"id_rsa.pub\" or \"id_dsa.pub\" in the current directory");
TEXTOUT(" if HOME is not set.");
TEXTOUT(" Note: you need to set both public and private key.");
TEXTOUT("--Ssh_PrivateKeyFileName=...");
TEXTOUT(" File name of the SSH private key.");
TEXTOUT(" Default is $HOME/.ssh/id_rsa or $HOME/.ssh/id_dsa");
TEXTOUT(" if the HOME environment variable is set, and just");
TEXTOUT(" \"id_rsa\" or \"id_dsa\" in the current directory");
TEXTOUT(" if HOME is not set.");
TEXTOUT(" Note: you need to set both public and private key.");
TEXTOUT(" Note: private key with a password is not supported.");
TEXTOUT("--Ssh_KnownHostsFileName=...");
TEXTOUT(" File name of the known hosts");
TEXTOUT(" The format is the OpenSSH file format (libssh2)");
TEXTOUT(" Default is $HOME/.ssh/known_hosts");
TEXTOUT(" if the HOME environment variable is set, and just");
TEXTOUT(" \"known_hosts\" in the current directory");
TEXTOUT(" if HOME is not set.");
TEXTOUT("--Ssh_IgnoreSecurity");
TEXTOUT(" Does not verify the authenticity of the peer");
TEXTOUT(" (you don't need to accept the key with ssh first)");
TEXTOUT(" Use it at your own risks");
return CLI_RETURN_FINISH;
}
//---------------------------------------------------------------------------
int Help_Policy()
{
TEXTOUT("--Policy=... Specify a schema to validate");
TEXTOUT("Usage: \"MediaConch --Policy=FileName\"");
TEXTOUT("");
TEXTOUT("FileName is the Schematron file used to validate");
TEXTOUT("");
return CLI_RETURN_FINISH;
}
//---------------------------------------------------------------------------
int Help_Xslt()
{
TEXTOUT("--Xslt=... Specify a schema to validate");
TEXTOUT("Usage: \"MediaConch --Xslt=FileName\"");
TEXTOUT("");
TEXTOUT("FileName is the XSLT file used to validate");
TEXTOUT("");
return CLI_RETURN_FINISH;
}
//---------------------------------------------------------------------------
int Version()
{
TEXTOUT("MediaConch Command Line Interface 18.03.2");
return CLI_RETURN_FINISH;
}
| 41.946429 | 96 | 0.548489 | g-maxime |
84e516b9e1e59f6a4ae14b137b25f29b09cc9e02 | 1,189 | cpp | C++ | source/Checkerboard.cpp | OxleyS/psx-toy-project | e9904d148416467e02407a9096b34e9091792b49 | [
"BSD-2-Clause"
] | 2 | 2016-12-05T00:20:55.000Z | 2018-12-08T04:50:04.000Z | source/Checkerboard.cpp | OxleyS/psx-toy-project | e9904d148416467e02407a9096b34e9091792b49 | [
"BSD-2-Clause"
] | null | null | null | source/Checkerboard.cpp | OxleyS/psx-toy-project | e9904d148416467e02407a9096b34e9091792b49 | [
"BSD-2-Clause"
] | null | null | null | #include "Checkerboard.h"
Texture g_CheckerboardTex;
void InitializeCheckboardTexture(int texX, int texY, int clutX, int clutY)
{
int colors[] = { 0x00000000, 0x11111111, 0x22222222 };
int nColors = sizeof(colors) / sizeof(int);
int colorIdx;
int texelsPerLong = 8;
int texelWidth = 64;
int texelHeight = 64;
u_long* pRgb = new u_long[(texelWidth * texelHeight) / 8];
int i, j, startIdx = 0, horIdx = 0, verIdx = 0;
for (i = 0; i < texelHeight; i++)
{
colorIdx = startIdx;
for (j = 0; j < texelWidth / texelsPerLong; j++)
{
pRgb[horIdx] = colors[colorIdx];
horIdx++;
if (horIdx % (8 / texelsPerLong) == 0) colorIdx = (colorIdx + 1) % nColors;
}
verIdx++;
if (verIdx % 4 == 0) startIdx = (startIdx + 1) % nColors;
}
u_long clut[] = { 0x03E0001F, 0xFFFF7C00, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF };
g_CheckerboardTex.InitFromMemoryClut(Texture::SEMITRANS_DONTCARE,
pRgb, texelWidth, texelHeight, texX, texY,
Texture::TEXTYPE_CLUT4, clut, clutX, clutY);
}
| 33.971429 | 122 | 0.589571 | OxleyS |
84f499d30221a5eda05df56def28b6576c2f13e8 | 1,577 | cpp | C++ | Sources/Inputs/Axes/CompoundInputAxis.cpp | Equilibrium-Games/Flounder | 1bd67dc8c2c2ebee2ca95f0cabb40b926f747fcf | [
"MIT"
] | 43 | 2017-08-09T04:03:38.000Z | 2018-07-17T15:25:32.000Z | Sources/Inputs/Axes/CompoundInputAxis.cpp | Equilibrium-Games/Flounder | 1bd67dc8c2c2ebee2ca95f0cabb40b926f747fcf | [
"MIT"
] | 3 | 2018-01-23T06:44:41.000Z | 2018-05-29T19:22:41.000Z | Sources/Inputs/Axes/CompoundInputAxis.cpp | Equilibrium-Games/Flounder | 1bd67dc8c2c2ebee2ca95f0cabb40b926f747fcf | [
"MIT"
] | 6 | 2017-11-03T10:48:20.000Z | 2018-04-28T21:44:59.000Z | #include "CompoundInputAxis.hpp"
namespace acid {
CompoundInputAxis::CompoundInputAxis(std::vector<std::unique_ptr<InputAxis>> &&axes) :
axes(std::move(axes)) {
ConnectAxes();
}
float CompoundInputAxis::GetAmount() const {
float result = 0.0f;
for (const auto &axis : axes)
result += axis->GetAmount();
return scale * std::clamp(result, -1.0f, 1.0f) + offset;
}
InputAxis::ArgumentDescription CompoundInputAxis::GetArgumentDescription() const {
return {
{"scale", "float", "Output amount scalar"},
{"axes", "axis[]", "The axes that will be combined into a compound axis"}
};
}
InputAxis *CompoundInputAxis::AddAxis(std::unique_ptr<InputAxis> &&axis) {
auto &result = axes.emplace_back(std::move(axis));
ConnectAxis(result);
return result.get();
}
void CompoundInputAxis::RemoveAxis(InputAxis *axis) {
//axis->OnAxis().RemoveObservers(this);
axes.erase(std::remove_if(axes.begin(), axes.end(), [axis](const auto &a) {
return a.get() == axis;
}), axes.end());
}
void CompoundInputAxis::ConnectAxis(std::unique_ptr<InputAxis> &axis) {
axis->OnAxis().connect(this, [this](float value) {
onAxis(GetAmount());
});
}
void CompoundInputAxis::ConnectAxes() {
for (auto &axis : axes)
ConnectAxis(axis);
}
const Node &operator>>(const Node &node, CompoundInputAxis &inputAxis) {
node["scale"].Get(inputAxis.scale);
node["axes"].Get(inputAxis.axes);
inputAxis.ConnectAxes();
return node;
}
Node &operator<<(Node &node, const CompoundInputAxis &inputAxis) {
node["scale"].Set(inputAxis.scale);
node["axes"].Set(inputAxis.axes);
return node;
}
}
| 25.852459 | 86 | 0.701966 | Equilibrium-Games |
84f9b419c05d61adc562cfaab2f58c2f84551bfb | 1,662 | cpp | C++ | tests/MemoryGame/Memory.cpp | sakex/NEAT-GRU | 2d96ff50415f38a8cf0ea7f3921c294b5766fc49 | [
"MIT"
] | 1 | 2021-05-21T21:40:11.000Z | 2021-05-21T21:40:11.000Z | tests/MemoryGame/Memory.cpp | sakex/NEAT-GRU | 2d96ff50415f38a8cf0ea7f3921c294b5766fc49 | [
"MIT"
] | 9 | 2020-06-01T14:33:32.000Z | 2020-06-01T16:38:28.000Z | tests/MemoryGame/Memory.cpp | sakex/NEAT-GRU | 2d96ff50415f38a8cf0ea7f3921c294b5766fc49 | [
"MIT"
] | null | null | null | //
// Created by sakex on 02.06.20.
//
#include "Memory.h"
Memory::Memory() : players() {
generate_random_grids();
}
void Memory::generate_random_grids() {
datasets.clear();
datasets.reserve(100);
for(int _ = 0; _ < 100; ++_){
numbers_list numbers;
for (int i = 0; i < NUMBERS / 2; ++i) {
constexpr int NUMBERS_BY_2 = (NUMBERS - 2) / 2;
double const value = static_cast<double>(i * 2 - NUMBERS_BY_2) / static_cast<double>(NUMBERS_BY_2);
numbers[i*2] = value;
numbers[i*2 + 1] = value;
}
std::shuffle(std::begin(numbers), std::end(numbers), std::mt19937(std::random_device()()));
datasets.push_back(numbers);
}
}
std::vector<double> Memory::do_run_generation() {
auto & _datasets = datasets;
auto &&cb = [_datasets](MemoryPlayer &player) {
player.play_rounds(_datasets);
};
Threading::for_each(players.begin(), players.end(), cb);
std::vector<double> outputs;
outputs.reserve(players.size());
std::transform(players.begin(), players.end(),
std::back_inserter(outputs),
[](const MemoryPlayer &player) { return player.score(); });
return outputs;
}
void Memory::do_reset_players(NN *nets, size_t count) {
players.clear();
players.reserve(count);
for (size_t it = 0; it < count; ++it) {
players.emplace_back(&nets[it]);
}
}
void Memory::do_post_training(NN * net) {
MemoryPlayer player(net);
generate_random_grids();
player.play_rounds(datasets, true);
std::cout << "Final score: " << player.score() << std::endl;
delete net;
} | 29.157895 | 112 | 0.599278 | sakex |
84fab1c486cf46a0ca03083743a709646452bf11 | 296 | cpp | C++ | skovalenko/sp-10/src/poisk.cpp | MeatSoft/cpp-study | e381a03f360e391036418b50b870450ac8183080 | [
"MIT"
] | null | null | null | skovalenko/sp-10/src/poisk.cpp | MeatSoft/cpp-study | e381a03f360e391036418b50b870450ac8183080 | [
"MIT"
] | 3 | 2021-02-23T18:09:57.000Z | 2021-02-28T17:28:40.000Z | skovalenko/sp-10/src/poisk.cpp | MeatSoft/prog-study | e381a03f360e391036418b50b870450ac8183080 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
int a, b, c, d, i, summ;
for (i = 1000; i < 10000; i++)
{
a = i % 10;
b = (i / 10) % 10;
c = (i / 100) % 10;
d = i / 1000;
summ = a + b + c + d;
if (summ > 10)
{
if (summ < 16)
cout << i << endl;
}
}
return 0;
}
| 13.454545 | 31 | 0.435811 | MeatSoft |
ebdcb03c1fc65a603e0a3ee3d675d3a4b13ee1c9 | 6,594 | cpp | C++ | apps/common/ospray_testing/builders/Builder.cpp | cainiaoC4/ospray | 616dcea05eefffe8c52e04753ae7e346581135f7 | [
"Apache-2.0"
] | 780 | 2017-01-28T01:30:14.000Z | 2022-03-20T16:54:42.000Z | apps/common/ospray_testing/builders/Builder.cpp | cainiaoC4/ospray | 616dcea05eefffe8c52e04753ae7e346581135f7 | [
"Apache-2.0"
] | 419 | 2017-01-20T22:22:05.000Z | 2022-03-31T01:32:22.000Z | apps/common/ospray_testing/builders/Builder.cpp | cainiaoC4/ospray | 616dcea05eefffe8c52e04753ae7e346581135f7 | [
"Apache-2.0"
] | 131 | 2017-02-26T20:23:45.000Z | 2022-02-07T19:49:26.000Z | // Copyright 2009-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include "Builder.h"
namespace ospray {
namespace testing {
namespace detail {
std::unique_ptr<Builder::BuilderFactory> Builder::factory;
void Builder::commit()
{
rendererType = getParam<std::string>("rendererType", "scivis");
tfColorMap = getParam<std::string>("tf.colorMap", "jet");
tfOpacityMap = getParam<std::string>("tf.opacityMap", "linear");
randomSeed = getParam<unsigned int>("randomSeed", 0);
}
cpp::World Builder::buildWorld() const
{
return buildWorld({});
}
cpp::World Builder::buildWorld(
const std::vector<cpp::Instance> &instances) const
{
cpp::World world;
auto group = buildGroup();
cpp::Instance instance(group);
instance.commit();
std::vector<cpp::Instance> inst = instances;
inst.push_back(instance);
if (addPlane)
inst.push_back(makeGroundPlane(group.getBounds<box3f>()));
world.setParam("instance", cpp::CopiedData(inst));
cpp::Light light("ambient");
light.setParam("visible", false);
light.commit();
world.setParam("light", cpp::CopiedData(light));
return world;
}
cpp::TransferFunction Builder::makeTransferFunction(
const vec2f &valueRange) const
{
cpp::TransferFunction transferFunction("piecewiseLinear");
std::vector<vec3f> colors;
std::vector<float> opacities;
if (tfColorMap == "jet") {
colors.emplace_back(0, 0, 0.562493);
colors.emplace_back(0, 0, 1);
colors.emplace_back(0, 1, 1);
colors.emplace_back(0.500008, 1, 0.500008);
colors.emplace_back(1, 1, 0);
colors.emplace_back(1, 0, 0);
colors.emplace_back(0.500008, 0, 0);
} else if (tfColorMap == "rgb") {
colors.emplace_back(0, 0, 1);
colors.emplace_back(0, 1, 0);
colors.emplace_back(1, 0, 0);
} else {
colors.emplace_back(0.f, 0.f, 0.f);
colors.emplace_back(1.f, 1.f, 1.f);
}
if (tfOpacityMap == "linear") {
opacities.emplace_back(0.f);
opacities.emplace_back(1.f);
} else if (tfOpacityMap == "linearInv") {
opacities.emplace_back(1.f);
opacities.emplace_back(0.f);
} else if (tfOpacityMap == "opaque") {
opacities.emplace_back(1.f);
}
transferFunction.setParam("color", cpp::CopiedData(colors));
transferFunction.setParam("opacity", cpp::CopiedData(opacities));
transferFunction.setParam("valueRange", valueRange);
transferFunction.commit();
return transferFunction;
}
cpp::Instance Builder::makeGroundPlane(const box3f &bounds) const
{
auto planeExtent = 0.8f * length(bounds.center() - bounds.lower);
cpp::Geometry planeGeometry("mesh");
std::vector<vec3f> v_position;
std::vector<vec3f> v_normal;
std::vector<vec4f> v_color;
std::vector<vec4ui> indices;
unsigned int startingIndex = 0;
const vec3f up = vec3f{0.f, 1.f, 0.f};
const vec4f gray = vec4f{0.9f, 0.9f, 0.9f, 0.75f};
v_position.emplace_back(-planeExtent, -1.f, -planeExtent);
v_position.emplace_back(planeExtent, -1.f, -planeExtent);
v_position.emplace_back(planeExtent, -1.f, planeExtent);
v_position.emplace_back(-planeExtent, -1.f, planeExtent);
v_normal.push_back(up);
v_normal.push_back(up);
v_normal.push_back(up);
v_normal.push_back(up);
v_color.push_back(gray);
v_color.push_back(gray);
v_color.push_back(gray);
v_color.push_back(gray);
indices.emplace_back(
startingIndex, startingIndex + 1, startingIndex + 2, startingIndex + 3);
// stripes on ground plane
const float stripeWidth = 0.025f;
const float paddedExtent = planeExtent + stripeWidth;
const size_t numStripes = 10;
const vec4f stripeColor = vec4f{1.0f, 0.1f, 0.1f, 1.f};
for (size_t i = 0; i < numStripes; i++) {
// the center coordinate of the stripe, either in the x or z
// direction
const float coord =
-planeExtent + float(i) / float(numStripes - 1) * 2.f * planeExtent;
// offset the stripes by an epsilon above the ground plane
const float yLevel = -1.f + 1e-3f;
// x-direction stripes
startingIndex = v_position.size();
v_position.emplace_back(-paddedExtent, yLevel, coord - stripeWidth);
v_position.emplace_back(paddedExtent, yLevel, coord - stripeWidth);
v_position.emplace_back(paddedExtent, yLevel, coord + stripeWidth);
v_position.emplace_back(-paddedExtent, yLevel, coord + stripeWidth);
v_normal.push_back(up);
v_normal.push_back(up);
v_normal.push_back(up);
v_normal.push_back(up);
v_color.push_back(stripeColor);
v_color.push_back(stripeColor);
v_color.push_back(stripeColor);
v_color.push_back(stripeColor);
indices.emplace_back(
startingIndex, startingIndex + 1, startingIndex + 2, startingIndex + 3);
// z-direction stripes
startingIndex = v_position.size();
v_position.emplace_back(coord - stripeWidth, yLevel, -paddedExtent);
v_position.emplace_back(coord + stripeWidth, yLevel, -paddedExtent);
v_position.emplace_back(coord + stripeWidth, yLevel, paddedExtent);
v_position.emplace_back(coord - stripeWidth, yLevel, paddedExtent);
v_normal.push_back(up);
v_normal.push_back(up);
v_normal.push_back(up);
v_normal.push_back(up);
v_color.push_back(stripeColor);
v_color.push_back(stripeColor);
v_color.push_back(stripeColor);
v_color.push_back(stripeColor);
indices.emplace_back(
startingIndex, startingIndex + 1, startingIndex + 2, startingIndex + 3);
}
planeGeometry.setParam("vertex.position", cpp::CopiedData(v_position));
planeGeometry.setParam("vertex.normal", cpp::CopiedData(v_normal));
planeGeometry.setParam("vertex.color", cpp::CopiedData(v_color));
planeGeometry.setParam("index", cpp::CopiedData(indices));
planeGeometry.commit();
cpp::GeometricModel plane(planeGeometry);
if (rendererType == "pathtracer" || rendererType == "scivis"
|| rendererType == "ao") {
cpp::Material material(rendererType, "obj");
material.commit();
plane.setParam("material", material);
}
plane.commit();
cpp::Group planeGroup;
planeGroup.setParam("geometry", cpp::CopiedData(plane));
planeGroup.commit();
cpp::Instance planeInst(planeGroup);
planeInst.commit();
return planeInst;
}
void Builder::registerBuilder(const std::string &name, BuilderFcn fcn)
{
if (factory.get() == nullptr)
factory = make_unique<BuilderFactory>();
(*factory)[name] = fcn;
}
Builder *Builder::createBuilder(const std::string &name)
{
if (factory.get() == nullptr)
return nullptr;
else {
auto &fcn = (*factory)[name];
return fcn();
}
}
} // namespace detail
} // namespace testing
} // namespace ospray
| 27.940678 | 80 | 0.696846 | cainiaoC4 |
ebdd6302c82aa044b089702726ac339db43f91ae | 345 | hpp | C++ | include/8859_15_character_set.hpp | jce-caba/gtkQRmm | 0a6f46bdbbc30195c2ddf993be43d218dbc2c47a | [
"MIT"
] | 1 | 2022-03-13T14:21:23.000Z | 2022-03-13T14:21:23.000Z | include/8859_15_character_set.hpp | jce-caba/gtkQRmm | 0a6f46bdbbc30195c2ddf993be43d218dbc2c47a | [
"MIT"
] | null | null | null | include/8859_15_character_set.hpp | jce-caba/gtkQRmm | 0a6f46bdbbc30195c2ddf993be43d218dbc2c47a | [
"MIT"
] | null | null | null | #ifndef _8859_15_CHARACTER_SET_HPP
#define _8859_15_CHARACTER_SET_HPP
namespace GtkQR
{
class _8859_15_character_set
{
public:
_8859_15_character_set() = delete;
~_8859_15_character_set() = delete;
static int get_character(int);
protected:
private:
};
}
#endif // 8859_15_CHARACTER_SET_HPP
| 15 | 43 | 0.689855 | jce-caba |
ebe08fdb3f52e5d86431f26af80645db16ad1197 | 630 | cpp | C++ | Libraries/LibHTML/Layout/LayoutListItem.cpp | JamiKettunen/serenity | 232da5cc188496f570ef55276a897f1095509c87 | [
"BSD-2-Clause"
] | 3 | 2020-05-01T02:39:03.000Z | 2021-11-26T08:34:54.000Z | Libraries/LibHTML/Layout/LayoutListItem.cpp | JamiKettunen/serenity | 232da5cc188496f570ef55276a897f1095509c87 | [
"BSD-2-Clause"
] | null | null | null | Libraries/LibHTML/Layout/LayoutListItem.cpp | JamiKettunen/serenity | 232da5cc188496f570ef55276a897f1095509c87 | [
"BSD-2-Clause"
] | null | null | null | #include <LibHTML/Layout/LayoutListItem.h>
#include <LibHTML/Layout/LayoutListItemMarker.h>
LayoutListItem::LayoutListItem(const Element& element, NonnullRefPtr<StyleProperties> style)
: LayoutBlock(&element, move(style))
{
}
LayoutListItem::~LayoutListItem()
{
}
void LayoutListItem::layout()
{
LayoutBlock::layout();
if (!m_marker) {
m_marker = adopt(*new LayoutListItemMarker);
if (first_child())
m_marker->set_inline(first_child()->is_inline());
append_child(*m_marker);
}
FloatRect marker_rect { x() - 8, y(), 4, height() };
m_marker->set_rect(marker_rect);
}
| 23.333333 | 92 | 0.67619 | JamiKettunen |
ebe13566ff2a5dfef57ded0ce6a533db0f4021d5 | 8,466 | hpp | C++ | Framework/general/cSmartSimpleIndexPool.hpp | echo-Mike/goOGL | bf5b58a7ecc5783aad0177c375cdb53e59880d07 | [
"MIT"
] | null | null | null | Framework/general/cSmartSimpleIndexPool.hpp | echo-Mike/goOGL | bf5b58a7ecc5783aad0177c375cdb53e59880d07 | [
"MIT"
] | null | null | null | Framework/general/cSmartSimpleIndexPool.hpp | echo-Mike/goOGL | bf5b58a7ecc5783aad0177c375cdb53e59880d07 | [
"MIT"
] | null | null | null | #ifndef SMARTSIMPLEINDEXPOOL_H
#define SMARTSIMPLEINDEXPOOL_H "[multi@cSmartSimpleIndexPool.hpp]"
/*
* DESCRIPTION:
* Module contains implementation of efficient index pool with simple logic and
* buld-in preallocated pool for indexes.
* Logic: double heap
* AUTHOR:
* Mikhail Demchenko
* mailto:dev.echo.mike@gmail.com
* https://github.com/echo-Mike
*/
//STD
#include <cmath>
#include <limits.h>
#include <cstring>
#include <string.h>
#include <stdexcept>
//OUR
#include "general\vs2013tweaks.h"
#include "general\mConcepts.hpp"
#include "cSimpleIndexPool.hpp"
//DEBUG
#if defined(DEBUG_SMARTSIMPLEINDEXPOOL) && !defined(OTHER_DEBUG)
#include "general\mDebug.h"
#elif defined(DEBUG_SMARTSIMPLEINDEXPOOL) && defined(OTHER_DEBUG)
#include OTHER_DEBUG
#endif
template < class TIndex = int >
/**
* \brief This class implements handling of pre-allocated pool of indexes over SimpleIndexPool functionality.
* Only integral index types are accepted with constant increment step (operaor++).
* Heavily depends on CHAR_BIT macro from <limits.h>
* !!!ATTENTION!!! This class directly operates on memory so all construct, copy and move operations may throw exceptions.
* Class template definition: SmartSimpleIndexPool
**/
class SmartSimpleIndexPool : public SimpleIndexPool<TIndex> {
CONCEPT_INTEGRAL(TIndex, "ASSERTION_ERROR::SMART_SIMPLE_INDEX_POOL::Provided type \"TIndex\" must be integral.")
typedef SimpleIndexPool<TIndex> Base;
//Pool of preallocated indexes
TIndex* preallocatedPool;
//Pointer to pool top
TIndex* topPtr;
//Estimated size of periodic requests
unsigned int meanRequestSize;
//Hide public interface of SimpleIndexPool
Base::newIndex;
Base::startLocation;
Base::deleteIndex;
Base::allocateMax;
Base::allocateMaxByArray;
public:
SmartSimpleIndexPool() = delete;
SmartSimpleIndexPool( TIndex _min, TIndex _max, unsigned int _meanRequestSize) :
SimpleIndexPool(_max, _min), meanRequestSize(_meanRequestSize)
{
//ERROR::SMART_SIMPLE_INDEX_POOL::Constructor::System can't allocate memory for preallocated pool.
//std::bad_alloc may be thrown here
preallocatedPool = new TIndex[meanRequestSize * 2];
auto _allocated = SimpleIndexPool::newIndex(preallocatedPool, meanRequestSize * 2);
topPtr = preallocatedPool + _allocated - 1;
}
~SmartSimpleIndexPool() NOEXCEPT {
topPtr = nullptr;
delete[] preallocatedPool;
}
SmartSimpleIndexPool(const SmartSimpleIndexPool& other) : SimpleIndexPool(other),
meanRequestSize(other.meanRequestSize)
{
//ERROR::SMART_SIMPLE_INDEX_POOL::CopyConstructor::System can't allocate memory for preallocated pool.
//std::bad_alloc may be thrown here
preallocatedPool = new TIndex[meanRequestSize * 2];
std::memcpy(preallocatedPool, other.preallocatedPool, meanRequestSize * 2 * sizeof(TIndex));
topPtr = preallocatedPool + (other.topPtr - other.preallocatedPool);
}
SmartSimpleIndexPool& operator= (const SmartSimpleIndexPool& other) {
if (&other == this)
return *this;
//std::bad_alloc may be thrown here
SimpleIndexPool::operator=(other);
delete[] preallocatedPool;
meanRequestSize = other.meanRequestSize;
//ERROR::SMART_SIMPLE_INDEX_POOL::CopyAssignment::System can't allocate memory for preallocated pool.
//std::bad_alloc may be thrown here
preallocatedPool = new TIndex[meanRequestSize * 2];
std::memcpy(preallocatedPool, other.preallocatedPool, meanRequestSize * 2 * sizeof(TIndex));
topPtr = preallocatedPool + (other.topPtr - other.preallocatedPool);
}
SmartSimpleIndexPool(SmartSimpleIndexPool&& other) NOEXCEPT_IF(CONCEPT_NOEXCEPT_MOVE_CONSTRUCTIBLE_V(Base)) :
SimpleIndexPool(std::move(other))
{
preallocatedPool = other.preallocatedPool;
other.preallocatedPool = nullptr;
other.topPtr = nullptr;
}
SmartSimpleIndexPool& operator= (SmartSimpleIndexPool&& other) NOEXCEPT_IF(CONCEPT_NOEXCEPT_MOVE_CONSTRUCTIBLE_V(Base)) {
delete[] preallocatedPool;
meanRequestSize = other.meanRequestSize;
//ERROR::SMART_SIMPLE_INDEX_POOL::MoveAssignment::Empty preallocatedPool of rvalue.
preallocatedPool = other.preallocatedPool;
//This is not safe:
topPtr = other.topPtr;
try { SimpleIndexPool::operator=(std::move(other)); }
catch (...) {
delete[] preallocatedPool;
preallocatedPool = nullptr;
topPtr = nullptr;
throw;
}
other.preallocatedPool = nullptr;
other.topPtr = nullptr;
}
/**
* Computes memory used by this pool.
**/
size_t usedMemory() NOEXCEPT { return SimpleIndexPool::usedMemory() - sizeof(SimpleIndexPool) + sizeof(SmartSimpleIndexPool); }
/**
* \brief Performs an allocation of new index.
* \throw nothrow
* \return Newly allocated index or 'notFoundIndex'.
**/
TIndex newIndex() NOEXCEPT {
if (topPtr < preallocatedPool + meanRequestSize) {
/*unsigned int _allocated = 2 * meanRequestSize - (topPtr - preallocatedPool + 1);
_allocated = SimpleIndexPool::newIndex(++topPtr, _allocated);
topPtr += _allocated;*/
//oneliner:
topPtr += SimpleIndexPool::newIndex(++topPtr, 2 * meanRequestSize - (topPtr - preallocatedPool)) - 1;
}
if (topPtr != preallocatedPool - 1) {
--topPtr;
return *(topPtr + 1);
}
//throw std::out_of_range("ERROR::SMART_SIMPLE_INDEX_POOL::newIndex::Can't allocate more indexes.");
return notFoundIndex;
}
/**
* \brief Tries to perform allocation of '_count' indexes.
* Allocated indexes returned via '_array' parameter.
* \param[out] _array Array filled with new indexes.
* \param[in] _count Count of indexes to be allocated.
* \throw nothrow Exept if defined DEBUG_SMARTSIMPLEINDEXPOOL and WARNINGS_SMARTSIMPLEINDEXPOOL then unkown.
* \return Count of successfully allocated indexes.
**/
unsigned int newIndex(TIndex _array[], unsigned int _count) NOEXCEPT {
if (!_count)
return 0;
if (_count < 2) {
try { _array[0] = newIndex(); }
catch (...) { return 0; }
return 1;
}
unsigned int _inStock = topPtr - preallocatedPool + 1;
if (_count <= _inStock) {
topPtr = preallocatedPool + (_inStock - _count) - 1;
std::memcpy(_array, topPtr + 1, _count * sizeof(TIndex));
return _count;
} else {
topPtr += SimpleIndexPool::newIndex(++topPtr, _count - _inStock) - 1;
_inStock = topPtr - preallocatedPool + 1;
if (_count <= _inStock) {
topPtr = preallocatedPool + (_inStock - _count) - 1;
std::memcpy(_array, topPtr + 1, _count * sizeof(TIndex));
return _count;
} else if(_inStock) {
std::memcpy(_array, preallocatedPool, _inStock * sizeof(TIndex));
topPtr = preallocatedPool - 1;
#if defined(DEBUG_SMARTSIMPLEINDEXPOOL) && defined(WARNINGS_SMARTSIMPLEINDEXPOOL)
DEBUG_NEW_MESSAGE("WARNING::SMART_SIMPLE_INDEX_POOL::newIndex")
DEBUG_WRITE1("\tMessage: Can't allocate more indexes.");
DEBUG_WRITE2("\tFinal allocated count: ", _index);
DEBUG_END_MESSAGE
#endif
return _inStock;
}
}
#if defined(DEBUG_SMARTSIMPLEINDEXPOOL) && defined(WARNINGS_SMARTSIMPLEINDEXPOOL)
DEBUG_NEW_MESSAGE("WARNING::SMART_SIMPLE_INDEX_POOL::newIndex")
DEBUG_WRITE1("\tMessage: Can't allocate more indexes.");
DEBUG_WRITE1("\tFinal allocated count: 0");
DEBUG_END_MESSAGE
#endif
return 0;
}
/**
* \brief Deallocate index '_index'.
* \param[in] _index Index to be deallocated.
* \throw nothrow
* \return noreturn
**/
void deleteIndex(TIndex _index) NOEXCEPT {
for (int _index = 0; _index <= topPtr - preallocatedPool; _index++)
if (*(preallocatedPool + _index) == _index)
return;
SimpleIndexPool::deleteIndex(_index);
}
/**
* \brief Deallocate indexex from '_begin' index to '_end' index.
* \param[in] _begin Begin of indexes to be deallocated.
* \param[in] _end End of indexes to be deallocated.
* \throw nothrow
* \return noreturn
**/
void deleteIndex(TIndex _begin, TIndex _end) NOEXCEPT {
SimpleIndexPool::deleteIndex(_begin, _end);
SimpleIndexPool::allocateSpecific(preallocatedPool, (unsigned int)(topPtr - preallocatedPool + 1));
}
/**
* \brief Check index allocation status of '_index'.
* \param[in] _index Index to be checked.
* \throw nothrow
* \return Index allocation status.
**/
bool isUsed(TIndex _index) NOEXCEPT {
if (_index < minIndex || _index > maxIndex)
return false;
if (SimpleIndexPool::isUsed(_index)) {
for (int _index0 = 0; _index0 <= topPtr - preallocatedPool; _index0++)
if (*(preallocatedPool + _index0) == _index0)
return false;
return true;
} else {
return false;
}
}
};
#endif | 35.128631 | 128 | 0.730097 | echo-Mike |
ebe638cc59dd5be9f33b1744046a9830ed12616f | 2,771 | cpp | C++ | RenderSystems/NULL/src/OgreNULLStagingTexture.cpp | Stazer/ogre-next | 4d3aa2aedf4575ac8a9e32a4e2af859562752d51 | [
"MIT"
] | 1 | 2021-05-12T18:01:21.000Z | 2021-05-12T18:01:21.000Z | RenderSystems/NULL/src/OgreNULLStagingTexture.cpp | Stazer/ogre-next | 4d3aa2aedf4575ac8a9e32a4e2af859562752d51 | [
"MIT"
] | 1 | 2020-07-25T19:20:07.000Z | 2020-07-25T19:20:07.000Z | RenderSystems/NULL/src/OgreNULLStagingTexture.cpp | Stazer/ogre-next | 4d3aa2aedf4575ac8a9e32a4e2af859562752d51 | [
"MIT"
] | 1 | 2021-09-28T18:44:28.000Z | 2021-09-28T18:44:28.000Z | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2017 Torus Knot Software Ltd
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 "OgreNULLStagingTexture.h"
#include "OgreNULLTextureGpu.h"
namespace Ogre
{
NULLStagingTexture::NULLStagingTexture( VaoManager *vaoManager, PixelFormatGpu formatFamily,
size_t size ) :
StagingTextureBufferImpl( vaoManager, formatFamily, size, 0, 0 ),
mDynamicBuffer( (uint8*)OGRE_MALLOC_SIMD( size, MEMCATEGORY_RENDERSYS ) ),
mMappedPtr( 0 ),
mLastMappedPtr( 0 )
{
mMappedPtr = mDynamicBuffer;
mLastMappedPtr = mMappedPtr;
}
//-----------------------------------------------------------------------------------
NULLStagingTexture::~NULLStagingTexture()
{
if( mDynamicBuffer )
{
OGRE_FREE_SIMD( mDynamicBuffer, MEMCATEGORY_RENDERSYS );
mDynamicBuffer = 0;
}
mMappedPtr = 0;
}
//-----------------------------------------------------------------------------------
bool NULLStagingTexture::belongsToUs( const TextureBox &box )
{
return box.data >= mLastMappedPtr &&
box.data <= static_cast<uint8*>( mLastMappedPtr ) + mCurrentOffset;
}
//-----------------------------------------------------------------------------------
void* RESTRICT_ALIAS_RETURN NULLStagingTexture::mapRegionImplRawPtr(void)
{
return static_cast<uint8*>( mMappedPtr ) + mCurrentOffset;
}
}
| 41.984848 | 96 | 0.605197 | Stazer |
ebe9247f3162257697e441ef3b8e2e50dd1f64f2 | 10,533 | hpp | C++ | speculative_threadpool.hpp | clin99/testing | 34c5768ca83b51b0c61d7f25c58e3e9b88be8926 | [
"MIT"
] | null | null | null | speculative_threadpool.hpp | clin99/testing | 34c5768ca83b51b0c61d7f25c58e3e9b88be8926 | [
"MIT"
] | 1 | 2018-03-28T03:27:48.000Z | 2018-03-28T03:27:48.000Z | speculative_threadpool.hpp | clin99/testing | 34c5768ca83b51b0c61d7f25c58e3e9b88be8926 | [
"MIT"
] | null | null | null | // 2018/09/12 - created by Tsung-Wei Huang and Chun-Xun Lin
//
// Speculative threadpool is similar to proactive threadpool except
// each thread will speculatively move a new task to its local worker
// data structure to reduce extract hit to the task queue.
// This can save time from locking the mutex during dynamic tasking.
#pragma once
#include <iostream>
#include <functional>
#include <vector>
#include <mutex>
#include <deque>
#include <thread>
#include <stdexcept>
#include <condition_variable>
#include <memory>
#include <future>
#include <unordered_set>
#include <unordered_map>
namespace speculative_threadpool {
template <typename T>
struct MoC {
MoC(T&& rhs): object(std::move(rhs)) {}
MoC(const MoC& other) : object(std::move(other.object)) {}
T& get() {return object; }
mutable T object;
};
// Class: BasicSpeculativeThreadpool
template < template<typename...> class Func >
class BasicSpeculativeThreadpool {
using TaskType = Func<void()>;
struct Worker{
std::condition_variable cv;
TaskType task;
bool ready {false};
};
public:
BasicSpeculativeThreadpool(unsigned);
~BasicSpeculativeThreadpool();
size_t num_tasks() const;
size_t num_workers() const;
bool is_owner() const;
void shutdown();
void spawn(unsigned);
void wait_for_all();
template <typename C>
void silent_async(C&&);
template <typename C>
void silent_async(std::deque<C>&&);
template <typename C>
auto async(C&&);
private:
mutable std::mutex _mutex;
std::condition_variable _empty_cv;
std::deque<TaskType> _task_queue;
std::vector<std::thread> _threads;
std::vector<Worker*> _idlers;
std::unordered_map<std::thread::id, Worker*> _worker_maps;
const std::thread::id _owner {std::this_thread::get_id()};
bool _exiting {false};
bool _wait_for_all {false};
std::vector<std::unique_ptr<Worker>> _works;
auto _this_worker() const;
}; // class BasicSpeculativeThreadpool. --------------------------------------
// Constructor
template < template<typename...> class Func >
BasicSpeculativeThreadpool<Func>::BasicSpeculativeThreadpool(unsigned N){
spawn(N);
}
// Destructor
template < template<typename...> class Func >
BasicSpeculativeThreadpool<Func>::~BasicSpeculativeThreadpool(){
shutdown();
}
// Function: is_owner
template < template<typename...> class Func >
bool BasicSpeculativeThreadpool<Func>::is_owner() const {
return std::this_thread::get_id() == _owner;
}
// Function: num_tasks
template < template<typename...> class Func >
size_t BasicSpeculativeThreadpool<Func>::num_tasks() const {
return _task_queue.size();
}
// Function: num_workers
template < template<typename...> class Func >
size_t BasicSpeculativeThreadpool<Func>::num_workers() const {
return _threads.size();
}
// Function: _this_worker
template < template<typename...> class Func >
auto BasicSpeculativeThreadpool<Func>::_this_worker() const {
auto id = std::this_thread::get_id();
return _worker_maps.find(id);
}
// Function: shutdown
template < template<typename...> class Func >
void BasicSpeculativeThreadpool<Func>::shutdown(){
if(!is_owner()){
throw std::runtime_error("Worker thread cannot shut down the pool");
}
if(_threads.empty()) {
return;
}
{
std::unique_lock lock(_mutex);
_wait_for_all = true;
while(_idlers.size() != num_workers()) {
_empty_cv.wait(lock);
}
_exiting = true;
for(auto w : _idlers){
w->ready = true;
w->task = nullptr;
w->cv.notify_one();
}
_idlers.clear();
}
for(auto& t : _threads){
t.join();
}
_threads.clear();
_works.clear();
_worker_maps.clear();
_wait_for_all = false;
_exiting = false;
// task queue might have tasks added by threads outside this pool...
//while(not _task_queue.empty()) {
// std::invoke(_task_queue.front());
// _task_queue.pop_front();
//}
}
// Function: spawn
template < template<typename...> class Func >
void BasicSpeculativeThreadpool<Func>::spawn(unsigned N) {
if(! is_owner()){
throw std::runtime_error("Worker thread cannot spawn threads");
}
// Wait untill all workers become idle if any
if(!_threads.empty()){
wait_for_all();
}
for(size_t i=0; i<N; ++i){
_works.push_back(std::make_unique<Worker>());
}
const size_t sz = _threads.size();
// Lock to synchronize all workers before creating _worker_mapss
std::scoped_lock<std::mutex> lock(_mutex);
for(size_t i=0; i<N; ++i){
_threads.emplace_back([this, i=i+sz]() -> void {
TaskType t {nullptr};
Worker& w = *(_works[i]);
size_t idle {0};
std::unique_lock<std::mutex> lock(_mutex);
while(!_exiting){
if(_task_queue.empty()){
w.ready = false;
_idlers.push_back(&w);
if(_wait_for_all && _idlers.size() == num_workers()){
_empty_cv.notify_one();
}
idle ++;
while(!w.ready) {
w.cv.wait(lock);
}
t = std::move(w.task);
}
else{
t = std::move(_task_queue.front());
_task_queue.pop_front();
}
if(t){
_mutex.unlock();
// speculation loop
while(t) {
t();
t = std::move(w.task);
}
_mutex.lock();
}
} // End of while ------------------------------------------------------
std::cout << idle << std::endl;
});
_worker_maps.insert({_threads.back().get_id(), _works[i+sz].get()});
} // End of For ---------------------------------------------------------------------------------
}
// Function: async
template < template<typename...> class Func >
template <typename C>
auto BasicSpeculativeThreadpool<Func>::async(C&& c){
using R = std::invoke_result_t<C>;
std::promise<R> p;
auto fu = p.get_future();
// master thread
if(num_workers() == 0){
if constexpr(std::is_same_v<void, R>){
c();
p.set_value();
}
else{
p.set_value(c());
}
}
// have worker(s)
else{
if constexpr(std::is_same_v<void, R>){
// speculation
if(std::this_thread::get_id() != _owner){
auto iter = _this_worker();
if(iter != _worker_maps.end() && iter->second->task == nullptr){
iter->second->task =
[p = MoC(std::move(p)), c = std::forward<C>(c)]() mutable {
c();
p.get().set_value();
};
return fu;
}
}
std::scoped_lock lock(_mutex);
if(_idlers.empty()){
_task_queue.emplace_back(
[p = MoC(std::move(p)), c = std::forward<C>(c)]() mutable {
c();
p.get().set_value();
}
);
}
// Got an idle work
else{
Worker* w = _idlers.back();
_idlers.pop_back();
w->ready = true;
w->task = [p = MoC(std::move(p)), c = std::forward<C>(c)]() mutable {
c();
p.get().set_value();
};
w->cv.notify_one();
}
}
else{
// speculation
if(std::this_thread::get_id() != _owner){
auto iter = _this_worker();
if(iter != _worker_maps.end() && iter->second->task == nullptr){
iter->second->task =
[p = MoC(std::move(p)), c = std::forward<C>(c)]() mutable {
p.get().set_value(c());
};
return fu;
}
}
std::scoped_lock lock(_mutex);
if(_idlers.empty()){
_task_queue.emplace_back(
[p = MoC(std::move(p)), c = std::forward<C>(c)]() mutable {
p.get().set_value(c());
}
);
}
else{
Worker* w = _idlers.back();
_idlers.pop_back();
w->ready = true;
w->task = [p = MoC(std::move(p)), c = std::forward<C>(c)]() mutable {
p.get().set_value(c());
};
w->cv.notify_one();
}
}
}
return fu;
}
template < template<typename...> class Func >
template <typename C>
void BasicSpeculativeThreadpool<Func>::silent_async(std::deque<C>&& c){
size_t consumed {0};
// speculation
if(std::this_thread::get_id() != _owner){
auto iter = _this_worker();
if(iter != _worker_maps.end() && iter->second->task == nullptr){
iter->second->task = std::move(c[consumed++]);
if(consumed == c.size())
return ;
}
}
{
size_t notified {0};
std::scoped_lock lock(_mutex);
while(notified != _idlers.size() && consumed < c.size()){
_idlers[notified]->task = std::move(c[consumed++]);
_idlers[notified]->cv.notify_one();
_idlers[notified]->ready = true;
notified ++;
}
_idlers.clear();
if(consumed == c.size()) return;
std::move(c.begin()+consumed, c.end(), std::back_inserter(_task_queue));
}
//std::scoped_lock lock(_mutex);
//for(auto &w: _idlers){
// w->cv.notify_one();
//}
//_idlers.clear();
//if(_idlers.empty()){
// _task_queue.push_back(std::move(t));
//}
//else{
// Worker* w = _idlers.back();
// _idlers.pop_back();
// w->ready = true;
// w->task = std::move(t);
// w->cv.notify_one();
//}
}
template < template<typename...> class Func >
template <typename C>
void BasicSpeculativeThreadpool<Func>::silent_async(C&& c){
TaskType t {std::forward<C>(c)};
//no worker thread available
if(num_workers() == 0){
t();
return;
}
// speculation
if(std::this_thread::get_id() != _owner){
auto iter = _this_worker();
if(iter != _worker_maps.end() && iter->second->task == nullptr){
iter->second->task = std::move(t);
return ;
}
}
std::scoped_lock lock(_mutex);
if(_idlers.empty()){
_task_queue.push_back(std::move(t));
}
else{
Worker* w = _idlers.back();
_idlers.pop_back();
w->ready = true;
w->task = std::move(t);
w->cv.notify_one();
}
}
// Function: wait_for_all
template < template<typename...> class Func >
void BasicSpeculativeThreadpool<Func>::wait_for_all() {
if(!is_owner()){
throw std::runtime_error("Worker thread cannot wait for all");
}
std::unique_lock lock(_mutex);
_wait_for_all = true;
while(_idlers.size() != num_workers()) {
_empty_cv.wait(lock);
}
_wait_for_all = false;
}
}; // namespace speculative_threadpool. --------------------------------------
| 22.897826 | 99 | 0.574006 | clin99 |
ebeaceb99df180ee3767afd506df696c092c4dca | 1,448 | cpp | C++ | tests/concurrent/set.cpp | mayant15/mlib | 4f7a466746a90b358808e214813dc95f2e3c62c6 | [
"MIT"
] | null | null | null | tests/concurrent/set.cpp | mayant15/mlib | 4f7a466746a90b358808e214813dc95f2e3c62c6 | [
"MIT"
] | null | null | null | tests/concurrent/set.cpp | mayant15/mlib | 4f7a466746a90b358808e214813dc95f2e3c62c6 | [
"MIT"
] | null | null | null | #include "../doctest.h"
#include <mm/concurrent/set.h>
#include <thread>
TEST_CASE("Test the concurrent set class")
{
mm::concurrent::lazy_set<int> set;
REQUIRE(set.size() == 0);
SUBCASE("Test set::add()")
{
CHECK(set.add(1));
CHECK(set.size() == 1);
CHECK_FALSE(set.add(1));
bool other_thread;
std::thread t1 ([&](){
other_thread = set.add(3);
});
bool this_thread = set.add(2);
t1.join();
CHECK(this_thread);
CHECK(other_thread);
CHECK(set.size() == 3);
}
SUBCASE("Test set::contains()")
{
std::thread t1 ([&](){
set.add(1);
});
std::thread t2 ([&](){
set.add(2);
});
t1.join();
t2.join();
CHECK(set.contains(1));
CHECK(set.contains(2));
CHECK_FALSE(set.contains(3));
}
SUBCASE("Test set::remove()")
{
set.add(1);
set.add(2);
bool out1;
std::thread t1 ([&](){
out1 = set.remove(1);
});
bool out2;
std::thread t2 ([&](){
out2 = set.remove(2);
});
t1.join();
t2.join();
CHECK(out1);
CHECK(out2);
CHECK(set.size() == 0);
CHECK(!set.contains(2));
CHECK(!set.contains(1));
CHECK_FALSE(set.remove(2));
CHECK_FALSE(set.remove(1));
}
}
| 18.564103 | 42 | 0.450276 | mayant15 |
ebebd6230a5d8b11e57417702586d669f3706a0d | 753 | cpp | C++ | Leetcode/1239. Maximum Length of a Concatenated String with Unique Characters.cpp | Aqiry/Competitive-coding | e4a091a4f79d62319fa95d15631606404853a33e | [
"MIT"
] | null | null | null | Leetcode/1239. Maximum Length of a Concatenated String with Unique Characters.cpp | Aqiry/Competitive-coding | e4a091a4f79d62319fa95d15631606404853a33e | [
"MIT"
] | 1 | 2021-11-12T16:31:25.000Z | 2021-11-12T16:31:25.000Z | Leetcode/1239. Maximum Length of a Concatenated String with Unique Characters.cpp | Aqiry/Competitive-coding | e4a091a4f79d62319fa95d15631606404853a33e | [
"MIT"
] | 1 | 2021-11-12T16:30:02.000Z | 2021-11-12T16:30:02.000Z | class Solution {
public int maxLength(List<String> arr) {
return helper(arr,0,new int[26]);
}
public int helper(List<String> arr, int idx,int[] freq){
if(idx == arr.size()){
return 0;
}
int exc = helper(arr,idx+1,freq);
boolean isunique = true;
String word = arr.get(idx);
for(char ch : word.toCharArray()){
if(freq[ch-'a'] != 0){
isunique = false;
}
freq[ch-'a']++;
}
int inc = 0;
if(isunique){
inc = helper(arr,idx+1,freq) + word.length();
}
for(char ch : word.toCharArray()){
freq[ch-'a']--;
}
return Math.max(inc,exc);
}
}
| 19.815789 | 60 | 0.451527 | Aqiry |
ebec568a82b0b536655bf832915302b2a67ade7f | 2,065 | cpp | C++ | MainWindow.cpp | dewf/dnd-inspect | 42dbef2ba87392d3e628814e77fa456335dda51c | [
"MIT"
] | null | null | null | MainWindow.cpp | dewf/dnd-inspect | 42dbef2ba87392d3e628814e77fa456335dda51c | [
"MIT"
] | 2 | 2019-03-28T16:19:08.000Z | 2019-03-31T07:17:33.000Z | MainWindow.cpp | dewf/dnd-inspect | 42dbef2ba87392d3e628814e77fa456335dda51c | [
"MIT"
] | 1 | 2019-03-28T16:12:03.000Z | 2019-03-28T16:12:03.000Z | #include "MainWindow.h"
#include <AppKit.h>
#include <InterfaceKit.h>
#include <LayoutBuilder.h>
#include <TabView.h>
#include <stdio.h>
#include "Globals.h"
#include "DNDEncoder.h"
static const int32 K_NEW_WINDOW_MSG = 'NWMg';
static const int32 K_QUIT_APP_MSG = 'EXiT';
static int numWindowsOpen = 0;
void MainWindow::MessageReceived(BMessage *message)
{
switch(message->what) {
case K_NEW_WINDOW_MSG:
{
BPoint p(50, 50);
ConvertToScreen(&p);
auto win = new MainWindow();
win->MoveTo(p);
win->Show();
break;
}
case K_QUIT_APP_MSG:
{
be_app->PostMessage(B_QUIT_REQUESTED);
break;
}
default:
BWindow::MessageReceived(message);
}
}
MainWindow::MainWindow()
:BWindow(BRect(0, 0, 300, 400), "DND Inspector", B_TITLED_WINDOW, 0 /*B_QUIT_ON_WINDOW_CLOSE*/)
{
CenterOnScreen();
// menu
auto menuBar = new BMenuBar("menubar");
auto fileMenu = new BMenu("File");
fileMenu->AddItem(new BMenuItem("New window", new BMessage(K_NEW_WINDOW_MSG), 'N'));
fileMenu->AddItem(new BMenuItem("Quit", new BMessage(K_QUIT_APP_MSG), 'Q'));
menuBar->AddItem(new BMenuItem(fileMenu));
// content
auto tabView = new BTabView("tabview");
dragSourceView = new DragSourceView();
auto tab = new BTab();
tabView->AddTab(dragSourceView, tab);
tab->SetLabel("Drag source");
dropTargetView = new DropTargetView();
auto tab2 = new BTab();
tabView->AddTab(dropTargetView, tab2);
tab2->SetLabel("Drop target");
tabView->SetBorder(B_NO_BORDER);
BLayoutBuilder::Group<>(this, B_VERTICAL, 1)
.Add(menuBar)
.Add(BSpaceLayoutItem::CreateVerticalStrut(B_USE_HALF_ITEM_SPACING))
.AddGroup(B_VERTICAL)
.SetInsets(-2) // to remove the spacing around the tab view
.Add(tabView);
SetSizeLimits(250, B_SIZE_UNLIMITED, 100, B_SIZE_UNLIMITED);
numWindowsOpen++;
}
MainWindow::~MainWindow()
{
numWindowsOpen--;
if (numWindowsOpen < 1) {
be_app->PostMessage(B_QUIT_REQUESTED);
}
}
| 23.465909 | 99 | 0.663438 | dewf |
ebfc56bc1cdc6b704a9358cb0746973fc126701b | 3,173 | cpp | C++ | opennurbs_pointgeometry.cpp | averbin/opennurbslib | 8904e11a90d108304f679d233ad1ea2d621dd3b2 | [
"Zlib"
] | 14 | 2015-07-06T13:04:49.000Z | 2022-02-06T10:09:05.000Z | opennurbs_pointgeometry.cpp | averbin/opennurbslib | 8904e11a90d108304f679d233ad1ea2d621dd3b2 | [
"Zlib"
] | 1 | 2020-12-07T03:26:39.000Z | 2020-12-07T03:26:39.000Z | opennurbs_pointgeometry.cpp | averbin/opennurbslib | 8904e11a90d108304f679d233ad1ea2d621dd3b2 | [
"Zlib"
] | 11 | 2015-07-06T13:04:43.000Z | 2022-03-29T10:57:04.000Z | /* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#include "opennurbs.h"
ON_OBJECT_IMPLEMENT( ON_Point, ON_Geometry, "C3101A1D-F157-11d3-BFE7-0010830122F0" );
ON_BOOL32 ON_Point::IsValid( ON_TextLog* text_log ) const
{
bool rc = point.IsValid();
if ( !rc && text_log )
{
text_log->Print("ON_Point::point is not a valid 3d point.\n");
}
return rc;
}
void ON_Point::Dump( ON_TextLog& dump ) const
{
dump.Print("ON_Point: ");
dump.Print(point);
dump.Print("\n");
}
ON_BOOL32 ON_Point::Write( ON_BinaryArchive& file ) const
{
ON_BOOL32 rc = file.Write3dmChunkVersion(1,0);
if (rc) rc = file.WritePoint( point );
return rc;
}
ON_BOOL32 ON_Point::Read( ON_BinaryArchive& file )
{
int major_version = 0;
int minor_version = 0;
ON_BOOL32 rc = file.Read3dmChunkVersion(&major_version,&minor_version);
if (rc && major_version==1) {
// common to all 1.x versions
rc = file.ReadPoint(point);
}
return rc;
}
ON::object_type ON_Point::ObjectType() const
{
return ON::point_object;
}
int ON_Point::Dimension() const
{
return 3;
}
ON_BOOL32 ON_Point::GetBBox( double* boxmin, double* boxmax, ON_BOOL32 bGrowBox ) const
{
return ON_GetPointListBoundingBox( 3, 0, 1, 3, &point.x, boxmin, boxmax, bGrowBox?true:false );
}
bool ON_Point::IsDeformable() const
{
return true;
}
bool ON_Point::MakeDeformable()
{
return true;
}
ON_BOOL32 ON_Point::Transform( const ON_Xform& xform )
{
TransformUserData(xform);
return ON_TransformPointList(3,0,1,3,&point.x,xform);
}
ON_BOOL32 ON_Point::SwapCoordinates( int i, int j )
{
return ON_SwapPointListCoordinates( 1, 3, &point.x, i, j );
}
ON_Point::ON_Point() : point(0.0,0.0,0.0)
{}
ON_Point::ON_Point(const ON_Point& src) : ON_Geometry(src), point(src.point)
{}
ON_Point::ON_Point(const ON_3dPoint& pt) : point(pt)
{}
ON_Point::ON_Point(double x,double y,double z) : point(x,y,z)
{}
ON_Point::~ON_Point()
{}
ON_Point& ON_Point::operator=(const ON_Point& src)
{
if ( this != &src ) {
ON_Geometry::operator=(src);
point=src.point;
}
return *this;
}
ON_Point& ON_Point::operator=(const ON_3dPoint& pt)
{
point=pt;
return *this;
}
ON_Point::operator double*()
{
return &point.x;
}
ON_Point::operator const double*() const
{
return &point.x;
}
ON_Point::operator ON_3dPoint*()
{
return &point;
}
ON_Point::operator const ON_3dPoint*() const
{
return &point;
}
ON_Point::operator ON_3dPoint&()
{
return point;
}
ON_Point::operator const ON_3dPoint&() const
{
return point;
}
| 20.875 | 98 | 0.6445 | averbin |
23027935cb11d56e16174a95ade58f3bdf490907 | 20,206 | cpp | C++ | source/direct3d10/StateBlockMask.cpp | HeavenWu/slimdx | e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac | [
"MIT"
] | 85 | 2015-04-06T05:37:10.000Z | 2022-03-22T19:53:03.000Z | source/direct3d10/StateBlockMask.cpp | HeavenWu/slimdx | e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac | [
"MIT"
] | 10 | 2016-03-17T11:18:24.000Z | 2021-05-11T09:21:43.000Z | source/direct3d10/StateBlockMask.cpp | HeavenWu/slimdx | e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac | [
"MIT"
] | 45 | 2015-09-14T03:54:01.000Z | 2022-03-22T19:53:09.000Z | #include "stdafx.h"
/*
* Copyright (c) 2007-2012 SlimDX Group
*
* 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 <d3d10.h>
#include "Direct3D10Exception.h"
#include "../Utilities.h"
#include "StateBlockMask.h"
using namespace System;
using namespace System::Collections::Generic;
using namespace System::Collections::ObjectModel;
namespace SlimDX
{
namespace Direct3D10
{
StateBlockMask::StateBlockMask()
{
m_VSSamplers = gcnew array<bool>( D3D10_BYTES_FROM_BITS( D3D10_COMMONSHADER_SAMPLER_SLOT_COUNT ) );
m_VSShaderResources = gcnew array<bool>( D3D10_BYTES_FROM_BITS( D3D10_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT ) );
m_VSConstantBuffers = gcnew array<bool>( D3D10_BYTES_FROM_BITS( D3D10_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT ) );
m_GSSamplers = gcnew array<bool>( D3D10_BYTES_FROM_BITS( D3D10_COMMONSHADER_SAMPLER_SLOT_COUNT ) );
m_GSShaderResources = gcnew array<bool>( D3D10_BYTES_FROM_BITS( D3D10_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT ) );
m_GSConstantBuffers = gcnew array<bool>( D3D10_BYTES_FROM_BITS( D3D10_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT ) );
m_PSSamplers = gcnew array<bool>( D3D10_BYTES_FROM_BITS( D3D10_COMMONSHADER_SAMPLER_SLOT_COUNT ) );
m_PSShaderResources = gcnew array<bool>( D3D10_BYTES_FROM_BITS( D3D10_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT ) );
m_PSConstantBuffers = gcnew array<bool>( D3D10_BYTES_FROM_BITS( D3D10_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT ) );
m_IAVertexBuffers = gcnew array<bool>( D3D10_BYTES_FROM_BITS( D3D10_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT ) );
}
StateBlockMask::StateBlockMask( StateBlockMask^ other )
{
if( other == nullptr )
throw gcnew ArgumentNullException( "other" );
m_VS = other->m_VS;
m_VSSamplers = (array<bool>^)other->m_VSSamplers->Clone();
m_VSShaderResources = (array<bool>^)other->m_VSShaderResources->Clone();
m_VSConstantBuffers = (array<bool>^)other->m_VSConstantBuffers->Clone();
m_GS = other->m_GS;
m_GSSamplers = (array<bool>^)other->m_GSSamplers->Clone();
m_GSShaderResources = (array<bool>^)other->m_GSShaderResources->Clone();
m_GSConstantBuffers = (array<bool>^)other->m_GSConstantBuffers->Clone();
m_PS = other->m_PS;
m_PSSamplers = (array<bool>^)other->m_PSSamplers->Clone();
m_PSShaderResources = (array<bool>^)other->m_PSShaderResources->Clone();
m_PSConstantBuffers = (array<bool>^)other->m_PSConstantBuffers->Clone();
m_IAVertexBuffers = (array<bool>^)other->m_IAVertexBuffers->Clone();
m_IAIndexBuffer = other->m_IAIndexBuffer;
m_IAInputLayout = other->m_IAInputLayout;
m_IAPrimitiveTopology = other->m_IAPrimitiveTopology;
m_OMRenderTargets = other->m_OMRenderTargets;
m_OMDepthStencilState = other->m_OMDepthStencilState;
m_OMBlendState = other->m_OMBlendState;
m_RSViewports = other->m_RSViewports;
m_RSScissorRects = other->m_RSScissorRects;
m_RSRasterizerState = other->m_RSRasterizerState;
m_SOBuffers = other->m_SOBuffers;
m_Predication = other->m_Predication;
}
StateBlockMask::StateBlockMask( const D3D10_STATE_BLOCK_MASK& native )
{
m_VS = native.VS ? true : false;
m_GS = native.GS ? true : false;
m_PS = native.PS ? true : false;
m_IAIndexBuffer = native.IAIndexBuffer ? true : false;
m_IAInputLayout = native.IAInputLayout ? true : false;
m_IAPrimitiveTopology = native.IAPrimitiveTopology ? true : false;
m_OMRenderTargets = native.OMRenderTargets ? true : false;
m_OMDepthStencilState = native.OMDepthStencilState ? true : false;
m_OMBlendState = native.OMBlendState ? true : false;
m_RSViewports = native.RSViewports ? true : false;
m_RSScissorRects = native.RSScissorRects ? true : false;
m_RSRasterizerState = native.RSRasterizerState ? true : false;
m_SOBuffers = native.SOBuffers ? true : false;
m_Predication = native.Predication ? true : false;
m_VSSamplers = gcnew array<bool>( D3D10_BYTES_FROM_BITS( D3D10_COMMONSHADER_SAMPLER_SLOT_COUNT ) );
for( int index = 0; index < m_VSSamplers->Length; ++index )
{
m_VSSamplers[index] = native.VSSamplers[index] ? true : false;
}
m_VSShaderResources = gcnew array<bool>( D3D10_BYTES_FROM_BITS( D3D10_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT ) );
for( int index = 0; index < m_VSShaderResources->Length; ++index )
{
m_VSShaderResources[index] = native.VSShaderResources[index] ? true : false;
}
m_VSConstantBuffers = gcnew array<bool>( D3D10_BYTES_FROM_BITS( D3D10_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT ) );
for( int index = 0; index < m_VSConstantBuffers->Length; ++index )
{
m_VSConstantBuffers[index] = native.VSConstantBuffers[index] ? true : false;
}
m_GSSamplers = gcnew array<bool>( D3D10_BYTES_FROM_BITS( D3D10_COMMONSHADER_SAMPLER_SLOT_COUNT ) );
for( int index = 0; index < m_GSSamplers->Length; ++index )
{
m_GSSamplers[index] = native.GSSamplers[index] ? true : false;
}
m_GSShaderResources = gcnew array<bool>( D3D10_BYTES_FROM_BITS( D3D10_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT ) );
for( int index = 0; index < m_GSShaderResources->Length; ++index )
{
m_GSShaderResources[index] = native.GSShaderResources[index] ? true : false;
}
m_GSConstantBuffers = gcnew array<bool>( D3D10_BYTES_FROM_BITS( D3D10_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT ) );
for( int index = 0; index < m_GSConstantBuffers->Length; ++index )
{
m_GSConstantBuffers[index] = native.GSConstantBuffers[index] ? true : false;
}
m_PSSamplers = gcnew array<bool>( D3D10_BYTES_FROM_BITS( D3D10_COMMONSHADER_SAMPLER_SLOT_COUNT ) );
for( int index = 0; index < m_PSSamplers->Length; ++index )
{
m_PSSamplers[index] = native.PSSamplers[index] ? true : false;
}
m_PSShaderResources = gcnew array<bool>( D3D10_BYTES_FROM_BITS( D3D10_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT ) );
for( int index = 0; index < m_PSShaderResources->Length; ++index )
{
m_PSShaderResources[index] = native.PSShaderResources[index] ? true : false;
}
m_PSConstantBuffers = gcnew array<bool>( D3D10_BYTES_FROM_BITS( D3D10_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT ) );
for( int index = 0; index < m_PSConstantBuffers->Length; ++index )
{
m_PSConstantBuffers[index] = native.PSConstantBuffers[index] ? true : false;
}
m_IAVertexBuffers = gcnew array<bool>( D3D10_BYTES_FROM_BITS( D3D10_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT ) );
for( int index = 0; index < m_IAVertexBuffers->Length; ++index )
{
m_IAVertexBuffers[index] = native.IAVertexBuffers[index] ? true : false;
}
}
D3D10_STATE_BLOCK_MASK StateBlockMask::CreateNativeVersion()
{
D3D10_STATE_BLOCK_MASK native;
native.VS = m_VS;
native.GS = m_GS;
native.PS = m_PS;
native.IAIndexBuffer = m_IAIndexBuffer;
native.IAInputLayout = m_IAInputLayout;
native.IAPrimitiveTopology = m_IAPrimitiveTopology;
native.OMRenderTargets = m_OMRenderTargets;
native.OMDepthStencilState = m_OMDepthStencilState;
native.OMBlendState = m_OMBlendState;
native.RSViewports = m_RSViewports;
native.RSScissorRects = m_RSScissorRects;
native.RSRasterizerState = m_RSRasterizerState;
native.SOBuffers = m_SOBuffers;
native.Predication = m_Predication;
for( int index = 0; index < m_VSSamplers->Length; ++index )
{
native.VSSamplers[index] = m_VSSamplers[index];
}
for( int index = 0; index < m_VSShaderResources->Length; ++index )
{
native.VSShaderResources[index] = m_VSShaderResources[index];
}
for( int index = 0; index < m_VSConstantBuffers->Length; ++index )
{
native.VSConstantBuffers[index] = m_VSConstantBuffers[index];
}
for( int index = 0; index < m_GSSamplers->Length; ++index )
{
native.GSSamplers[index] = m_GSSamplers[index];
}
for( int index = 0; index < m_GSShaderResources->Length; ++index )
{
native.GSShaderResources[index] = m_GSShaderResources[index];
}
for( int index = 0; index < m_GSConstantBuffers->Length; ++index )
{
native.GSConstantBuffers[index] = m_GSConstantBuffers[index];
}
for( int index = 0; index < m_PSSamplers->Length; ++index )
{
native.PSSamplers[index] = m_PSSamplers[index];
}
for( int index = 0; index < m_PSShaderResources->Length; ++index )
{
native.PSShaderResources[index] = m_PSShaderResources[index];
}
for( int index = 0; index < m_PSConstantBuffers->Length; ++index )
{
native.PSConstantBuffers[index] = m_PSConstantBuffers[index];
}
for( int index = 0; index < m_IAVertexBuffers->Length; ++index )
{
native.IAVertexBuffers[index] = m_IAVertexBuffers[index];
}
return native;
}
System::Object^ StateBlockMask::Clone2()
{
return Clone();
}
bool StateBlockMask::VertexShader::get()
{
return m_VS;
}
void StateBlockMask::VertexShader::set( bool value )
{
m_VS = value;
}
array<bool>^ StateBlockMask::VertexShaderSamplers::get()
{
return m_VSSamplers;
}
array<bool>^ StateBlockMask::VertexShaderResources::get()
{
return m_VSShaderResources;
}
array<bool>^ StateBlockMask::VertexShaderConstantBuffers::get()
{
return m_VSConstantBuffers;
}
bool StateBlockMask::GeometryShader::get()
{
return m_GS;
}
void StateBlockMask::GeometryShader::set( bool value )
{
m_GS = value;
}
array<bool>^ StateBlockMask::GeometryShaderSamplers::get()
{
return m_GSSamplers;
}
array<bool>^ StateBlockMask::GeometryShaderResources::get()
{
return m_GSShaderResources;
}
array<bool>^ StateBlockMask::GeometryShaderConstantBuffers::get()
{
return m_GSConstantBuffers;
}
bool StateBlockMask::PixelShader::get()
{
return m_PS;
}
void StateBlockMask::PixelShader::set( bool value )
{
m_PS = value;
}
array<bool>^ StateBlockMask::PixelShaderSamplers::get()
{
return m_PSSamplers;
}
array<bool>^ StateBlockMask::PixelShaderResources::get()
{
return m_PSShaderResources;
}
array<bool>^ StateBlockMask::PixelShaderConstantBuffers::get()
{
return m_PSConstantBuffers;
}
array<bool>^ StateBlockMask::VertexBuffers::get()
{
return m_IAVertexBuffers;
}
bool StateBlockMask::IndexBuffer::get()
{
return m_IAIndexBuffer;
}
void StateBlockMask::IndexBuffer::set( bool value )
{
m_IAIndexBuffer = value;
}
bool StateBlockMask::InputLayout::get()
{
return m_IAInputLayout;
}
void StateBlockMask::InputLayout::set( bool value )
{
m_IAInputLayout = value;
}
bool StateBlockMask::PrimitiveTopology::get()
{
return m_IAPrimitiveTopology;
}
void StateBlockMask::PrimitiveTopology::set( bool value )
{
m_IAPrimitiveTopology = value;
}
bool StateBlockMask::RenderTargets::get()
{
return m_OMRenderTargets;
}
void StateBlockMask::RenderTargets::set( bool value )
{
m_OMRenderTargets = value;
}
bool StateBlockMask::DepthStencilState::get()
{
return m_OMDepthStencilState;
}
void StateBlockMask::DepthStencilState::set( bool value )
{
m_OMDepthStencilState = value;
}
bool StateBlockMask::BlendState::get()
{
return m_OMBlendState;
}
void StateBlockMask::BlendState::set( bool value )
{
m_OMBlendState = value;
}
bool StateBlockMask::Viewports::get()
{
return m_RSViewports;
}
void StateBlockMask::Viewports::set( bool value )
{
m_RSViewports = value;
}
bool StateBlockMask::ScissorRectangles::get()
{
return m_RSScissorRects;
}
void StateBlockMask::ScissorRectangles::set( bool value )
{
m_RSScissorRects = value;
}
bool StateBlockMask::RasterizerState::get()
{
return m_RSRasterizerState;
}
void StateBlockMask::RasterizerState::set( bool value )
{
m_RSRasterizerState = value;
}
bool StateBlockMask::StreamOutputBuffers::get()
{
return m_SOBuffers;
}
void StateBlockMask::StreamOutputBuffers::set( bool value )
{
m_SOBuffers = value;
}
bool StateBlockMask::Predication::get()
{
return m_Predication;
}
void StateBlockMask::Predication::set( bool value )
{
m_Predication = value;
}
StateBlockMask^ StateBlockMask::Clone()
{
return gcnew StateBlockMask( this );
}
StateBlockMask^ StateBlockMask::Difference(StateBlockMask^ other)
{
if( other == nullptr )
throw gcnew ArgumentNullException( "other" );
D3D10_STATE_BLOCK_MASK nA = this->CreateNativeVersion();
D3D10_STATE_BLOCK_MASK nB = other->CreateNativeVersion();
D3D10_STATE_BLOCK_MASK nResult;
if( RECORD_D3D10( D3D10StateBlockMaskDifference( &nA, &nB, &nResult ) ).IsFailure )
throw gcnew Direct3D10Exception( Result::Last );
return gcnew StateBlockMask( nResult );
}
StateBlockMask^ StateBlockMask::DisableAll()
{
D3D10_STATE_BLOCK_MASK native;
if( RECORD_D3D10( D3D10StateBlockMaskDisableAll( &native ) ).IsFailure )
throw gcnew Direct3D10Exception( Result::Last );
return gcnew StateBlockMask( native );
}
StateBlockMask^ StateBlockMask::EnableAll()
{
D3D10_STATE_BLOCK_MASK native;
if( RECORD_D3D10( D3D10StateBlockMaskEnableAll( &native ) ).IsFailure )
throw gcnew Direct3D10Exception( Result::Last );
return gcnew StateBlockMask(native);
}
StateBlockMask^ StateBlockMask::Intersect(StateBlockMask^ other)
{
if( other == nullptr )
throw gcnew ArgumentNullException( "other" );
D3D10_STATE_BLOCK_MASK nA = this->CreateNativeVersion();
D3D10_STATE_BLOCK_MASK nB = other->CreateNativeVersion();
D3D10_STATE_BLOCK_MASK nResult;
if( RECORD_D3D10( D3D10StateBlockMaskIntersect( &nA, &nB, &nResult ) ).IsFailure )
throw gcnew Direct3D10Exception( Result::Last );
return gcnew StateBlockMask( nResult );
}
StateBlockMask^ StateBlockMask::Union(StateBlockMask^ other)
{
if( other == nullptr )
throw gcnew ArgumentNullException( "other" );
D3D10_STATE_BLOCK_MASK nA = this->CreateNativeVersion();
D3D10_STATE_BLOCK_MASK nB = other->CreateNativeVersion();
D3D10_STATE_BLOCK_MASK nResult;
if( RECORD_D3D10( D3D10StateBlockMaskUnion( &nA, &nB, &nResult ) ).IsFailure )
throw gcnew Direct3D10Exception( Result::Last );
return gcnew StateBlockMask( nResult );
}
bool StateBlockMask::operator == ( StateBlockMask^ left, StateBlockMask^ right )
{
return StateBlockMask::Equals( left, right );
}
bool StateBlockMask::operator != ( StateBlockMask^ left, StateBlockMask^ right )
{
return !StateBlockMask::Equals( left, right );
}
int StateBlockMask::GetHashCode()
{
return m_VS.GetHashCode() +
m_VSSamplers->GetHashCode() +
m_VSShaderResources->GetHashCode() +
m_VSConstantBuffers->GetHashCode() +
m_GS.GetHashCode() +
m_GSSamplers->GetHashCode() +
m_GSShaderResources->GetHashCode() +
m_GSConstantBuffers->GetHashCode() +
m_PS.GetHashCode() +
m_PSSamplers->GetHashCode() +
m_PSShaderResources->GetHashCode() +
m_PSConstantBuffers->GetHashCode() +
m_IAVertexBuffers->GetHashCode() +
m_IAIndexBuffer.GetHashCode() +
m_IAInputLayout.GetHashCode() +
m_IAPrimitiveTopology.GetHashCode() +
m_OMRenderTargets.GetHashCode() +
m_OMDepthStencilState.GetHashCode() +
m_OMBlendState.GetHashCode() +
m_RSViewports.GetHashCode() +
m_RSScissorRects.GetHashCode() +
m_RSRasterizerState.GetHashCode() +
m_SOBuffers.GetHashCode() +
m_Predication.GetHashCode();
}
bool StateBlockMask::Equals( Object^ value )
{
if( value == nullptr )
return false;
if( value->GetType() != GetType() )
return false;
return Equals( safe_cast<StateBlockMask^>( value ) );
}
bool StateBlockMask::Equals( StateBlockMask^ value )
{
return m_VS == value->m_VS &&
Utilities::CheckElementEquality( m_VSSamplers, value->m_VSSamplers ) &&
Utilities::CheckElementEquality( m_VSShaderResources, value->m_VSShaderResources ) &&
Utilities::CheckElementEquality( m_VSConstantBuffers,value->m_VSConstantBuffers ) &&
m_GS == value->m_GS &&
Utilities::CheckElementEquality( m_GSSamplers, value->m_GSSamplers ) &&
Utilities::CheckElementEquality( m_GSShaderResources, value->m_GSShaderResources ) &&
Utilities::CheckElementEquality( m_GSConstantBuffers, value->m_GSConstantBuffers ) &&
m_PS == value->m_PS &&
Utilities::CheckElementEquality( m_PSSamplers, value->m_PSSamplers ) &&
Utilities::CheckElementEquality( m_PSShaderResources, value->m_PSShaderResources ) &&
Utilities::CheckElementEquality( m_PSConstantBuffers, value->m_PSConstantBuffers ) &&
Utilities::CheckElementEquality( m_IAVertexBuffers, value->m_IAVertexBuffers ) &&
m_IAIndexBuffer == value->m_IAIndexBuffer &&
m_IAInputLayout == value->m_IAInputLayout &&
m_IAPrimitiveTopology == value->m_IAPrimitiveTopology &&
m_OMRenderTargets == value->m_OMRenderTargets &&
m_OMDepthStencilState == value->m_OMDepthStencilState &&
m_OMBlendState == value->m_OMBlendState &&
m_RSViewports == value->m_RSViewports &&
m_RSScissorRects == value->m_RSScissorRects &&
m_RSRasterizerState == value->m_RSRasterizerState &&
m_SOBuffers == value->m_SOBuffers &&
m_Predication == value->m_Predication;
}
bool StateBlockMask::Equals( StateBlockMask^ value1, StateBlockMask^ value2 )
{
return value1->m_VS == value2->m_VS &&
Utilities::CheckElementEquality( value1->m_VSSamplers, value2->m_VSSamplers ) &&
Utilities::CheckElementEquality( value1->m_VSShaderResources, value2->m_VSShaderResources ) &&
Utilities::CheckElementEquality( value1->m_VSConstantBuffers,value2->m_VSConstantBuffers ) &&
value1->m_GS == value2->m_GS &&
Utilities::CheckElementEquality( value1->m_GSSamplers, value2->m_GSSamplers ) &&
Utilities::CheckElementEquality( value1->m_GSShaderResources, value2->m_GSShaderResources ) &&
Utilities::CheckElementEquality( value1->m_GSConstantBuffers, value2->m_GSConstantBuffers ) &&
value1->m_PS == value2->m_PS &&
Utilities::CheckElementEquality( value1->m_PSSamplers, value2->m_PSSamplers ) &&
Utilities::CheckElementEquality( value1->m_PSShaderResources, value2->m_PSShaderResources ) &&
Utilities::CheckElementEquality( value1->m_PSConstantBuffers, value2->m_PSConstantBuffers ) &&
Utilities::CheckElementEquality( value1->m_IAVertexBuffers, value2->m_IAVertexBuffers ) &&
value1->m_IAIndexBuffer == value2->m_IAIndexBuffer &&
value1->m_IAInputLayout == value2->m_IAInputLayout &&
value1->m_IAPrimitiveTopology == value2->m_IAPrimitiveTopology &&
value1->m_OMRenderTargets == value2->m_OMRenderTargets &&
value1->m_OMDepthStencilState == value2->m_OMDepthStencilState &&
value1->m_OMBlendState == value2->m_OMBlendState &&
value1->m_RSViewports == value2->m_RSViewports &&
value1->m_RSScissorRects == value2->m_RSScissorRects &&
value1->m_RSRasterizerState == value2->m_RSRasterizerState &&
value1->m_SOBuffers == value2->m_SOBuffers &&
value1->m_Predication == value2->m_Predication;
}
}
}
| 33.343234 | 121 | 0.719836 | HeavenWu |
2303b4b1deecc07f699c64a8796cc36d85333671 | 2,688 | cc | C++ | tests/elle/cryptography/random.cc | infinitio/elle | d9bec976a1217137436db53db39cda99e7024ce4 | [
"Apache-2.0"
] | 521 | 2016-02-14T00:39:01.000Z | 2022-03-01T22:39:25.000Z | tests/elle/cryptography/random.cc | infinitio/elle | d9bec976a1217137436db53db39cda99e7024ce4 | [
"Apache-2.0"
] | 8 | 2017-02-21T11:47:33.000Z | 2018-11-01T09:37:14.000Z | tests/elle/cryptography/random.cc | infinitio/elle | d9bec976a1217137436db53db39cda99e7024ce4 | [
"Apache-2.0"
] | 48 | 2017-02-21T10:18:13.000Z | 2022-03-25T02:35:20.000Z | #include "cryptography.hh"
#include <boost/type_index.hpp>
#include <elle/cryptography/random.hh>
// On some platforms "random" exists:
//
// /usr/include/stdlib.h:321:17: note: previous declaration 'long int random()'
// extern long int random (void) __THROW;
// ^
namespace icrand = elle::cryptography::random;
/*--------.
| Operate |
`--------*/
static
void
test_operate_boolean()
{
icrand::generate<bool>();
}
static
void
test_operate_real()
{
double value1 = icrand::generate<double>();
double value2 = icrand::generate<double>();
// With very high probability.
BOOST_CHECK_NE(value1, value2);
}
template <typename T>
void
test_operate_x(T min, T max)
{
BOOST_TEST_MESSAGE("Testing T = "
<< boost::typeindex::type_id<T>().pretty_name());
{
auto min = std::numeric_limits<T>::min();
auto max = std::numeric_limits<T>::max();
auto val = icrand::generate<T>();
BOOST_TEST_MESSAGE("min = " << +min);
BOOST_TEST_MESSAGE("val = " << +val);
BOOST_TEST_MESSAGE("max = " << +max);
BOOST_CHECK_LE(std::numeric_limits<T>::min(), val);
BOOST_CHECK_LE(val, std::numeric_limits<T>::max());
}
{
T val = icrand::generate<T>(min, max);
BOOST_TEST_MESSAGE("min = " << +min);
BOOST_TEST_MESSAGE("val = " << +val);
BOOST_TEST_MESSAGE("max = " << +max);
BOOST_CHECK_LE(min, val);
BOOST_CHECK_LE(val, max);
}
}
static
void
test_operate_string()
{
std::string value1 = icrand::generate<std::string>(262);
std::string value2 = icrand::generate<std::string>(262);
// With very high probability.
std::cerr << std::hex;
BOOST_CHECK_NE(elle::ConstWeakBuffer(value1), elle::ConstWeakBuffer(value2));
}
static
void
test_operate_buffer()
{
elle::Buffer value1 = icrand::generate<elle::Buffer>(262);
elle::Buffer value2 = icrand::generate<elle::Buffer>(262);
// With very high probability.
std::cerr << std::hex;
BOOST_CHECK_NE(value1, value2);
}
static
void
test_operate()
{
test_operate_boolean();
test_operate_x<char>(15, 48);
test_operate_x<int8_t>(-60, -58);
test_operate_x<int16_t>(-21000, 21000);
test_operate_x<int32_t>(-848, 73435);
test_operate_x<int64_t>(-324923, 32212394);
test_operate_x<uint8_t>(75, 126);
test_operate_x<uint16_t>(1238, 53104);
test_operate_x<uint32_t>(424242, 424242);
test_operate_x<uint64_t>(23409, 1209242094821);
test_operate_real();
test_operate_string();
test_operate_buffer();
}
/*-----.
| Main |
`-----*/
ELLE_TEST_SUITE()
{
boost::unit_test::test_suite* suite = BOOST_TEST_SUITE("random");
suite->add(BOOST_TEST_CASE(test_operate));
boost::unit_test::framework::master_test_suite().add(suite);
}
| 23.787611 | 79 | 0.669271 | infinitio |
2305d65514de6fea6b78ec33f8659e52cd6163c3 | 2,764 | hpp | C++ | source/rs-game/english.hpp | CaptainCrowbar/rs-game | 8066b0fc823edffabdfb61ea1ade5d4acc7c076e | [
"BSL-1.0"
] | null | null | null | source/rs-game/english.hpp | CaptainCrowbar/rs-game | 8066b0fc823edffabdfb61ea1ade5d4acc7c076e | [
"BSL-1.0"
] | null | null | null | source/rs-game/english.hpp | CaptainCrowbar/rs-game | 8066b0fc823edffabdfb61ea1ade5d4acc7c076e | [
"BSL-1.0"
] | null | null | null | #pragma once
#include "rs-format/string.hpp"
#include <iterator>
#include <string>
#include <vector>
namespace RS::Game {
// Case conversion functions
std::string extended_titlecase(const std::string& str, bool initial = true);
std::string sentence_case(const std::string& str);
// List formatting functions
namespace Detail {
std::string comma_list_helper(const std::vector<std::string>& list, const std::string& conj);
}
template <typename Range>
std::string comma_list(const Range& range, const std::string& conj = {}) {
using std::begin;
using std::end;
std::vector<std::string> vec(begin(range), end(range));
return Detail::comma_list_helper(vec, conj);
}
// Number formatting functions
std::string cardinal(size_t n, size_t threshold = std::string::npos);
std::string ordinal(size_t n, size_t threshold = std::string::npos);
std::string format_count(double n, int prec);
std::string number_of(size_t n, const std::string& name, const std::string& plural_name = {}, size_t threshold = 21);
// Pluralization functions
std::string plural(const std::string& noun);
// Text generators
class LoremIpsum {
public:
using result_type = std::string;
LoremIpsum() = default;
explicit LoremIpsum(size_t bytes, bool paras = true): bytes_(bytes), paras_(paras) {}
template <typename RNG> std::string operator()(RNG& rng) const;
private:
size_t bytes_ = 1000;
bool paras_ = true;
static const std::vector<std::string>& classic();
};
template <typename RNG>
std::string LoremIpsum::operator()(RNG& rng) const {
if (bytes_ == 0)
return {};
std::string text;
text.reserve(bytes_ + 20);
for (size_t i = 0; i < classic().size() && text.size() <= bytes_; ++i)
text += classic()[i];
if (paras_)
text.replace(text.size() - 1, 1, "\n\n");
while (text.size() <= bytes_) {
size_t n_para = paras_ ? rng() % 7 + 1 : std::string::npos;
for (size_t i = 0; i < n_para && text.size() <= bytes_; ++i)
text += classic()[rng() % classic().size()];
if (paras_)
text.replace(text.size() - 1, 1, "\n\n");
}
size_t cut = text.find_first_of("\n .,", bytes_);
if (cut != std::string::npos)
text.resize(cut);
while (! Format::ascii_isalpha(text.back()))
text.pop_back();
text += ".";
if (paras_)
text += "\n";
return text;
}
}
| 28.494845 | 121 | 0.549928 | CaptainCrowbar |
230a9628a1c6d2039066ea56cdc5fd4be5eed691 | 4,870 | hpp | C++ | src/timer.hpp | rrahn/align_bench | eed206e113f2aa1a2ef7a2441f19e56ecafa23fc | [
"BSD-3-Clause"
] | 2 | 2017-03-08T05:35:46.000Z | 2019-08-21T16:09:18.000Z | src/timer.hpp | rrahn/align_bench | eed206e113f2aa1a2ef7a2441f19e56ecafa23fc | [
"BSD-3-Clause"
] | null | null | null | src/timer.hpp | rrahn/align_bench | eed206e113f2aa1a2ef7a2441f19e56ecafa23fc | [
"BSD-3-Clause"
] | null | null | null | // ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2018, Knut Reinert, FU Berlin
// 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Rene Rahn <rene.rahn@fu-berlin.de>
// ==========================================================================
#pragma once
#include <iostream>
#include <seqan/basic.h>
using namespace seqan;
// ----------------------------------------------------------------------------
// Class Timer
// ----------------------------------------------------------------------------
template <typename TValue, typename TSpec = void>
struct Timer
{
TValue _begin;
TValue _end;
unsigned _rep;
Timer() : _begin(0), _end(0), _rep(1)
{};
};
// ============================================================================
// Functions
// ============================================================================
// ----------------------------------------------------------------------------
// Function setRep()
// ----------------------------------------------------------------------------
template <typename TValue, typename TSpec>
inline void setRep(Timer<TValue, TSpec> & timer, unsigned const rep)
{
timer._rep = rep;
}
// ----------------------------------------------------------------------------
// Function start()
// ----------------------------------------------------------------------------
template <typename TValue, typename TSpec>
inline void start(Timer<TValue, TSpec> & timer)
{
timer._begin = sysTime();
}
// ----------------------------------------------------------------------------
// Function stop()
// ----------------------------------------------------------------------------
template <typename TValue, typename TSpec>
inline void stop(Timer<TValue, TSpec> & timer)
{
timer._end = sysTime();
}
// ----------------------------------------------------------------------------
// Function getValue()
// ----------------------------------------------------------------------------
template <typename TValue, typename TSpec>
inline TValue getValue(Timer<TValue, TSpec> const & timer)
{
return (timer._end - timer._begin) / timer._rep;
}
template <typename TValue, typename TSpec>
inline TValue getValue(Timer<TValue, TSpec> & timer)
{
return getValue(static_cast<Timer<TValue, TSpec> const &>(timer));
}
// ----------------------------------------------------------------------------
// Function operator<<
// ----------------------------------------------------------------------------
template <typename TStream, typename TValue, typename TSpec>
inline TStream & operator<<(TStream & os, Timer<TValue, TSpec> const & timer)
{
os << getValue(timer) << " sec";
return os;
}
// ----------------------------------------------------------------------------
// Function printRuler()
// ----------------------------------------------------------------------------
template <typename TStream>
inline void printRuler(TStream & os)
{
os << std::endl
<< "================================================================================"
<< std::endl << std::endl;
}
| 37.175573 | 89 | 0.469405 | rrahn |
230b2236bb1e037345e3ebc30c42fb1bc9083de8 | 2,138 | cpp | C++ | src_smartcontract/lang/sc_expression_literal/LiteralExpression.cpp | alinous-core/codable-cash | 32a86a152a146c592bcfd8cc712f4e8cb38ee1a0 | [
"MIT"
] | 6 | 2019-01-06T05:02:39.000Z | 2020-10-01T11:45:32.000Z | src_smartcontract/lang/sc_expression_literal/LiteralExpression.cpp | Codablecash/codablecash | 8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9 | [
"MIT"
] | 209 | 2018-05-18T03:07:02.000Z | 2022-03-26T11:42:41.000Z | src_smartcontract/lang/sc_expression_literal/LiteralExpression.cpp | Codablecash/codablecash | 8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9 | [
"MIT"
] | 3 | 2019-07-06T09:16:36.000Z | 2020-10-15T08:23:28.000Z | /*
* LiteralExpression.cpp
*
* Created on: 2019/02/05
* Author: iizuka
*/
#include "lang/sc_expression_literal/LiteralExpression.h"
#include "base/UnicodeString.h"
#include "engine/sc_analyze/AnalyzedType.h"
#include "instance/instance_ref/VmRootReference.h"
#include "instance/instance_string/VmStringInstance.h"
#include "vm/VirtualMachine.h"
#include "base/StackRelease.h"
namespace alinous {
LiteralExpression::LiteralExpression() : AbstractExpression(CodeElement::EXP_LITERAL){
this->str = nullptr;
this->dquote = true;
this->reference = nullptr;
}
LiteralExpression::~LiteralExpression() {
delete this->str;
this->reference = nullptr;
}
void LiteralExpression::preAnalyze(AnalyzeContext* actx) {
}
void LiteralExpression::analyzeTypeRef(AnalyzeContext* actx) {
}
void LiteralExpression::analyze(AnalyzeContext* actx) {
}
void LiteralExpression::setString(UnicodeString* str, bool dquote) noexcept {
this->str = str;
this->dquote = dquote;
}
UnicodeString* LiteralExpression::getStringBody() const noexcept {
UnicodeString* invalue = this->str->substring(1, this->str->length() - 1);
return invalue;
}
int LiteralExpression::binarySize() const {
checkNotNull(this->str);
int total = sizeof(uint16_t);
total += sizeof(uint8_t);
total += stringSize(this->str);
return total;
}
void LiteralExpression::toBinary(ByteBuffer* out) {
out->putShort(CodeElement::EXP_LITERAL);
out->put(this->dquote ? 1 : 0);
putString(out, this->str);
}
void LiteralExpression::fromBinary(ByteBuffer* in) {
char bl = in->get();
this->dquote = (bl == 1);
this->str = getString(in);
}
AnalyzedType LiteralExpression::getType(AnalyzeContext* actx) {
return AnalyzedType(AnalyzedType::TYPE_STRING);
}
void LiteralExpression::init(VirtualMachine* vm) {
VmRootReference* rootRef = vm->getVmRootReference();
UnicodeString* invalue = this->str->substring(1, this->str->length() - 1); __STP(invalue);
this->reference = rootRef->newStringConstReferenece(rootRef, invalue, vm);
}
AbstractVmInstance* LiteralExpression::interpret(VirtualMachine* vm) {
return this->reference;
}
} /* namespace alinous */
| 22.041237 | 91 | 0.739476 | alinous-core |
230e3bc4ff3d4cf1e5dbad6ff1d433b30691bc2a | 35,838 | hpp | C++ | applications/bed/bedmap/src/Input.hpp | bedops/bedops | abf5c517d921cf1ec188119293b021491e891e66 | [
"bzip2-1.0.6"
] | 217 | 2015-01-02T12:27:14.000Z | 2022-03-19T06:57:14.000Z | applications/bed/bedmap/src/Input.hpp | bedops/bedops | abf5c517d921cf1ec188119293b021491e891e66 | [
"bzip2-1.0.6"
] | 147 | 2015-01-29T01:15:19.000Z | 2022-02-26T01:39:23.000Z | applications/bed/bedmap/src/Input.hpp | bedops/bedops | abf5c517d921cf1ec188119293b021491e891e66 | [
"bzip2-1.0.6"
] | 55 | 2015-01-29T16:08:57.000Z | 2021-12-16T15:16:01.000Z | /*
Author: Scott Kuehn, Shane Neph
Date: Fri Oct 19 08:20:50 PDT 2007
*/
//
// BEDOPS
// Copyright (C) 2011-2021 Shane Neph, Scott Kuehn and Alex Reynolds
//
// 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 2 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, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
#ifndef _BEDMAP_INPUT_HPP
#define _BEDMAP_INPUT_HPP
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <exception>
#include <limits>
#include <sstream>
#include <string>
#include <vector>
#include "data/bed/BedCompare.hpp"
#include "algorithm/visitors/BedVisitors.hpp"
#include "algorithm/visitors/helpers/NamedVisitors.hpp"
#include "utility/Assertion.hpp"
#include "utility/Typify.hpp"
#include "TDefs.hpp"
namespace BedMap {
struct NoInput { /* */ };
namespace details {
struct dummyBase {
typedef int RefType;
typedef int MapType;
};
template <typename T>
std::string name() {
return(Visitors::Helpers::VisitorName<T>::Name());
}
} // details
//=============
// Input<T,U>:
//=============
template <typename ArgError, typename HelpType, typename VersionType>
class Input {
typedef VisitorTypes<details::dummyBase> VT;
public:
// Constructor
Input(int argc, char **argv)
: refFileName_(""), mapFileName_(""), rangeBP_(0), overlapBP_(0),
percOvr_(0.0), isPercMap_(false), isPercRef_(false), isPercEither_(false),
isPercBoth_(false), isRangeBP_(false), isOverlapBP_(false), isExact_(false),
precision_(6), useScientific_(false), useMinMemory_(false), setPrec_(false), numFiles_(0),
minRefFields_(0), minMapFields_(0), errorCheck_(false), sweepAll_(false),
outDelim_("|"), multiDelim_(";"), fastMode_(false), rangeAlias_(false),
chrom_("all"), skipUnmappedRows_(false), unmappedVal_("") {
// Process user's operation options
if ( argc <= 1 )
throw(NoInput()); // prints usage statement and returns EXIT_FAILURE
const std::string posIntegers = "0123456789";
const std::string integers = "-" + posIntegers;
const std::string reals = "." + integers;
int argcntr = 1;
bool hasVisitor = false;
while ( argcntr < argc ) {
std::string next = argv[argcntr++];
if ( next.find("--") == std::string::npos && argc - argcntr < 2 ) // process file inputs
break;
Ext::Assert<ArgError>(next.find("--") == 0, "Option " + next + " does not start with '--'");
next = next.substr(2);
if ( next == "help" ) {
throw(HelpType()); // prints usage statement and returns EXIT_SUCCESS
} else if ( next == "version" ) {
throw(VersionType()); // prints version and returns EXIT_SUCCESS
} else if ( next == "ec" || next == "header" ) {
// bed_check_iterator<> allows silly headers
errorCheck_ = true;
} else if ( next == "faster" ) {
fastMode_ = true;
} else if ( next == "sweep-all" ) { // --> sweep through all of second file
sweepAll_ = true;
} else if ( next == "unmapped-val" ) {
Ext::Assert<ArgError>(unmappedVal_.empty(), "--unmapped-val specified multiple times");
Ext::Assert<ArgError>(argcntr < argc, "No value given for --unmapped-val");
unmappedVal_ = argv[argcntr++];
Ext::Assert<ArgError>(unmappedVal_.find("--") != 0,
"Apparent option: " + std::string(argv[argcntr]) + " where <val> expected for --unmapped-val.");
} else if ( next == "delim" ) {
Ext::Assert<ArgError>(outDelim_ == "|", "--delim specified multiple times");
Ext::Assert<ArgError>(argcntr < argc, "No output delimiter given");
outDelim_ = argv[argcntr++];
Ext::Assert<ArgError>(outDelim_.find("--") != 0,
"Apparent option: " + std::string(argv[argcntr]) + " where output delimiter expected.");
} else if ( next == "chrom" ) {
Ext::Assert<ArgError>(chrom_ == "all", "--chrom specified multiple times");
Ext::Assert<ArgError>(argcntr < argc, "No chromosome name given");
chrom_ = argv[argcntr++];
Ext::Assert<ArgError>(chrom_.find("--") != 0,
"Apparent option: " + std::string(argv[argcntr]) + " where chromosome expected.");
} else if ( next == "multidelim" ) {
Ext::Assert<ArgError>(multiDelim_ == ";", "--multidelim specified multiple times");
Ext::Assert<ArgError>(argcntr < argc, "No multi-value column delimmiter given");
multiDelim_ = argv[argcntr++];
Ext::Assert<ArgError>(multiDelim_.find("--") != 0,
"Apparent option: " + std::string(argv[argcntr]) + " where output delimiter expected.");
} else if ( next == "skip-unmapped" ) {
skipUnmappedRows_ = true;
} else if ( next == "sci" ) {
useScientific_ = true;
} else if ( next == "min-memory" ) {
useMinMemory_ = true;
} else if ( next == "prec" ) {
Ext::Assert<ArgError>(argcntr < argc, "No precision value given");
Ext::Assert<ArgError>(!setPrec_, "--prec specified multiple times.");
std::string sval = argv[argcntr++];
Ext::Assert<ArgError>(sval.find_first_not_of(posIntegers) == std::string::npos,
"Non-positive-integer argument: " + sval + " for --prec");
std::stringstream conv(sval);
conv >> precision_;
Ext::Assert<ArgError>(precision_ >= 0, "--prec value must be >= 0");
setPrec_ = true;
} else if ( next == "bp-ovr" ) {
// first check that !rangeAlias_ before !isOverlapBP_
Ext::Assert<ArgError>(!rangeAlias_, "--range and --bp-ovr detected. Choose one.");
Ext::Assert<ArgError>(!isOverlapBP_, "multiple --bp-ovr's detected");
Ext::Assert<ArgError>(argcntr < argc, "No arg for --bp-ovr");
std::string sval = argv[argcntr++];
Ext::Assert<ArgError>(sval.find_first_not_of(posIntegers) == std::string::npos,
"Non-positive-integer argument: " + sval + " for --bp-ovr");
std::stringstream conv(sval);
conv >> overlapBP_;
Ext::Assert<ArgError>(overlapBP_ > 0, "--bp-ovr value must be > 0");
isOverlapBP_ = true;
} else if ( next == "range" ) {
Ext::Assert<ArgError>(!isRangeBP_ && !rangeAlias_, "multiple --range's detected");
Ext::Assert<ArgError>(argcntr < argc, "No arg for --range");
std::string sval = argv[argcntr++];
Ext::Assert<ArgError>(sval.find_first_not_of(posIntegers) == std::string::npos,
"Non-positive-integer argument: " + sval + " for --range");
std::stringstream conv(sval);
conv >> rangeBP_;
Ext::Assert<ArgError>(rangeBP_ >= 0, "--range value must be >= 0");
isRangeBP_ = true;
if ( 0 == rangeBP_ ) { // alias for --bp-ovr 1
Ext::Assert<ArgError>(!rangeAlias_, "--range 0 specified multiple times.");
Ext::Assert<ArgError>(!isOverlapBP_, "--bp-ovr and --range detected. Choose one.");
isRangeBP_ = false;
isOverlapBP_ = true;
rangeAlias_ = true;
overlapBP_ = 1;
}
} else if ( next == "fraction-ref" ) {
Ext::Assert<ArgError>(!isPercRef_, "multiple --fraction-ref's detected");
Ext::Assert<ArgError>(argcntr < argc, "No arg for --fraction-ref");
std::string sval = argv[argcntr++];
Ext::Assert<ArgError>(sval.find_first_not_of(reals) == std::string::npos,
"Non-numeric argument: " + sval + " for --fraction-ref");
std::stringstream conv(sval);
conv >> percOvr_;
Ext::Assert<ArgError>(percOvr_ > 0 && percOvr_ <= 1, "--fraction-ref value must be: >0-1.0");
isPercRef_ = true;
} else if ( next == "fraction-map" ) {
Ext::Assert<ArgError>(!isPercMap_, "multiple --fraction-map's detected");
Ext::Assert<ArgError>(argcntr < argc, "No arg for --fraction-map");
std::string sval = argv[argcntr++];
Ext::Assert<ArgError>(sval.find_first_not_of(reals) == std::string::npos,
"Non-numeric argument: " + sval + " for --fraction-map");
std::stringstream conv(sval);
conv >> percOvr_;
Ext::Assert<ArgError>(percOvr_ > 0 && percOvr_ <= 1, "--fraction-map value must be: >0-1.0");
isPercMap_ = true;
} else if ( next == "fraction-either" ) {
Ext::Assert<ArgError>(!isPercEither_, "multiple --fraction-either's detected");
Ext::Assert<ArgError>(argcntr < argc, "No arg for --fraction-either");
std::string sval = argv[argcntr++];
Ext::Assert<ArgError>(sval.find_first_not_of(reals) == std::string::npos,
"Non-numeric argument: " + sval + " for --fraction-either");
std::stringstream conv(sval);
conv >> percOvr_;
Ext::Assert<ArgError>(percOvr_ > 0 && percOvr_ <= 1, "--fraction-either value must be: >0-1.0");
isPercEither_ = true;
} else if ( next == "fraction-both" ) {
Ext::Assert<ArgError>(!isPercBoth_, "multiple --fraction-both's detected");
Ext::Assert<ArgError>(argcntr < argc, "No arg for --fraction-both");
std::string sval = argv[argcntr++];
Ext::Assert<ArgError>(sval.find_first_not_of(reals) == std::string::npos,
"Non-numeric argument: " + sval + " for --fraction-both");
std::stringstream conv(sval);
conv >> percOvr_;
Ext::Assert<ArgError>(percOvr_ > 0 && percOvr_ <= 1, "--fraction-both value must be: >0-1.0");
isPercBoth_ = true;
} else if ( next == "exact" ) { // same as --fraction-both 1
Ext::Assert<ArgError>(!isExact_, "multiple --exact's detected - use one");
isExact_ = true;
}
else if ( next == details::name<typename VT::OvrAgg>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::OvrAgg>());
else if ( next == details::name<typename VT::OvrUniq>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::OvrUniq>());
else if ( next == details::name<typename VT::OvrUniqFract>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::OvrUniqFract>());
else if ( next == details::name<typename VT::EchoRefAll>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::EchoRefAll>());
else if ( next == details::name<typename VT::EchoRefLength>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::EchoRefLength>());
else if ( next == details::name<typename VT::EchoRefSpan>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::EchoRefSpan>());
else if ( next == details::name<typename VT::EchoRefRowNumber>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::EchoRefRowNumber>());
else if ( next == details::name<typename VT::EchoMapAll>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::EchoMapAll>());
else if ( next == details::name<typename VT::EchoMapID>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::EchoMapID>());
else if ( next == details::name<typename VT::EchoMapUniqueID>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::EchoMapUniqueID>());
else if ( next == details::name<typename VT::EchoMapLength>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::EchoMapLength>());
else if ( next == details::name<typename VT::EchoMapIntersectLength>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::EchoMapIntersectLength>());
else if ( next == details::name<typename VT::EchoMapRange>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::EchoMapRange>());
else if ( next == details::name<typename VT::EchoMapScore>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::EchoMapScore>());
else if ( next == details::name<typename VT::Count>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::Count>());
else if ( next == details::name<typename VT::Indicator>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::Indicator>());
else if ( next == details::name<typename VT::Max>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::Max>());
else if ( next == details::name<typename VT::MaxElementRand>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::MaxElementRand>());
else if ( next == details::name<typename VT::MaxElementStable>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::MaxElementStable>());
else if ( next == details::name<typename VT::Min>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::Min>());
else if ( next == details::name<typename VT::MinElementRand>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::MinElementRand>());
else if ( next == details::name<typename VT::MinElementStable>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::MinElementStable>());
else if ( next == details::name<typename VT::Average>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::Average>());
else if ( next == details::name<typename VT::Variance>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::Variance>());
else if ( next == details::name<typename VT::StdDev>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::StdDev>());
else if ( next == details::name<typename VT::CoeffVariation>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::CoeffVariation>());
else if ( next == details::name<typename VT::Sum>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::Sum>());
else if ( next == details::name<typename VT::WMean>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::WMean>());
else if ( next == details::name<typename VT::Median>() )
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::Median>());
else if ( next == details::name<typename VT::MedianAbsoluteDeviation>() ) {
std::string sval = argv[argcntr];
if ( sval.find_first_not_of(reals) == std::string::npos ) { // assume argument for this option
++argcntr;
std::stringstream conv(sval);
double val = -1;
conv >> val;
Ext::Assert<ArgError>(val > 0, "--" + details::name<typename VT::MedianAbsoluteDeviation>() + " Expect 0 < val");
std::vector<std::string> tmpVec;
tmpVec.push_back(sval);
hasVisitor = addVisitor(Ext::Type2Type<typename VT::MedianAbsoluteDeviation>(), tmpVec);
}
else // use default multiplier for MAD
hasVisitor = addNoArgVisitor(Ext::Type2Type<typename VT::MedianAbsoluteDeviation>());
}
else if ( next == details::name<typename VT::KthAverage>() ) {
Ext::Assert<ArgError>(argcntr < argc, "No arg for --" + details::name<typename VT::KthAverage>());
std::string sval = argv[argcntr++];
Ext::Assert<ArgError>(sval.find_first_not_of(reals) == std::string::npos,
"Non-numeric argument: " + sval + " for --" + details::name<typename VT::KthAverage>());
std::stringstream conv(sval);
double val = -1;
conv >> val;
Ext::Assert<ArgError>(val >= 0 && val <= 1, "--" + details::name<typename VT::KthAverage>() + " Expect 0 <= val <= 1");
std::vector<std::string> tmpVec;
tmpVec.push_back(sval);
hasVisitor = addVisitor(Ext::Type2Type<typename VT::KthAverage>(), tmpVec);
}
else if ( next == details::name<typename VT::TMean>() ) {
Ext::Assert<ArgError>(argcntr < argc, "No <low> arg given for --" + details::name<typename VT::TMean>());
std::string svalLow = argv[argcntr++];
Ext::Assert<ArgError>(svalLow.find_first_not_of(reals) == std::string::npos,
"Non-numeric argument: " + svalLow + " for --" + details::name<typename VT::TMean>());
Ext::Assert<ArgError>(argcntr < argc, "No <hi> arg given for --" + details::name<typename VT::TMean>());
std::string svalHigh = argv[argcntr++];
Ext::Assert<ArgError>(svalHigh.find_first_not_of(reals) == std::string::npos,
"Non-numeric argument: " + svalHigh + " for --" + details::name<typename VT::TMean>());
std::stringstream convLow(svalLow), convHigh(svalHigh);
double valLow = 100, valHigh = 100;
convLow >> valLow; convHigh >> valHigh;
Ext::Assert<ArgError>(valLow >= 0 && valLow <= 1,
"--" + details::name<typename VT::TMean>() + " Expect 0 <= low < hi <= 1");
Ext::Assert<ArgError>(valHigh >= 0 && valHigh <= 1,
"--" + details::name<typename VT::TMean>() + " Expect 0 <= low < hi <= 1");
Ext::Assert<ArgError>(valLow + valHigh <= 1,
"--" + details::name<typename VT::TMean>() + " Expect (low + hi) <= 1.");
std::vector<std::string> tmpVec;
tmpVec.push_back(svalLow); tmpVec.push_back(svalHigh);
hasVisitor = addVisitor(Ext::Type2Type<typename VT::TMean>(), tmpVec);
}
else
throw(ArgError("Unknown option: --" + next));
} // while
if ( !(isPercMap_ || isPercRef_ || isPercEither_ || isPercBoth_ || isRangeBP_ || isOverlapBP_ || isExact_) ) {
// use defaults
isOverlapBP_ = true;
overlapBP_ = 1;
}
int count = isPercMap_;
count += isPercRef_;
count += isPercEither_;
count += isPercBoth_;
count += isRangeBP_;
count += isOverlapBP_;
count += isExact_;
Ext::Assert<ArgError>(1 == count, "More than one overlap specification used.");
Ext::Assert<ArgError>(hasVisitor, "No processing option specified (ie; --max).");
Ext::Assert<ArgError>(0 <= argc - argcntr, "No files");
Ext::Assert<ArgError>(3 == minRefFields_, "Program error: Input.hpp::minRefFields_");
Ext::Assert<ArgError>(3 <= minMapFields_ && 5 >= minMapFields_, "Program error: Input.hpp::minMapFields_");
Ext::Assert<ArgError>(!fastMode_ || isOverlapBP_ || isRangeBP_ || isPercBoth_ || isExact_, "--faster compatible with --range, --bp-ovr, --fraction-both, and --exact only");
// Process files inputs
Ext::Assert<ArgError>(2 >= argc - argcntr, "Need [one or] two input files");
Ext::Assert<ArgError>(0 <= argc - argcntr, "Need [one or] two input files");
numFiles_ = argc - argcntr + 1;
Ext::Assert<ArgError>(1 <= numFiles_ && numFiles_ <= 2, "Need [one or] two input files");
if ( 2 == numFiles_ ) {
refFileName_ = argv[argc-2];
mapFileName_ = argv[argc-1];
} else { // single-file mode
refFileName_ = argv[argc-1];
mapFileName_ = "";
minRefFields_ = minMapFields_;
minMapFields_ = 0;
}
Ext::Assert<ArgError>(refFileName_ != "-" || mapFileName_ != "-",
"Cannot have stdin set for two files");
}
public:
std::string refFileName_;
std::string mapFileName_;
std::vector<std::string> visitorNames_;
std::vector< std::vector<std::string> > visitorArgs_;
long rangeBP_;
long overlapBP_;
double percOvr_;
bool isPercMap_;
bool isPercRef_;
bool isPercEither_;
bool isPercBoth_;
bool isRangeBP_;
bool isOverlapBP_;
bool isExact_;
int precision_;
bool useScientific_;
bool useMinMemory_;
bool setPrec_;
unsigned int numFiles_;
unsigned int minRefFields_;
unsigned int minMapFields_;
bool errorCheck_;
bool sweepAll_;
std::string outDelim_;
std::string multiDelim_;
bool fastMode_;
bool rangeAlias_;
std::string chrom_;
bool skipUnmappedRows_;
std::string unmappedVal_;
private:
struct MapFields {
template <typename T> static unsigned int num(Ext::Type2Type<T>) { return 5; }
static unsigned int num(Ext::Type2Type<typename VT::Count>) { return 3; }
static unsigned int num(Ext::Type2Type<typename VT::EchoMapAll>) { return 3; }
static unsigned int num(Ext::Type2Type<typename VT::EchoMapID>) { return 4; }
static unsigned int num(Ext::Type2Type<typename VT::EchoMapIntersectLength>) { return 3; }
static unsigned int num(Ext::Type2Type<typename VT::EchoMapLength>) { return 3; }
static unsigned int num(Ext::Type2Type<typename VT::EchoMapRange>) { return 3; }
static unsigned int num(Ext::Type2Type<typename VT::EchoMapUniqueID>) { return 4; }
static unsigned int num(Ext::Type2Type<typename VT::EchoRefAll>) { return 3; }
static unsigned int num(Ext::Type2Type<typename VT::EchoRefLength>) { return 3; }
static unsigned int num(Ext::Type2Type<typename VT::EchoRefSpan>) { return 3; }
static unsigned int num(Ext::Type2Type<typename VT::EchoRefRowNumber>) { return 3; }
static unsigned int num(Ext::Type2Type<typename VT::Indicator>) { return 3; }
static unsigned int num(Ext::Type2Type<typename VT::OvrAgg>) { return 3; }
static unsigned int num(Ext::Type2Type<typename VT::OvrUniq>) { return 3; }
static unsigned int num(Ext::Type2Type<typename VT::OvrUniqFract>) { return 3; }
};
struct RefFields {
template <typename T> static unsigned int num(Ext::Type2Type<T>) { return 3; }
};
template <typename T>
bool addNoArgVisitor(Ext::Type2Type<T> t) {
visitorNames_.push_back(details::name<T>());
visitorArgs_.push_back(std::vector<std::string>());
minMapFields_ = std::max(minMapFields_, static_cast<unsigned int>(MapFields::num(t)));
minRefFields_ = std::max(minRefFields_, static_cast<unsigned int>(RefFields::num(t)));
return(true);
}
template <typename T>
bool addVisitor(Ext::Type2Type<T> t, const std::vector<std::string>& args) {
visitorNames_.push_back(details::name<T>());
visitorArgs_.push_back(args);
minMapFields_ = std::max(minMapFields_, static_cast<unsigned int>(MapFields::num(t)));
minRefFields_ = std::max(minRefFields_, static_cast<unsigned int>(RefFields::num(t)));
return(true);
}
};
//---------
// Usage()
std::string Usage() {
typedef BedMap::VisitorTypes<details::dummyBase> VT;
std::stringstream usage;
usage << " \n";
usage << " USAGE: bedmap [process-flags] [overlap-option] <operation(s)...> <ref-file> [map-file] \n";
usage << " Any input file must be sorted per the sort-bed utility. \n";
usage << " The program accepts BED and Starch file formats. \n";
usage << " You may use '-' for a BED file to indicate the input comes from stdin. \n";
usage << " \n";
usage << " Traverse <ref-file>, while applying <operation(s)> on qualified, overlapping elements from \n";
usage << " <map-file>. Output is one line for each line in <ref-file>, sent to standard output. There \n";
usage << " is no limit on the number of operations you can specify to compute in one bedmap call. \n";
usage << " If <map-file> is omitted, the given file is treated as both the <ref-file> and <map-file>. \n";
usage << " This usage is more efficient than specifying the same file twice. \n";
usage << " Arguments may be given in any order before the input file(s). \n";
usage << " \n";
usage << " Process Flags: \n";
usage << " -------- \n";
usage << " --chrom <chromosome> Jump to and process data for given <chromosome> only. \n";
usage << " --delim <delim> Change output delimiter from '|' to <delim> between columns (e.g. \'\\t\').\n";
usage << " --ec Error check all input files (slower). \n";
usage << " --faster (advanced) Strong input assumptions are made. Compatible with: \n";
usage << " --bp-ovr, --range, --fraction-both, and --exact overlap options only. \n";
usage << " --header Accept headers (VCF, GFF, SAM, BED, WIG) in any input file. \n";
usage << " --help Print this message and exit successfully. \n";
usage << " --min-memory Minimize memory usage (slower). \n";
usage << " --multidelim <delim> Change delimiter of multi-value output columns from ';' to <delim>. \n";
usage << " --prec <int> Change the post-decimal precision of scores to <int>. 0 <= <int>. \n";
usage << " --sci Use scientific notation for score outputs. \n";
usage << " --skip-unmapped Print no output for a row with no mapped elements. \n";
usage << " --sweep-all Ensure <map-file> is read completely (helps to prevent broken pipes). \n";
usage << " --unmapped-val <val> Print <val> on unmapped --echo-map* and --min/max-element* operations. \n";
usage << " The default is to print nothing. \n";
usage << " --version Print program information. \n";
usage << " \n";
usage << " \n";
usage << " Overlap Options (At most, one may be selected. By default, --bp-ovr 1 is used): \n";
usage << " -------- \n";
usage << " --bp-ovr <int> Require <int> bp overlap between elements of input files. \n";
usage << " --exact First 3 fields from <map-file> must be identical to <ref-file>'s. \n";
usage << " --fraction-both <val> Both --fraction-ref <val> and --fraction-map <val> must be true to \n";
usage << " qualify as overlapping. Expect 0 < val <= 1. \n";
usage << " --fraction-either <val> Either --fraction-ref <val> or --fraction-map <val> must be true to \n";
usage << " qualify as overlapping. Expect 0 < val <= 1. \n";
usage << " --fraction-map <val> The fraction of the element's size from <map-file> that must overlap \n";
usage << " the element in <ref-file>. Expect 0 < val <= 1. \n";
usage << " --fraction-ref <val> The fraction of the element's size from <ref-file> that must overlap \n";
usage << " an element in <map-file>. Expect 0 < val <= 1. \n";
usage << " --range <int> Grab <map-file> elements within <int> bp of <ref-file>'s element, \n";
usage << " where 0 <= int. --range 0 is an alias for --bp-ovr 1. \n";
usage << " \n";
usage << " \n";
usage << " Operations: (Any number of operations may be used any number of times.) \n";
usage << " ---------- \n";
usage << " SCORE: \n";
usage << " <ref-file> must have at least 3 columns and <map-file> 5 columns. \n";
usage << " \n";
usage << " --" + details::name<VT::CoeffVariation>() + " The result of --" + details::name<VT::StdDev>() + " divided by the result of --" + details::name<VT::Average>() + ".\n";
usage << " --" + details::name<VT::KthAverage>() + " <val> Generalized median. Report the value, x, such that the fraction <val>\n";
usage << " of overlapping elements' scores from <map-file> is less than x,\n";
usage << " and the fraction 1-<val> of scores is greater than x. 0 < val <= 1.\n";
usage << " --" + details::name<VT::MedianAbsoluteDeviation>() + " <mult=1> The median absolute deviation of overlapping elements in <map-file>.\n";
usage << " Multiply mad score by <mult>. 0 < mult, and mult is 1 by default.\n";
usage << " --" + details::name<VT::Max>() + " The highest score from overlapping elements in <map-file>.\n";
usage << " --" + details::name<VT::MaxElementStable>() + " A (non-random) highest-scoring and overlapping element in <map-file>.\n";
usage << " --" + details::name<VT::MaxElementRand>() + " A random highest-scoring and overlapping element in <map-file>.\n";
usage << " --" + details::name<VT::Average>() + " The average score from overlapping elements in <map-file>.\n";
usage << " --" + details::name<VT::Median>() + " The median score from overlapping elements in <map-file>.\n";
usage << " --" + details::name<VT::Min>() + " The lowest score from overlapping elements in <map-file>.\n";
usage << " --" + details::name<VT::MinElementStable>() + " A (non-random) lowest-scoring and overlapping element in <map-file>.\n";
usage << " --" + details::name<VT::MinElementRand>() + " A random lowest-scoring and overlapping element in <map-file>.\n";
usage << " --" + details::name<VT::StdDev>() + " The square root of the result of --" + details::name<VT::Variance>() + ".\n";
usage << " --" + details::name<VT::Sum>() + " Accumulated scores from overlapping elements in <map-file>.\n";
usage << " --" + details::name<VT::TMean>() + " <low> <hi> The mean score from overlapping elements in <map-file>, after\n";
usage << " ignoring the bottom <low> and top <hi> fractions of those scores.\n";
usage << " 0 <= low <= 1. 0 <= hi <= 1. low+hi <= 1.\n";
usage << " --" + details::name<VT::Variance>() + " The variance of scores from overlapping elements in <map-file>.\n";
usage << " --" + details::name<VT::WMean>() + " Weighted mean, scaled in proportion to the coverage of the <ref-file>\n";
usage << " element by each overlapping <map-file> element.\n";
usage << " \n";
usage << " ----------\n";
usage << " NON-SCORE:\n";
usage << " <ref-file> must have at least 3 columns.\n";
usage << " For --" + details::name<VT::EchoMapID>() + "/" + details::name<VT::EchoMapUniqueID>() + ", <map-file> must have at least 4 columns.\n";
usage << " For --" + details::name<VT::EchoMapScore>() + ", <map-file> must have at least 5 columns.\n";
usage << " For all others, <map-file> requires at least 3 columns.\n\n";
usage << " --" + details::name<VT::OvrAgg>() + " The total number of overlapping bases from <map-file>.\n";
usage << " --" + details::name<VT::OvrUniq>() + " The number of distinct bases from <ref-file>'s element covered by\n";
usage << " overlapping elements in <map-file>.\n";
usage << " --" + details::name<VT::OvrUniqFract>() + " The fraction of distinct bases from <ref-file>'s element covered by\n";
usage << " overlapping elements in <map-file>.\n";
usage << " --" + details::name<VT::Count>() + " The number of overlapping elements in <map-file>.\n";
usage << " --" + details::name<VT::EchoRefAll>() + " Print each line from <ref-file>.\n";
usage << " --" + details::name<VT::EchoMapAll>() + " List all overlapping elements from <map-file>.\n";
usage << " --" + details::name<VT::EchoMapID>() + " List IDs from all overlapping <map-file> elements.\n";
usage << " --" + details::name<VT::EchoMapUniqueID>() + " List unique IDs from overlapping <map-file> elements.\n";
usage << " --" + details::name<VT::EchoMapRange>() + " Print genomic range of overlapping elements from <map-file>.\n";
usage << " --" + details::name<VT::EchoMapScore>() + " List scores from overlapping <map-file> elements.\n";
usage << " --" + details::name<VT::EchoMapLength>() + " List the full length of every overlapping element.\n";
usage << " --" + details::name<VT::EchoMapIntersectLength>() + " List lengths of overlaps.\n";
usage << " --" + details::name<VT::EchoRefSpan>() + " Print the first 3 fields of <ref-file> using chrom:start-end format.\n";
usage << " --" + details::name<VT::EchoRefRowNumber>() + " Print 'id-' followed by the line number of <ref-file>.\n";
usage << " --" + details::name<VT::EchoRefLength>() + " Print the length of each line from <ref-file>.\n";
usage << " --" + details::name<VT::Indicator>() + " Print 1 if there exists an overlapping element in <map-file>, 0 otherwise.\n";
usage << "\n";
return(usage.str());
}
} // namespace BedMap
#endif // _BEDMAP_INPUT_HPP
| 62.763573 | 201 | 0.552179 | bedops |
2311fb70363bcb5c9fae97119475008f307830cb | 3,337 | cpp | C++ | OSX_Modern_OpenGL/Examples/Example2/example2.cpp | txaidw/Learning_OSX_OpenGL_and_iOS_OpenGL_ES | d845b1216a85965e431225fe3d71c90883a412d7 | [
"WTFPL"
] | 2 | 2017-08-14T09:12:49.000Z | 2020-12-02T03:32:41.000Z | OSX_Modern_OpenGL/Examples/Example2/example2.cpp | txaidw/LearningOpenGLwithXcodeOnMac | d845b1216a85965e431225fe3d71c90883a412d7 | [
"WTFPL"
] | null | null | null | OSX_Modern_OpenGL/Examples/Example2/example2.cpp | txaidw/LearningOpenGLwithXcodeOnMac | d845b1216a85965e431225fe3d71c90883a412d7 | [
"WTFPL"
] | 1 | 2021-08-17T02:17:18.000Z | 2021-08-17T02:17:18.000Z | // Based on http://www.opengl-tutorial.org/beginners-tutorials/tutorial-2-the-first-triangle/
#define GLEW_STATIC
#include <stdio.h>
#include <stdlib.h>
#include <cmath>
// Open-source library 1: Access to the OpenGL 3.2 API functions
/* Use glew.h instead of gl.h to get all the GL prototypes declared */
// open-source library 1: Access to the OpenGL 3.2 API functions
/* Use glew.h instead of gl.h to get all the GL prototypes declared */
#include <OpenGl/OpenGL.h>
// open-source library 2: Windows + input/output cross-platform access
#include <GLUT/glut.h>
// open-source library 3: Math library
// Include GLM
#include "glm.hpp"
using namespace glm;
// Handle to the shader program
GLuint programID;
GLuint VertexArrayID;
GLuint vertexbuffer;
int init_resources() {
// Dark blue background
glClearColor(0.0f, 0.0f, 0.4f, 0.0f);
// Allocate and assign a VAO to our handle
glGenVertexArrays(1, &VertexArrayID);
// Bind our VAO as the current used object
glBindVertexArray(VertexArrayID);
// Create and compile our GLSL program from the shaders
programID = LoadShaders( "SimpleVertexShader.vertexshader", "SimpleFragmentShader.fragmentshader" );
// Triangle created using 3 points in GLfloat
static const GLfloat g_vertex_buffer_data[] = {
// x y z
-1.0f, -1.0f, 0.0f, // v1
1.0f, -1.0f, 0.0f, // v2
0.0f, 1.0f, 0.0f, // v3
};
// Allocate and assign a VBO to our handle
glGenBuffers(1, &vertexbuffer);
// Bind our VBO as being the active buffer and storing vertex attributes (coordinates)
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
// Copy the data of the triangle crated to the VBO buffer
glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);
return 1;
}
//metodo para desenhar
void onDisplay() {
// Clear the screen
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Use our shader
glUseProgram(programID);
// Enable attibute index 0
glEnableVertexAttribArray(0);
// Bind our VBO as being the active buffer and storing vertex attributes (coordinates)
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
// Specify how the data buffer below is organized
glVertexAttribPointer(
0, // attribute 0. No particular reason for 0, but must match the layout in the shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
NULL // array buffer offset
);
// Draw the triangle !
glDrawArrays(GL_TRIANGLES, 0, 3); // 3 indices starting at 0 -> 1 triangle
glutSwapBuffers();
glutPostRedisplay();
}
//libera recursos
void free_resources() {
glDeleteBuffers(1, &vertexbuffer);
glDeleteVertexArrays(1, &VertexArrayID);
glDeleteProgram(programID);
}
int main(int argc, char* argv[]) {
//inicia janela
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH|GLUT_MULTISAMPLE);
glutInitWindowSize(800, 450);
glutCreateWindow("Example 2");
if (init_resources() != 0) {
glutDisplayFunc(onDisplay);
glutMainLoop();
}
free_resources();
return 0;
}
| 29.27193 | 113 | 0.662871 | txaidw |
231430f0844b37b36b10573c4fdb6b74da47273b | 624 | cpp | C++ | EU4toV3Tests/EU4WorldTests/CountryManagerTests/EU4ActiveIdeasTests.cpp | ParadoxGameConverters/EU4toVic3 | e055d5fbaadc21e37f4bce5b3a4f4c1e415598fa | [
"MIT"
] | 5 | 2021-05-22T20:10:05.000Z | 2021-05-28T08:07:05.000Z | EU4toV3Tests/EU4WorldTests/CountryManagerTests/EU4ActiveIdeasTests.cpp | klorpa/EU4toVic3 | 36b53a76402c715f618dd88f0caf962072bda8cf | [
"MIT"
] | 13 | 2021-05-25T08:26:11.000Z | 2022-01-13T18:24:12.000Z | EU4toV3Tests/EU4WorldTests/CountryManagerTests/EU4ActiveIdeasTests.cpp | Zemurin/EU4toVic3 | 532b9a11e0e452be54d89e12cff5fb1f84ac3d11 | [
"MIT"
] | 5 | 2021-05-22T13:45:43.000Z | 2021-12-25T00:00:04.000Z | #include "CountryManager/EU4ActiveIdeas.h"
#include "gtest/gtest.h"
#include <gmock/gmock-matchers.h>
using testing::UnorderedElementsAre;
TEST(EU4World_EU4ActiveIdeasTests, primitivesDefaultToBlank)
{
std::stringstream input;
const EU4::EU4ActiveIdeas ideas(input);
EXPECT_TRUE(ideas.getActiveIdeas().empty());
}
TEST(EU4World_EU4ActiveIdeasTests, ideasDevelopedTo7OrMoreAreLoaded)
{
std::stringstream input;
input << "idea1 = 4\n";
input << "idea2 = 7\n";
input << "idea3 = 14\n"; // mods?
const EU4::EU4ActiveIdeas ideas(input);
EXPECT_THAT(ideas.getActiveIdeas(), UnorderedElementsAre("idea2", "idea3"));
}
| 26 | 77 | 0.75641 | ParadoxGameConverters |
2314e75b9ccc2be302ac5e57dd0beb92b03c6a2c | 3,763 | cpp | C++ | NYP_Framework_Week08_SOLUTION/Base/Source/SkyBox/SkyBoxEntity.cpp | KianMarvi/Assignment | 8133acec4dd65bc49316aec8deb3961035bdef27 | [
"MIT"
] | null | null | null | NYP_Framework_Week08_SOLUTION/Base/Source/SkyBox/SkyBoxEntity.cpp | KianMarvi/Assignment | 8133acec4dd65bc49316aec8deb3961035bdef27 | [
"MIT"
] | 8 | 2019-12-29T17:17:00.000Z | 2020-02-07T08:08:01.000Z | NYP_Framework_Week08_SOLUTION/Base/Source/SkyBox/SkyBoxEntity.cpp | KianMarvi/Assignment | 8133acec4dd65bc49316aec8deb3961035bdef27 | [
"MIT"
] | null | null | null | #include "SkyBoxEntity.h"
#include "MeshBuilder.h"
#include "../EntityManager.h"
#include "GraphicsManager.h"
#include "RenderHelper.h"
SkyBoxEntity::SkyBoxEntity(void)
: size(1000.0f, 1000.0f, 1000.0f)
, m_bBoundaryDefined(false)
{
}
SkyBoxEntity::~SkyBoxEntity()
{
}
void SkyBoxEntity::Update(double _dt)
{
// Does nothing here, can inherit & override or create your own version of this class :D
}
void SkyBoxEntity::Render()
{
MS& modelStack = GraphicsManager::GetInstance()->GetModelStack();
modelStack.PushMatrix();
// Front
modelStack.PushMatrix();
modelStack.Translate(0, 0, -size.z / 2);
modelStack.Scale(size.x, size.y, size.z);
RenderHelper::RenderMesh(modelMesh[FRONT]);
modelStack.PopMatrix();
// Back
modelStack.PushMatrix();
modelStack.Rotate(180, 0, 1, 0);
modelStack.Translate(0, 0, -size.z / 2);
modelStack.Scale(size.x, size.y, size.z);
RenderHelper::RenderMesh(modelMesh[BACK]);
modelStack.PopMatrix();
// Left
modelStack.PushMatrix();
modelStack.Rotate(-90, 0, 1, 0);
modelStack.Translate(0, 0, -size.z / 2);
modelStack.Scale(size.x, size.y, size.z);
RenderHelper::RenderMesh(modelMesh[LEFT]);
modelStack.PopMatrix();
// Right
modelStack.PushMatrix();
modelStack.Rotate(90, 0, 1, 0);
modelStack.Translate(0, 0, -size.z / 2);
modelStack.Scale(size.x, size.y, size.z);
RenderHelper::RenderMesh(modelMesh[RIGHT]);
modelStack.PopMatrix();
// Top
modelStack.PushMatrix();
modelStack.Rotate(90, 1, 0, 0);
modelStack.Translate(0, 0, -size.z / 2);
modelStack.Rotate(-90, 0, 0, 1);
modelStack.Scale(size.x, size.y, size.z);
RenderHelper::RenderMesh(modelMesh[TOP]);
modelStack.PopMatrix();
// Bottom
modelStack.PushMatrix();
modelStack.Rotate(-90, 1, 0, 0);
modelStack.Translate(0, 0, -size.z / 2);
modelStack.Rotate(90, 0, 0, 1);
modelStack.Scale(size.x, size.y, size.z);
RenderHelper::RenderMesh(modelMesh[BOTTOM]);
modelStack.PopMatrix();
modelStack.PopMatrix();
}
// Set a mesh to this class
void SkyBoxEntity::SetMesh(const int _side, Mesh* _modelMesh)
{
modelMesh[_side] = _modelMesh;
}
Vector3 SkyBoxEntity::GetBoundary(void)
{
if (!m_bBoundaryDefined)
{
boundary = Vector3( position.x - (size.x*scale.x) / 2.0f,
position.y - (size.y*scale.y) / 2.0f,
position.z - (size.z*scale.z) / 2.0f);
m_bBoundaryDefined = true;
}
return boundary;
};
SkyBoxEntity* Create::SkyBox( const std::string& _meshName0,
const std::string& _meshName1,
const std::string& _meshName2,
const std::string& _meshName3,
const std::string& _meshName4,
const std::string& _meshName5)
{
Mesh* modelMesh0 = MeshBuilder::GetInstance()->GetMesh(_meshName0);
if (modelMesh0 == nullptr)
return nullptr;
Mesh* modelMesh1 = MeshBuilder::GetInstance()->GetMesh(_meshName1);
if (modelMesh1 == nullptr)
return nullptr;
Mesh* modelMesh2 = MeshBuilder::GetInstance()->GetMesh(_meshName2);
if (modelMesh2 == nullptr)
return nullptr;
Mesh* modelMesh3 = MeshBuilder::GetInstance()->GetMesh(_meshName3);
if (modelMesh3 == nullptr)
return nullptr;
Mesh* modelMesh4 = MeshBuilder::GetInstance()->GetMesh(_meshName4);
if (modelMesh4 == nullptr)
return nullptr;
Mesh* modelMesh5 = MeshBuilder::GetInstance()->GetMesh(_meshName5);
if (modelMesh5 == nullptr)
return nullptr;
SkyBoxEntity* result = new SkyBoxEntity();
result->SetMesh(SkyBoxEntity::FRONT, modelMesh0);
result->SetMesh(SkyBoxEntity::BACK, modelMesh1);
result->SetMesh(SkyBoxEntity::LEFT, modelMesh2);
result->SetMesh(SkyBoxEntity::RIGHT, modelMesh3);
result->SetMesh(SkyBoxEntity::TOP, modelMesh4);
result->SetMesh(SkyBoxEntity::BOTTOM, modelMesh5);
EntityManager::GetInstance()->AddEntity(result);
return result;
}
| 27.071942 | 89 | 0.701568 | KianMarvi |
231a04d00e8095c9da18b3b9165cd376cf0ded30 | 2,972 | hpp | C++ | include/vfs/file_view_interface.hpp | nathalie-raffray/vfs | 3aebcc84c141cac79b2eb5a84dc74be396928e64 | [
"MIT"
] | 3 | 2017-08-03T14:28:03.000Z | 2019-02-22T03:14:17.000Z | include/vfs/file_view_interface.hpp | nathalie-raffray/vfs | 3aebcc84c141cac79b2eb5a84dc74be396928e64 | [
"MIT"
] | null | null | null | include/vfs/file_view_interface.hpp | nathalie-raffray/vfs | 3aebcc84c141cac79b2eb5a84dc74be396928e64 | [
"MIT"
] | 1 | 2021-05-31T15:28:46.000Z | 2021-05-31T15:28:46.000Z | #pragma once
#include "vfs/path.hpp"
#include "vfs/file_flags.hpp"
namespace vfs {
//----------------------------------------------------------------------------------------------
template<typename _Impl>
class file_view_interface
: _Impl
{
public:
//------------------------------------------------------------------------------------------
using base_type = _Impl;
using self_type = file_view_interface<_Impl>;
public:
//------------------------------------------------------------------------------------------
file_view_interface(file_sptr spFile, int64_t viewSize)
: base_type(std::move(spFile), viewSize)
{}
//------------------------------------------------------------------------------------------
file_view_interface(file_sptr spFile)
: file_view_interface(std::move(spFile), 0ull)
{}
//------------------------------------------------------------------------------------------
file_view_interface(const path &name, int64_t size, bool openExisting)
: base_type(name, size, openExisting)
{}
//------------------------------------------------------------------------------------------
bool isValid() const
{
return base_type::isValid();
}
//------------------------------------------------------------------------------------------
file_sptr getFile() const
{
return base_type::getFile();
}
//------------------------------------------------------------------------------------------
int64_t totalSize() const
{
return base_type::totalSize();
}
//------------------------------------------------------------------------------------------
int64_t read(uint8_t *dst, int64_t sizeInBytes)
{
return base_type::read(dst, sizeInBytes);
}
//------------------------------------------------------------------------------------------
int64_t write(const uint8_t *src, int64_t sizeInBytes)
{
return base_type::write(src, sizeInBytes);
}
//------------------------------------------------------------------------------------------
bool skip(int64_t offsetInBytes)
{
return base_type::skip(offsetInBytes);
}
//------------------------------------------------------------------------------------------
template<typename T = uint8_t>
auto cursor()
{
return base_type::template cursor<T>();
}
//------------------------------------------------------------------------------------------
uint8_t* cursor()
{
return cursor<>();
}
};
//----------------------------------------------------------------------------------------------
} /*vfs*/
| 36.691358 | 100 | 0.284993 | nathalie-raffray |
231a1e95d5e51fd325e42f24cca69baca9228681 | 3,364 | hpp | C++ | android-31/android/telephony/euicc/EuiccManager.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/telephony/euicc/EuiccManager.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-31/android/telephony/euicc/EuiccManager.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #pragma once
#include "../../../JObject.hpp"
namespace android::app
{
class Activity;
}
namespace android::app
{
class PendingIntent;
}
namespace android::content
{
class Intent;
}
namespace android::telephony::euicc
{
class DownloadableSubscription;
}
namespace android::telephony::euicc
{
class EuiccInfo;
}
class JString;
namespace android::telephony::euicc
{
class EuiccManager : public JObject
{
public:
// Fields
static JString ACTION_MANAGE_EMBEDDED_SUBSCRIPTIONS();
static JString ACTION_NOTIFY_CARRIER_SETUP_INCOMPLETE();
static JString ACTION_START_EUICC_ACTIVATION();
static jint EMBEDDED_SUBSCRIPTION_RESULT_ERROR();
static jint EMBEDDED_SUBSCRIPTION_RESULT_OK();
static jint EMBEDDED_SUBSCRIPTION_RESULT_RESOLVABLE_ERROR();
static jint ERROR_ADDRESS_MISSING();
static jint ERROR_CARRIER_LOCKED();
static jint ERROR_CERTIFICATE_ERROR();
static jint ERROR_CONNECTION_ERROR();
static jint ERROR_DISALLOWED_BY_PPR();
static jint ERROR_EUICC_INSUFFICIENT_MEMORY();
static jint ERROR_EUICC_MISSING();
static jint ERROR_INCOMPATIBLE_CARRIER();
static jint ERROR_INSTALL_PROFILE();
static jint ERROR_INVALID_ACTIVATION_CODE();
static jint ERROR_INVALID_CONFIRMATION_CODE();
static jint ERROR_INVALID_RESPONSE();
static jint ERROR_NO_PROFILES_AVAILABLE();
static jint ERROR_OPERATION_BUSY();
static jint ERROR_SIM_MISSING();
static jint ERROR_TIME_OUT();
static jint ERROR_UNSUPPORTED_VERSION();
static JString EXTRA_EMBEDDED_SUBSCRIPTION_DETAILED_CODE();
static JString EXTRA_EMBEDDED_SUBSCRIPTION_DOWNLOADABLE_SUBSCRIPTION();
static JString EXTRA_EMBEDDED_SUBSCRIPTION_ERROR_CODE();
static JString EXTRA_EMBEDDED_SUBSCRIPTION_OPERATION_CODE();
static JString EXTRA_EMBEDDED_SUBSCRIPTION_SMDX_REASON_CODE();
static JString EXTRA_EMBEDDED_SUBSCRIPTION_SMDX_SUBJECT_CODE();
static JString EXTRA_USE_QR_SCANNER();
static JString META_DATA_CARRIER_ICON();
static jint OPERATION_APDU();
static jint OPERATION_DOWNLOAD();
static jint OPERATION_EUICC_CARD();
static jint OPERATION_EUICC_GSMA();
static jint OPERATION_HTTP();
static jint OPERATION_METADATA();
static jint OPERATION_SIM_SLOT();
static jint OPERATION_SMDX();
static jint OPERATION_SMDX_SUBJECT_REASON_CODE();
static jint OPERATION_SWITCH();
static jint OPERATION_SYSTEM();
// QJniObject forward
template<typename ...Ts> explicit EuiccManager(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {}
EuiccManager(QJniObject obj);
// Constructors
// Methods
android::telephony::euicc::EuiccManager createForCardId(jint arg0) const;
void deleteSubscription(jint arg0, android::app::PendingIntent arg1) const;
void downloadSubscription(android::telephony::euicc::DownloadableSubscription arg0, jboolean arg1, android::app::PendingIntent arg2) const;
JString getEid() const;
android::telephony::euicc::EuiccInfo getEuiccInfo() const;
jboolean isEnabled() const;
void startResolutionActivity(android::app::Activity arg0, jint arg1, android::content::Intent arg2, android::app::PendingIntent arg3) const;
void switchToSubscription(jint arg0, android::app::PendingIntent arg1) const;
void updateSubscriptionNickname(jint arg0, JString arg1, android::app::PendingIntent arg2) const;
};
} // namespace android::telephony::euicc
| 35.410526 | 153 | 0.791914 | YJBeetle |
231d9182b9f1771b0cd3cf53ce2636bd93867657 | 4,090 | cpp | C++ | CocosNet/CCInetAddress.cpp | LingJiJian/Tui-x | e00e79109db466143ed2b399a8991be4e5fea28f | [
"MIT"
] | 67 | 2015-02-09T03:20:59.000Z | 2022-01-17T05:53:07.000Z | CocosNet/CCInetAddress.cpp | fuhongxue/Tui-x | 9b288540a36942dd7f3518dc3e12eb2112bd93b0 | [
"MIT"
] | 3 | 2015-04-14T01:47:27.000Z | 2016-03-15T06:56:04.000Z | CocosNet/CCInetAddress.cpp | fuhongxue/Tui-x | 9b288540a36942dd7f3518dc3e12eb2112bd93b0 | [
"MIT"
] | 34 | 2015-02-18T04:42:07.000Z | 2019-08-15T05:34:46.000Z | /****************************************************************************
Copyright (c) 2014 Lijunlin - Jason lee
Created by Lijunlin - Jason lee on 2014
jason.lee.c@foxmail.com
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCInetAddress.h"
#if( CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 )
#pragma comment(lib, "Ws2_32.lib")
#endif
NS_CC_BEGIN
CInetAddress::CInetAddress()
{
#if( CC_TARGET_PLATFORM == CC_PLATFORM_IOS )
sin_len = sizeof(struct sockaddr_in);
sin_family = AF_INET;
sin_addr.s_addr = INADDR_ANY;
sin_port = 0;
memset(sin_zero, 0, 8);
#endif
#if( CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 )
sin_family = AF_INET;
sin_addr.s_addr = INADDR_ANY;
sin_port = 0;
memset(sin_zero, 0, 8);
#endif
#if( CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID )
sin_family = AF_INET;
sin_addr.s_addr = INADDR_ANY;
sin_port = 0;
memset(sin_zero, 0, 8);
#endif
}
CInetAddress::CInetAddress(const char* ip, unsigned short port)
{
sin_family = AF_INET;
sin_addr.s_addr = inet_addr(ip);
sin_port = htons(port);
memset(sin_zero, 0, 8);
}
CInetAddress::CInetAddress(const struct sockaddr * addr)
{
memcpy(&this->sin_family, addr, sizeof(struct sockaddr));
}
CInetAddress::~CInetAddress(void)
{
}
CInetAddress::operator struct sockaddr*()
{
#if( CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 )
return (struct sockaddr *)(&this->sin_family);
#endif
#if( CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID )
return (struct sockaddr *)(&this->sin_family);
#endif
#if( CC_TARGET_PLATFORM == CC_PLATFORM_IOS )
return (struct sockaddr *)(&this->sin_len);
#endif
}
CInetAddress::operator const struct sockaddr*() const
{
#if( CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 )
return (const struct sockaddr *)(&this->sin_family);
#endif
#if( CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID )
return (const struct sockaddr *)(&this->sin_family);
#endif
#if( CC_TARGET_PLATFORM == CC_PLATFORM_IOS )
return (const struct sockaddr *)(&this->sin_len);
#endif
}
const char* CInetAddress::getHostAddress() const
{
static char addr[64];
#if( CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 )
sprintf_s(addr, 64, "%s:%u", inet_ntoa(sin_addr), getPort());
#endif
#if( CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID )
snprintf(addr, 64, "%s:%u", inet_ntoa(sin_addr), getPort());
#endif
#if( CC_TARGET_PLATFORM == CC_PLATFORM_IOS )
snprintf(addr, 64, "%s:%u", inet_ntoa(sin_addr), getPort());
#endif
return addr;
}
const char* CInetAddress::getIp() const
{
return inet_ntoa(sin_addr);
}
unsigned short CInetAddress::getPort() const
{
return ntohs(sin_port);
}
void CInetAddress::setIp(const char* ip)
{
sin_addr.s_addr = inet_addr(ip);
}
void CInetAddress::setIp(unsigned int ip)
{
sin_addr.s_addr = ip;
}
void CInetAddress::setPort(unsigned short port)
{
sin_port = htons(port);
}
void CInetAddress::setHost(const char* name)
{
hostent* h = gethostbyname(name);
if( h != NULL )
{
sin_addr.s_addr = *((u_long *)h->h_addr_list[0]);
}
}
int CInetAddress::getLength()
{
return sizeof(sockaddr_in);
}
NS_CC_END | 24.939024 | 78 | 0.717359 | LingJiJian |
231f02f6d4d1546f049dad611beaeb393815d12d | 13,594 | cc | C++ | src/logic/server/mod_replace.cc | etolabo/kumofs | b0f7ce8263194dbfa92d10ae75849e676e77c067 | [
"Apache-2.0"
] | 38 | 2015-01-21T09:57:36.000Z | 2021-12-13T11:05:19.000Z | src/logic/server/mod_replace.cc | etolabo/kumofs | b0f7ce8263194dbfa92d10ae75849e676e77c067 | [
"Apache-2.0"
] | 3 | 2015-12-15T12:43:13.000Z | 2021-07-30T10:31:42.000Z | src/logic/server/mod_replace.cc | etolabo/kumofs | b0f7ce8263194dbfa92d10ae75849e676e77c067 | [
"Apache-2.0"
] | 2 | 2015-03-19T18:54:38.000Z | 2019-03-19T13:37:29.000Z | //
// kumofs
//
// Copyright (C) 2009 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 "server/framework.h"
#include "server/mod_replace.h"
#include "manager/mod_replace.h"
namespace kumo {
namespace server {
mod_replace_t::mod_replace_t() :
m_copying(false), m_deleting(false) { }
mod_replace_t::~mod_replace_t() { }
bool mod_replace_t::test_replicator_assign(const HashSpace& hs, uint64_t h, const address& target)
{
EACH_ASSIGN(hs, h, r,
if(r.is_active()) { // don't write to fault node
if(r.addr() == target) return true;
})
return false;
}
mod_replace_t::replace_state::replace_state() :
m_push_waiting(0),
m_clocktime(0) {}
mod_replace_t::replace_state::~replace_state() {}
inline void mod_replace_t::replace_state::reset(const address& mgr, ClockTime ct)
{
m_push_waiting = 0;
m_clocktime = ct;
m_mgr = mgr;
}
inline void mod_replace_t::replace_state::pushed(ClockTime ct)
{
if(ct == m_clocktime) { ++m_push_waiting; }
}
inline void mod_replace_t::replace_state::push_returned(ClockTime ct)
{
if(ct == m_clocktime) { --m_push_waiting; }
}
inline bool mod_replace_t::replace_state::is_finished(ClockTime ct) const
{
return m_clocktime == ct && m_push_waiting == 0;
}
inline void mod_replace_t::replace_state::invalidate()
{
m_push_waiting = -1;
}
inline const address& mod_replace_t::replace_state::mgr_addr() const
{
return m_mgr;
}
void mod_replace_t::replace_offer_push(ClockTime replace_time, REQUIRE_STLK)
{
m_state.pushed(replace_time);
}
void mod_replace_t::replace_offer_pop(ClockTime replace_time, REQUIRE_STLK)
{
m_state.push_returned(replace_time);
if(m_state.is_finished(replace_time)) {
finish_replace_copy(replace_time, stlk);
}
}
RPC_IMPL(mod_replace_t, ReplaceCopyStart, req, z, response)
{
net->clock_update(req.param().adjust_clock);
HashSpace hs(req.param().hsseed);
shared_zone life(z.release());
response.result(true);
try {
if(req.param().full) {
wavy::submit(&mod_replace_t::full_replace_copy, this,
req.node()->addr(), hs, life);
} else {
wavy::submit(&mod_replace_t::replace_copy, this,
req.node()->addr(), hs, life);
}
} catch (std::runtime_error& e) {
LOG_ERROR("replace copy failed: ",e.what());
} catch (...) {
LOG_ERROR("replace copy failed: unknown error");
}
}
RPC_IMPL(mod_replace_t, ReplaceDeleteStart, req, z, response)
{
net->clock_update(req.param().adjust_clock);
HashSpace hs(req.param().hsseed);
shared_zone life(z.release());
response.result(true);
try {
wavy::submit(&mod_replace_t::replace_delete, this,
req.node(), hs, life);
} catch (std::runtime_error& e) {
LOG_ERROR("replace delete failed: ",e.what());
} catch (...) {
LOG_ERROR("replace delete failed: unknown error");
}
}
struct mod_replace_t::for_each_replace_copy {
for_each_replace_copy(
const address& addr,
const HashSpace& src, const HashSpace& dst,
mod_replace_stream_t::offer_storage** offer_storage,
const addrvec_t& faults, const ClockTime rtime) :
self(addr),
srchs(src), dsths(dst),
offer(offer_storage), fault_nodes(faults),
replace_time(rtime)
{
Sa.reserve(NUM_REPLICATION+1);
Da.reserve(NUM_REPLICATION+1);
current_owners.reserve(NUM_REPLICATION+1);
newbies.reserve(NUM_REPLICATION+1);
}
inline void operator() (Storage::iterator& kv);
private:
addrvec_t Sa;
addrvec_t Da;
addrvec_t current_owners;
addrvec_t newbies;
const address& self;
const HashSpace& srchs;
const HashSpace& dsths;
mod_replace_stream_t::offer_storage** offer;
const addrvec_t& fault_nodes;
const ClockTime replace_time;
private:
for_each_replace_copy();
};
void mod_replace_t::replace_copy(const address& manager_addr, HashSpace& hs, shared_zone life)
{
scoped_set_true set_copying(&m_copying);
ClockTime replace_time = hs.clocktime();
{
pthread_scoped_lock stlk(m_state_mutex);
m_state.reset(manager_addr, replace_time);
replace_offer_push(replace_time, stlk); // replace_copy;
}
LOG_INFO("start replace copy for time(",replace_time.get(),")");
pthread_scoped_wrlock whlk(share->whs_mutex());
pthread_scoped_wrlock rhlk(share->rhs_mutex());
HashSpace srchs(share->rhs());
rhlk.unlock();
share->whs() = hs;
whlk.unlock();
HashSpace& dsths(hs);
addrvec_t fault_nodes;
{
addrvec_t src_nodes;
addrvec_t dst_nodes;
srchs.get_active_nodes(src_nodes);
dsths.get_active_nodes(dst_nodes);
for(addrvec_iterator it(src_nodes.begin()); it != src_nodes.end(); ++it) {
LOG_INFO("src active node: ",*it);
}
for(addrvec_iterator it(dst_nodes.begin()); it != dst_nodes.end(); ++it) {
LOG_INFO("dst active node: ",*it);
}
if(src_nodes.empty() || dst_nodes.empty()) {
LOG_WARN("empty hash space. skip replacing.");
goto skip_replace;
}
std::sort(src_nodes.begin(), src_nodes.end());
std::sort(dst_nodes.begin(), dst_nodes.end());
for(addrvec_iterator it(src_nodes.begin()); it != src_nodes.end(); ++it) {
if(!std::binary_search(dst_nodes.begin(), dst_nodes.end(), *it)) {
fault_nodes.push_back(*it);
}
}
for(addrvec_iterator it(fault_nodes.begin()); it != fault_nodes.end(); ++it) {
LOG_INFO("fault node: ",*it);
}
if(std::binary_search(fault_nodes.begin(), fault_nodes.end(), net->addr())) {
LOG_WARN("I'm marked as fault. skip replacing.");
goto skip_replace;
}
}
{
mod_replace_stream_t::offer_storage* offer = new mod_replace_stream_t::offer_storage(
share->cfg_offer_tmpdir(), replace_time);
share->db().for_each(
for_each_replace_copy(net->addr(), srchs, dsths, &offer, fault_nodes, replace_time),
net->clocktime_now());
net->mod_replace_stream.send_offer(*offer, replace_time);
delete offer;
}
skip_replace:
pthread_scoped_lock stlk(m_state_mutex);
replace_offer_pop(replace_time, stlk); // replace_copy
}
void mod_replace_t::for_each_replace_copy::operator() (Storage::iterator& kv)
{
const char* raw_key = kv.key();
size_t raw_keylen = kv.keylen();
const char* raw_val = kv.val();
size_t raw_vallen = kv.vallen();
unsigned long size_total = 0;
// Note: it is done in storage wrapper.
//if(raw_vallen < Storage::VALUE_META_SIZE) { return; }
//if(raw_keylen < Storage::KEY_META_SIZE) { return; }
uint64_t h = Storage::hash_of(kv.key());
Sa.clear();
EACH_ASSIGN(srchs, h, r, {
if(r.is_active()) Sa.push_back(r.addr()); });
Da.clear();
EACH_ASSIGN(dsths, h, r, {
if(r.is_active()) Da.push_back(r.addr()); });
current_owners.clear();
for(addrvec_iterator it(Sa.begin()); it != Sa.end(); ++it) {
if(!std::binary_search(fault_nodes.begin(), fault_nodes.end(), *it)) {
current_owners.push_back(*it);
}
}
// FIXME 再配置中にServerがダウンしたときコピーが正常に行われないかもしれない?
if(current_owners.empty() || current_owners.front() != self) {
LOG_WARN("current_owners.empty() || current_owners.front() != self");
return;
}
//if(std::find(current_owners.begin(), current_owners.end(), self)
// == current_owners.end()) { return; }
newbies.clear();
for(addrvec_iterator it(Da.begin()); it != Da.end(); ++it) {
if(std::find(Sa.begin(), Sa.end(), *it) == Sa.end()) {
newbies.push_back(*it);
}
}
if(newbies.empty()) { return; }
for(addrvec_iterator it(newbies.begin()); it != newbies.end(); ++it) {
(*offer)->add(*it,
raw_key, raw_keylen,
raw_val, raw_vallen);
size_total += (*offer)->stream_size(*it);
}
// offer内のストリームのサイズの合計が制限値を超えていたら、この時点までのofferをサーバに送る
if((unsigned long)share->cfg_replace_set_limit_mem() > 0) {
if(size_total >= (unsigned long)share->cfg_replace_set_limit_mem()*1024*1024) {
LOG_INFO("send replace offer by limit for time(",replace_time.get(),")");
net->mod_replace_stream.send_offer(*(*offer), replace_time);
while(net->mod_replace_stream.accum_set_size()) {
sleep(1);
}
delete (*offer);
(*offer) = new mod_replace_stream_t::offer_storage(share->cfg_offer_tmpdir(), replace_time);
}
}
}
struct mod_replace_t::for_each_full_replace_copy {
for_each_full_replace_copy(
const address& addr, const HashSpace& hs,
mod_replace_stream_t::offer_storage** offer_storage,
const ClockTime rtime) :
self(addr),
dsths(hs),
offer(offer_storage),
replace_time(rtime) { }
inline void operator() (Storage::iterator& kv);
private:
addrvec_t Da;
const address& self;
const HashSpace& dsths;
mod_replace_stream_t::offer_storage** offer;
const ClockTime replace_time;
private:
for_each_full_replace_copy();
};
void mod_replace_t::full_replace_copy(const address& manager_addr, HashSpace& hs, shared_zone life)
{
scoped_set_true set_copying(&m_copying);
ClockTime replace_time = hs.clocktime();
{
pthread_scoped_lock stlk(m_state_mutex);
m_state.reset(manager_addr, replace_time);
replace_offer_push(replace_time, stlk); // replace_copy;
}
LOG_INFO("start full replace copy for time(",replace_time.get(),")");
{
mod_replace_stream_t::offer_storage* offer = new mod_replace_stream_t::offer_storage(
share->cfg_offer_tmpdir(), replace_time);
share->db().for_each(
for_each_full_replace_copy(net->addr(), hs, &offer, replace_time),
net->clocktime_now());
net->mod_replace_stream.send_offer(*offer, replace_time);
delete offer;
}
pthread_scoped_lock stlk(m_state_mutex);
replace_offer_pop(replace_time, stlk); // replace_copy
}
void mod_replace_t::for_each_full_replace_copy::operator() (Storage::iterator& kv)
{
const char* raw_key = kv.key();
size_t raw_keylen = kv.keylen();
const char* raw_val = kv.val();
size_t raw_vallen = kv.vallen();
unsigned long size_total = 0;
// Note: it is done in storage wrapper.
//if(raw_vallen < Storage::VALUE_META_SIZE) { return; }
//if(raw_keylen < Storage::KEY_META_SIZE) { return; }
uint64_t h = Storage::hash_of(kv.key());
Da.clear();
EACH_ASSIGN(dsths, h, r, {
if(r.is_active()) Da.push_back(r.addr()); });
for(addrvec_iterator it(Da.begin()); it != Da.end(); ++it) {
(*offer)->add(*it,
raw_key, raw_keylen,
raw_val, raw_vallen);
size_total += (*offer)->stream_size(*it);
}
// offer内のストリームのサイズの合計が制限値を超えていたら、この時点までのofferをサーバに送る
if((unsigned long)share->cfg_replace_set_limit_mem() > 0) {
if(size_total >= (unsigned long)share->cfg_replace_set_limit_mem()*1024*1024) {
LOG_INFO("send replace offer by limit for time(",replace_time.get(),")");
net->mod_replace_stream.send_offer(*(*offer), replace_time);
while(net->mod_replace_stream.accum_set_size()) {
sleep(1);
}
delete (*offer);
(*offer) = new mod_replace_stream_t::offer_storage(share->cfg_offer_tmpdir(), replace_time);
}
}
}
void mod_replace_t::finish_replace_copy(ClockTime replace_time, REQUIRE_STLK)
{
LOG_INFO("finish replace copy for time(",replace_time.get(),")");
shared_zone nullz;
manager::mod_replace_t::ReplaceCopyEnd param(
replace_time, net->clock_incr());
address addr;
//{
// pthread_scoped_lock stlk(m_state_mutex);
addr = m_state.mgr_addr();
m_state.invalidate();
//}
using namespace mp::placeholders;
net->get_node(addr)->call(param, nullz,
BIND_RESPONSE(mod_replace_t, ReplaceCopyEnd), 10);
}
RPC_REPLY_IMPL(mod_replace_t, ReplaceCopyEnd, from, res, err, z)
{
if(!err.is_nil()) { LOG_ERROR("ReplaceCopyEnd failed: ",err); }
// FIXME retry
}
struct mod_replace_t::for_each_replace_delete {
for_each_replace_delete(const HashSpace& hs, const address& addr) :
self(addr), m_hs(hs) { }
inline void operator() (Storage::iterator& kv);
private:
const address& self;
const HashSpace& m_hs;
private:
for_each_replace_delete();
};
void mod_replace_t::replace_delete(shared_node& manager, HashSpace& hs, shared_zone life)
{
scoped_set_true set_deleting(&m_deleting);
pthread_scoped_rdlock whlk(share->whs_mutex());
ClockTime replace_time = share->whs().clocktime();
{
pthread_scoped_wrlock rhlk(share->rhs_mutex());
share->rhs() = share->whs();
}
LOG_INFO("start replace delete for time(",replace_time.get(),")");
if(!share->whs().empty()) {
HashSpace dsths(share->whs());
whlk.unlock();
share->db().for_each(
for_each_replace_delete(dsths, net->addr()),
net->clocktime_now() );
} else {
whlk.unlock();
}
shared_zone nullz;
manager::mod_replace_t::ReplaceDeleteEnd param(
replace_time, net->clock_incr());
using namespace mp::placeholders;
manager->call(param, nullz,
BIND_RESPONSE(mod_replace_t, ReplaceDeleteEnd), 10);
LOG_INFO("finish replace for time(",replace_time.get(),")");
}
void mod_replace_t::for_each_replace_delete::operator() (Storage::iterator& kv)
{
// Note: it is done in storage wrapper.
//if(kv.keylen() < Storage::KEY_META_SIZE ||
// kv.vallen() < Storage::VALUE_META_SIZE) {
// LOG_TRACE("delete invalid key: ",kv.key());
// kv.del();
//}
uint64_t h = Storage::hash_of(kv.key());
if(!mod_replace_t::test_replicator_assign(m_hs, h, self)) {
LOG_TRACE("replace delete key: ",kv.key());
kv.del();
}
}
RPC_REPLY_IMPL(mod_replace_t, ReplaceDeleteEnd, from, res, err, z)
{
if(!err.is_nil()) {
LOG_ERROR("ReplaceDeleteEnd failed: ",err);
}
// FIXME retry
}
} // namespace server
} // namespace kumo
| 25.456929 | 99 | 0.70715 | etolabo |
23213d1150f594761537fd98d01e289efb0bf3cb | 10,345 | cpp | C++ | DcxUXModule.cpp | dlsocool/dcx | 3d209d27cbd719f1d6c6d125b6f935ecaa79094c | [
"BSD-3-Clause"
] | null | null | null | DcxUXModule.cpp | dlsocool/dcx | 3d209d27cbd719f1d6c6d125b6f935ecaa79094c | [
"BSD-3-Clause"
] | null | null | null | DcxUXModule.cpp | dlsocool/dcx | 3d209d27cbd719f1d6c6d125b6f935ecaa79094c | [
"BSD-3-Clause"
] | null | null | null | #include "defines.h"
#include "DcxUXModule.h"
#include "Dcx.h"
// Theme functions
PFNSETTHEME DcxUXModule::SetWindowThemeUx = NULL;
PFNISTHEMEACTIVE DcxUXModule::IsThemeActiveUx = NULL;
PFNOPENTHEMEDATA DcxUXModule::OpenThemeDataUx = NULL;
PFNCLOSETHEMEDATA DcxUXModule::CloseThemeDataUx = NULL;
PFNDRAWTHEMEBACKGROUND DcxUXModule::DrawThemeBackgroundUx = NULL;
PFNGETTHEMEBACKGROUNDCONTENTRECT DcxUXModule::GetThemeBackgroundContentRectUx = NULL;
PFNISTHEMEBACKGROUNDPARTIALLYTRANSPARENT DcxUXModule::IsThemeBackgroundPartiallyTransparentUx = NULL;
PFNDRAWTHEMEPARENTBACKGROUND DcxUXModule::DrawThemeParentBackgroundUx = NULL;
PFNDRAWTHEMETEXT DcxUXModule::DrawThemeTextUx = NULL;
PFNGETTHEMEBACKGROUNDREGION DcxUXModule::GetThemeBackgroundRegionUx = NULL;
PFNGETWINDOWTHEME DcxUXModule::GetWindowThemeUx = NULL;
PFNDRAWTHEMEEDGE DcxUXModule::DrawThemeEdgeUx = NULL;
PFNGETTHEMECOLOR DcxUXModule::GetThemeColorUx = NULL;
PFNDRAWTHEMEPARENTBACKGROUNDEX DcxUXModule::DrawThemeParentBackgroundExUx = NULL;
//PFNGETTHEMEBITMAP DcxUXModule::GetThemeBitmapUx = NULL;
// Vista Function pointers.
#ifdef DCX_USE_WINSDK
PFNBUFFEREDPAINTINIT DcxUXModule::BufferedPaintInitUx = NULL;
PFNBUFFEREDPAINTUNINIT DcxUXModule::BufferedPaintUnInitUx = NULL;
PFNBEGINBUFFEREDPAINT DcxUXModule::BeginBufferedPaintUx = NULL;
PFNENDBUFFEREDPAINT DcxUXModule::EndBufferedPaintUx = NULL;
#endif
DcxUXModule::DcxUXModule(void)
{
}
DcxUXModule::~DcxUXModule(void)
{
if (isUseable()) unload();
}
bool DcxUXModule::load(mIRCLinker &mIRCLink)
{
if (isUseable()) return false;
DcxModule::load(mIRCLink);
// UXModule Loading
DCX_DEBUG(mIRCLink.debug,"LoadDLL", "Loading UXTHEME.DLL...");
m_hModule = LoadLibrary("UXTHEME.DLL");
if (m_hModule) {
// Get XP+ function pointers.
SetWindowThemeUx = (PFNSETTHEME) GetProcAddress(m_hModule, "SetWindowTheme");
IsThemeActiveUx = (PFNISTHEMEACTIVE) GetProcAddress(m_hModule, "IsThemeActive");
OpenThemeDataUx = (PFNOPENTHEMEDATA) GetProcAddress(m_hModule, "OpenThemeData");
CloseThemeDataUx = (PFNCLOSETHEMEDATA) GetProcAddress(m_hModule, "CloseThemeData");
DrawThemeBackgroundUx = (PFNDRAWTHEMEBACKGROUND) GetProcAddress(m_hModule, "DrawThemeBackground");
GetThemeBackgroundContentRectUx = (PFNGETTHEMEBACKGROUNDCONTENTRECT) GetProcAddress(m_hModule, "GetThemeBackgroundContentRect");
IsThemeBackgroundPartiallyTransparentUx = (PFNISTHEMEBACKGROUNDPARTIALLYTRANSPARENT) GetProcAddress(m_hModule, "IsThemeBackgroundPartiallyTransparent");
DrawThemeParentBackgroundUx = (PFNDRAWTHEMEPARENTBACKGROUND) GetProcAddress(m_hModule, "DrawThemeParentBackground");
DrawThemeTextUx = (PFNDRAWTHEMETEXT) GetProcAddress(m_hModule, "DrawThemeText");
GetThemeBackgroundRegionUx = (PFNGETTHEMEBACKGROUNDREGION) GetProcAddress(m_hModule, "GetThemeBackgroundRegion");
GetWindowThemeUx = (PFNGETWINDOWTHEME) GetProcAddress(m_hModule, "GetWindowTheme");
DrawThemeEdgeUx = (PFNDRAWTHEMEEDGE) GetProcAddress(m_hModule, "DrawThemeEdge");
GetThemeColorUx = (PFNGETTHEMECOLOR) GetProcAddress(m_hModule, "GetThemeColor");
// Get Vista function pointers.
#ifdef DCX_USE_WINSDK
DrawThemeParentBackgroundExUx = (PFNDRAWTHEMEPARENTBACKGROUNDEX) GetProcAddress(m_hModule, "DrawThemeParentBackgroundEx"); // Vista ONLY!
//GetThemeBitmapUx = (PFNGETTHEMEBITMAP) GetProcAddress(UXModule, "GetThemeBitmap");
BufferedPaintInitUx = (PFNBUFFEREDPAINTINIT) GetProcAddress(m_hModule, "BufferedPaintInit");
BufferedPaintUnInitUx = (PFNBUFFEREDPAINTUNINIT) GetProcAddress(m_hModule, "BufferedPaintUnInit");
BeginBufferedPaintUx = (PFNBEGINBUFFEREDPAINT) GetProcAddress(m_hModule, "BeginBufferedPaint");
EndBufferedPaintUx = (PFNENDBUFFEREDPAINT) GetProcAddress(m_hModule, "EndBufferedPaint");
#endif
// NB: DONT count vista functions in XP+ check.
if (SetWindowThemeUx && IsThemeActiveUx && OpenThemeDataUx && CloseThemeDataUx &&
DrawThemeBackgroundUx && GetThemeBackgroundContentRectUx && IsThemeBackgroundPartiallyTransparentUx &&
DrawThemeParentBackgroundUx && DrawThemeTextUx && GetThemeBackgroundRegionUx && GetWindowThemeUx && DrawThemeEdgeUx && GetThemeColorUx) {
DCX_DEBUG(mIRCLink.debug,"LoadDLL", "Found XP+ Theme Functions");
#ifdef DCX_USE_WINSDK
if (DrawThemeParentBackgroundExUx && BufferedPaintInitUx && BufferedPaintUnInitUx &&
BeginBufferedPaintUx && EndBufferedPaintUx) {
DCX_DEBUG(mIRCLink.debug,"LoadDLL", "Found Vista Theme Functions");
BufferedPaintInitUx();
}
#endif
}
else {
FreeLibrary(m_hModule);
m_hModule = NULL;
// make sure all functions are NULL
SetWindowThemeUx = NULL;
IsThemeActiveUx = NULL;
OpenThemeDataUx = NULL;
CloseThemeDataUx = NULL;
DrawThemeBackgroundUx = NULL;
GetThemeBackgroundContentRectUx = NULL;
IsThemeBackgroundPartiallyTransparentUx = NULL;
DrawThemeParentBackgroundUx = NULL;
DrawThemeTextUx = NULL;
GetThemeBackgroundRegionUx = NULL;
GetWindowThemeUx = NULL;
DrawThemeEdgeUx = NULL;
GetThemeColorUx = NULL;
DrawThemeParentBackgroundExUx = NULL;
#ifdef DCX_USE_WINSDK
BufferedPaintInitUx = NULL;
BufferedPaintUnInitUx = NULL;
BeginBufferedPaintUx = NULL;
EndBufferedPaintUx = NULL;
#endif
Dcx::error("LoadDLL","There was a problem loading IsThemedXP");
}
}
return isUseable();
}
bool DcxUXModule::unload(void)
{
if (isUseable()) {
#ifdef DCX_USE_WINSDK
if (BufferedPaintUnInitUx)
BufferedPaintUnInitUx();
#endif
FreeLibrary(m_hModule);
m_hModule = NULL;
return true;
}
return false;
}
/*!
* \brief Check if theme is active
*
*
*/
BOOL DcxUXModule::dcxIsThemeActive(void)
{
if (IsThemeActiveUx != NULL)
return IsThemeActiveUx();
return FALSE;
}
/*!
* \brief Windows Theme Setting Function
*
* Used to remove theme on controls
*/
HRESULT DcxUXModule::dcxSetWindowTheme(const HWND hwnd, const LPCWSTR pszSubAppName, const LPCWSTR pszSubIdList) {
if (SetWindowThemeUx != NULL)
return SetWindowThemeUx(hwnd, pszSubAppName, pszSubIdList);
return 0;
}
HTHEME DcxUXModule::dcxGetWindowTheme(HWND hWnd)
{
if (GetWindowThemeUx != NULL)
return GetWindowThemeUx(hWnd);
return NULL;
}
HTHEME DcxUXModule::dcxOpenThemeData(HWND hwnd, LPCWSTR pszClassList)
{
if (OpenThemeDataUx != NULL)
return OpenThemeDataUx(hwnd, pszClassList);
return NULL;
}
HRESULT DcxUXModule::dcxCloseThemeData(HTHEME hTheme)
{
if (CloseThemeDataUx != NULL)
return CloseThemeDataUx(hTheme);
return NULL;
}
//int DcxUXModule::dcxGetThemeBackgroundRegion(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, LPRECT pRect, HRGN *pRegion)
//{
// if (GetThemeBackgroundRegionUx != NULL)
// return GetThemeBackgroundRegionUx(hTheme, hdc, iPartId, iStateId, pRect, pRegion);
// return NULL;
//}
BOOL DcxUXModule::dcxIsThemeBackgroundPartiallyTransparent(HTHEME hTheme, int iPartId, int iStateId)
{
if (IsThemeBackgroundPartiallyTransparentUx != NULL)
return IsThemeBackgroundPartiallyTransparentUx(hTheme, iPartId, iStateId);
return NULL;
}
HRESULT DcxUXModule::dcxDrawThemeBackground(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, LPCRECT pRect, LPCRECT pClipRect)
{
if (DrawThemeBackgroundUx != NULL)
return DrawThemeBackgroundUx(hTheme, hdc, iPartId, iStateId, pRect, pClipRect);
return NULL;
}
HRESULT DcxUXModule::dcxGetThemeBackgroundContentRect(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, LPCRECT pBoundingRect, LPRECT pContentRect)
{
if (GetThemeBackgroundContentRectUx != NULL)
return GetThemeBackgroundContentRectUx(hTheme, hdc, iPartId, iStateId, pBoundingRect, pContentRect);
return NULL;
}
HRESULT DcxUXModule::dcxDrawThemeParentBackground(HWND hwnd, HDC hdc, const RECT *prc)
{
if (DrawThemeParentBackgroundUx != NULL)
return DrawThemeParentBackgroundUx(hwnd, hdc, prc);
return NULL;
}
HRESULT DcxUXModule::dcxDrawThemeText(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, LPCWSTR pszText, int cchText, DWORD dwTextFlags, DWORD dwTextFlags2, LPCRECT pRect)
{
if (DrawThemeTextUx != NULL)
return DrawThemeTextUx(hTheme, hdc, iPartId, iStateId, pszText, cchText, dwTextFlags, dwTextFlags2, pRect);
return NULL;
}
HRESULT DcxUXModule::dcxGetThemeBackgroundRegion(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, LPCRECT pRect, HRGN *pRegion)
{
if (GetThemeBackgroundRegionUx != NULL)
return GetThemeBackgroundRegionUx(hTheme, hdc, iPartId, iStateId, pRect, pRegion);
return NULL;
}
HRESULT DcxUXModule::dcxDrawThemeEdge(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, LPCRECT pDestRect, UINT uEdge, UINT uFlags, LPRECT pContentRect)
{
if (DrawThemeEdgeUx != NULL)
return DrawThemeEdgeUx(hTheme, hdc, iPartId, iStateId, pDestRect, uEdge, uFlags, pContentRect);
return NULL;
}
HRESULT DcxUXModule::dcxGetThemeColor(HTHEME hTheme, int iPartId, int iStateId, int iPropId, COLORREF *pColor)
{
if (GetThemeColorUx != NULL)
return GetThemeColorUx(hTheme, iPartId, iStateId, iPropId, pColor);
return NULL;
}
HRESULT DcxUXModule::dcxDrawThemeParentBackgroundEx(HWND hwnd, HDC hdc, DWORD dwFlags, const RECT *prc)
{
if (DrawThemeParentBackgroundExUx != NULL)
return DrawThemeParentBackgroundExUx(hwnd, hdc, dwFlags, prc);
return NULL;
}
#ifdef DCX_USE_WINSDK
HPAINTBUFFER DcxUXModule::dcxBeginBufferedPaint(HDC hdcTarget, const RECT *prcTarget, BP_BUFFERFORMAT dwFormat, BP_PAINTPARAMS *pPaintParams, HDC *phdc)
{
if (BeginBufferedPaintUx != NULL)
return BeginBufferedPaintUx(hdcTarget, prcTarget, dwFormat, pPaintParams, phdc);
return NULL;
}
HRESULT DcxUXModule::dcxEndBufferedPaint(HPAINTBUFFER hBufferedPaint, BOOL fUpdateTarget)
{
if (EndBufferedPaintUx != NULL)
return EndBufferedPaintUx(hBufferedPaint, fUpdateTarget);
return NULL;
}
HRESULT DcxUXModule::dcxBufferedPaintInit(void)
{
if (BufferedPaintInitUx != NULL)
return BufferedPaintInitUx();
return NULL;
}
HRESULT DcxUXModule::dcxBufferedPaintUnInit(void)
{
if (BufferedPaintUnInitUx != NULL)
return BufferedPaintUnInitUx();
return NULL;
}
bool DcxUXModule::IsBufferedPaintSupported(void)
{
return ((BufferedPaintInitUx != NULL) && (BufferedPaintUnInitUx != NULL) && (BeginBufferedPaintUx != NULL) && (EndBufferedPaintUx != NULL));
}
#endif
| 37.21223 | 173 | 0.771774 | dlsocool |
232193aaefdd08ba83f0825eab25d99e56dd3424 | 8,580 | cpp | C++ | operator/plugin/init.cpp | zjd1988/Tengine-Convert-Tools | 694e2f3c93ed7fbbfae926c131d45f136406a8ab | [
"Apache-2.0"
] | 2 | 2021-01-05T01:44:12.000Z | 2022-01-30T19:04:16.000Z | operator/plugin/init.cpp | daquexian/Tengine-Convert-Tools | d7773522833346d6ffbe87791280fe7041a95129 | [
"Apache-2.0"
] | null | null | null | operator/plugin/init.cpp | daquexian/Tengine-Convert-Tools | d7773522833346d6ffbe87791280fe7041a95129 | [
"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.
*/
/*
* Copyright (c) 2017, Open AI Lab
* Author: haitao@openailab.com
*/
#include <iostream>
#include <functional>
#include "logger.hpp"
#include "operator/convolution.hpp"
#include "operator/input_op.hpp"
#include "operator/pooling.hpp"
#include "operator/softmax.hpp"
#include "operator/fully_connected.hpp"
#include "operator/split.hpp"
#include "operator/concat.hpp"
#include "operator/const_op.hpp"
#include "operator/accuracy.hpp"
#include "operator/dropout.hpp"
#include "operator/relu.hpp"
#include "operator/relu6.hpp"
#include "operator/batch_norm.hpp"
#include "operator/scale.hpp"
#include "operator/lrn.hpp"
#include "operator/fused_operator.hpp"
#include "operator/prelu.hpp"
#include "operator/eltwise.hpp"
#include "operator/slice.hpp"
#include "operator/demo_op.hpp"
#include "operator/normalize.hpp"
#include "operator/permute.hpp"
#include "operator/flatten.hpp"
#include "operator/priorbox.hpp"
#include "operator/reshape.hpp"
#include "operator/detection_output.hpp"
#include "operator/rpn.hpp"
#include "operator/roi_pooling.hpp"
#include "operator/reorg.hpp"
#include "operator/region.hpp"
#include "operator/deconvolution.hpp"
#include "operator/resize.hpp"
#include "operator/gemm.hpp"
#include "operator/generic.hpp"
#include "operator/lstm.hpp"
#include "operator/logistic.hpp"
#include "operator/detection_postprocess.hpp"
#include "operator/rnn.hpp"
#include "operator/tanh.hpp"
#include "operator/sigmoid.hpp"
#include "operator/squeeze.hpp"
#include "operator/pad.hpp"
#include "operator/reduction.hpp"
#include "operator/swap_axis.hpp"
#include "operator/gru.hpp"
#include "operator/add_n.hpp"
#include "operator/stridedslice.hpp"
#include "operator/upsample.hpp"
#include "operator/crop.hpp"
#include "operator/copy.hpp"
#include "operator/power.hpp"
#include "operator/floor.hpp"
#include "operator/clip.hpp"
#include "operator/tile.hpp"
#include "operator/topkv2.hpp"
#include "operator/maximum.hpp"
#include "operator/minimum.hpp"
#include "operator/argmax.hpp"
#include "operator/argmin.hpp"
#include "operator/reverse.hpp"
#include "operator/feature_match.hpp"
#include "operator/shuffle_channel.hpp"
#include "operator/batchToSpaceND.hpp"
#include "operator/spaceToBatchND.hpp"
#include "operator/absval.hpp"
#include "operator/hardswish.hpp"
#include "operator/interp.hpp"
#include "operator/selu.hpp"
#include "operator/l2normalization.hpp"
#include "operator/l2pool.hpp"
#include "operator/elu.hpp"
#include "operator/layernormlstm.hpp"
#include "operator/relu1.hpp"
#include "operator/log_softmax.hpp"
#include "operator/cast.hpp"
#include "operator/expanddims.hpp"
#include "operator/unary.hpp"
#include "operator/roialign.hpp"
#include "operator/psroipooling.hpp"
#include "operator/bias.hpp"
#include "operator/noop.hpp"
#include "operator/threshold.hpp"
#include "operator/hardsigmoid.hpp"
#include "operator/embed.hpp"
#include "operator/instancenorm.hpp"
#include "operator/mvn.hpp"
#include "operator/broadmul.hpp"
#include "operator/logical.hpp"
#include "operator/gather.hpp"
#include "operator/transpose.hpp"
#include "operator/comparison.hpp"
#include "operator/spacetodepth.hpp"
#include "operator/depthtospace.hpp"
#include "operator/squared_difference.hpp"
#include "operator/sparsetodense.hpp"
#include "operator/ceil.hpp"
#include "operator/round.hpp"
#include "operator/zeros_like.hpp"
#include "operator/unsqueeze.hpp"
#include "operator/reducel2.hpp"
#include "operator/matmul.hpp"
#include "operator/mean.hpp"
#include "operator/expand.hpp"
#include "operator/scatter.hpp"
#include "operator/shape.hpp"
#include "operator/where.hpp"
#include "operator/mish.hpp"
using namespace TEngine;
int operator_plugin_init(void)
{
RegisterOp<Convolution>("Convolution");
RegisterOp<InputOp>("InputOp");
RegisterOp<Pooling>("Pooling");
RegisterOp<Softmax>("Softmax");
RegisterOp<FullyConnected>("FullyConnected");
RegisterOp<Accuracy>("Accuracy");
RegisterOp<Concat>("Concat");
RegisterOp<Dropout>("Dropout");
RegisterOp<Split>("Split");
RegisterOp<ConstOp>("Const");
RegisterOp<ReLu>("ReLu");
RegisterOp<ReLu6>("ReLu6");
RegisterOp<BatchNorm>(BatchNormName);
RegisterOp<Scale>("Scale");
RegisterOp<LRN>("LRN");
RegisterOp<FusedBNScaleReLu>(FusedBNScaleReLu::class_name);
RegisterOp<PReLU>("PReLU");
RegisterOp<Eltwise>("Eltwise");
RegisterOp<Slice>("Slice");
RegisterOp<DemoOp>("DemoOp");
RegisterOp<Normalize>("Normalize");
RegisterOp<Permute>("Permute");
RegisterOp<Flatten>("Flatten");
RegisterOp<PriorBox>("PriorBox");
RegisterOp<Reshape>("Reshape");
RegisterOp<DetectionOutput>("DetectionOutput");
RegisterOp<RPN>("RPN");
RegisterOp<ROIPooling>("ROIPooling");
RegisterOp<Reorg>("Reorg");
RegisterOp<Region>("Region");
RegisterOp<Deconvolution>("Deconvolution");
RegisterOp<Resize>("Resize");
RegisterOp<Gemm>("Gemm");
RegisterOp<Generic>("Generic");
RegisterOp<LSTM>("LSTM");
RegisterOp<Logistic>("Logistic");
RegisterOp<DetectionPostProcess>("DetectionPostProcess");
RegisterOp<RNN>("RNN");
RegisterOp<Tanh>("Tanh");
RegisterOp<Sigmoid>("Sigmoid");
RegisterOp<Squeeze>("Squeeze");
RegisterOp<Pad>("Pad");
RegisterOp<Reduction>("Reduction");
RegisterOp<SwapAxis>("SwapAxis");
RegisterOp<GRU>("GRU");
RegisterOp<Addn>("Addn");
RegisterOp<StridedSlice>("StridedSlice");
RegisterOp<Floor>("Floor");
RegisterOp<Upsample>("Upsample");
RegisterOp<Crop>("Crop");
RegisterOp<Copy>("Copy");
RegisterOp<Power>("Power");
RegisterOp<Clip>("Clip");
RegisterOp<Tile>("Tile");
RegisterOp<Maximum>("Maximum");
RegisterOp<Minimum>("Minimum");
RegisterOp<ArgMax>("ArgMax");
RegisterOp<ArgMin>("ArgMin");
RegisterOp<TopKV2>("TopKV2");
RegisterOp<Reverse>("Reverse");
RegisterOp<FeatureMatch>("FeatureMatch");
RegisterOp<ShuffleChannel>("ShuffleChannel");
RegisterOp<BatchToSpaceND>("BatchToSpaceND");
RegisterOp<SpaceToBatchND>("SpaceToBatchND");
RegisterOp<Absval>("Absval");
RegisterOp<Hardswish>("Hardswish");
RegisterOp<Interp>("Interp");
RegisterOp<Selu>("Selu");
RegisterOp<L2Normalization>("L2Normalization");
RegisterOp<L2Pool>("L2Pool");
RegisterOp<Elu>("Elu");
RegisterOp<LayerNormLSTM>("LayerNormLSTM");
RegisterOp<ReLU1>("ReLU1");
RegisterOp<LogSoftmax>("LogSoftmax");
RegisterOp<Cast>("Cast");
RegisterOp<ExpandDims>("ExpandDims");
RegisterOp<Unary>("Unary");
RegisterOp<Roialign>("Roialign");
RegisterOp<Psroipooling>("Psroipooling");
RegisterOp<Bias>("Bias");
RegisterOp<Noop>("Noop");
RegisterOp<Threshold>("Threshold");
RegisterOp<Hardsigmoid>("Hardsigmoid");
RegisterOp<Embed>("Embedding");
RegisterOp<InstanceNorm>("InstanceNorm");
RegisterOp<MVN>("MVN");
RegisterOp<BroadMul>("BroadMul");
RegisterOp<Logical>("Logical");
RegisterOp<Gather>("Gather");
RegisterOp<Transpose>("Transpose");
RegisterOp<Comparison>("Comparison");
RegisterOp<SpaceToDepth>("SpaceToDepth");
RegisterOp<DepthToSpace>("DepthToSpace");
RegisterOp<Ceil>("Ceil");
RegisterOp<Round>("Round");
RegisterOp<SquaredDifference>("SquaredDifference");
RegisterOp<SparseToDense>("SparseToDense");
RegisterOp<ZerosLike>("ZerosLike");
RegisterOp<Unsqueeze>("Unsqueeze");
RegisterOp<ReduceL2>("ReduceL2");
RegisterOp<Mean>("Mean");
RegisterOp<Expand>("Expand");
RegisterOp<MatMul>("MatMul");
RegisterOp<Scatter>("Scatter");
RegisterOp<Shape>("Shape");
RegisterOp<Where>("Where");
RegisterOp<ReduceL2>("ReduceL2");
//add for yolov4
RegisterOp<Mish>("Mish");
// std::cout<<"OPERATOR PLUGIN INITED\n";
return 0;
}
| 34.183267 | 63 | 0.728205 | zjd1988 |
232218e5cb52fd28ea917b60c4289a221f3b5482 | 3,997 | hpp | C++ | 3rdparty/stout/include/stout/os/windows/write.hpp | zagrev/mesos | eefec152dffc4977183089b46fbfe37dbd19e9d7 | [
"Apache-2.0"
] | 4,537 | 2015-01-01T03:26:40.000Z | 2022-03-31T03:07:00.000Z | 3rdparty/stout/include/stout/os/windows/write.hpp | zagrev/mesos | eefec152dffc4977183089b46fbfe37dbd19e9d7 | [
"Apache-2.0"
] | 227 | 2015-01-29T02:21:39.000Z | 2022-03-29T13:35:50.000Z | 3rdparty/stout/include/stout/os/windows/write.hpp | zagrev/mesos | eefec152dffc4977183089b46fbfe37dbd19e9d7 | [
"Apache-2.0"
] | 1,992 | 2015-01-05T12:29:19.000Z | 2022-03-31T03:07:07.000Z | // 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 __STOUT_OS_WINDOWS_WRITE_HPP__
#define __STOUT_OS_WINDOWS_WRITE_HPP__
#include <stout/nothing.hpp>
#include <stout/try.hpp>
#include <stout/unreachable.hpp>
#include <stout/windows.hpp>
#include <stout/internal/windows/overlapped.hpp>
#include <stout/os/int_fd.hpp>
#include <stout/os/socket.hpp>
namespace os {
// Asynchronous write on a overlapped int_fd. Returns `Error` on fatal errors,
// `None()` on a successful pending IO operation or number of bytes written on
// a successful IO operation that finished immediately.
inline Result<size_t> write_async(
const int_fd& fd,
const void* data,
size_t size,
OVERLAPPED* overlapped)
{
CHECK_LE(size, UINT_MAX);
switch (fd.type()) {
case WindowsFD::Type::HANDLE: {
DWORD bytes;
const bool success =
::WriteFile(fd, data, static_cast<DWORD>(size), &bytes, overlapped);
return ::internal::windows::process_async_io_result(success, bytes);
}
case WindowsFD::Type::SOCKET: {
static_assert(
std::is_same<OVERLAPPED, WSAOVERLAPPED>::value,
"Expected `WSAOVERLAPPED` to be of type `OVERLAPPED`.");
// Note that it's okay to allocate this on the stack, since the WinSock
// providers must copy the WSABUF to their internal buffers. See
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms741688(v=vs.85).aspx // NOLINT(whitespace/line_length)
WSABUF buf = {
static_cast<u_long>(size),
static_cast<char*>(const_cast<void*>(data))
};
DWORD bytes;
const int result =
::WSASend(fd, &buf, 1, &bytes, 0, overlapped, nullptr);
return ::internal::windows::process_async_io_result(result == 0, bytes);
}
}
UNREACHABLE();
}
inline ssize_t write(const int_fd& fd, const void* data, size_t size)
{
CHECK_LE(size, INT_MAX);
switch (fd.type()) {
case WindowsFD::Type::HANDLE: {
// Handle non-overlapped case. We just use the regular `WriteFile` since
// seekable overlapped files require an offset, which we don't track.
if (!fd.is_overlapped()) {
DWORD bytes;
const BOOL result =
::WriteFile(fd, data, static_cast<DWORD>(size), &bytes, nullptr);
if (result == FALSE) {
// Indicates an error, but we can't return a `WindowsError`.
return -1;
}
return static_cast<ssize_t>(bytes);
}
// Asynchronous handle, we can use the `write_async` function
// and then wait on the overlapped object for a synchronous write.
Try<OVERLAPPED> overlapped_ =
::internal::windows::init_overlapped_for_sync_io();
if (overlapped_.isError()) {
return -1;
}
OVERLAPPED overlapped = overlapped_.get();
Result<size_t> result = write_async(fd, data, size, &overlapped);
if (result.isError()) {
return -1;
}
if (result.isSome()) {
return result.get();
}
// IO is pending, so wait for the overlapped object.
DWORD bytes;
const BOOL wait_success =
::GetOverlappedResult(fd, &overlapped, &bytes, TRUE);
if (wait_success == FALSE) {
return -1;
}
return static_cast<ssize_t>(bytes);
}
case WindowsFD::Type::SOCKET: {
return ::send(fd, (const char*)data, static_cast<int>(size), 0);
}
}
UNREACHABLE();
}
} // namespace os {
#endif // __STOUT_OS_WINDOWS_WRITE_HPP__
| 29.389706 | 122 | 0.656993 | zagrev |
2323ec4a0447369ac1a650be31334df5eb14c9e9 | 3,447 | ipp | C++ | cppwamp/include/cppwamp/internal/rawsockoptions.ipp | katreniak/cppwamp | b37d3a9e83bca9594d6acd29a3fb7db39bda6cc9 | [
"BSL-1.0"
] | 39 | 2015-04-04T00:29:47.000Z | 2021-06-27T11:25:38.000Z | cppwamp/include/cppwamp/internal/rawsockoptions.ipp | katreniak/cppwamp | b37d3a9e83bca9594d6acd29a3fb7db39bda6cc9 | [
"BSL-1.0"
] | 115 | 2015-04-04T01:59:32.000Z | 2020-12-04T09:23:09.000Z | cppwamp/include/cppwamp/internal/rawsockoptions.ipp | katreniak/cppwamp | b37d3a9e83bca9594d6acd29a3fb7db39bda6cc9 | [
"BSL-1.0"
] | 8 | 2015-05-04T06:24:55.000Z | 2020-11-11T12:38:46.000Z | /*------------------------------------------------------------------------------
Copyright Butterfly Energy Systems 2014-2015.
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)
------------------------------------------------------------------------------*/
#include <boost/asio/socket_base.hpp>
#include <boost/asio/ip/unicast.hpp>
#include <boost/asio/ip/v6_only.hpp>
namespace wamp
{
//------------------------------------------------------------------------------
namespace internal
{
template <typename TRawsockOptions, typename TSocket>
void applyRawsockOptions(const TRawsockOptions& options, TSocket& socket)
{
options.socketOptions_.applyTo(socket);
}
} // namespace internal
//------------------------------------------------------------------------------
template <typename D, typename P>
RawsockOptions<D,P>::RawsockOptions()
: maxRxLength_(defaultMaxRxLength)
{}
template <typename D, typename P>
D& RawsockOptions<D,P>::withMaxRxLength(RawsockMaxLength length)
{
maxRxLength_ = length;
return static_cast<D&>(*this);
}
template <typename D, typename P>
D& RawsockOptions<D,P>::withBroadcast(bool enabled)
{
return addOption(boost::asio::socket_base::broadcast(enabled));
}
template <typename D, typename P>
D& RawsockOptions<D,P>::withDebug(bool enabled)
{
return addOption(boost::asio::socket_base::debug(enabled));
}
template <typename D, typename P>
D& RawsockOptions<D,P>::withDoNotRoute(bool enabled)
{
return addOption(boost::asio::socket_base::do_not_route(enabled));
}
template <typename D, typename P>
D& RawsockOptions<D,P>::withKeepAlive(bool enabled)
{
return addOption(boost::asio::socket_base::keep_alive(enabled));
}
template <typename D, typename P>
D& RawsockOptions<D,P>::withLinger(bool enabled, int timeout)
{
return addOption(boost::asio::socket_base::linger(enabled, timeout));
}
template <typename D, typename P>
D& RawsockOptions<D,P>::withReceiveBufferSize(int size)
{
return addOption(boost::asio::socket_base::receive_buffer_size(size));
}
template <typename D, typename P>
D& RawsockOptions<D,P>::withReceiveLowWatermark(int size)
{
return addOption(boost::asio::socket_base::receive_low_watermark(size));
}
template <typename D, typename P>
D& RawsockOptions<D,P>::withReuseAddress(bool enabled)
{
return addOption(boost::asio::socket_base::reuse_address(enabled));
}
template <typename D, typename P>
D& RawsockOptions<D,P>::withSendBufferSize(int size)
{
return addOption(boost::asio::socket_base::send_buffer_size(size));
}
template <typename D, typename P>
D& RawsockOptions<D,P>::withSendLowWatermark(int size)
{
return addOption(boost::asio::socket_base::send_low_watermark(size));
}
template <typename D, typename P>
RawsockMaxLength RawsockOptions<D,P>::maxRxLength() const {return maxRxLength_;}
//------------------------------------------------------------------------------
template <typename D, typename P>
IpOptions<D,P>::IpOptions() {}
template <typename D, typename P>
D& IpOptions<D,P>::withUnicastHops(int hops)
{
return this->addOption(boost::asio::ip::unicast::hops(hops));
}
template <typename D, typename P>
D& IpOptions<D,P>::withIpV6Only(bool enabled)
{
return this->addOption(boost::asio::ip::v6_only(true));
}
} // namespace wamp
| 27.798387 | 80 | 0.64752 | katreniak |
2324151c13cdded137df6b4333f6a4d49c4f6b31 | 1,804 | cpp | C++ | Engine/source/platform/input/oculusVR/oculusVRSensorData.cpp | fr1tz/alux3d | 249a3b51751ce3184d52879b481f83eabe89e7e3 | [
"MIT"
] | null | null | null | Engine/source/platform/input/oculusVR/oculusVRSensorData.cpp | fr1tz/alux3d | 249a3b51751ce3184d52879b481f83eabe89e7e3 | [
"MIT"
] | null | null | null | Engine/source/platform/input/oculusVR/oculusVRSensorData.cpp | fr1tz/alux3d | 249a3b51751ce3184d52879b481f83eabe89e7e3 | [
"MIT"
] | 1 | 2018-10-26T03:18:22.000Z | 2018-10-26T03:18:22.000Z | // Copyright information can be found in the file named COPYING
// located in the root directory of this distribution.
#include "platform/input/oculusVR/oculusVRSensorData.h"
#include "platform/input/oculusVR/oculusVRUtil.h"
#include "console/console.h"
OculusVRSensorData::OculusVRSensorData()
{
reset();
}
void OculusVRSensorData::reset()
{
mDataSet = false;
}
void OculusVRSensorData::setData(const OVR::SensorFusion& data, const F32& maxAxisRadius)
{
// Sensor rotation
OVR::Quatf orientation;
if(data.GetPredictionDelta() > 0)
{
orientation = data.GetPredictedOrientation();
}
else
{
orientation = data.GetOrientation();
}
OVR::Matrix4f orientMat(orientation);
OculusVRUtil::convertRotation(orientMat.M, mRot);
mRotQuat.set(mRot);
// Sensor rotation in Euler format
OculusVRUtil::convertRotation(orientation, mRotEuler);
// Sensor rotation as axis
OculusVRUtil::calculateAxisRotation(mRot, maxAxisRadius, mRotAxis);
mDataSet = true;
}
void OculusVRSensorData::simulateData(const F32& maxAxisRadius)
{
// Sensor rotation
mRot.identity();
mRotQuat.identity();
mRotEuler.zero();
// Sensor rotation as axis
OculusVRUtil::calculateAxisRotation(mRot, maxAxisRadius, mRotAxis);
mDataSet = true;
}
U32 OculusVRSensorData::compare(OculusVRSensorData* other)
{
S32 result = DIFF_NONE;
// Check rotation
if(mRotEuler.x != other->mRotEuler.x || mRotEuler.y != other->mRotEuler.y || mRotEuler.z != other->mRotEuler.z || !mDataSet)
{
result |= DIFF_ROT;
}
// Check rotation as axis
if(mRotAxis.x != other->mRotAxis.x || !mDataSet)
{
result |= DIFF_ROTAXISX;
}
if(mRotAxis.y != other->mRotAxis.y || !mDataSet)
{
result |= DIFF_ROTAXISY;
}
return result;
}
| 23.128205 | 127 | 0.695676 | fr1tz |
23257562599efa6d8ada04bde5ea7acb384fcae8 | 1,122 | cpp | C++ | 10_App/5.cpp | HCMUS-Eakan/DSA-Synthesis | 2739e20bed0865d8f6f722b3da9c1d6df54774e0 | [
"MIT"
] | null | null | null | 10_App/5.cpp | HCMUS-Eakan/DSA-Synthesis | 2739e20bed0865d8f6f722b3da9c1d6df54774e0 | [
"MIT"
] | null | null | null | 10_App/5.cpp | HCMUS-Eakan/DSA-Synthesis | 2739e20bed0865d8f6f722b3da9c1d6df54774e0 | [
"MIT"
] | 1 | 2021-09-05T00:59:12.000Z | 2021-09-05T00:59:12.000Z | // 5.
// Problem: Put n people in a row in order from highest to lowest by the 2 people in front swap with the person behind if taller and repeat until the row is complete. Count the number of items needed to complete the order as required.
// Solution: Implement bubble sort algorithm in order from smallest to largest for n arrays containing height information of each person.
// Code:
#include <iostream>
#include <ctime>
using namespace std;
void swap(int* a, int* b) {
int* c;
c = new int;
*c = *a;
*a = *b;
*b = *c;
delete c;
}
int main(){
srand((int)time(0));
int n, a[100], k = 0;
cout << "n= ";
cin >> n;
cout << "At first: ";
for (int i = 0; i < n; i++) {
a[i] = rand() % 200 + 1;
cout << a[i] << " ";
}
cout << "\nAfter: ";
for (int i = 1; i < n; i++)
for (int j = n - 1; j >= i; j--)
if (a[j] < a[j - 1]) {
swap(a[j], a[j - 1]);
k++;
}
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout << "\nNumber of times to change places: " << k << endl;
return 0;
}
| 23.375 | 234 | 0.511586 | HCMUS-Eakan |
2327344ab6e5c9d3e6fdd5722c0cec3431e272a1 | 4,064 | hpp | C++ | src/ngraph/op/topk.hpp | tzerrell/ngraph | b02b0812745ca1cb5f73d426ae9e0ad729eb0bbd | [
"Apache-2.0"
] | null | null | null | src/ngraph/op/topk.hpp | tzerrell/ngraph | b02b0812745ca1cb5f73d426ae9e0ad729eb0bbd | [
"Apache-2.0"
] | null | null | null | src/ngraph/op/topk.hpp | tzerrell/ngraph | b02b0812745ca1cb5f73d426ae9e0ad729eb0bbd | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#pragma once
#include <memory>
#include "ngraph/axis_set.hpp"
#include "ngraph/graph_util.hpp"
#include "ngraph/op/op.hpp"
namespace ngraph
{
namespace op
{
//brief Computes indices of top k maximum/minimum index along a specified axis for a given tensor
class TopK : public Op
{
public:
enum class SortType
{
// Returned values are not sorted
NONE,
// Sort result based on element indices
SORT_INDICES,
// Sort result based on element values
SORT_VALUES,
};
NGRAPH_API
static const std::string type_name;
const std::string& description() const override { return type_name; }
/// \brief Constructs a TopK operation
TopK();
/// \brief Constructs a TopK operation.
///
/// \param arg The input tensor
/// \param top_k_axis The axis along which to compute top k indices
/// \param index_element_type produce indices. Currently, only int64 or int32 are supported
/// \param k Number of top indices to compute. Compute all indices if k = 0
/// \param compute_max Compute top k max or top k min?
/// \param sort SortType for sorting results, default - NONE
TopK(const Output<Node>& arg,
size_t top_k_axis,
const element::Type& index_element_type,
size_t k = 0,
bool compute_max = true,
SortType sort = SortType::NONE);
/// \brief Constructs a TopK operation.
///
/// \param arg The input tensor
/// \param k Number of top indices to compute. Compute all indices if k = 0
/// \param top_k_axis The axis along which to compute top k indices
/// \param index_element_type produce indices. Currently, only int64 or int32 are supported
/// \param compute_max Compute top k max or top k min?
/// \param sort SortType for sorting results, default - NONE
TopK(const Output<Node>& arg,
const Output<Node>& k,
size_t top_k_axis,
const element::Type& index_element_type,
bool compute_max = true,
SortType sort = SortType::NONE);
void validate_and_infer_types() override;
virtual std::shared_ptr<Node>
copy_with_new_args(const NodeVector& new_args) const override;
size_t get_k() const;
void set_k(size_t k);
size_t get_top_k_axis() const { return m_top_k_axis; }
element::Type get_index_element_type() const { return m_index_element_type; }
bool get_compute_max() const { return m_compute_max; }
SortType get_sort() const { return m_sort; }
protected:
size_t m_top_k_axis{0};
element::Type m_index_element_type;
bool m_compute_max{false};
SortType m_sort;
virtual void generate_adjoints(autodiff::Adjoints& adjoints,
const NodeVector& deltas) override;
};
}
}
| 41.050505 | 105 | 0.569636 | tzerrell |
2328ebb46dea319768cdcc5762ec36836729f5ca | 5,248 | cpp | C++ | ianlmk/cs161b/assignment2/a02.cpp | ianlmk/cs161 | 7a50740d1642ca0111a6d0d076b600744552a066 | [
"MIT"
] | null | null | null | ianlmk/cs161b/assignment2/a02.cpp | ianlmk/cs161 | 7a50740d1642ca0111a6d0d076b600744552a066 | [
"MIT"
] | 1 | 2022-03-25T18:34:47.000Z | 2022-03-25T18:35:23.000Z | ianlmk/cs161b/assignment2/a02.cpp | ianlmk/cs161 | 7a50740d1642ca0111a6d0d076b600744552a066 | [
"MIT"
] | null | null | null | /*
########################################################################################################
# Author: Ian LaMotte-Kerr
# Assignment: Assignment 2
# Date: $(date -j -f "%a %b %d %T %Z %Y" "`date`" "+%s")
# Description: This assignment calculates interest accrual over time.
# Input: principal, time, interestRate, compoundEventCounts
# Output: interestAccrued, totalAccrued
# Sources: https://docs.google.com/document/d/1PGPeT1WWj1Gcxh_8TdMjbiR75LlhEUtsZiQ3vIIbl1w/edit
#########################################################################################################
*/
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
using namespace std;
// prototypes
void welcome();
void menu();
char readOption(string);
void executeOption(char);
double simpleInterest(double,double,double);
double compoundInterest(double,double,double,int);
double input(string);
int main () {
cout << "\033[2J\033[1;1H";
char selection = '\0';
string option = "";
welcome();
do {
menu();
option = "selection: ";
selection = readOption(option);
cout << "\n";
executeOption(selection);
} while (selection == '1' or selection =='2' or selection == '3');
return 0;
}
void welcome() {
// description: clear screen and write "Welcome" to stdout
// input Parameters: n/a
// output to console: "Welcome"
// return: n/a
cout << setw(60) << setfill('#') << "\n";
cout << setw(18) << setfill(' ') << left << "#" << right << "Lets count some MONEY!!" << setw(18) << right << "#" << endl;
cout << setw(60) << setfill('#') << "\n" << setfill (' ');
}
void menu() {
// description: menu print function
// input Parameters: n/a
// output to console: menu text
// return: n/a
const char *arr[3] = {"Calculate Simple Interest","Calculate Compound Interest","Quit"};
cout << "What would you like to do today?" << endl;
for (int i=0; i < 3; i++) {
cout << setw(10) << right << i + 1 << ". " << arr[i] << endl;
}
}
char readOption(string option) {
// description: accepts and validates menu selection
// input Parameters: n/a
// output to console: "select <option>: "
// return: selection of menu char
char selection = '\0';
cout << option;
cin >> selection;
while (selection != '1' and selection != '2' and selection != '3') {
cin.ignore();
cin.clear();
cout << "\nSadly, that is not an acceptable selection. Try again." << endl;
cout << option;
cin >> selection;
}
return selection;
}
void executeOption(char selection) {
// description: executes the math on the selected option
// input Parameters: selection from readOption to determine which math to perform
// output to console:
// return: n/a
double totals = 0.0;
double principal = 0.0;
double rate = 0.0;
double years = 0.0;
int periodCount;
switch (selection) {
case '1':
principal = input("Enter the principal amount in dollars: $");
rate = input("Enter the interest rate (ex, for 3.75\% enter: 3.75): ");
rate = rate / 100;
years = input("Enter the number of years: ");
totals = simpleInterest(principal,years,rate);
break;
case '2':
principal = input("Enter the principal amount in dollars: $");
rate = input("Enter the interest rate (ex, for 3.75% enter: 3.75): ");
rate = rate / 100;
years = input("Enter the number of years: ");
periodCount = input("Enter the number of times to compound: ");
totals = compoundInterest(principal,years,rate,periodCount);
break;
case '3':
cout << "Thanks for banking with us. Come again!" << endl;
cout << setw(60) << setfill('#') << "\n";
exit(0);
default:
break;
}
cout << "\nInterest Accrued: " << totals - principal << endl;
cout << "Total Accrued Amount (principal + interest): " << totals;
cout << "\n" << setw(60) << setfill('-') << "\n" << setfill(' ') << "\n";
}
double input(string saySomething) {
// description: double input acceptance and type check function > 0
// input Parameters: string: description of var to accept and check
// output to console: n/a
// return: double: greater than zero.
double var;
do {
cin.clear();
cin.ignore();
cout << saySomething;
cin >> var;
if (var < 0) {
cout << "you entered a value less than zero. Please retry." << endl;
}
} while (!cin or var < 0);
return var;
}
double simpleInterest(double principal, double years, double rate) {
// description: accept var values and calculates simple interest, then returns the calculation
// input Parameters: doubles-[principal, rate, years]
// output to console: n/a
// return: total: calculated interest + principal
double total = 0.0;
total = principal * (1 + (rate * years));
return total;
}
double compoundInterest(double principal, double years, double rate, int periodCount) {
double total = 0.0;
total = principal * pow((1 + (rate / periodCount)),(periodCount * years));
return total;
}
| 31.42515 | 124 | 0.577363 | ianlmk |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.