hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d7b5f2d8d3b45a6788476aad0e8defa2f6765ed7 | 6,231 | cc | C++ | dense_map/geometry_mapper/tools/get_depth_data_from_mesh.cc | trey0/isaac | 2f8223458f79a9b9fc1ac74d415c94041c19c094 | [
"Apache-2.0"
] | 19 | 2021-11-18T19:29:16.000Z | 2022-02-23T01:55:51.000Z | dense_map/geometry_mapper/tools/get_depth_data_from_mesh.cc | trey0/isaac | 2f8223458f79a9b9fc1ac74d415c94041c19c094 | [
"Apache-2.0"
] | 13 | 2021-11-30T17:14:46.000Z | 2022-03-22T21:38:33.000Z | dense_map/geometry_mapper/tools/get_depth_data_from_mesh.cc | trey0/isaac | 2f8223458f79a9b9fc1ac74d415c94041c19c094 | [
"Apache-2.0"
] | 6 | 2021-12-03T02:38:21.000Z | 2022-02-23T01:52:03.000Z | /* Copyright (c) 2017, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
*
* All rights reserved.
*
* The Astrobee platform is licensed under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include <depth_from_mesh_utils.h>
#include <ff_common/init.h>
#include <localization_common/utilities.h>
#include <msg_conversions/msg_conversions.h>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <glog/logging.h>
#include <string>
namespace dm = dense_map;
namespace fs = boost::filesystem;
namespace po = boost::program_options;
namespace lc = localization_common;
namespace mc = msg_conversions;
int main(int argc, char** argv) {
std::string robot_config_file;
std::string world;
std::string sensor_frame;
std::string output_file;
po::options_description desc(
"Adds depth data to desired points at provided timestamps. Uses a provided mesh and sequence of groundtruth poses "
"to obtain the depth data.");
desc.add_options()("help,h", "produce help message")(
"timestamps-file", po::value<std::string>()->required(),
"File containing a set of timestamps to generate depth data for. Each timestamp should be on a newline.")(
"sensor-rays-file", po::value<std::string>()->required(),
"File containing a set of rays from the sensor frame to generate depth data for. Each point has an assumed x "
"offset of 1 meter from the sensor, so only y z pairs are required. Each point pair should be on a newline.")(
"groundtruth-directory", po::value<std::string>()->required(),
"Directory containing groundtruth poses with timestamps as filenames.")(
"mesh", po::value<std::string>()->required(), "Mesh used to provide depth data.")(
"config-path,c", po::value<std::string>()->required(), "Path to astrobee config directory.")(
"robot-config-file,r", po::value<std::string>(&robot_config_file)->default_value("config/robots/bumble.config"),
"Robot config file")("world,w", po::value<std::string>(&world)->default_value("iss"), "World name")(
"output-file,o", po::value<std::string>(&output_file)->default_value("depths.csv"),
"Output file containing timestamp, depth, x, y values on each line. Timestamps for which depth data was not "
"successfully loaded are not included in the output.")
// TODO(rsoussan): Add soundsee sensor trafo to astrobee configs!
("sensor-frame,s", po::value<std::string>(&sensor_frame)->default_value("soundsee"),
"Sensor frame to generate depth data in.");
po::positional_options_description p;
p.add("timestamps-file", 1);
p.add("sensor-rays-file", 1);
p.add("groundtruth-directory", 1);
p.add("mesh", 1);
p.add("config-path", 1);
po::variables_map vm;
try {
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
if (vm.count("help") || (argc <= 1)) {
std::cout << desc << "\n";
return 1;
}
po::notify(vm);
} catch (std::exception& e) {
std::cerr << "Error: " << e.what() << "\n";
return 1;
}
const std::string timestamps_file = vm["timestamps-file"].as<std::string>();
const std::string sensor_rays_file = vm["sensor-rays-file"].as<std::string>();
const std::string groundtruth_directory = vm["groundtruth-directory"].as<std::string>();
const std::string mesh_file = vm["mesh"].as<std::string>();
const std::string config_path = vm["config-path"].as<std::string>();
// Only pass program name to free flyer so that boost command line options
// are ignored when parsing gflags.
int ff_argc = 1;
ff_common::InitFreeFlyerApplication(&ff_argc, &argv);
if (!fs::exists(timestamps_file)) {
LOG(FATAL) << "Timestamps file " << timestamps_file << " not found.";
}
if (!fs::exists(sensor_rays_file)) {
LOG(FATAL) << "Sensor rays file " << sensor_rays_file << " not found.";
}
if (!fs::exists(groundtruth_directory)) {
LOG(FATAL) << "Groundtruth directory " << groundtruth_directory << " not found.";
}
if (!fs::exists(mesh_file)) {
LOG(FATAL) << "Mesh " << mesh_file << " not found.";
}
lc::SetEnvironmentConfigs(config_path, world, robot_config_file);
config_reader::ConfigReader config;
config.AddFile("geometry.config");
if (!config.ReadFiles()) {
LOG(FATAL) << "Failed to read config files.";
}
// Needed later to write results in correct format
int mesh_rows;
const auto sensor_t_rays = dm::LoadSensorRays(sensor_rays_file, mesh_rows);
const auto query_timestamps = dm::LoadTimestamps(timestamps_file);
const auto body_T_sensor = mc::LoadEigenTransform(config, sensor_frame + "_transform");
std::vector<std::string> groundtruth_sensor_frames{"nav_cam", "sci_cam", "haz_cam"};
// TODO(rsoussan): Add option to pass these as args?
std::vector<double> timestamp_offsets{0, 0, 0};
std::vector<Eigen::Isometry3d> body_T_groundtruth_sensor_vec;
for (const auto& sensor_frame : groundtruth_sensor_frames) {
body_T_groundtruth_sensor_vec.emplace_back(mc::LoadEigenTransform(config, sensor_frame + "_transform"));
}
const auto groundtruth_pose_interpolater = dm::MakePoseInterpolater(
groundtruth_directory, body_T_sensor, groundtruth_sensor_frames, body_T_groundtruth_sensor_vec, timestamp_offsets);
const auto mesh_tree = dm::LoadMeshTree(mesh_file);
const auto depths = dm::GetDepthData(query_timestamps, sensor_t_rays, groundtruth_pose_interpolater, *mesh_tree);
int depth_count = 0;
for (const auto& depth : depths) {
if (depth) ++depth_count;
}
LOG(INFO) << "Got " << depth_count << " of " << depths.size() << " depths successfully.";
dm::SaveDepthData(query_timestamps, sensor_t_rays, depths, output_file, mesh_rows);
}
| 45.481752 | 120 | 0.708714 | [
"mesh",
"geometry",
"vector"
] |
d7b74f141dd2ec973af13e29f04b04034ca43b81 | 2,004 | hpp | C++ | src/hook/impl.hpp | geode-sdk/core | 25dc195eafd7169ef9696bae081ff38c7bb2d47f | [
"MIT"
] | 1 | 2022-01-21T08:44:41.000Z | 2022-01-21T08:44:41.000Z | src/hook/impl.hpp | geode-sdk/core | 25dc195eafd7169ef9696bae081ff38c7bb2d47f | [
"MIT"
] | 1 | 2022-01-23T17:08:28.000Z | 2022-01-23T17:08:40.000Z | src/hook/impl.hpp | geode-sdk/core | 25dc195eafd7169ef9696bae081ff38c7bb2d47f | [
"MIT"
] | null | null | null | #ifndef GEODE_CORE_HOOK_IMPL_HPP
#define GEODE_CORE_HOOK_IMPL_HPP
#include <hook.hpp>
#include <unordered_map>
#include <vector>
#if defined(GEODE_IS_WINDOWS)
#include "windows.hpp"
#elif defined(GEODE_IS_IOS)
#include "ios.hpp"
#elif defined(GEODE_IS_MACOS)
#include "macos.hpp"
#endif
namespace geode::core::hook {
class HookManager {
private:
struct HookChain;
struct CallFrame {
const void* address = nullptr;
HookChain* parent = nullptr;
char original_bytes[sizeof(TargetPlatform::trap())] = { 0 };
};
struct HookChain {
const void* address = nullptr;
std::vector<const void*> detours = {};
std::vector<CallFrame*> frames = {};
char original_bytes[sizeof(TargetPlatform::trap())] = { 0 };
};
struct Handle {
const void* address;
const void* detour;
};
private:
static inline auto& all_hooks() {
static std::unordered_map<const void*, HookChain> ret;
return ret;
}
static inline auto& all_frames() {
static std::unordered_map<const void*, CallFrame> ret;
return ret;
}
private:
/* these don't check char buffer bounds. it should have sizeof(trap) size.
* pass nullptr to add_trap if you don't want to save the old bytes into a buffer.
*/
static void add_trap(const void* address, char buffer[]);
static void remove_trap(const void* address, char buffer[]);
static bool find_in_hooks(Exception& info);
static bool find_in_frames(Exception& info);
public:
// returns true if handled, false if not.
static bool handler(Exception& info);
static hook::Handle GEODE_CALL add_hook(const void* address, const void* detour);
static bool GEODE_CALL remove_hook(hook::Handle handle);
};
}
#endif /* GEODE_CORE_HOOK_IMPL_HPP */
| 28.225352 | 90 | 0.610778 | [
"vector"
] |
d7bb407f42694a4d6463c7580862af37a51e84c6 | 2,923 | cc | C++ | chrome/common/privacy_budget/field_trial_param_conversions.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | chrome/common/privacy_budget/field_trial_param_conversions.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | chrome/common/privacy_budget/field_trial_param_conversions.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/privacy_budget/field_trial_param_conversions.h"
#include <algorithm>
#include <utility>
#include "base/ranges/algorithm.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "third_party/blink/public/common/privacy_budget/identifiable_surface.h"
namespace privacy_budget_internal {
bool DecodeIdentifiabilityType(const base::StringPiece s,
blink::IdentifiableSurface* out) {
uint64_t hash = 0;
if (!base::StringToUint64(s, &hash))
return false;
*out = blink::IdentifiableSurface::FromMetricHash(hash);
return true;
}
bool DecodeIdentifiabilityType(const base::StringPiece s,
blink::IdentifiableSurface::Type* out) {
uint64_t hash = 0;
if (!base::StringToUint64(s, &hash))
return false;
if ((hash & blink::IdentifiableSurface::kTypeMask) != hash)
return false;
*out = static_cast<blink::IdentifiableSurface::Type>(hash);
return true;
}
bool DecodeIdentifiabilityType(const base::StringPiece s, int* out) {
return base::StringToInt(s, out);
}
bool DecodeIdentifiabilityType(const base::StringPiece s, unsigned int* out) {
return base::StringToUint(s, out);
}
bool DecodeIdentifiabilityType(const base::StringPiece s, double* out) {
return base::StringToDouble(s, out);
}
bool DecodeIdentifiabilityType(const base::StringPiece s,
std::vector<blink::IdentifiableSurface>* out) {
*out = DecodeIdentifiabilityFieldTrialParam<
std::vector<blink::IdentifiableSurface>, ';'>(s);
return !out->empty();
}
std::string EncodeIdentifiabilityType(const blink::IdentifiableSurface& s) {
return base::NumberToString(s.ToUkmMetricHash());
}
std::string EncodeIdentifiabilityType(
const blink::IdentifiableSurface::Type& t) {
return base::NumberToString(static_cast<uint64_t>(t));
}
std::string EncodeIdentifiabilityType(
const std::pair<const blink::IdentifiableSurface, int>& v) {
return base::StrCat({EncodeIdentifiabilityType(v.first), ";",
base::NumberToString(v.second)});
}
std::string EncodeIdentifiabilityType(const unsigned int& v) {
return base::NumberToString(v);
}
std::string EncodeIdentifiabilityType(const double& value) {
return base::NumberToString(value);
}
std::string EncodeIdentifiabilityType(
const std::vector<blink::IdentifiableSurface>& value) {
std::vector<std::string> parts;
base::ranges::transform(
value, std::back_inserter(parts),
[](const blink::IdentifiableSurface v) -> std::string {
return EncodeIdentifiabilityType(v);
});
return base::JoinString(parts, ";");
}
} // namespace privacy_budget_internal
| 32.120879 | 80 | 0.716387 | [
"vector",
"transform"
] |
d7bcd4481744854b1fde6ec69378ea33da1e4006 | 1,305 | cpp | C++ | motivateApp/motivateApp/src/model.cpp | RuolinZheng08/playground | 0c933c9f3d1846496c455de56225cc0afb0e94df | [
"MIT"
] | 1 | 2021-01-18T05:01:03.000Z | 2021-01-18T05:01:03.000Z | motivateApp/motivateApp/src/model.cpp | RuolinZheng08/playground | 0c933c9f3d1846496c455de56225cc0afb0e94df | [
"MIT"
] | null | null | null | motivateApp/motivateApp/src/model.cpp | RuolinZheng08/playground | 0c933c9f3d1846496c455de56225cc0afb0e94df | [
"MIT"
] | null | null | null | //
// model.cpp
// motivateApp
//
// Created by Ruolin Zheng on 2019/8/23.
// Copyright © 2019 Ruolin Zheng. All rights reserved.
//
#include "model.hpp"
MyModel::MyModel() {
std::ifstream in;
in.open(PATH);
if (!in) {
// create file
std::ofstream out;
out.open(PATH);
out.close();
} else {
// read into mRecordMap
std::string str;
const char *delim = ",";
char *tok;
while (std::getline(in, str)) {
// parse time,name,numTok
tok = strtok(const_cast<char*>(str.c_str()), delim);
time_t seconds = atol(tok);
tok = strtok(NULL, delim);
std::string name = std::string(tok);
tok = strtok(NULL, delim);
int numTok = atoi(tok);
// construct Record
std::string time = timeToDate(seconds);
Record record = Record(seconds, name, numTok);
mRecordMap[time].push_back(record);
}
in.close();
}
}
void MyModel::addRecord(std::string date, Record record) {
std::ofstream out;
out.open(PATH, std::ios_base::app);
mRecordMap[date].push_back(record);
out << record.mTime << "," << record.mName << "," << record.mNumTok << "\n";
out.close();
}
| 26.632653 | 80 | 0.529502 | [
"model"
] |
d7bf9e87d92783911820061583f212b151fa2df5 | 3,517 | hpp | C++ | system.hpp | lichang98/raft_demo | 337bc56d04a4ee24509be7eba02c26ef4e990b55 | [
"Apache-2.0"
] | null | null | null | system.hpp | lichang98/raft_demo | 337bc56d04a4ee24509be7eba02c26ef4e990b55 | [
"Apache-2.0"
] | null | null | null | system.hpp | lichang98/raft_demo | 337bc56d04a4ee24509be7eba02c26ef4e990b55 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <iostream>
#include <fstream>
#include <memory>
#include "json.hpp"
#include "server.hpp"
#include "router.hpp"
/*
* this file contains system configures
*/
namespace my_system
{
struct config
{
int32_t num_servers;
std::vector<server::ServerEnt> servers;
friend std::ostream& operator<<(std::ostream& out, config& obj)
{
out << "num servers=" << obj.num_servers << ", server configs are:\n";
for(const server::ServerEnt& server : obj.servers)
{
out << "idx= " <<server.server_idx << "\n";
}
return out;
}
};
static config system_config;
static my_router::MyRouter* opaque_router;
class MySys
{
public:
static void sys_start()
{
LOG(INFO) << "start each server ......";
for(server::ServerEnt& serv: system_config.servers)
{
serv.start();
}
}
static void shutdown()
{
opaque_router->is_sys_running=false;
for(server::ServerEnt& serv: system_config.servers)
{
serv.is_server_running=false;
}
}
static void parse_json_config(const char* file)
{
LOG(INFO) << "system parse json configure";
std::ifstream f;
f.open(file,std::ifstream::in);
f.seekg(0,f.end);
int64_t file_size=f.tellg();
char* buf = new char[file_size];
f.seekg(0,f.beg);
f.read(buf,file_size);
nlohmann::json config=nlohmann::json::parse(buf);
system_config.num_servers = (int32_t)config.value("num_servers",0);
int32_t router_port = (int32_t)(config["router_info"].value("port",0));
std::string router_ip = (std::string)(config["router_info"].value("ip_addr",""));
LOG(INFO) << "num_servers=" << system_config.num_servers << ", create opaque router";
opaque_router = new my_router::MyRouter(router_port, router_ip.c_str());
std::vector<int32_t> serv_idxs;
for(nlohmann::json::basic_json::reference ele : config["server_info"])
{
int32_t idx = (int32_t)(ele.value("id",0));
serv_idxs.push_back(idx);
std::string ip_addr = (std::string)(ele.value("ip_addr",""));
int32_t port=(int32_t)(ele.value("port",0));
LOG(INFO) << "create new server instance, idx=" << idx << ", ip=" <<ip_addr << ", port="
<< port;
server::ServerEnt new_server(\
idx,(char*)ip_addr.c_str(),port,\
router_ip.c_str(),router_port);
system_config.servers.emplace_back(new_server);
}
LOG(INFO) << "server info load finish";
// initial each server's match index
for(server::ServerEnt& sv: system_config.servers)
{
for(int32_t idx : serv_idxs)
{
if(idx == sv.server_idx)
continue;
sv.match_index.insert(std::make_pair(idx,-1));
}
}
server::ServerEnt::num_majority=(system_config.num_servers / 2)+(system_config.num_servers % 2);
server::ServerEnt::num_servers=system_config.num_servers;
}
};
}; // namespace system
| 34.480392 | 108 | 0.526016 | [
"vector"
] |
d7c0cd55336fc9a5124b546f11846e489c7353e8 | 21,224 | cpp | C++ | multiview/multiview_cpp/src/perceive/io/perceive-assets.cpp | prcvlabs/multiview | 1a03e14855292967ffb0c0ec7fff855c5abbc9d2 | [
"Apache-2.0"
] | 5 | 2021-09-03T23:12:08.000Z | 2022-03-04T21:43:32.000Z | multiview/multiview_cpp/src/perceive/io/perceive-assets.cpp | prcvlabs/multiview | 1a03e14855292967ffb0c0ec7fff855c5abbc9d2 | [
"Apache-2.0"
] | 3 | 2021-09-08T02:57:46.000Z | 2022-02-26T05:33:02.000Z | multiview/multiview_cpp/src/perceive/io/perceive-assets.cpp | prcvlabs/multiview | 1a03e14855292967ffb0c0ec7fff855c5abbc9d2 | [
"Apache-2.0"
] | 2 | 2021-09-26T03:14:40.000Z | 2022-01-26T06:42:52.000Z |
#include <boost/endian/conversion.hpp>
#include "ieee754-packing.hpp"
#include "perceive-assets.hpp"
#include "stdinc.hpp"
#include "perceive/calibration/aruco-cube.hpp"
#include "perceive/calibration/plane-set/phase-plane-data.hpp"
#include "perceive/cost-functions/classifier/classifier.hpp"
#include "perceive/geometry/projective/binocular-camera.hpp"
#include "perceive/geometry/projective/caching-undistort-inverse.hpp"
#include "perceive/geometry/projective/polynomial-model.hpp"
#include "perceive/graphics/colour-set.hpp"
#include "perceive/graphics/image-container.hpp"
#include "perceive/graphics/sprite.hpp"
#include "perceive/io/lazy-s3.hpp"
#include "perceive/io/s3.hpp"
#include "perceive/scene/aruco-result-info.hpp"
#include "perceive/scene/scene-description-info.hpp"
#include "perceive/utils/file-system.hpp"
#include "perceive/utils/md5.hpp"
namespace perceive
{
static std::once_flag init_perceive_files_flag;
static DataSource source_ = DataSource::LAZY_S3;
static string s3_bucket_ = ""s;
static string mv_data_dir_ = ""s;
// ------------------------------------------------------------------ Initialize
static void run_once_init_perceive_files()
{
bool has_error = false;
s3_bucket_ = multiview_asset_s3_bucket();
mv_data_dir_ = multiview_asset_dir();
// ------------------------ Data Source
source_ = DataSource::LAZY_S3;
const string value = string_to_uppercase(multiview_asset_store());
if(value == "S3"s) {
source_ = DataSource::S3;
} else if(value == "MULTIVIEW_ASSET_DIR"s) {
source_ = DataSource::MULTIVIEW_ASSET_DIR;
if(mv_data_dir_.empty() or !is_directory(mv_data_dir_)) {
LOG_ERR(
format("env variable 'MULTIVIEW_ASSET_DIR' set to '{}'; however, "
"this directory was not found.",
mv_data_dir_));
has_error = true;
} else {
for(auto ftype : k_filetypes) {
auto path
= format("{}/{}", mv_data_dir_, file_type_relative_path(ftype));
if(!is_directory(path)) {
INFO(format("creating MULTIVIEW_ASSET_DIR '{}'", path));
mkdir_p(path);
}
}
}
} else if(value == "LAZY_S3"s) {
source_ = DataSource::LAZY_S3;
} else {
LOG_ERR(
format("env variable 'MULTIVIEW_STORE' set to an invalid value '{}'. "
"Note that if you want to set it to a path, it "
"must be an absolute path, i.e., beginning with, "
"'/'.",
value));
has_error = true;
}
if(has_error) FATAL("aborting");
}
void init_perceive_files()
{
std::call_once(init_perceive_files_flag, run_once_init_perceive_files);
}
static void ensure_init() { init_perceive_files(); }
// ----------------------------------------------------------------- Data Source
DataSource default_data_source() noexcept
{
ensure_init();
return source_;
}
void set_default_data_source(DataSource value) { ensure_init(); }
// ------------------------------------------------------------------ File Types
const string& file_type_relative_path(AssetType type) noexcept
{
static string cad_model_relpath = "calibration/cad-models"s;
static string aruco_relpath = "calibration/aruco-results"s;
static string aruco_cubes_relpath = "calibration/aruco-cubes"s;
static string cache_file_relpath = "cached-data"s;
static string distortion_model_relpath = "calibration/sensors"s;
static string bcam_info_relpath = "calibration/binocular"s;
static string scene_still_relpath = "calibration/stills"s;
static string phase_plane_data_relpath = "calibration/plane-data"s;
static string classifier_relpath = "calibration/classifiers"s;
static string scene_bg_image_relpath = "calibration/backgrounds"s;
static string scene_disparity_relpath = "calibration/disparities"s;
static string scene_desc_relpath = "calibration/scenes"s;
switch(type) {
case AssetType::CAD_MODEL: return cad_model_relpath;
case AssetType::ARUCO_RESULT: return aruco_relpath;
case AssetType::ARUCO_CUBE: return aruco_cubes_relpath;
case AssetType::CACHE_FILE: return cache_file_relpath;
case AssetType::DISTORTION_MODEL: return distortion_model_relpath;
case AssetType::BCAM_INFO: return bcam_info_relpath;
case AssetType::SCENE_STILL: return scene_still_relpath;
case AssetType::PHASE_PLANE_DATA: return phase_plane_data_relpath;
case AssetType::CLASSIFIER: return classifier_relpath;
case AssetType::SCENE_BACKGROUND_IMAGE: return scene_bg_image_relpath;
case AssetType::SCENE_DISPARITY: return scene_disparity_relpath;
case AssetType::SCENE_DESCRIPTION: return scene_desc_relpath;
}
}
const string& file_type_extension(AssetType type) noexcept
{
static string cad_model_ext = ""s;
static string aruco_ext = ".json"s;
static string aruco_cubes_ext = ".json"s;
static string cache_file_ext = ".mdata"s;
static string distortion_model_ext = ".json"s;
static string bcam_info_ext = ".json"s;
static string scene_still_ext = ".ppm"s;
static string phase_plane_data_ext = ".json"s;
static string classifier_ext = ".ml.gz"s;
static string scene_bg_image_ext = ".png"s;
static string scene_disparity_ext = ".float-image"s;
static string scene_desc_ext = ".json"s;
switch(type) {
case AssetType::CAD_MODEL: return cad_model_ext;
case AssetType::ARUCO_RESULT: return aruco_ext;
case AssetType::ARUCO_CUBE: return aruco_cubes_ext;
case AssetType::CACHE_FILE: return cache_file_ext;
case AssetType::DISTORTION_MODEL: return distortion_model_ext;
case AssetType::BCAM_INFO: return bcam_info_ext;
case AssetType::PHASE_PLANE_DATA: return phase_plane_data_ext;
case AssetType::SCENE_STILL: return scene_still_ext;
case AssetType::CLASSIFIER: return classifier_ext;
case AssetType::SCENE_BACKGROUND_IMAGE: return scene_bg_image_ext;
case AssetType::SCENE_DISPARITY: return scene_disparity_ext;
case AssetType::SCENE_DESCRIPTION: return scene_desc_ext;
}
}
// ----------------------------------------------------------------- Resolve Key
static string
resolve_key_(AssetType type, const string& key, DataSource source) noexcept
{
if(source == DataSource::DEFAULT) source = source_;
Expects(source != DataSource::DEFAULT);
const auto& path = file_type_relative_path(type);
auto ext = file_type_extension(type);
switch(source) {
case DataSource::DEFAULT: FATAL("logic error");
case DataSource::LAZY_S3:
case DataSource::S3: return format("{}/{}/{}{}", s3_bucket_, path, key, ext);
case DataSource::MULTIVIEW_ASSET_DIR:
return format("{}/{}/{}{}", mv_data_dir_, path, key, ext);
}
return ""s;
}
string
resolve_key(AssetType type, const string& key, DataSource source) noexcept
{
ensure_init();
return resolve_key_(type, key, source);
}
// ----------------------------------------------------------- Data Source Fetch
template<typename T>
static string data_source_fetchT_(T& data,
AssetType type,
const string& key,
DataSource source) noexcept(false)
{
if(source == DataSource::DEFAULT) source = source_;
Expects(source != DataSource::DEFAULT);
string path = ""s;
switch(source) {
case DataSource::DEFAULT: FATAL("logic error"); break;
case DataSource::S3:
TRACE(format("s3 load {}", path));
path = resolve_key_(type, key, source);
s3_load(path, data);
break;
case DataSource::MULTIVIEW_ASSET_DIR:
TRACE(format("load {}", path));
path = resolve_key_(type, key, source);
file_get_contents(path, data);
break;
case DataSource::LAZY_S3:
path = resolve_key_(type, key, source);
TRACE(format("lazy-load {}", path));
lazy_s3_load(path, data);
break;
}
{
MD5 md5;
md5.update(&data[0], unsigned(data.size()));
const string ref_digest = md5.finalize().hexdigest();
const string md5_digest = extract_md5_hexdigest(path);
// if(!k_is_testcase_build) INFO(format("fetch {} {}", path,
// ref_digest));
if(!md5_digest.empty() and md5_digest != ref_digest) {
data.clear();
throw std::runtime_error(
format("failed to load asset '{}', because md5 "
"check failed. Calculated digest was: {}",
path,
ref_digest));
}
}
return path;
}
void data_source_fetch(string& data,
AssetType type,
const string& key,
DataSource source) noexcept(false)
{
ensure_init();
data_source_fetchT_(data, type, key, source);
}
void data_source_fetch(vector<char>& data,
AssetType type,
const string& key,
DataSource source) noexcept(false)
{
ensure_init();
data_source_fetchT_(data, type, key, source);
}
// ----------------------------------------------------------- Data Source
// Store
template<typename T>
static void data_source_storeT_(const T& data,
AssetType type,
const string& key,
DataSource source)
{
if(source == DataSource::DEFAULT) source = source_;
Expects(source != DataSource::DEFAULT);
auto path = resolve_key_(type, key, source);
{
const string md5_digest = extract_md5_hexdigest(path);
if(!md5_digest.empty()) {
MD5 md5;
md5.update(&data[0], unsigned(data.size()));
const string ref_digest = md5.finalize().hexdigest();
if(md5_digest != ref_digest) {
throw std::runtime_error(
format("failed to store asset '{}', because md5 "
"check failed. Calculated digest was: {}",
ref_digest));
}
}
}
if(source == DataSource::S3) {
s3_store(path, data);
return;
} else if(source == DataSource::LAZY_S3) {
lazy_s3_store(path, data);
return;
}
file_put_contents(path, data);
}
void data_source_store(const string& data,
AssetType type,
const string& key,
DataSource source)
{
ensure_init();
data_source_storeT_(data, type, key, source);
}
void data_source_store(const vector<char>& data,
AssetType type,
const string& key,
DataSource source)
{
ensure_init();
data_source_storeT_(data, type, key, source);
}
// ---------------------------------------------------------------------- Exists
static bool
data_source_exists_(AssetType type, const string& key, DataSource source)
{
if(source == DataSource::DEFAULT) source = source_;
Expects(source != DataSource::DEFAULT);
auto path = resolve_key(type, key, source);
{ // Handle S3
if(source == DataSource::S3) {
const auto ret = s3_exists(path);
return ret;
}
if(source == DataSource::LAZY_S3) {
const auto ret = lazy_s3_exists(path) != LazyExists::NOWHERE;
return ret;
}
}
return is_regular_file(path);
}
bool data_source_exists(AssetType type, const string& key, DataSource source)
{
ensure_init();
return data_source_exists_(type, key, source);
}
// ------------------------------------------------------------- DistortionModel
void fetch(DistortionModel& model,
string key,
DataSource source) noexcept(false)
{
ensure_init();
string data;
data_source_fetch(data, AssetType::DISTORTION_MODEL, key, source);
read(model, data);
}
void store(const DistortionModel& model,
string key,
DataSource source) noexcept(false)
{
ensure_init();
string data;
write(model, data);
data_source_store(data, AssetType::DISTORTION_MODEL, key, source);
}
// --------------------------------------------------- Caching Undistort Inverse
void fetch(CachingUndistortInverse& data,
string key,
DataSource source) noexcept(false)
{
ensure_init();
if(source == DataSource::DEFAULT) source = source_;
if(source != DataSource::S3 and source != DataSource::LAZY_S3) {
auto fname = resolve_key(AssetType::CACHE_FILE, key, source);
// INFO(format("Loading cache-undistort file {} {}",
// fname,
// md5(file_get_contents(fname))));
load(data, fname);
} else {
vector<char> buffer;
data_source_fetch(buffer, AssetType::CACHE_FILE, key, source);
FILE* fp = fmemopen(&buffer[0], buffer.size(), "rb");
try {
read(data, fp);
fclose(fp);
} catch(std::exception& e) {
LOG_ERR(format("failed to read cache-undistort file: {}", e.what()));
if(fp != nullptr) fclose(fp);
throw e;
}
}
}
void store(const CachingUndistortInverse& data,
string key,
DataSource source) noexcept(false)
{
ensure_init();
if(source == DataSource::DEFAULT) source = source_;
if(source != DataSource::S3 and source != DataSource::LAZY_S3) {
auto fname = resolve_key(AssetType::CACHE_FILE, key, source);
save(data, fname);
INFO(format("Stored cache-undistort file {} {}",
fname,
md5(file_get_contents(fname))));
} else {
FILE* fp = nullptr;
try {
vector<char> buffer;
fp = tmpfile();
write(data, fp);
buffer.resize(size_t(ftell(fp)));
fseek(fp, 0, SEEK_SET);
if(buffer.size() != fread(&buffer[0], 1, buffer.size(), fp))
throw std::runtime_error("failed to write file");
fclose(fp);
data_source_store(buffer, AssetType::CACHE_FILE, key, source);
} catch(std::exception& e) {
if(fp != nullptr) fclose(fp);
throw e;
}
}
}
// ------------------------------------------------------- Binocular Camera Info
void fetch(BinocularCameraInfo& out,
string key,
DataSource source) noexcept(false)
{
const auto s0 = time_thunk([&]() { ensure_init(); });
string data;
const auto s1 = time_thunk(
[&]() { data_source_fetch(data, AssetType::BCAM_INFO, key, source); });
const auto s2 = time_thunk([&]() { read(out, data); });
if(false) {
TRACE(format(
"fetch(\"{}\") timing: init={:6.3f}s, fetch={:6.3f}s, read={:6.3f}s",
key,
s0,
s1,
s2));
}
}
void store(const BinocularCameraInfo& in,
string key,
DataSource source) noexcept(false)
{
ensure_init();
string data;
write(in, data);
data_source_store(data, AssetType::BCAM_INFO, key, source);
}
// ------------------------------------------------------- Scene Descrption Info
void fetch(SceneDescriptionInfo& out,
string key,
DataSource source) noexcept(false)
{
ensure_init();
string data;
data_source_fetch(data, AssetType::SCENE_DESCRIPTION, key, source);
read(out, data);
}
void store(const SceneDescriptionInfo& in,
string key,
DataSource source) noexcept(false)
{
ensure_init();
string data;
write(in, data);
data_source_store(data, AssetType::SCENE_DESCRIPTION, key, source);
}
// ----------------------------------------------------------- Aruco Result Info
void fetch(ArucoResultInfo& out, string key, DataSource source) noexcept(false)
{
ensure_init();
string data;
data_source_fetch(data, AssetType::ARUCO_RESULT, key, source);
read(out, data);
}
void store(const ArucoResultInfo& in,
string key,
DataSource source) noexcept(false)
{
ensure_init();
string data;
write(in, data);
data_source_store(data, AssetType::ARUCO_RESULT, key, source);
}
// ------------------------------------------------------------------ Aruco Cube
void fetch(ArucoCube& out, string key, DataSource source) noexcept(false)
{
ensure_init();
string data;
data_source_fetch(data, AssetType::ARUCO_CUBE, key, source);
read(out, data);
}
void store(const ArucoCube& in, string key, DataSource source) noexcept(false)
{
ensure_init();
string data;
write(in, data);
data_source_store(data, AssetType::ARUCO_CUBE, key, source);
}
// ---------------------------------------------------------------------- Sprite
void fetch(Sprite& out, string key, DataSource source) noexcept(false)
{
ensure_init();
string data;
data_source_fetch(data, AssetType::CAD_MODEL, key, source);
read(out, data);
}
// ----------------------------------------------------------------- Scene Still
void fetch(ARGBImage& out, string key, DataSource source) noexcept(false)
{
ensure_init();
string data;
data_source_fetch(data, AssetType::SCENE_STILL, key, source);
string magic;
int width = 0, height = 0, max_val = 0;
std::stringstream ss(data);
ss >> magic >> width >> height >> max_val;
// INFO(
// format("magin = {}, wh = {}x{}, val={}", magic, width,
// height, max_val));
if(ss.peek() != '\n')
throw std::runtime_error(
"expected newline character at end of PPM header");
ss.get();
out.resize(width, height);
int r = 0, g = 0, b = 0;
for(auto y = 0u; y < out.height; ++y) {
for(auto x = 0u; x < out.width; ++x) {
r = ss.get();
g = ss.get();
b = ss.get();
out(x, y) = make_colour(r, g, b);
}
}
}
void store(const ARGBImage& in, string key, DataSource source) noexcept(false)
{
ensure_init();
std::stringstream ss("");
ss << format("P6\n{} {}\n255\n", in.width, in.height);
char r = 0, g = 0, b = 0;
for(auto y = 0u; y < in.height; ++y) {
for(auto x = 0u; x < in.width; ++x) {
auto k = in(x, y);
r = char(red(k));
g = char(green(k));
b = char(blue(k));
ss.write(&r, 1);
ss.write(&g, 1);
ss.write(&b, 1);
}
}
data_source_store(ss.str(), AssetType::SCENE_STILL, key, source);
}
// ------------------------------------------------------------- Scene Disparity
void fetch(FloatImage& out, string key, DataSource source) noexcept(false)
{
ensure_init();
string data;
data_source_fetch(data, AssetType::SCENE_DISPARITY, key, source);
string magic;
int width = 0, height = 0;
std::stringstream ss(data);
ss >> magic >> width >> height;
// INFO(
// format("magin = {}, wh = {}x{}, val={}", magic, width,
// height, max_val));
if(ss.peek() != '\n')
throw std::runtime_error(
"expected newline character at end of FloatImage header");
ss.get();
out.resize(width, height);
for(auto y = 0u; y < out.height; ++y) {
for(auto x = 0u; x < out.width; ++x) {
uint32_t v = 0;
ss.read(reinterpret_cast<char*>(&v), sizeof(v));
out(x, y) = unpack_f32(boost::endian::little_to_native(v));
}
}
}
void store(const FloatImage& in, string key, DataSource source) noexcept(false)
{
ensure_init();
std::stringstream ss("");
ss << format("FI\n{} {}\n", in.width, in.height);
for(auto y = 0u; y < in.height; ++y) {
for(auto x = 0u; x < in.width; ++x) {
uint32_t v = boost::endian::native_to_little(pack_f32(in(x, y)));
ss.write(reinterpret_cast<char*>(&v), sizeof(v));
}
}
data_source_store(ss.str(), AssetType::SCENE_DISPARITY, key, source);
}
// ------------------------------------------------------------ Phase Plane Data
void fetch(calibration::PhasePlaneData& out,
string key,
DataSource source) noexcept(false)
{
ensure_init();
string data;
data_source_fetch(data, AssetType::PHASE_PLANE_DATA, key, source);
read(out, data);
}
void store(const calibration::PhasePlaneData& in,
string key,
DataSource source) noexcept(false)
{
ensure_init();
string data;
write(in, data);
data_source_store(data, AssetType::PHASE_PLANE_DATA, key, source);
}
// ------------------------------------------------------------------ Classifier
void fetch(Classifier& out, string key, DataSource source) noexcept(false)
{
ensure_init();
string data;
data_source_fetch(data, AssetType::CLASSIFIER, key, source);
out.read(data);
}
void store(const Classifier& in, string key, DataSource source) noexcept(false)
{
ensure_init();
string data = in.write();
data_source_store(data, AssetType::CLASSIFIER, key, source);
}
// ------------------------------------------------------ Scene Background Image
void fetch_bg_image(ARGBImage& im,
string key,
DataSource source) noexcept(false)
{
ensure_init();
vector<char> data;
data_source_fetch(data, AssetType::SCENE_BACKGROUND_IMAGE, key, source);
im = decode_image(data);
}
} // namespace perceive
| 30.233618 | 80 | 0.592631 | [
"cad",
"geometry",
"vector",
"model"
] |
d7cfb0d8905620c46b9039d0be5af1be539c1a40 | 892 | cpp | C++ | Algorithms on Graphs/week1_graph_decomposition1/1_finding_exit_from_maze/reachability.cpp | hovmikayelyan/Data_Structures_and_Algorithms | abfd3c63f8bce200c2379c44e755e53611f26ac7 | [
"MIT"
] | null | null | null | Algorithms on Graphs/week1_graph_decomposition1/1_finding_exit_from_maze/reachability.cpp | hovmikayelyan/Data_Structures_and_Algorithms | abfd3c63f8bce200c2379c44e755e53611f26ac7 | [
"MIT"
] | null | null | null | Algorithms on Graphs/week1_graph_decomposition1/1_finding_exit_from_maze/reachability.cpp | hovmikayelyan/Data_Structures_and_Algorithms | abfd3c63f8bce200c2379c44e755e53611f26ac7 | [
"MIT"
] | null | null | null | /**
* @file reachability.cpp
* @author Hovhannes Mikayelyan (hovmikayelyan@gmail.com)
* @brief
* @version 0.1
* @date 2022-01-12
*
* @copyright Copyright (c) 2022
*
*/
#include <bits/stdc++.h>
using namespace std;
/**
* @brief
* Main Program
*/
void explore(vector<vector<int>> &adj, vector<bool> &visited, int u, int v)
{
visited[u] = 1;
for (auto elem : adj[u])
{
if (!visited[elem])
{
explore(adj, visited, elem, v);
}
}
}
int main()
{
size_t n, m;
cin >> n >> m;
vector<vector<int>> adj(n, vector<int>());
for (size_t i = 0; i < m; i++)
{
int x, y;
cin >> x >> y;
adj[x - 1].push_back(y - 1);
adj[y - 1].push_back(x - 1);
}
int u, v;
cin >> u >> v;
vector<bool> visited(n, 0);
explore(adj, visited, u - 1, v - 1);
if (visited[v - 1])
{
cout << 1;
}
else
{
cout << 0;
}
return 0;
}
| 13.723077 | 75 | 0.517937 | [
"vector"
] |
d7d309bb9bbfa3dfe253d8238af2d425e92067fb | 11,857 | cpp | C++ | window.cpp | ichristen/pGDS | c6959ea7db0cc01549eb170b7fdc273801735dbc | [
"MIT"
] | null | null | null | window.cpp | ichristen/pGDS | c6959ea7db0cc01549eb170b7fdc273801735dbc | [
"MIT"
] | null | null | null | window.cpp | ichristen/pGDS | c6959ea7db0cc01549eb170b7fdc273801735dbc | [
"MIT"
] | null | null | null | #include "window.hpp"
GLuint LoadShaders(const char * vertex_file_path,const char * fragment_file_path){
// Create the shaders
GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);
// Read the Vertex Shader code from the file
std::string VertexShaderCode;
std::ifstream VertexShaderStream(vertex_file_path, std::ios::in);
if(VertexShaderStream.is_open()){
std::stringstream sstr;
sstr << VertexShaderStream.rdbuf();
VertexShaderCode = sstr.str();
VertexShaderStream.close();
}else{
printf("Impossible to open %s. Are you in the right directory ? Don't forget to read the FAQ !\n", vertex_file_path);
getchar();
return 0;
}
// Read the Fragment Shader code from the file
std::string FragmentShaderCode;
std::ifstream FragmentShaderStream(fragment_file_path, std::ios::in);
if(FragmentShaderStream.is_open()){
std::stringstream sstr;
sstr << FragmentShaderStream.rdbuf();
FragmentShaderCode = sstr.str();
FragmentShaderStream.close();
}
GLint Result = GL_FALSE;
int InfoLogLength;
// Compile Vertex Shader
printf("Compiling shader : %s\n", vertex_file_path);
char const * VertexSourcePointer = VertexShaderCode.c_str();
glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL);
glCompileShader(VertexShaderID);
// Check Vertex Shader
glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result);
glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
if ( InfoLogLength > 0 ){
std::vector<char> VertexShaderErrorMessage(InfoLogLength+1);
glGetShaderInfoLog(VertexShaderID, InfoLogLength, NULL, &VertexShaderErrorMessage[0]);
printf("%s\n", &VertexShaderErrorMessage[0]);
}
// Compile Fragment Shader
printf("Compiling shader : %s\n", fragment_file_path);
char const * FragmentSourcePointer = FragmentShaderCode.c_str();
glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer , NULL);
glCompileShader(FragmentShaderID);
// Check Fragment Shader
glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result);
glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
if ( InfoLogLength > 0 ){
std::vector<char> FragmentShaderErrorMessage(InfoLogLength+1);
glGetShaderInfoLog(FragmentShaderID, InfoLogLength, NULL, &FragmentShaderErrorMessage[0]);
printf("%s\n", &FragmentShaderErrorMessage[0]);
}
// Link the program
printf("Linking program\n");
GLuint ProgramID = glCreateProgram();
glAttachShader(ProgramID, VertexShaderID);
glAttachShader(ProgramID, FragmentShaderID);
glLinkProgram(ProgramID);
// Check the program
glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result);
glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength);
if ( InfoLogLength > 0 ){
std::vector<char> ProgramErrorMessage(InfoLogLength+1);
glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]);
printf("%s\n", &ProgramErrorMessage[0]);
}
glDetachShader(ProgramID, VertexShaderID);
glDetachShader(ProgramID, FragmentShaderID);
glDeleteShader(VertexShaderID);
glDeleteShader(FragmentShaderID);
return ProgramID;
}
WINDOW::WINDOW() {
screen = BOUNDINGBOX(VECTOR(0,0), VECTOR(XRES, YRES));
rotation = 0;
bb = BOUNDINGBOX(VECTOR(-1.5,-1), VECTOR(1.5, 1));
focus = nullptr;
init();
}
int WINDOW::init() {
if(!glfwInit()) {
fprintf( stderr, "Failed to initialize GLFW\n" );
return -1;
}
glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); // We want OpenGL 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // We don't want the old OpenGL
// Open a window and create its OpenGL context
// (In the accompanying source code, this variable is global for simplicity)
window = glfwCreateWindow( XRES, YRES, "pGDS", NULL, NULL);
if( window == NULL ){
fprintf( stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n" );
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window); // Initialize GLEW
glewExperimental=true; // Needed in core profile
if (glewInit() != GLEW_OK) {
fprintf(stderr, "Failed to initialize GLEW\n");
return -1;
}
glfwSwapInterval(1);
GLuint VertexArrayID;
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
// static const GLfloat g_vertex_buffer_data[] = {
// -1.0f, -1.0f,
// 1.0f, -1.0f,
// 0.0f, 1.0f,
// };
//
//// glColor3ub(0, 255, 255);
//
//// GLuint vertexbuffer;
// glGenBuffers(1, &vertexbuffer);
// glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
// glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);
MATERIAL::shaders = LoadShaders("/Users/i/Documents/pGDS/test.vert", "/Users/i/Documents/pGDS/test.frag");
// shaders = LoadShaders("/Users/i/Documents/pGDS/test.vert", "/Users/i/Documents/pGDS/test.frag");
glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
// int tick = 0;
// printf("JOYSTICK: %i", glfwJoystickPresent(GLFW_JOYSTICK_1));
// auto func = [](GLFWwindow* w, double, double)
// {
// static_cast<WINDOW*>(glfwGetWindowUserPointer(w))->mouseButtonPressed( /* ... */ );
// }
// HackFullContentView(window);
glfwSetWindowUserPointer(window, this);
glfwSetScrollCallback(window, scroll);
glfwSetFramebufferSizeCallback(window, frame);
getScreen();
// glfwSetMouseButtonCallback(window, mousebutton);
return 0;
}
void WINDOW::getScreen() {
int xpos, ypos;
glfwGetWindowPos(window, &xpos, &ypos);
int width, height;
glfwGetWindowSize(window, &width, &height);
// int left, top, right, bottom;
// glfwGetWindowFrameSize(window, &left, &top, &right, &bottom);
// printf("[ %i, %i ] - [ %i, %i ]\n", left, bottom, right, top);
screen = BOUNDINGBOX(xpos, xpos + width, ypos + height, ypos);
}
void scroll(GLFWwindow* window, double xoffset, double yoffset) {
WINDOW* w = (WINDOW*)glfwGetWindowUserPointer(window);
bool zoom = glfwGetKey(window, GLFW_KEY_LEFT_ALT) || glfwGetKey(window, GLFW_KEY_RIGHT_ALT);
if (zoom) {
VECTOR screenCoords;
glfwGetCursorPos(window, &screenCoords.x, &screenCoords.y);
// screenCoords.printNL();
screenCoords.y = w->screen.height() - screenCoords.y;
// VECTOR realCoords = AFFINE(w->screen, w->bb) * screenCoords;
VECTOR realCoords = w->bb.center();
// realCoords.printNL();
// w->screen.print();
// w->bb.print();
// (AFFINE(-realCoords) * w->bb).print();
// (AFFINE( realCoords) * w->bb).print();
// printf("\n");
GLdouble scale = (1 + max(-.5, -.1*yoffset*.25));
w->bb = AFFINE(realCoords / scale) * ( (AFFINE(-realCoords) * w->bb) * scale );
} else {
// GLdouble mult = w->bb.width()/w->screen.width();
//
// printf("WID=%f, MULT=%f\n", w->bb.width(), mult);
// printf("WID=%f, MULT=%f\n", mult);
GLdouble mult = 0.03;
VECTOR dv = VECTOR(xoffset * mult, -yoffset * mult);
// dv.printNL();
w->bb.ll += dv;
w->bb.ur += dv;
// w->bb.print();
}
}
void frame(GLFWwindow* window, int width, int height) {
WINDOW* w = (WINDOW*)glfwGetWindowUserPointer(window);
// BOUNDINGBOX screen = BOUNDINGBOX(VECTOR(), VECTOR(width, height));
BOUNDINGBOX oldScreen = w->screen;
printf("oldScreen = ");
oldScreen.print();
w->getScreen();
BOUNDINGBOX newScreen = w->screen;
printf("newScreen = ");
newScreen.print();
printf("w->bb before = ");
w->bb.print();
GLdouble cameraWidth = w->bb.width() * (newScreen.width() / oldScreen.width());
GLdouble cameraHeight = cameraWidth * (newScreen.height() / newScreen.width());
w->bb = BOUNDINGBOX(w->bb.center(), cameraWidth, cameraHeight);
// printf("AFFINE = \n");
// AFFINE(oldScreen, newScreen).print();
//
// AFFINE m = AFFINE(oldScreen, newScreen);
// m.e = 0;
// m.f = 0;
//
// w->bb = m * w->bb;
printf("w->bb after = ");
w->bb.print();
}
void WINDOW::loop() {
glEnable(GL_LINE_SMOOTH);
glLineWidth(5.0f);
POLYLINE c = circle(2);
glfwWaitEventsTimeout(0.1);
do{
// tick++;
// glClearColor(0, (rand() % 100)/200., 0, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// if (glfwGetMouseButton(window, 1)) { bb *= .99; }
// if (glfwGetMouseButton(window, 0)) { bb /= .99; }
// if (glfwGetKey(window, GLFW_KEY_GRAVE_ACCENT)) { bb = BOUNDINGBOX(VECTOR(-1.5,-1), VECTOR(1.5, 1)); }
if (glfwGetKey(window, GLFW_KEY_GRAVE_ACCENT)) { bb = focus.device->bb; }
GLfloat scalex = 2./bb.width();
GLfloat scaley = 2./bb.height();
const GLfloat m[] = {
scalex, 0.0f, 0.0f, 0.0f,
0.0f, scaley, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
(GLfloat)bb.center().x, (GLfloat)bb.center().y, 0.0f, 1.0f
};
AFFINE camera = AFFINE(scalex, 0, 0, scaley, bb.center().x, bb.center().y);
// camera.print();
// const GLfloat red[] = { 1.0, 0.0, 0.0 };
// const GLfloat green[] = { 0.0, 1.0, 0.0 };
// GLuint colorID = glGetUniformLocation(shaders, "c");
// glUniform4f(colorID, 1, 0, 0, 1);
//
GLuint MatrixID = glGetUniformLocation(MATERIAL::shaders, "m");
glUniformMatrix4fv(MatrixID, 1, GL_FALSE, m);
//
// glUseProgram(shaders);
// focus->polylines[0].outline();
// focus->polylines[0].fillOutline();
// focus->polylines[0].print();
focus.render(camera, false);
// c.fillOutline();
// focus->render(shaders);
// glEnableVertexAttribArray(0);
// glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
// glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
// glDrawArrays(GL_TRIANGLES, 0, 3);
// glDisableVertexAttribArray(0);
//
// {
// GLuint colorID = glGetUniformLocation(shaders, "c");
// glUniform4f(colorID, 1, 1, 1, .5);
//
// GLuint MatrixID = glGetUniformLocation(shaders, "m");
// glUniformMatrix4fv(MatrixID, 1, GL_FALSE, m);
//
// glUseProgram(shaders);
//
//// focus->polylines[0].outline();
//
// glEnableVertexAttribArray(0);
// glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
// glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
// glDrawArrays(GL_LINE_LOOP, 0, 3);
// glDisableVertexAttribArray(0);
// }
glfwSwapBuffers(window);
glfwWaitEvents();
} while( glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS && glfwWindowShouldClose(window) == 0 );
}
| 32.844875 | 152 | 0.6042 | [
"render",
"vector"
] |
d7dade0c88b11acb231d250f98de5cdad7e5269a | 2,696 | hxx | C++ | src/sumCuda.hxx | puzzlef/sum-cuda-memcpy-vs-inplace | fd8b711bcaf34d981f91ad5798499417c22a1fdf | [
"MIT"
] | null | null | null | src/sumCuda.hxx | puzzlef/sum-cuda-memcpy-vs-inplace | fd8b711bcaf34d981f91ad5798499417c22a1fdf | [
"MIT"
] | null | null | null | src/sumCuda.hxx | puzzlef/sum-cuda-memcpy-vs-inplace | fd8b711bcaf34d981f91ad5798499417c22a1fdf | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <algorithm>
#include "_main.hxx"
#include "sum.hxx"
#include "sumSeq.hxx"
using std::vector;
using std::min;
template <class T>
__device__ void sumKernelReduce(T* a, int N, int i) {
__syncthreads();
for (N=N/2; N>0; N/=2) {
if (i<N) a[i] += a[N+i];
__syncthreads();
}
}
template <class T>
__device__ T sumKernelLoop(const T *x, int N, int i, int DI) {
T a = T();
for (; i<N; i+=DI)
a += x[i];
return a;
}
template <class T, int C=BLOCK_LIMIT>
__global__ void sumKernel(T *a, const T *x, int N) {
DEFINE(t, b, B, G);
__shared__ T cache[C];
cache[t] = sumKernelLoop(x, N, B*b+t, G*B);
sumKernelReduce(cache, B, t);
if (t==0) a[b] = cache[0];
}
template <class T>
void sumMemcpyCu(T *a, const T *x, int N) {
const int B = BLOCK_DIM_R<T>();
const int G = min(ceilDiv(N, B), GRID_DIM_R<T>());
sumKernel<<<G, B>>>(a, x, N);
}
template <class T>
void sumInplaceCu(T *a, const T *x, int N) {
const int B = BLOCK_DIM_R<T>();
const int G = min(ceilDiv(N, B), GRID_DIM_R<T>());
const int H = min(G, BLOCK_LIMIT);
sumKernel<<<G, B>>>(a, x, N);
sumKernel<<<1, H>>>(a, a, G);
}
template <class T>
void sumCu(T *a, const T *x, int N) {
sumInplaceCu(a, x, N);
}
template <class T>
SumResult<T> sumMemcpyCuda(const T *x, int N, const SumOptions& o={}) {
const int G = GRID_DIM_R<T>();
size_t N1 = N * sizeof(T);
size_t G1 = G * sizeof(T);
T *aD, *xD, aH[G];
TRY( cudaMalloc(&aD, G1) );
TRY( cudaMalloc(&xD, N1) );
TRY( cudaMemcpy(xD, x, N1, cudaMemcpyHostToDevice) );
T a = T();
float t = measureDuration([&] {
sumMemcpyCu(aD, xD, N);
TRY( cudaMemcpy(aH, aD, G1, cudaMemcpyDeviceToHost) );
a = sumLoop(aH, reduceSizeCu<T>(N));
}, o.repeat);
TRY( cudaFree(aD) );
TRY( cudaFree(xD) );
return {a, t};
}
template <class T>
SumResult<T> sumMemcpyCuda(const vector<T>& x, const SumOptions& o={}) {
return sumMemcpyCuda(x.data(), x.size(), o);
}
template <class T>
SumResult<T> sumInplaceCuda(const T *x, int N, const SumOptions& o={}) {
const int G = GRID_DIM_R<T>();
size_t N1 = N * sizeof(T);
size_t G1 = G * sizeof(T);
T *aD, *xD;
TRY( cudaMalloc(&aD, G1) );
TRY( cudaMalloc(&xD, N1) );
TRY( cudaMemcpy(xD, x, N1, cudaMemcpyHostToDevice) );
T a = T();
float t = measureDuration([&] {
sumInplaceCu(aD, xD, N);
TRY( cudaDeviceSynchronize() );
}, o.repeat);
TRY( cudaMemcpy(&a, aD, sizeof(T), cudaMemcpyDeviceToHost) );
TRY( cudaFree(aD) );
TRY( cudaFree(xD) );
return {a, t};
}
template <class T>
SumResult<T> sumInplaceCuda(const vector<T>& x, const SumOptions& o={}) {
return sumInplaceCuda(x.data(), x.size(), o);
}
| 21.568 | 73 | 0.604599 | [
"vector"
] |
d7e4de710f5f4f5c589723c56dd4832a5145cd2a | 11,502 | cpp | C++ | Source/Engine/SceneEditor/UI/OutlinerUI.cpp | yuvanw/ViceEngine | 7259b53483b3d5a516182c9ded42a3c5219ba66f | [
"MIT"
] | null | null | null | Source/Engine/SceneEditor/UI/OutlinerUI.cpp | yuvanw/ViceEngine | 7259b53483b3d5a516182c9ded42a3c5219ba66f | [
"MIT"
] | null | null | null | Source/Engine/SceneEditor/UI/OutlinerUI.cpp | yuvanw/ViceEngine | 7259b53483b3d5a516182c9ded42a3c5219ba66f | [
"MIT"
] | null | null | null | #include "OutlinerUI.h"
#include "RenderManager.h"
#include "RendererFileSystem.h"
#include "imgui/imgui.h"
#include <string>
const ANSICHAR* FOutlinerUI::WindowName = "Outliner";
void FOutlinerUI::Init()
{
Scene = FRenderManager::GetRenderer()->GetScene();
Camera = FRenderManager::GetRenderer()->GetCamera();
// Store scene objects.
Skybox = Scene->GetSkybox();
Models.Empty();
Models.Append(Scene->GetVisibleModels());
Models.Append(Scene->GetInvisibleModels());
DirectionalLights.Empty();
DirectionalLights.Append(Scene->GetVisibleDirectionalLights());
DirectionalLights.Append(Scene->GetInvisibleDirectionalLights());
PointLights.Empty();
PointLights.Append(Scene->GetVisiblePointLights());
PointLights.Append(Scene->GetInvisiblePointLights());
// Select the camera by default.
SelectedObjectIndex = 0;
SelectedSceneIndex = 0;
SelectedAddIndex = 0;
}
void FOutlinerUI::Shutdown()
{
}
void FOutlinerUI::Update()
{
ImGui::Begin(WindowName);
// List scene configuration buttons.
RenderLoadSceneButton();
ImGui::SameLine();
RenderAddButton();
ImGui::SameLine();
RenderRemoveButton();
ImGui::Spacing();
// List camera.
int32 CurrentObjectIndex = 0;
if (ImGui::Selectable("Camera", SelectedObjectIndex == CurrentObjectIndex))
{
SelectedObjectIndex = CurrentObjectIndex;
}
// List skybox.
CurrentObjectIndex = 1;
if (Skybox)
{
bool bIsVisible = Skybox->IsVisible();
std::string VisibilityLabel = std::string("##IsSkyboxVisible") + Skybox->GetName().GetString().GetData();
ImGui::Checkbox(VisibilityLabel.c_str(), &bIsVisible);
ImGui::SameLine();
if (bIsVisible)
{
Skybox->SetVisible();
}
else
{
Skybox->SetInvisible();
}
if (ImGui::Selectable(Skybox->GetName().GetString().GetData(), SelectedObjectIndex == CurrentObjectIndex))
{
SelectedObjectIndex = CurrentObjectIndex;
}
++CurrentObjectIndex;
}
// List models.
int32 StartIndex = CurrentObjectIndex;
int32 EndIndex = CurrentObjectIndex + Models.GetSize();
for (CurrentObjectIndex; CurrentObjectIndex < EndIndex; ++CurrentObjectIndex)
{
int32 Index = CurrentObjectIndex - StartIndex;
bool bIsVisible = Models[Index]->IsVisible();
std::string VisibilityLabel = std::string("##IsVisible") + Models[Index]->GetName().GetString().GetData();
ImGui::Checkbox(VisibilityLabel.c_str(), &bIsVisible);
ImGui::SameLine();
if (bIsVisible)
{
Models[Index]->SetVisible();
}
else
{
Models[Index]->SetInvisible();
}
if (ImGui::Selectable(Models[Index]->GetName().GetString().GetData(), SelectedObjectIndex == CurrentObjectIndex))
{
SelectedObjectIndex = CurrentObjectIndex;
}
}
// List directional lights.
StartIndex = CurrentObjectIndex;
EndIndex = CurrentObjectIndex + DirectionalLights.GetSize();
for (CurrentObjectIndex; CurrentObjectIndex < EndIndex; ++CurrentObjectIndex)
{
int32 Index = CurrentObjectIndex - StartIndex;
bool bIsVisible = DirectionalLights[Index]->IsVisible();
std::string VisibilityLabel = std::string("##IsVisible") + DirectionalLights[Index]->GetName().GetString().GetData();
ImGui::Checkbox(VisibilityLabel.c_str(), &bIsVisible);
ImGui::SameLine();
if (bIsVisible)
{
DirectionalLights[Index]->SetVisible();
}
else
{
DirectionalLights[Index]->SetInvisible();
}
if (ImGui::Selectable(DirectionalLights[Index]->GetName().GetString().GetData(), SelectedObjectIndex == CurrentObjectIndex))
{
SelectedObjectIndex = CurrentObjectIndex;
}
}
// List point lights.
StartIndex = CurrentObjectIndex;
EndIndex = CurrentObjectIndex + PointLights.GetSize();
for (CurrentObjectIndex; CurrentObjectIndex < EndIndex; ++CurrentObjectIndex)
{
int32 Index = CurrentObjectIndex - StartIndex;
bool bIsVisible = PointLights[Index]->IsVisible();
std::string VisibilityLabel = std::string("##IsVisible") + PointLights[Index]->GetName().GetString().GetData();
ImGui::Checkbox(VisibilityLabel.c_str(), &bIsVisible);
ImGui::SameLine();
if (bIsVisible)
{
PointLights[Index]->SetVisible();
}
else
{
PointLights[Index]->SetInvisible();
}
if (ImGui::Selectable(PointLights[Index]->GetName().GetString().GetData(), SelectedObjectIndex == CurrentObjectIndex))
{
SelectedObjectIndex = CurrentObjectIndex;
}
}
ImGui::End();
}
TSharedPtr<FCamera> FOutlinerUI::GetSelectedCamera()
{
return (SelectedObjectIndex == 0) ? Camera : nullptr;
}
TSharedPtr<FSkybox> FOutlinerUI::GetSelectedSkybox()
{
if (!Skybox)
{
return nullptr;
}
return (SelectedObjectIndex == 1) ? Skybox : nullptr;
}
TSharedPtr<FModel> FOutlinerUI::GetSelectedModel()
{
int32 FirstModelIndex = (Skybox) ? 2 : 1;
int32 LastModelIndex = FirstModelIndex + Models.GetSize() - 1;
bool bIsSelected = !Models.IsEmpty() && (FirstModelIndex <= SelectedObjectIndex) && (SelectedObjectIndex <= LastModelIndex);
if (bIsSelected)
{
int32 Index = SelectedObjectIndex - FirstModelIndex;
return Models[Index];
}
else
{
return nullptr;
}
}
TSharedPtr<FDirectionalLight> FOutlinerUI::GetSelectedDirectionalLight()
{
int32 NumModels = Models.GetSize();
int32 FirstDirectionalLightIndex = (Skybox) ? NumModels + 2 : NumModels + 1;
int32 LastDirectionalLightIndex = FirstDirectionalLightIndex + DirectionalLights.GetSize() - 1;
bool bIsSelected = !DirectionalLights.IsEmpty() && (FirstDirectionalLightIndex <= SelectedObjectIndex) && (SelectedObjectIndex <= LastDirectionalLightIndex);
if (bIsSelected)
{
int32 Index = SelectedObjectIndex - FirstDirectionalLightIndex;
return DirectionalLights[Index];
}
else
{
return nullptr;
}
}
TSharedPtr<FPointLight> FOutlinerUI::GetSelectedPointLight()
{
int32 NumModels = Models.GetSize();
int32 NumDirectionalLights = DirectionalLights.GetSize();
int32 FirstPointLightIndex = (Skybox) ? NumModels + NumDirectionalLights + 2 : NumModels + NumDirectionalLights + 1;
int32 LastPointLightIndex = FirstPointLightIndex + PointLights.GetSize() - 1;
bool bIsSelected = !PointLights.IsEmpty() && (FirstPointLightIndex <= SelectedObjectIndex) && (SelectedObjectIndex <= LastPointLightIndex);
if (bIsSelected)
{
int32 Index = SelectedObjectIndex - FirstPointLightIndex;
return PointLights[Index];
}
else
{
return nullptr;
}
}
void FOutlinerUI::RenderLoadSceneButton()
{
if (ImGui::Button("Load Scene"))
{
ImGui::OpenPopup("Load Scene");
}
ImVec2 Center = ImGui::GetMainViewport()->GetCenter();
ImGui::SetNextWindowPos(Center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
if (ImGui::BeginPopupModal("Load Scene", nullptr, ImGuiWindowFlags_AlwaysAutoResize))
{
TArray<FStringId> SceneFileNames = FRendererFileSystem::GetAllSceneFileNames();
for (int32 Index = 0; Index < SceneFileNames.GetSize(); ++Index)
{
if (ImGui::Selectable(SceneFileNames[Index].GetString().GetData(), SelectedSceneIndex == Index, ImGuiSelectableFlags_DontClosePopups))
{
SelectedSceneIndex = Index;
}
}
ImGui::Separator();
if (ImGui::Button("OK", ImVec2(120, 0)))
{
FRenderManager::GetRenderer()->SetScene(SceneFileNames[SelectedSceneIndex].GetString().GetData());
Init();
ImGui::CloseCurrentPopup();
}
ImGui::SetItemDefaultFocus();
ImGui::SameLine();
if (ImGui::Button("Cancel", ImVec2(120, 0)))
{
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
}
void FOutlinerUI::RenderAddButton()
{
if (ImGui::Button("Add"))
{
ImGui::OpenPopup("Add");
}
ImVec2 Center = ImGui::GetMainViewport()->GetCenter();
ImGui::SetNextWindowPos(Center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
if (ImGui::BeginPopupModal("Add", nullptr, ImGuiWindowFlags_AlwaysAutoResize))
{
ImGui::Separator();
ImGui::Text("Name");
ImGui::Separator();
static char ObjectName[128] = "New Object";
ImGui::InputText("##Name", ObjectName, IM_ARRAYSIZE(ObjectName));
bool bIsNameUnique = true;
if (Scene->IsModelContained(ObjectName) || Scene->IsDirectionalLightContained(ObjectName) || Scene->IsPointLightContained(ObjectName))
{
bIsNameUnique = false;
ImGui::Text("Object name must be unique!");
}
ImGui::Separator();
ImGui::Text("Models");
ImGui::Separator();
int32 Index = 0;
TArray<FStringId> ModelFileNames = FRendererFileSystem::GetAllModelFileNames();
for (Index; Index < ModelFileNames.GetSize(); ++Index)
{
if (ImGui::Selectable(ModelFileNames[Index].GetString().GetData(), SelectedAddIndex == Index, ImGuiSelectableFlags_DontClosePopups))
{
SelectedAddIndex = Index;
}
}
ImGui::Separator();
ImGui::Text("Lights");
ImGui::Separator();
if (ImGui::Selectable("Directional Light", SelectedAddIndex == Index, ImGuiSelectableFlags_DontClosePopups))
{
SelectedAddIndex = Index;
}
++Index;
if (ImGui::Selectable("Point Light", SelectedAddIndex == Index, ImGuiSelectableFlags_DontClosePopups))
{
SelectedAddIndex = Index;
}
if (!bIsNameUnique)
{
ImGui::BeginDisabled();
}
if (ImGui::Button("OK", ImVec2(120, 0)))
{
int32 NumModels = ModelFileNames.GetSize();
bool bIsModelSelected = (SelectedAddIndex < NumModels);
bool bIsDirectionalLightSelected = (SelectedAddIndex == NumModels);
bool bIsPointLightSelected = (SelectedAddIndex == NumModels + 1);
if (bIsModelSelected)
{
// Add selected model to scene.
TSharedPtr<FModel> Model = MakeShared<FModel>(ObjectName, ModelFileNames[SelectedAddIndex].GetString().GetData());
Scene->AddModel(Model);
Models.Add(Model);
}
else if (bIsDirectionalLightSelected)
{
// Add default directional light.
TSharedPtr<FDirectionalLight> DirectionalLight = MakeShared<FDirectionalLight>(
// Name.
ObjectName,
// Light direction.
FVector3D(0.0f, 0.0f, 0.0f),
// Light color.
FColor(1.0f, 1.0f, 1.0f),
// Light intensity.
1.0f);
Scene->AddDirectionalLight(DirectionalLight);
DirectionalLights.Add(DirectionalLight);
}
else if (bIsPointLightSelected)
{
// Add default point light.
TSharedPtr<FPointLight> PointLight = MakeShared<FPointLight>(
// Name
ObjectName,
// Light position.
FVector3D(0.0f, 0.0f, 0.0f),
// Light color.
FColor(1.0f, 1.0f, 1.0f),
// Light intensity.
1.0f,
// Light attenuation.
FAttenuation(1.0f, 0.032f, 0.09f)
);
Scene->AddPointLight(PointLight);
PointLights.Add(PointLight);
}
// Reset default object name.
strcpy(ObjectName, "New Object");
ImGui::CloseCurrentPopup();
}
ImGui::SetItemDefaultFocus();
if (!bIsNameUnique)
{
ImGui::EndDisabled();
}
ImGui::SameLine();
if (ImGui::Button("Cancel", ImVec2(120, 0)))
{
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
}
void FOutlinerUI::RenderRemoveButton()
{
if (GetSelectedCamera())
{
// Disable the "Remove" button if the camera is selected.
ImGui::BeginDisabled();
ImGui::Button("Remove");
ImGui::EndDisabled();
}
else if (ImGui::Button("Remove"))
{
if (GetSelectedSkybox())
{
Scene->SetSkybox(nullptr);
}
else if (TSharedPtr<FModel> Model = GetSelectedModel())
{
Scene->RemoveModel(Model);
Models.RemoveFirst(Model);
}
else if (TSharedPtr<FDirectionalLight> DirectionalLight = GetSelectedDirectionalLight())
{
Scene->RemoveDirectionalLight(DirectionalLight);
DirectionalLights.RemoveFirst(DirectionalLight);
}
else if (TSharedPtr<FPointLight> PointLight = GetSelectedPointLight())
{
Scene->RemovePointLight(PointLight);
PointLights.RemoveFirst(PointLight);
}
SelectedObjectIndex = 0;
}
}
| 25.789238 | 158 | 0.71005 | [
"object",
"model"
] |
d7f61115c862e4e8f386cc26cd6577447a488bdd | 972 | cpp | C++ | aws-cpp-sdk-quicksight/source/model/GutterStyle.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-01-05T18:20:03.000Z | 2022-01-05T18:20:03.000Z | aws-cpp-sdk-quicksight/source/model/GutterStyle.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-quicksight/source/model/GutterStyle.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/quicksight/model/GutterStyle.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace QuickSight
{
namespace Model
{
GutterStyle::GutterStyle() :
m_show(false),
m_showHasBeenSet(false)
{
}
GutterStyle::GutterStyle(JsonView jsonValue) :
m_show(false),
m_showHasBeenSet(false)
{
*this = jsonValue;
}
GutterStyle& GutterStyle::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Show"))
{
m_show = jsonValue.GetBool("Show");
m_showHasBeenSet = true;
}
return *this;
}
JsonValue GutterStyle::Jsonize() const
{
JsonValue payload;
if(m_showHasBeenSet)
{
payload.WithBool("Show", m_show);
}
return payload;
}
} // namespace Model
} // namespace QuickSight
} // namespace Aws
| 15.677419 | 69 | 0.699588 | [
"model"
] |
d7f7cabedf04299dfd9e2753000318ffbc3ad9de | 1,680 | cpp | C++ | Iteration1/Desk.cpp | zackszhu/SimpleQuidditch | 6a5066631e0619701a57d25432b37ccc370830a9 | [
"MIT"
] | null | null | null | Iteration1/Desk.cpp | zackszhu/SimpleQuidditch | 6a5066631e0619701a57d25432b37ccc370830a9 | [
"MIT"
] | null | null | null | Iteration1/Desk.cpp | zackszhu/SimpleQuidditch | 6a5066631e0619701a57d25432b37ccc370830a9 | [
"MIT"
] | null | null | null | #include "Desk.h"
#include <fstream>
const GLfloat deskWidth = 5.0;
const GLfloat deskLength = 5.0;
const GLfloat deskHeight = 0.25;
void Desk::addEdges(GLfloat x, GLfloat y, GLfloat w, GLfloat l) {
// false is by x
edges.push_back(std::move(Edge(Point(x - w / 2, y - l / 2, 0), false)));
edges.push_back(std::move(Edge(Point(x + w / 2, y - l / 2, 0), false)));
edges.push_back(std::move(Edge(Point(x - w / 2, y - l / 2, 0), true)));
edges.push_back(std::move(Edge(Point(x - w / 2, y + l / 2, 0), true)));
}
Desk::Desk(int level) : rects(4), tiles(10, std::vector<Tile>(10)) {
rects[0] = std::move(Rect(deskWidth + deskHeight, 0.0, 0.0, deskHeight * 2, 2 * deskLength, deskHeight * 4));
rects[1] = std::move(Rect(-(deskWidth + deskHeight), 0.0, 0.0, deskHeight * 2, 2 * deskLength, deskHeight * 4));
rects[2] = std::move(Rect(0.0, deskLength + deskHeight, 0.0, 2 * deskWidth + deskHeight * 4, deskHeight * 2, deskHeight * 4));
rects[3] = std::move(Rect(0.0, -(deskLength + deskHeight), 0.0, 2 * deskWidth + deskHeight * 4, deskHeight * 2, deskHeight * 4));
addEdges(0.0, 0.0, 2 * deskWidth, 2 * deskLength);
std::ifstream infile("terrain.dat");
std::vector<std::vector<float>> temp(11, std::vector<float>(11, 0));
for (auto i = 0; i < 11; i++) {
for (auto j = 0; j < 11; j++) {
float tmp = 0;
infile >> tmp;
temp[i][j] = tmp;
}
}
for (auto i = 0; i < 10; i++) {
for (auto j = 0; j < 10; j++) {
Point lt = Point(i - 5, j - 5, temp[i][j]);
Point rt = Point(i - 4, j - 5, temp[i + 1][j]);
Point rb = Point(i - 4, j - 4, temp[i + 1][j + 1]);
Point lb = Point(i - 5, j - 4, temp[i][j + 1]);
tiles[i][j] = Tile(lt, rt, rb, lb);
}
}
} | 40.97561 | 130 | 0.580952 | [
"vector"
] |
d7f834cb434842e8c276fc671f064e22a0d87c4e | 2,688 | hpp | C++ | tools/protoGen/ParserRoot.hpp | carnegie-technologies/pravala-toolkit | 77dac4a910dc0692b7515a8e3b77d34eb2888256 | [
"Apache-2.0"
] | null | null | null | tools/protoGen/ParserRoot.hpp | carnegie-technologies/pravala-toolkit | 77dac4a910dc0692b7515a8e3b77d34eb2888256 | [
"Apache-2.0"
] | null | null | null | tools/protoGen/ParserRoot.hpp | carnegie-technologies/pravala-toolkit | 77dac4a910dc0692b7515a8e3b77d34eb2888256 | [
"Apache-2.0"
] | 2 | 2020-02-07T00:16:51.000Z | 2020-02-11T15:10:45.000Z | /*
* Copyright 2019 Carnegie Technologies
*
* 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 "basic/String.hpp"
#include "basic/HashSet.hpp"
#include "ProtoSpec.hpp"
#include "Symbol.hpp"
namespace Pravala
{
/// @brief The starting object for parsing input files
class ParserRoot
{
public:
/// @brief Adds a directory to the list of import directories.
/// Those directories are used while looking for files included with 'import' keyword.
/// @param [in] dir The directory to add to the list.
/// @return True if the directory was added; False otherwise.
bool addImportDir ( const String & dir );
/// @brief Adds a file to the list of input files.
/// @param [in] file The file path to add to the list.
/// @return True if the path was added; False otherwise.
bool addInputFile ( const String & file );
/// @brief Returns the list of import directories.
/// Those directories are used while looking for files included with 'import' keyword.
/// @return The list of import directories.
inline const StringList & getImportDirs() const
{
return _importDirs;
}
/// @brief Returns the list of input files.
/// @return The list of input files.
inline const StringList & getInputFiles() const
{
return _inputFiles;
}
/// @brief Runs the parsers for all input files
/// @param [in,out] protoSpec The protocol specification object to append tokens to
/// @return True if parsing was successful, false otherwise
bool run ( ProtocolSpec & protoSpec );
protected:
StringList _importDirs; ///< The list of directories to use while looking for imported files.
StringList _inputFiles; ///< The list of input files.
/// @brief A set with MD5 sums of all files that already were parsed.
HashSet<String> _parsedFiles;
/// @brief A set with MD5 sums of all files that we want to generate the output for.
HashSet<String> _generateOutputForFiles;
friend class Parser;
};
}
| 36.324324 | 101 | 0.662202 | [
"object"
] |
cc008677091081a5e117191843585741593c2a49 | 3,779 | hpp | C++ | include/HSGIL/window/iWindow.hpp | AsulconS/MAVeD | f52b88c929873c025df4e2f07164fdfa07b05b95 | [
"Zlib"
] | 1 | 2020-08-14T04:48:10.000Z | 2020-08-14T04:48:10.000Z | include/HSGIL/window/iWindow.hpp | AsulconS/MAVeD | f52b88c929873c025df4e2f07164fdfa07b05b95 | [
"Zlib"
] | null | null | null | include/HSGIL/window/iWindow.hpp | AsulconS/MAVeD | f52b88c929873c025df4e2f07164fdfa07b05b95 | [
"Zlib"
] | null | null | null | /********************************************************************************
* *
* HSGIL - Handy Scalable Graphics Integration Library *
* Copyright (c) 2020 Adrian Bedregal and Gabriela Chipana *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgment in the product documentation would be *
* appreciated but is not required. *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
* *
********************************************************************************/
#ifndef HSGIL_I_WINDOW_HPP
#define HSGIL_I_WINDOW_HPP
#include <HSGIL/core/config.hpp>
#include <HSGIL/core/common.hpp>
#include <HSGIL/window/windowManager.hpp>
#include <HSGIL/window/iEventHandler.hpp>
#include <string>
#include <iostream>
namespace gil
{
/**
* @brief Window Class that handle a Window of the program
*
*/
class HSGIL_API IWindow
{
public:
/**
* @brief Construct a new Window object
*
* @param t_title
* @param t_width
* @param t_height
*/
IWindow(const uint32 t_width, const uint32 t_height, const char* t_title, IEventHandler* t_eventHandler) : m_width {t_width}, m_height {t_height}, m_title {t_title}, m_ready {false}, m_eventHandler {t_eventHandler} {}
/**
* @brief Destroy the Window object
*
*/
virtual ~IWindow() {}
/**
* @brief Check if the Window shouldn't close
*
* @return true if the Window is active
* @return false if not
*/
virtual bool isActive() = 0;
/**
* @brief Check if the Window is able to start rendering
*
* @return true if right
* @return false if not
*/
virtual bool isReady() = 0;
/**
* @brief Send signal to close window
*
*/
virtual void close() = 0;
/**
* @brief Set the Event Handler object
*
*/
virtual void setEventHandler(IEventHandler& t_eventHandler) = 0;
/**
* @brief Poll the Events to process the input
*
*/
virtual void pollEvents() = 0;
/**
* @brief Get the Aspect Ratio
*
* @return float
*/
virtual float getAspectRatio() const = 0;
protected:
/**
* @brief Initializes the Window itself
*
*/
virtual void initializeWindow() = 0;
uint32 m_width;
uint32 m_height;
std::string m_title;
bool m_ready;
WindowManager* m_windowManager;
IEventHandler* m_eventHandler;
};
} // namespace gil
#endif // HSGIL_I_WINDOW_HPP
| 32.577586 | 221 | 0.517333 | [
"object"
] |
cc012fc14edb214bab9416c2f3269d0168f8e65f | 3,534 | cxx | C++ | tests/small-vector/driver.cxx | build2/libbutl | 405dfa3e28ab71d4f6b5210faba0e3600070a0f3 | [
"MIT"
] | 6 | 2018-05-31T06:16:37.000Z | 2021-03-19T10:37:11.000Z | tests/small-vector/driver.cxx | build2/libbutl | 405dfa3e28ab71d4f6b5210faba0e3600070a0f3 | [
"MIT"
] | 3 | 2020-06-19T05:08:42.000Z | 2021-09-29T05:23:07.000Z | tests/small-vector/driver.cxx | build2/libbutl | 405dfa3e28ab71d4f6b5210faba0e3600070a0f3 | [
"MIT"
] | 1 | 2020-06-16T14:56:48.000Z | 2020-06-16T14:56:48.000Z | // file : tests/small-vector/driver.cxx -*- C++ -*-
// license : MIT; see accompanying LICENSE file
#include <string>
#include <iostream>
#include <libbutl/small-vector.hxx>
#undef NDEBUG
#include <cassert>
using namespace std;
using namespace butl;
// Return true if v.data() points to somewhere inside v.
//
template <typename T, size_t N>
inline bool
small (const small_vector<T, N>& v)
{
const void* d (v.data ());
return d >= &v && d < (&v + 1);
}
int
main ()
{
using vector = small_vector<string, 2>;
{
vector v;
assert (v.capacity () == 2 && small (v));
v.push_back ("abc");
assert (v[0] == "abc" && v.capacity () == 2 && small (v));
v.push_back ("ABC");
assert (v[1] == "ABC" && v.capacity () == 2 && small (v));
string* d (v.data ()); // Small buffer...
v.push_back ("xyz");
assert (v[0] == "abc" && v.data () != d && !small (v));
v.pop_back ();
v.shrink_to_fit ();
assert (v[0] == "abc" && v.data () == d);
}
// Allocator comparison.
//
{
vector v1, v2;
assert (v1.get_allocator () != v2.get_allocator ()); // stack/stack
v1.assign ({"abc", "ABC", "xyz"});
assert (v1.get_allocator () != v2.get_allocator ()); // heap/stack
v2.assign ({"abc", "ABC", "xyz"});
assert (v1.get_allocator () == v2.get_allocator ()); // heap/heap
v1.pop_back ();
v1.shrink_to_fit ();
assert (v1.get_allocator () != v2.get_allocator ()); // stack/heap
v2.pop_back ();
v2.shrink_to_fit ();
assert (v1.get_allocator () != v2.get_allocator ()); // stack/stack
}
// Copy constructor.
//
{
vector s1 ({"abc"}), s2 (s1);
assert (s1 == s2 && s2.capacity () == 2 && small (s2));
vector l1 ({"abc", "ABC", "xyz"}), l2 (l1);
assert (l1 == l2 && !small (l2));
}
// Move constructor.
//
{
struct mstring: string // Move-only string.
{
mstring () = default;
explicit mstring (const char* s): string (s) {}
mstring (mstring&&) = default;
mstring& operator= (mstring&&) = default;
mstring (const mstring&) = delete;
mstring& operator= (const mstring&) = delete;
};
using vector = small_vector<mstring, 2>;
{
vector s1;
s1.emplace_back ("abc");
vector s2 (move (s1));
assert (s2[0] == "abc" && s2.capacity () == 2 && small (s2));
assert (s1.empty ()); // The source vector must be empty now.
}
{
vector s1;
s1.emplace_back ("abc");
s1.emplace_back ("ABC");
vector s2 (move (s1));
assert (s2[0] == "abc" && s2[1] == "ABC" &&
s2.capacity () == 2 && small (s2));
}
vector l1;
l1.emplace_back ("abc");
l1.emplace_back ("ABC");
l1.emplace_back ("xyz");
vector l2 (move (l1));
assert (l2[0] == "abc" && l2[1] == "ABC" && l2[2] == "xyz" && !small (l2));
}
// Other constructors.
//
{
const char* sa[] = {"abc"};
const char* la[] = {"abc", "ABC", "xyz"};
vector s (sa, sa + 1);
assert (s[0] == "abc" && s.capacity () == 2 && small (s));
vector l (la, la + 3);
assert (l[0] == "abc" && l[1] == "ABC" && l[2] == "xyz" && !small (l));
}
{
vector s (1, "abc");
assert (s[0] == "abc" && s.capacity () == 2 && small (s));
vector l (3, "abc");
assert (l[0] == "abc" && l[2] == "abc" && !small (l));
}
{
vector s (1);
assert (s[0] == "" && s.capacity () == 2 && small (s));
vector l (3);
assert (l[0] == "" && l[2] == "" && !small (l));
}
}
| 23.098039 | 79 | 0.50481 | [
"vector"
] |
cc025fc28231e83f08cac852b15c16fdbf327cbc | 5,137 | cpp | C++ | Hackerrank/Magic Spells/Magic Spells.cpp | rajatjha28/CPP-Questions-and-Solutions | fc5bae0da3dc7aed69e663e93128cd899b7bb263 | [
"MIT"
] | 42 | 2021-09-26T18:02:52.000Z | 2022-03-15T01:52:15.000Z | Hackerrank/Magic Spells/Magic Spells.cpp | rajatjha28/CPP-Questions-and-Solutions | fc5bae0da3dc7aed69e663e93128cd899b7bb263 | [
"MIT"
] | 404 | 2021-09-24T19:55:10.000Z | 2021-11-03T05:47:47.000Z | Hackerrank/Magic Spells/Magic Spells.cpp | rajatjha28/CPP-Questions-and-Solutions | fc5bae0da3dc7aed69e663e93128cd899b7bb263 | [
"MIT"
] | 140 | 2021-09-22T20:50:04.000Z | 2022-01-22T16:59:09.000Z | //While playing a video game, you are battling a powerful dark wizard. He casts his spells from a distance, giving you only a few seconds to react and conjure your counterspells. For a counterspell to be effective, you must first identify what kind of spell you are dealing with.
//The wizard uses scrolls to conjure his spells, and sometimes he uses some of his generic spells that restore his stamina. In that case, you will be able to extract the name of the scroll from the spell. Then you need to find out how similar this new spell is to the spell formulas written in your spell journal.
//Spend some time reviewing the locked code in your editor, and complete the body of the counterspell function.
//Check Dynamic cast to get an idea of how to solve this challenge.
//Full Application Based Question.
//Logic:-
//The wizard will read t scrolls, which are hidden from you.
//Every time he casts a spell, it's passed as an argument to your counterspell function.
//Constraints
//1 <= t <= 100
//1 <= | s | <= 1000 , where s is a scroll name.
//Each scroll name, s , consists of uppercase and lowercase letters.
//After identifying the given spell, print its name and power.
//If it is a generic spell, find a subsequence of letters that are contained in both the spell name and your spell journal. Among all such subsequences, find and print the length of the longest one on a new line.
//these are different types of library required for this program.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// ThIS is the Spells code.
class Spell {
private:
string scrollName;
public:
Spell(): scrollName("") { }
Spell(string name): scrollName(name) { }
virtual ~Spell() { }
string revealScrollName() {
return scrollName;
}
};
//This is the Fireball Code.
class Fireball : public Spell {
private: int power;
public:
Fireball(int power): power(power) { }
void revealFirepower(){
cout << "Fireball: " << power << endl;
}
};
//This is the Frostbite Code.
class Frostbite : public Spell {
private: int power;
public:
Frostbite(int power): power(power) { }
void revealFrostpower(){
cout << "Frostbite: " << power << endl;
}
};
//This is the Thunderstorm Code.
class Thunderstorm : public Spell {
private: int power;
public:
Thunderstorm(int power): power(power) { }
void revealThunderpower(){
cout << "Thunderstorm: " << power << endl;
}
};
//This is the Waterbolt Code.
class Waterbolt : public Spell {
private: int power;
public:
Waterbolt(int power): power(power) { }
void revealWaterpower(){
cout << "Waterbolt: " << power << endl;
}
};
//This is the SpellJournal Code.
class SpellJournal {
public:
static string journal;
static string read() {
return journal;
}
};
string SpellJournal::journal = "";
void counterspell(Spell *spell) {
//This is the if-else ladder.
if (Fireball *fb = dynamic_cast<Fireball*>(spell))
{
fb->revealFirepower();
}
else if (Frostbite *fb = dynamic_cast<Frostbite*>(spell))
{
fb->revealFrostpower();
}
else if (Thunderstorm *ts = dynamic_cast<Thunderstorm*>(spell))
{
ts->revealThunderpower();
}
else if (Waterbolt *wb = dynamic_cast<Waterbolt*>(spell))
{
wb->revealWaterpower();
}
else
{
std::string strA = spell->revealScrollName();
std::string strB = SpellJournal::read();
int m = strA.length();
int n = strB.length();
std::vector<std::vector<int>> vLCSMatrix(m + 1, std::vector<int>(n + 1));
//This is the for loop and if-else ladder.
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
if (strA[i - 1] == strB[j - 1])
{
vLCSMatrix[i][j] = 1 + vLCSMatrix[i - 1][j - 1];
}
else
{
vLCSMatrix[i][j] = std::max(vLCSMatrix[i - 1][j], vLCSMatrix[i][j - 1]);
}
}
}
std::cout << vLCSMatrix[m][n] << std::endl;
}
}
//This is the If-else ladder.
class Wizard {
public:
Spell *cast() {
Spell *spell;
string s; cin >> s;
int power; cin >> power;
if(s == "fire") {
spell = new Fireball(power);
}
else if(s == "frost") {
spell = new Frostbite(power);
}
else if(s == "water") {
spell = new Waterbolt(power);
}
else if(s == "thunder") {
spell = new Thunderstorm(power);
}
else {
spell = new Spell(s);
cin >> SpellJournal::journal;
}
return spell;
}
};
int main() {
int T;
cin >> T;
Wizard Arawn;
while(T--) {
Spell *spell = Arawn.cast();
counterspell(spell);
}
return 0;
}
| 29.354286 | 313 | 0.576017 | [
"vector"
] |
cc1095425f12cfe12fc25e944bc8963d08eaa2ca | 22,640 | cpp | C++ | qttools/src/assistant/3rdparty/clucene/src/CLucene/index/IndexWriter.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | qttools/src/assistant/3rdparty/clucene/src/CLucene/index/IndexWriter.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | qttools/src/assistant/3rdparty/clucene/src/CLucene/index/IndexWriter.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2003-2006 Ben van Klinken and the CLucene Team
*
* Distributable under the terms of either the Apache License (Version 2.0) or
* the GNU Lesser General Public License, as specified in the COPYING file.
*
* Changes are Copyright (C) 2015 The Qt Company Ltd.
*/
#include "CLucene/StdHeader.h"
#include "IndexWriter.h"
#include "CLucene/document/Document.h"
#include "CLucene/store/Directory.h"
#include "CLucene/store/Lock.h"
#include "CLucene/util/VoidList.h"
#include "DocumentWriter.h"
#include "SegmentInfos.h"
#include "SegmentMerger.h"
CL_NS_USE(store)
CL_NS_USE(util)
CL_NS_USE(document)
CL_NS_USE(analysis)
CL_NS_DEF(index)
const QLatin1String IndexWriter::WRITE_LOCK_NAME("write.lock");
const QLatin1String IndexWriter::COMMIT_LOCK_NAME("commit.lock");
IndexWriter::IndexWriter(const QString& path, Analyzer* a, const bool create,
const bool _closeDir)
: directory(FSDirectory::getDirectory(path, create))
, analyzer(a)
, segmentInfos(true)
, closeDir(_closeDir)
{
//Func - Constructor
// Constructs an IndexWriter for the index in path.
//Pre - path != NULL and contains a named directory path
// a holds a valid reference to an analyzer and analyzes the text to
// be indexed create indicates if the indexWriter must create a new
// index located at path or just open it
//Post - If create is true, then a new, empty index has been created in
// path, replacing the index already there, if any. The named
// directory path is owned by this Instance
CND_PRECONDITION(!path.isEmpty(), "path is NULL");
//Continue initializing the instance by _IndexWriter
_IndexWriter(create);
}
IndexWriter::IndexWriter(Directory* d, Analyzer* a, const bool create,
const bool _closeDir)
: directory(_CL_POINTER(d))
, analyzer(a)
, segmentInfos(true)
, closeDir(_closeDir)
{
//Func - Constructor
// Constructs an IndexWriter for the index in path.
//Pre - d contains a valid reference to a directory
// a holds a valid reference to an analyzer and analyzes the text to
// be indexed create indicates if the indexWriter must create a new
// index located at path or just open it
//Post - If create is true, then a new, empty index has been created in
// path, replacing the index already there, if any. The directory d
// is not owned by this Instance
//Continue initializing the instance by _IndexWriter
_IndexWriter ( create );
}
void IndexWriter::_IndexWriter(const bool create)
{
//Func - Initialises the instances
//Pre - create indicates if the indexWriter must create a new index
// located at path or just open it
similarity = CL_NS(search)::Similarity::getDefault();
useCompoundFile = true;
if ( directory->getDirectoryType() == RAMDirectory::DirectoryType() )
useCompoundFile = false;
//Create a ramDirectory
ramDirectory = _CLNEW TransactionalRAMDirectory;
CND_CONDITION(ramDirectory != NULL, "ramDirectory is NULL");
//Initialize the writeLock to
writeLock = NULL;
//initialise the settings...
maxFieldLength = DEFAULT_MAX_FIELD_LENGTH;
mergeFactor = DEFAULT_MERGE_FACTOR;
maxMergeDocs = DEFAULT_MAX_MERGE_DOCS;
writeLockTimeout = WRITE_LOCK_TIMEOUT;
commitLockTimeout = COMMIT_LOCK_TIMEOUT;
minMergeDocs = DEFAULT_MAX_BUFFERED_DOCS;
termIndexInterval = DEFAULT_TERM_INDEX_INTERVAL;
//Create a new lock using the name "write.lock"
LuceneLock* newLock = directory->makeLock(IndexWriter::WRITE_LOCK_NAME);
//Condition check to see if newLock has been allocated properly
CND_CONDITION(newLock != NULL,
"No memory could be allocated for LuceneLock newLock");
//Try to obtain a write lock
if (!newLock->obtain(writeLockTimeout)){
//Write lock could not be obtained so delete it
_CLDELETE(newLock);
//Reset the instance
_finalize();
//throw an exception because no writelock could be created or obtained
_CLTHROWA(CL_ERR_IO, "Index locked for write or no write access." );
}
//The Write Lock has been obtained so save it for later use
this->writeLock = newLock;
//Create a new lock using the name "commit.lock"
LuceneLock* lock = directory->makeLock(IndexWriter::COMMIT_LOCK_NAME);
//Condition check to see if lock has been allocated properly
CND_CONDITION(lock != NULL, "No memory could be allocated for LuceneLock lock");
LockWith2 with(lock, commitLockTimeout, this, NULL, create);
{
SCOPED_LOCK_MUTEX(directory->THIS_LOCK) // in- & inter-process sync
with.run();
}
//Release the commit lock
_CLDELETE(lock);
isOpen = true;
}
IndexWriter::~IndexWriter()
{
//Func - Destructor
//Pre - true
//Post - The instance has been destroyed
close();
_finalize();
}
void IndexWriter::close()
{
//Func - Flushes all changes to an index, closes all associated files, and
// closes the directory that the index is stored in.
//Pre - closeDir indicates if the directory must be closed or not
//Post - All the changes have been flushed to disk and the write lock has
// been released. The ramDirectory has also been closed. The
// directory has been closed if the reference count of the directory
// reaches zero
SCOPED_LOCK_MUTEX(THIS_LOCK)
if (isOpen) {
//Flush the Ram Segments
flushRamSegments();
//Close the ram directory
if (ramDirectory != NULL) {
ramDirectory->close();
_CLDECDELETE(ramDirectory);
}
//Check if this instance must close the directory
if (closeDir)
directory->close();
_CLDECDELETE(directory);
// release write lock
if (writeLock != NULL) {
writeLock->release();
_CLDELETE(writeLock);
}
isOpen = false;
}
}
void IndexWriter::_finalize()
{
//Func - Releases all the resources of the instance
//Pre - true
//Post - All the releases have been released
if(writeLock != NULL) {
//release write lock
writeLock->release();
_CLDELETE( writeLock );
}
//Delete the ramDirectory
if (ramDirectory != NULL) {
ramDirectory->close();
_CLDECDELETE(ramDirectory);
}
}
int32_t IndexWriter::docCount()
{
//Func - Counts the number of documents in the index
//Pre - true
//Post - The number of documents have been returned
SCOPED_LOCK_MUTEX(THIS_LOCK)
//Initialize count
int32_t count = 0;
//Iterate through all segmentInfos
for (int32_t i = 0; i < segmentInfos.size(); i++) {
//Get the i-th SegmentInfo
SegmentInfo* si = segmentInfos.info(i);
//Retrieve the number of documents of the segment and add it to count
count += si->docCount;
}
return count;
}
void IndexWriter::addDocument(Document* doc, Analyzer* analyzer)
{
//Func - Adds a document to the index
//Pre - doc contains a valid reference to a document
// ramDirectory != NULL
//Post - The document has been added to the index of this IndexWriter
CND_PRECONDITION(ramDirectory != NULL, "ramDirectory is NULL");
if (analyzer == NULL)
analyzer = this->analyzer;
ramDirectory->transStart();
try {
QString segmentName = newSegmentName();
CND_CONDITION(!segmentName.isEmpty(), "segmentName is NULL");
try {
//Create the DocumentWriter using a ramDirectory and analyzer
// supplied by the IndexWriter (this).
DocumentWriter* dw = _CLNEW DocumentWriter(ramDirectory, analyzer,
this );
CND_CONDITION(dw != NULL, "dw is NULL");
try {
//Add the client-supplied document to the new segment.
dw->addDocument(segmentName, doc);
} _CLFINALLY (
_CLDELETE(dw);
);
//Create a new SegmentInfo instance about this new segment.
SegmentInfo* si = _CLNEW SegmentInfo(segmentName, 1, ramDirectory);
CND_CONDITION(si != NULL, "Si is NULL");
{
SCOPED_LOCK_MUTEX(THIS_LOCK)
//Add the info object for this particular segment to the list
// of all segmentInfos->
segmentInfos.add(si);
//Check to see if the segments must be merged
maybeMergeSegments();
}
} _CLFINALLY()
} catch (...) {
ramDirectory->transAbort();
throw;
}
ramDirectory->transCommit();
}
void IndexWriter::optimize()
{
//Func - Optimizes the index for which this Instance is responsible
//Pre - true
//Post -
SCOPED_LOCK_MUTEX(THIS_LOCK)
//Flush the RamSegments to disk
flushRamSegments();
while (segmentInfos.size() > 1
|| (segmentInfos.size() == 1
&& (SegmentReader::hasDeletions(segmentInfos.info(0))
|| segmentInfos.info(0)->getDir()!=directory
|| (useCompoundFile
&& (!SegmentReader::usesCompoundFile(segmentInfos.info(0))
|| SegmentReader::hasSeparateNorms(segmentInfos.info(0))))))) {
int32_t minSegment = segmentInfos.size() - mergeFactor;
mergeSegments(minSegment < 0 ? 0 : minSegment);
}
}
QString IndexWriter::newSegmentName()
{
SCOPED_LOCK_MUTEX(THIS_LOCK)
return QLatin1Char('_') + QString::number(segmentInfos.counter++, 36);
}
void IndexWriter::flushRamSegments()
{
//Func - Merges all RAM-resident segments.
//Pre - ramDirectory != NULL
//Post - The RAM-resident segments have been merged to disk
CND_PRECONDITION(ramDirectory != NULL, "ramDirectory is NULL");
int32_t minSegment = segmentInfos.size()-1; //don't make this unsigned...
CND_CONDITION(minSegment >= -1, "minSegment must be >= -1");
int32_t docCount = 0;
//Iterate through all the segements and check if the directory is a ramDirectory
while (minSegment >= 0 &&
segmentInfos.info(minSegment)->getDir() == ramDirectory) {
docCount += segmentInfos.info(minSegment)->docCount;
minSegment--;
}
if (minSegment < 0 || // add one FS segment?
(docCount + segmentInfos.info(minSegment)->docCount) > mergeFactor ||
!(segmentInfos.info(segmentInfos.size()-1)->getDir() == ramDirectory))
minSegment++;
CND_CONDITION(minSegment >= 0, "minSegment must be >= 0");
if (minSegment >= segmentInfos.size())
return; // none to merge
mergeSegments(minSegment);
}
void IndexWriter::maybeMergeSegments() {
//Func - Incremental Segment Merger
//Pre -
//Post -
int64_t targetMergeDocs = minMergeDocs;
// find segments smaller than current target size
while (targetMergeDocs <= maxMergeDocs) {
int32_t minSegment = segmentInfos.size();
int32_t mergeDocs = 0;
while (--minSegment >= 0) {
SegmentInfo* si = segmentInfos.info(minSegment);
if (si->docCount >= targetMergeDocs)
break;
mergeDocs += si->docCount;
}
if (mergeDocs >= targetMergeDocs){
// found a merge to do
mergeSegments(minSegment+1);
}else
break;
//increase target size
targetMergeDocs *= mergeFactor;
}
}
void IndexWriter::mergeSegments(const uint32_t minSegment)
{
mergeSegments(minSegment, segmentInfos.size());
}
void IndexWriter::mergeSegments(const uint32_t minSegment, const uint32_t end)
{
CLVector<SegmentReader*> segmentsToDelete(false);
QString mergedName = newSegmentName();
#ifdef _CL_DEBUG_INFO
fprintf(_CL_DEBUG_INFO, "merging segments\n");
#endif
SegmentMerger merger(this, mergedName);
for (size_t i = minSegment; i < end; i++) {
SegmentInfo* si = segmentInfos.info(i);
#ifdef _CL_DEBUG_INFO
fprintf(_CL_DEBUG_INFO, " %s (%d docs)\n",
si->name.toLocal8Bit().constData(), si->docCount);
#endif
SegmentReader* reader = _CLNEW SegmentReader(si);
merger.add(reader);
// if we own the directory
if ((reader->getDirectory() == this->directory)
|| (reader->getDirectory() == this->ramDirectory)) {
// queue segment for deletion
segmentsToDelete.push_back(reader);
}
}
int32_t mergedDocCount = merger.merge();
#ifdef _CL_DEBUG_INFO
fprintf(_CL_DEBUG_INFO, "\n into %s (%d docs)\n",
mergedName.toLocal8Bit().constData(), mergedDocCount);
#endif
segmentInfos.clearto(minSegment);// remove old infos & add new
segmentInfos.add(_CLNEW SegmentInfo(mergedName, mergedDocCount, directory));
// close readers before we attempt to delete now-obsolete segments
merger.closeReaders();
LuceneLock* lock = directory->makeLock(IndexWriter::COMMIT_LOCK_NAME);
LockWith2 with (lock, commitLockTimeout, this, &segmentsToDelete, true);
{
SCOPED_LOCK_MUTEX(directory->THIS_LOCK) // in- & inter-process sync
with.run();
}
_CLDELETE( lock );
if (useCompoundFile) {
QStringList filesToDelete;
merger.createCompoundFile(mergedName + QLatin1String(".tmp"), filesToDelete);
LuceneLock* lock = directory->makeLock(IndexWriter::COMMIT_LOCK_NAME);
LockWithCFS with(lock, commitLockTimeout, directory, this, mergedName,
filesToDelete);
{
SCOPED_LOCK_MUTEX(directory->THIS_LOCK) // in- & inter-process sync
with.run();
}
_CLDELETE(lock);
}
}
void IndexWriter::deleteSegments(CLVector<SegmentReader*>* segments)
{
QStringList deletable;
{//scope delete deleteArray object
QStringList deleteArray;
readDeleteableFiles(deleteArray);
deleteFiles(deleteArray, deletable); // try to delete deleteable
}
QStringList files;
for (uint32_t i = 0; i < segments->size(); i++) {
SegmentReader* reader = (*segments)[i];
files.clear();
reader->files(files);
if (reader->getDirectory() == this->directory)
deleteFiles(files, deletable); // try to delete our files
else
deleteFiles(files, reader->getDirectory()); // delete, eg, RAM files
}
writeDeleteableFiles(deletable); // note files we can't delete
}
void IndexWriter::deleteFiles(const QStringList& files)
{
QStringList currentDeletable;
readDeleteableFiles(currentDeletable);
// try to delete deleteable
QStringList deletable;
deleteFiles(currentDeletable, deletable);
// try to delete our files
deleteFiles(files, deletable);
// note files we can't delete
writeDeleteableFiles(deletable);
}
void IndexWriter::readDeleteableFiles(QStringList& result)
{
if (!directory->fileExists(QLatin1String("deletable")))
return;
IndexInput* input = directory->openInput(QLatin1String("deletable"));
try {
// read file names
TCHAR tname[CL_MAX_PATH];
for (int32_t i = input->readInt(); i > 0; i--) {
int32_t read = input->readString(tname, CL_MAX_PATH);
result.push_back(QString::fromWCharArray(tname, read));
}
} _CLFINALLY (
input->close();
_CLDELETE(input);
);
}
void IndexWriter::deleteFiles(const QStringList& files, QStringList& deletable)
{
QStringList::const_iterator itr;
for (itr = files.begin(); itr != files.end(); ++itr) {
if (!getDirectory()->fileExists((*itr)))
continue;
if (!getDirectory()->deleteFile((*itr), false)) {
if (directory->fileExists((*itr))) {
#ifdef _CL_DEBUG_INFO
fprintf(_CL_DEBUG_INFO, "%s; Will re-try later.\n", err.what());
#endif
// add to deletable
deletable.push_back((*itr));
}
}
}
}
void IndexWriter::deleteFiles(const QStringList& files, Directory* directory)
{
QStringList::const_iterator itr;
for (itr = files.begin(); itr != files.end(); ++itr)
directory->deleteFile((*itr), true);
}
void IndexWriter::writeDeleteableFiles(const QStringList& files)
{
IndexOutput* output = directory->createOutput(QLatin1String("deleteable.new"));
try {
output->writeInt(files.size());
TCHAR tfile[CL_MAX_PATH];
QStringList::const_iterator itr;
for (itr = files.begin(); itr != files.end(); ++itr) {
tfile[(*itr).toWCharArray(tfile)] = '\0';
output->writeString(tfile, _tcslen(tfile));
}
} _CLFINALLY (
output->close();
_CLDELETE(output);
);
directory->renameFile(QLatin1String("deleteable.new"),
QLatin1String("deletable"));
}
void IndexWriter::addIndexes(Directory** dirs)
{
//Func - Add several indexes located in different directories into the current
// one managed by this instance
//Pre - dirs != NULL and contains directories of several indexes
// dirsLength > 0 and contains the number of directories
//Post - The indexes located in the directories in dirs have been merged with
// the pre(current) index. The Resulting index has also been optimized
SCOPED_LOCK_MUTEX(THIS_LOCK)
CND_PRECONDITION(dirs != NULL, "dirs is NULL");
// start with zero or 1 seg so optimize the current
optimize();
int32_t start = segmentInfos.size();
//Iterate through the directories
for (int32_t i = 0; dirs[i] != NULL; ++i) {
// DSR: Changed SegmentInfos constructor arg (see bug discussion below).
SegmentInfos sis(false);
sis.read(dirs[i]);
for (int32_t j = 0; j < sis.size(); j++)
segmentInfos.add(sis.info(j)); // add each info
}
// commented out by tbusch to solve a bug and to be conform with
// java lucene
// merge newly added segments in log(n) passes
//while (segmentInfos.size() > start + mergeFactor) {
// for (int32_t base = start; base < segmentInfos.size(); base++) {
// int32_t end = min(segmentInfos.size(), base + mergeFactor);
// if (end - base > 1)
// mergeSegments(base, end);
// }
//}
// cleanup
optimize();
}
void IndexWriter::addIndexes(IndexReader** readers)
{
SCOPED_LOCK_MUTEX(THIS_LOCK)
optimize(); // start with zero or 1 seg
QString mergedName = newSegmentName();
SegmentMerger merger(this, mergedName);
CLVector<SegmentReader*> segmentsToDelete;
SegmentReader* sReader = NULL;
if (segmentInfos.size() == 1) { // add existing index, if any
sReader = _CLNEW SegmentReader(segmentInfos.info(0));
merger.add(sReader);
segmentsToDelete.push_back(sReader); // queue segment for deletion
}
int32_t readersLength = 0;
while (readers[readersLength] != NULL)
merger.add(readers[readersLength++]);
int32_t docCount = merger.merge(); // merge 'em
// pop old infos & add new
segmentInfos.clearto(0);
segmentInfos.add(_CLNEW SegmentInfo(mergedName, docCount, directory));
if (sReader != NULL) {
sReader->close();
_CLDELETE(sReader);
}
LuceneLock* lock = directory->makeLock(IndexWriter::COMMIT_LOCK_NAME);
LockWith2 with(lock, commitLockTimeout, this, &segmentsToDelete, true);
{
// in- & inter-process sync
SCOPED_LOCK_MUTEX(directory->THIS_LOCK)
with.run();
}
_CLDELETE(lock);
if (useCompoundFile) {
QStringList filesToDelete;
merger.createCompoundFile(mergedName + QLatin1String(".tmp"),
filesToDelete);
LuceneLock* cfslock = directory->makeLock(IndexWriter::COMMIT_LOCK_NAME);
LockWithCFS with(cfslock, commitLockTimeout, directory, this, mergedName,
filesToDelete);
{
// in- & inter-process sync
SCOPED_LOCK_MUTEX(directory->THIS_LOCK)
with.run();
}
_CLDELETE(cfslock);
}
}
// #pragma mark -- IndexWriter::LockWith2
IndexWriter::LockWith2::LockWith2(CL_NS(store)::LuceneLock* lock,
int64_t lockWaitTimeout,
IndexWriter* indexWriter,
CL_NS(util)::CLVector<SegmentReader*>* std,
bool _create)
: CL_NS(store)::LuceneLockWith<void>(lock, lockWaitTimeout)
, create(_create)
, writer(indexWriter)
, segmentsToDelete(std)
{
}
void IndexWriter::LockWith2::doBody()
{
//Func - Writes segmentInfos to or reads segmentInfos from disk
//Pre - writer != NULL
//Post - if create is true then segementInfos has been written to disk
// otherwise segmentInfos has been read from disk
CND_PRECONDITION(writer != NULL, "writer is NULL");
if (create) {
writer->segmentInfos.write(writer->getDirectory());
// delete now-unused segments
if (segmentsToDelete != NULL)
writer->deleteSegments(segmentsToDelete);
} else {
writer->segmentInfos.read(writer->getDirectory());
}
}
// #pragma mark -- IndexWriter::LockWithCFS
IndexWriter::LockWithCFS::LockWithCFS(CL_NS(store)::LuceneLock* lock,
int64_t lockWaitTimeout,
CL_NS(store)::Directory* dir,
IndexWriter* indexWriter,
const QString& segmentName,
const QStringList& ftd)
: CL_NS(store)::LuceneLockWith<void>(lock, lockWaitTimeout)
, segName(segmentName)
, writer(indexWriter)
, directory(dir)
, filesToDelete(ftd)
{
}
void IndexWriter::LockWithCFS::doBody()
{
//Func - Writes segmentInfos to or reads segmentInfos from disk
//Pre - writer != NULL
//Post - if create is true then segementInfos has been written to disk
// otherwise segmentInfos has been read from disk
CND_PRECONDITION(directory != NULL, "directory is NULL");
CND_PRECONDITION(!segName.isEmpty(), "mergedName is NULL");
// make compound file visible for SegmentReaders
directory->renameFile(segName + QLatin1String(".tmp"),
segName + QLatin1String(".cfs"));
// delete now unused files of segment
writer->deleteFiles(filesToDelete);
}
CL_NS_END
| 32.43553 | 85 | 0.634541 | [
"object"
] |
cc110c099e38c32fe76864fcb15cffb3af317abe | 2,560 | cpp | C++ | 3dbody/src/scene/SceneCamera.cpp | GuangfuWang/threedbody | 31c544c25e524cecf107a505c3b4438fc04cd766 | [
"BSD-2-Clause"
] | null | null | null | 3dbody/src/scene/SceneCamera.cpp | GuangfuWang/threedbody | 31c544c25e524cecf107a505c3b4438fc04cd766 | [
"BSD-2-Clause"
] | null | null | null | 3dbody/src/scene/SceneCamera.cpp | GuangfuWang/threedbody | 31c544c25e524cecf107a505c3b4438fc04cd766 | [
"BSD-2-Clause"
] | null | null | null | #include "include/scene/SceneCamera.h"
#include <glm/gtx/norm.hpp>
namespace gf {
void SceneCamera::update(Shader *shader) {
shader->setMat4(mModelMatrix, "model");
shader->setMat4(mViewMatrix, "view");
shader->setMat4(mProjection, "projection");
shader->setVec3(mPosition, "camPos");
}
void SceneCamera::onPanMovement(const double &x, const double &y) {
GF_CORE_INFO("Panning...");
float delta_x = x - mCurrentMonitorPos.x;
float delta_y = y - mCurrentMonitorPos.y;
if (delta_x < mSensitivity && delta_y < mSensitivity) {
mCurrentMonitorPos.x = x;
mCurrentMonitorPos.y = y;
}
Vec monitorX = glm::cross(mCurrentFocus, mUp);
monitorX = glm::normalize(monitorX) * delta_x * mPanSpeed;
mPosition += monitorX + mUp * delta_y * mPanSpeed;
updateViewMatrix();
mCurrentMonitorPos.x = x;
mCurrentMonitorPos.y = y;
}
void SceneCamera::onRotateMovement(const double &x, const double &y) {
GF_CORE_INFO("Rotating...");
float delta_x = x - mCurrentMonitorPos.x;
float delta_y = y - mCurrentMonitorPos.y;
if (delta_x < mSensitivity && delta_y < mSensitivity) {
mCurrentMonitorPos.x = x;
mCurrentMonitorPos.y = y;
}
delta_x *= mRotateSpeed;
delta_y *= mRotateSpeed;
Quaternion rotateAngle = Quaternion(0.0f, -delta_x, -delta_y, 0.0f);
mUp = glm::rotate(rotateAngle, mUp);
mCurrentFocus = glm::rotate(rotateAngle, mCurrentFocus);
mPosition = mSceneCenter - mCurrentFocus;
updateViewMatrix();
mCurrentMonitorPos.x = x;
mCurrentMonitorPos.y = y;
}
void SceneCamera::onZoomMovement(const double &wheelOffset) {
mPosition += glm::normalize(mCurrentFocus) * (float) wheelOffset * mZoomSpeed;
updateViewMatrix();
}
Mat4 SceneCamera::computeViewMatrix(const Vec &eye,
const Vec ¤tFocus,
const Vec &up) {
return glm::lookAt(eye, glm::normalize(currentFocus), up);
}
void SceneCamera::updateViewMatrix() {
mViewMatrix = computeViewMatrix(mPosition, mCurrentFocus, mUp);
mViewMatrix = glm::inverse(mViewMatrix);
}
void SceneCamera::setScenePositionInfo(
const Vec &sceneCenter,
const Vec &sceneMinBox,
const Vec &sceneMaxBox) {
updateViewMatrix();
}
}
| 33.684211 | 86 | 0.601172 | [
"model"
] |
cc13f6e3a4f470e26b24634a0529b65bf8e37990 | 422 | hpp | C++ | src/math/geometry/interval/interval.hpp | dmilos/math | 977cb171d8d582411cfab73a23ce85a8ccf3b132 | [
"Apache-2.0"
] | 3 | 2020-07-02T12:44:32.000Z | 2021-04-07T20:31:41.000Z | src/math/geometry/interval/interval.hpp | dmilos/math | 977cb171d8d582411cfab73a23ce85a8ccf3b132 | [
"Apache-2.0"
] | null | null | null | src/math/geometry/interval/interval.hpp | dmilos/math | 977cb171d8d582411cfab73a23ce85a8ccf3b132 | [
"Apache-2.0"
] | 1 | 2020-09-04T11:01:28.000Z | 2020-09-04T11:01:28.000Z | #include "./structure.hpp"
#include "./center.hpp"
#include "./extend.hpp"
#include "./in.hpp"
#include "./out.hpp"
#include "./intersect.hpp"
#include "./inflate.hpp"
#include "./valid.hpp"
#include "./volume.hpp"
#include "./translate.hpp"
#include "./correct.hpp"
#include "./load.hpp"
#include "./unit.hpp"
#include "./transform.hpp"
#include "./confine.hpp"
#include "./clip.hpp"
#include "./size.hpp" | 24.823529 | 27 | 0.64218 | [
"transform"
] |
cc160371c20d9c94c6b7674640229ede949a1b9b | 294 | cc | C++ | Projects/OpenGrafik/opengrafik-2/src/canvas/canvas.cc | fredmorcos/attic | 0da3b94aa525df59ddc977c32cb71c243ffd0dbd | [
"Unlicense"
] | 2 | 2021-01-24T09:00:51.000Z | 2022-01-23T20:52:17.000Z | Projects/OpenGrafik/opengrafik-2/src/canvas/canvas.cc | fredmorcos/attic | 0da3b94aa525df59ddc977c32cb71c243ffd0dbd | [
"Unlicense"
] | 6 | 2020-02-29T01:59:03.000Z | 2022-02-15T10:25:40.000Z | Projects/OpenGrafik/opengrafik-2/src/canvas/canvas.cc | fredmorcos/attic | 0da3b94aa525df59ddc977c32cb71c243ffd0dbd | [
"Unlicense"
] | 1 | 2019-03-22T14:41:21.000Z | 2019-03-22T14:41:21.000Z | #include "canvas.h"
#include "shape.h"
Canvas::Canvas() {}
Canvas::~Canvas()
{
while (!ShapeList.empty())
{
delete ShapeList.front();
ShapeList.pop_front();
}
}
void Canvas::addShape(Shape *s)
{
ShapeList.push_back(s);
}
void Canvas::removeShape(Shape *s)
{
ShapeList.remove(s);
}
| 12.25 | 34 | 0.659864 | [
"shape"
] |
cc1a90f994fd196d15c53e3169c740b87db92586 | 2,014 | cpp | C++ | Contrib-Intel/RSD-PSME-RMM/common/agent-framework/src/module/requests/psme/component_notification.cpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 5 | 2019-11-11T07:57:26.000Z | 2022-03-28T08:26:53.000Z | Contrib-Intel/RSD-PSME-RMM/common/agent-framework/src/module/requests/psme/component_notification.cpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 3 | 2019-09-05T21:47:07.000Z | 2019-09-17T18:10:45.000Z | Contrib-Intel/RSD-PSME-RMM/common/agent-framework/src/module/requests/psme/component_notification.cpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 11 | 2019-07-20T00:16:32.000Z | 2022-01-11T14:17:48.000Z | /*!
* @copyright
* Copyright (c) 2017-2019 Intel Corporation
*
* @copyright
* 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
*
* @copyright
* http://www.apache.org/licenses/LICENSE-2.0
*
* @copyright
* 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.
*
* @file module/requests/psme/component_notification.cpp
*
* @brief PSME component_notification request
* */
#include "agent-framework/module/requests/psme/component_notification.hpp"
#include "json-wrapper/json-wrapper.hpp"
using namespace agent_framework::model;
using namespace agent_framework::model::requests;
ComponentNotification::ComponentNotification() {}
json::Json ComponentNotification::to_json() const {
json::Json value = json::Json();
value[literals::ComponentNotification::GAMI_ID] = m_gami_id;
value[literals::ComponentNotification::NOTIFICATIONS] = json::Json::array();
for (const auto& notification : m_notifications) {
value[literals::ComponentNotification::NOTIFICATIONS].emplace_back(notification.to_json());
}
return value;
}
ComponentNotification ComponentNotification::from_json(const json::Json& value) {
ComponentNotification component_notification{};
component_notification.set_gami_id(value[literals::ComponentNotification::GAMI_ID]);
attribute::EventData::Vector notifications;
for (auto& notification_json : value.at(literals::ComponentNotification::NOTIFICATIONS)) {
notifications.emplace_back(attribute::EventData::from_json(notification_json));
}
component_notification.set_notifications(notifications);
return component_notification;
}
| 36.618182 | 99 | 0.759682 | [
"vector",
"model"
] |
cc21e9377f2308a1fcb4462d0116d62e0fec2919 | 7,309 | cpp | C++ | Code/Engine/Render/Components/Component_SkeletalMesh.cpp | JuanluMorales/KRG | f3a11de469586a4ef0db835af4bc4589e6b70779 | [
"MIT"
] | 419 | 2022-01-27T19:37:43.000Z | 2022-03-31T06:14:22.000Z | Code/Engine/Render/Components/Component_SkeletalMesh.cpp | jagt/KRG | ba20cd8798997b0450491b0cc04dc817c4a4bc76 | [
"MIT"
] | 2 | 2022-01-28T20:35:33.000Z | 2022-03-13T17:42:52.000Z | Code/Engine/Render/Components/Component_SkeletalMesh.cpp | jagt/KRG | ba20cd8798997b0450491b0cc04dc817c4a4bc76 | [
"MIT"
] | 20 | 2022-01-27T20:41:02.000Z | 2022-03-26T16:16:57.000Z | #include "Component_SkeletalMesh.h"
#include "System/Animation/AnimationPose.h"
#include "System/Core/Drawing/DebugDrawing.h"
#include "System/Core/Profiling/Profiling.h"
//-------------------------------------------------------------------------
namespace KRG::Render
{
void SkeletalMeshComponent::Initialize()
{
MeshComponent::Initialize();
if ( HasMeshResourceSet() )
{
KRG_ASSERT( m_pMesh.IsLoaded() );
SetLocalBounds( m_pMesh->GetBounds() );
if ( HasSkeletonResourceSet() )
{
GenerateAnimationBoneMap();
}
// Set mesh to reference pose
//-------------------------------------------------------------------------
m_boneTransforms.resize( m_pMesh->GetNumBones() );
ResetPose();
//-------------------------------------------------------------------------
// Allocate skinning transforms and calculate initial values
m_skinningTransforms.resize( m_boneTransforms.size() );
FinalizePose();
}
}
void SkeletalMeshComponent::Shutdown()
{
m_boneTransforms.clear();
m_skinningTransforms.clear();
m_animToMeshBoneMap.clear();
MeshComponent::Shutdown();
}
TVector<TResourcePtr<Render::Material>> const& SkeletalMeshComponent::GetDefaultMaterials() const
{
KRG_ASSERT( IsInitialized() && HasMeshResourceSet() );
return m_pMesh->GetMaterials();
}
bool SkeletalMeshComponent::TryFindAttachmentSocketTransform( StringID socketID, Transform& outSocketWorldTransform ) const
{
KRG_ASSERT( socketID.IsValid() );
outSocketWorldTransform = GetWorldTransform();
if ( m_pMesh.IsValid() && m_pMesh.IsLoaded() )
{
auto const boneIdx = m_pMesh->GetBoneIndex( socketID );
if ( boneIdx != InvalidIndex )
{
if ( IsInitialized() )
{
outSocketWorldTransform = m_boneTransforms[boneIdx] * outSocketWorldTransform;
}
else
{
outSocketWorldTransform = m_pMesh->GetBindPose()[boneIdx] * outSocketWorldTransform;
}
return true;
}
}
return false;
}
bool SkeletalMeshComponent::HasSocket( StringID socketID ) const
{
KRG_ASSERT( socketID.IsValid() );
if ( m_pMesh.IsValid() && m_pMesh.IsLoaded() )
{
int32 boneIdx = m_pMesh->GetBoneIndex( socketID );
return boneIdx != InvalidIndex;
}
return false;
}
//-------------------------------------------------------------------------
void SkeletalMeshComponent::SetSkeleton( ResourceID skeletonResourceID )
{
KRG_ASSERT( IsUnloaded() );
KRG_ASSERT( skeletonResourceID.IsValid() );
m_pSkeleton = skeletonResourceID;
}
void SkeletalMeshComponent::SetPose( Animation::Pose const* pPose )
{
KRG_PROFILE_FUNCTION_ANIMATION();
KRG_ASSERT( IsInitialized() );
KRG_ASSERT( HasMeshResourceSet() && HasSkeletonResourceSet() );
KRG_ASSERT( !m_animToMeshBoneMap.empty() );
KRG_ASSERT( pPose != nullptr && pPose->HasGlobalTransforms() );
int32 const numAnimBones = pPose->GetNumBones();
for ( auto animBoneIdx = 0; animBoneIdx < numAnimBones; animBoneIdx++ )
{
int32 const meshBoneIdx = m_animToMeshBoneMap[animBoneIdx];
if ( meshBoneIdx != InvalidIndex )
{
Transform const boneTransform = pPose->GetGlobalTransform( animBoneIdx );
m_boneTransforms[meshBoneIdx] = boneTransform;
}
}
}
void SkeletalMeshComponent::ResetPose()
{
KRG_ASSERT( IsInitialized() );
if ( HasSkeletonResourceSet() )
{
Animation::Pose referencePose( m_pSkeleton.GetPtr() );
referencePose.CalculateGlobalTransforms();
SetPose( &referencePose );
}
else
{
m_boneTransforms = m_pMesh->GetBindPose();
}
}
void SkeletalMeshComponent::FinalizePose()
{
KRG_PROFILE_FUNCTION_RENDER();
KRG_ASSERT( m_pMesh.IsValid() && m_pMesh.IsLoaded() );
NotifySocketsUpdated();
UpdateBounds();
UpdateSkinningTransforms();
}
//-------------------------------------------------------------------------
void SkeletalMeshComponent::UpdateBounds()
{
KRG_ASSERT( m_pMesh.IsValid() && m_pMesh.IsLoaded() );
AABB newBounds;
for ( auto const& boneTransform : m_boneTransforms )
{
newBounds.AddPoint( boneTransform.GetTranslation() );
}
SetLocalBounds( OBB( newBounds ) );
}
void SkeletalMeshComponent::UpdateSkinningTransforms()
{
KRG_ASSERT( m_pMesh.IsValid() && m_pMesh.IsLoaded() );
auto const numBones = m_boneTransforms.size();
KRG_ASSERT( m_skinningTransforms.size() == numBones );
auto const& inverseBindPose = m_pMesh->GetInverseBindPose();
for ( auto i = 0; i < numBones; i++ )
{
Transform const skinningTransform = inverseBindPose[i] * m_boneTransforms[i];
m_skinningTransforms[i] = ( skinningTransform ).ToMatrix();
}
}
void SkeletalMeshComponent::GenerateAnimationBoneMap()
{
KRG_ASSERT( m_pMesh != nullptr && m_pSkeleton != nullptr );
auto const pMesh = GetMesh();
auto const numBones = m_pSkeleton->GetNumBones();
m_animToMeshBoneMap.resize( numBones, InvalidIndex );
for ( auto boneIdx = 0; boneIdx < numBones; boneIdx++ )
{
auto const& boneID = m_pSkeleton->GetBoneID( boneIdx );
m_animToMeshBoneMap[boneIdx] = pMesh->GetBoneIndex( boneID );
}
}
//-------------------------------------------------------------------------
#if KRG_DEVELOPMENT_TOOLS
void SkeletalMeshComponent::DrawPose( Drawing::DrawContext& drawingContext ) const
{
KRG_ASSERT( IsInitialized() );
if ( !m_pMesh.IsValid() || !m_pMesh.IsLoaded() )
{
return;
}
//-------------------------------------------------------------------------
Transform const& worldTransform = GetWorldTransform();
auto const numBones = m_boneTransforms.size();
Transform boneWorldTransform = m_boneTransforms[0] * worldTransform;
drawingContext.DrawBox( boneWorldTransform, Float3( 0.005f ), Colors::Orange );
drawingContext.DrawAxis( boneWorldTransform, 0.05f );
for ( auto i = 1; i < numBones; i++ )
{
boneWorldTransform = m_boneTransforms[i] * worldTransform;
auto const parentBoneIdx = m_pMesh->GetParentBoneIndex( i );
Transform const parentBoneWorldTransform = m_boneTransforms[parentBoneIdx] * worldTransform;
drawingContext.DrawLine( parentBoneWorldTransform.GetTranslation(), boneWorldTransform.GetTranslation(), Colors::Orange );
drawingContext.DrawAxis( boneWorldTransform, 0.03f, 2.0f );
}
}
#endif
}
| 32.198238 | 134 | 0.558353 | [
"mesh",
"render",
"transform"
] |
cc226c2562ed91aa6ed48c5c4e8b477dc72ed3c1 | 295 | cpp | C++ | src/Interpreter/Interpreter.cpp | atom9393/CUBE | b398a1c7b317047b89a7eeddf67aed1a78d20f36 | [
"MIT"
] | 7 | 2021-12-27T05:43:40.000Z | 2022-01-12T09:35:52.000Z | src/Interpreter/Interpreter.cpp | atom9393/CUBE | b398a1c7b317047b89a7eeddf67aed1a78d20f36 | [
"MIT"
] | 6 | 2021-12-24T11:29:05.000Z | 2022-01-11T12:23:19.000Z | src/Interpreter/Interpreter.cpp | atom9393/CUBE | b398a1c7b317047b89a7eeddf67aed1a78d20f36 | [
"MIT"
] | 1 | 2021-12-22T02:41:33.000Z | 2021-12-22T02:41:33.000Z | #include "error.h"
#include "debug.h"
#include "Token.h"
#include "Object.h"
#include "Node.h"
#include "BuiltinFunc.h"
#include "Interpreter.h"
static Interpreter* _instance;
Interpreter::Interpreter() {
_instance = this;
}
Interpreter* Interpreter::get_instance() {
return _instance;
}
| 16.388889 | 42 | 0.722034 | [
"object"
] |
cc2dfdb0a74a85cb60122d9103194a22ae8c8981 | 3,625 | cc | C++ | xdl/ps-plus/ps-plus/server/udf/hash_variable_initializer.cc | Ru-Xiang/x-deeplearning | 04cc0497150920c64b06bb8c314ef89977a3427a | [
"Apache-2.0"
] | 4,071 | 2018-12-13T04:17:38.000Z | 2022-03-30T03:29:35.000Z | xdl/ps-plus/ps-plus/server/udf/hash_variable_initializer.cc | laozhuang727/x-deeplearning | 781545783a4e2bbbda48fc64318fb2c6d8bbb3cc | [
"Apache-2.0"
] | 359 | 2018-12-21T01:14:57.000Z | 2022-02-15T07:18:02.000Z | xdl/ps-plus/ps-plus/server/udf/hash_variable_initializer.cc | laozhuang727/x-deeplearning | 781545783a4e2bbbda48fc64318fb2c6d8bbb3cc | [
"Apache-2.0"
] | 1,054 | 2018-12-20T09:57:42.000Z | 2022-03-29T07:16:53.000Z | /* Copyright (C) 2016-2018 Alibaba Group Holding Limited
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 "ps-plus/server/udf/simple_udf.h"
#include "ps-plus/common/hashmap.h"
#include "ps-plus/common/string_utils.h"
namespace ps {
namespace server {
namespace udf {
class HashVariableInitializer : public SimpleUdf<DataType, TensorShape, std::string, std::unique_ptr<Initializer>> {
public:
virtual Status SimpleRun(
UdfContext* ctx,
const DataType& dt,
const TensorShape& shape,
const std::string& extra_info,
const std::unique_ptr<Initializer>& initializer) const {
if (shape.IsScalar()) {
return Status::ArgumentError("Hash Shape Should not be Scalar");
}
std::unordered_map<std::string, std::string> kvs = StringUtils::ParseMap(extra_info);
bool hash64 = false;
int32_t bloom_filter_threthold = 0;
for (const auto iter : kvs) {
if (iter.first == "hash64" && iter.second == "true") {
hash64 = true;
} else if (iter.first == "bloom_filter") {
if (!StringUtils::strToInt32(iter.second.c_str(), bloom_filter_threthold)) {
return Status::ArgumentError("HashVariableInitializer: bloom_filter not int " + iter.first + "=" + iter.second);
}
if (bloom_filter_threthold >= 65500) {
return Status::ArgumentError("HashVariableInitializer: bloom_filter_threthold too large, only support < 65500, " + iter.first + "=" + iter.second);
}
GlobalBloomFilter::SetThrethold(bloom_filter_threthold);
}
}
if (bloom_filter_threthold != 0) {
LOG(INFO) << ctx->GetVariableName() << ", bloom_filter_threthold " << bloom_filter_threthold;
}
std::string var_name = ctx->GetVariableName();
Variable* var;
ps::Status status = GetStorageManager(ctx)->Get(var_name, &var);
if (!status.IsOk()) {
return ctx->GetStorageManager()->Set(var_name, [&]{
HashMap* hashmap = nullptr;
if (hash64) {
hashmap = new HashMapImpl<int64_t>(shape[0]);
} else {
hashmap = new HashMapImpl<Hash128Key>(shape[0]);
}
hashmap->SetBloomFilterThrethold(bloom_filter_threthold);
Variable* var = new Variable(new Tensor(dt, shape, initializer->Clone(), Tensor::TType::kSegment, true), new WrapperData<std::unique_ptr<HashMap> >(hashmap), var_name);
var->SetRealInited(true);
return var;
});
} else {
std::unique_ptr<HashMap>& hashmap = dynamic_cast<WrapperData<std::unique_ptr<HashMap> >*>(var->GetSlicer())->Internal();
if (hashmap.get() == nullptr) {
return Status::ArgumentError("hashmap is empty for " + var_name);
}
var->GetData()->SetInititalizer(initializer->Clone());
var->GetData()->InitChunkFrom(hashmap->GetSize());
hashmap->SetBloomFilterThrethold(bloom_filter_threthold);
var->SetRealInited(true);
return Status::Ok();
}
}
};
SIMPLE_UDF_REGISTER(HashVariableInitializer, HashVariableInitializer);
}
}
}
| 40.277778 | 180 | 0.654621 | [
"shape"
] |
cc2f6a6b4792f90a042ffeee92e47ffc0ed53549 | 668 | cpp | C++ | src/parser/transform/statement/transform_show.cpp | GuinsooLab/guinsoodb | f200538868738ae460f62fb89211deec946cefff | [
"MIT"
] | 1 | 2021-04-22T05:41:54.000Z | 2021-04-22T05:41:54.000Z | src/parser/transform/statement/transform_show.cpp | GuinsooLab/guinsoodb | f200538868738ae460f62fb89211deec946cefff | [
"MIT"
] | null | null | null | src/parser/transform/statement/transform_show.cpp | GuinsooLab/guinsoodb | f200538868738ae460f62fb89211deec946cefff | [
"MIT"
] | 1 | 2021-12-12T10:24:57.000Z | 2021-12-12T10:24:57.000Z | #include "guinsoodb/parser/statement/pragma_statement.hpp"
#include "guinsoodb/parser/transformer.hpp"
namespace guinsoodb {
unique_ptr<PragmaStatement> Transformer::TransformShow(guinsoodb_libpgquery::PGNode *node) {
// we transform SHOW x into PRAGMA SHOW('x')
auto stmt = reinterpret_cast<guinsoodb_libpgquery::PGVariableShowStmt *>(node);
auto result = make_unique<PragmaStatement>();
auto &info = *result->info;
if (string(stmt->name) == "tables") {
// show all tables
info.name = "show_tables";
} else {
// show one specific table
info.name = "show";
info.parameters.emplace_back(stmt->name);
}
return result;
}
} // namespace guinsoodb
| 24.740741 | 92 | 0.730539 | [
"transform"
] |
cc3b5005cac13e369f8bf95bd502ce5a8c9541ab | 618 | cpp | C++ | spec/cpp_stl_98/test_bits_signed_b64_le.cpp | DarkShadow44/kaitai_struct_tests | 4bb13cef82965cca66dda2eb2b77cd64e9f70a12 | [
"MIT"
] | 11 | 2018-04-01T03:58:15.000Z | 2021-08-14T09:04:55.000Z | spec/cpp_stl_98/test_bits_signed_b64_le.cpp | DarkShadow44/kaitai_struct_tests | 4bb13cef82965cca66dda2eb2b77cd64e9f70a12 | [
"MIT"
] | 73 | 2016-07-20T10:27:15.000Z | 2020-12-17T18:56:46.000Z | spec/cpp_stl_98/test_bits_signed_b64_le.cpp | DarkShadow44/kaitai_struct_tests | 4bb13cef82965cca66dda2eb2b77cd64e9f70a12 | [
"MIT"
] | 37 | 2016-08-15T08:25:56.000Z | 2021-08-28T14:48:46.000Z | // Autogenerated from KST: please remove this line if doing any edits by hand!
#include <boost/test/unit_test.hpp>
#include "bits_signed_b64_le.h"
#include <iostream>
#include <fstream>
#include <vector>
BOOST_AUTO_TEST_CASE(test_bits_signed_b64_le) {
std::ifstream ifs("src/bits_signed_b64_le.bin", std::ifstream::binary);
kaitai::kstream ks(&ifs);
bits_signed_b64_le_t* r = new bits_signed_b64_le_t(&ks);
BOOST_CHECK_EQUAL(r->a_num(), 0);
BOOST_CHECK_EQUAL(r->a_bit(), true);
BOOST_CHECK_EQUAL(r->b_num(), 9223372036854775807LL);
BOOST_CHECK_EQUAL(r->b_bit(), false);
delete r;
}
| 29.428571 | 78 | 0.726537 | [
"vector"
] |
cc42b63e27a63edcb72d78713588fa7acae33fd9 | 2,247 | cpp | C++ | src/main.cpp | nabijaczleweli/ctffs | b193ccc0ebcabe9bf3e7d74719b35957d7763f3a | [
"MIT"
] | null | null | null | src/main.cpp | nabijaczleweli/ctffs | b193ccc0ebcabe9bf3e7d74719b35957d7763f3a | [
"MIT"
] | null | null | null | src/main.cpp | nabijaczleweli/ctffs | b193ccc0ebcabe9bf3e7d74719b35957d7763f3a | [
"MIT"
] | null | null | null | // The MIT License (MIT)
// Copyright (c) 2016 nabijaczleweli
// 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 "filesystem.hpp"
#include "fs_config.hpp"
#include "options.hpp"
#include <fstream>
#include <iostream>
#include <vector>
int main(int argc, const char ** argv) {
options opts(argc, argv);
std::cout << "config_paths = {";
for(auto && cp : opts.config_paths)
std::cout << cp << ", ";
std::cout << "}\n";
std::vector<fs_config> configs;
configs.reserve(opts.config_paths.size());
for(auto && cp : opts.config_paths) {
std::ifstream cfg_f(cp);
auto cfg = fs_config::from(cfg_f);
if(std::get<int>(cfg) == 0) {
configs.emplace_back(std::move(std::get<fs_config>(cfg)));
} else {
std::cerr << "Failed to parse config file \"" << cp << "\": " << std::get<std::string>(cfg) << '\n';
return std::get<int>(cfg);
}
}
std::cout << "configs = {\n";
for(auto && cfg : configs)
std::cout << " {\n"
<< " mount_point = \"" << cfg.mount_point << "\"\n" //
<< " db_location = \"" << cfg.db_location << "\"\n" //
<< " }, \n";
std::cout << "}\n";
filesystem fs(configs[0]);
std::cout << "Enter to unmount...";
char _;
std::cin.get(_);
}
| 34.045455 | 103 | 0.663551 | [
"vector"
] |
cc42fb4ca36595a9c491c109a8f70d8070df6991 | 2,166 | cc | C++ | tests/cpp/fm_loss_test.cc | llebel/difacto | 78e356215f659101e21f9b38ffba6dfcc356f628 | [
"Apache-2.0"
] | 304 | 2015-12-16T23:50:19.000Z | 2022-03-06T11:53:26.000Z | tests/cpp/fm_loss_test.cc | llebel/difacto | 78e356215f659101e21f9b38ffba6dfcc356f628 | [
"Apache-2.0"
] | 15 | 2016-01-13T22:57:32.000Z | 2020-04-16T13:44:17.000Z | tests/cpp/fm_loss_test.cc | llebel/difacto | 78e356215f659101e21f9b38ffba6dfcc356f628 | [
"Apache-2.0"
] | 110 | 2015-12-18T06:44:27.000Z | 2021-12-09T20:05:02.000Z | /**
* Copyright (c) 2015 by Contributors
*/
#include <gtest/gtest.h>
#include "./utils.h"
#include "loss/fm_loss.h"
#include "data/localizer.h"
#include "loss/bin_class_metric.h"
using namespace difacto;
TEST(FMLoss, NoV) {
SArray<real_t> weight(47149);
for (size_t i = 0; i < weight.size(); ++i) {
weight[i] = i / 5e4;
}
dmlc::data::RowBlockContainer<unsigned> rowblk;
std::vector<feaid_t> uidx;
load_data(&rowblk, &uidx);
SArray<real_t> w(uidx.size());
for (size_t i = 0; i < uidx.size(); ++i) {
w[i] = weight[uidx[i]];
}
KWArgs args = {{"V_dim", "0"}};
FMLoss loss; loss.Init(args);
auto data = rowblk.GetBlock();
SArray<real_t> pred(data.size);
loss.Predict(data, w, {}, {}, &pred);
BinClassMetric eval(data.label, pred.data(), data.size);
// Progress prog;
EXPECT_LT(fabs(eval.LogitObjv() - 147.4672), 1e-3);
SArray<real_t> grad(w.size());
loss.CalcGrad(data, w, {}, {}, pred, &grad);
EXPECT_LT(fabs(norm2(grad) - 90.5817), 1e-3);
}
TEST(FMLoss, HasV) {
int V_dim = 5;
int n = 47149;
std::vector<real_t> weight(n*(V_dim+1));
for (int i = 0; i < n; ++i) {
weight[i*(V_dim+1)] = i / 5e4;
for (int j = 1; j <= V_dim; ++j) {
weight[i*(V_dim+1)+j] = i * j / 5e5;
}
}
dmlc::data::RowBlockContainer<unsigned> rowblk;
std::vector<feaid_t> uidx;
load_data(&rowblk, &uidx);
SArray<int> w_pos(uidx.size());
SArray<int> V_pos(uidx.size());
int p = 0;
SArray<real_t> w(uidx.size()*(V_dim+1));
for (size_t i = 0; i < uidx.size(); ++i) {
for (int j = 0; j < V_dim+1; ++j) {
w[i*(V_dim+1)+j] = weight[uidx[i]*(V_dim+1)+j];
}
w_pos[i] = p;
V_pos[i] = p+1;
p += V_dim + 1;
}
KWArgs args = {{"V_dim", std::to_string(V_dim)}};
FMLoss loss; loss.Init(args);
auto data = rowblk.GetBlock();
SArray<real_t> pred(data.size);
loss.Predict(data, w, w_pos, V_pos, &pred);
// Progress prog;
BinClassMetric eval(data.label, pred.data(), data.size);
EXPECT_LT(fabs(eval.LogitObjv() - 330.628), 1e-3);
SArray<real_t> grad(w.size());
loss.CalcGrad(data, w, w_pos, V_pos, pred, &grad);
EXPECT_LT(fabs(norm2(grad) - 1.2378e+03), 1e-1);
}
| 25.785714 | 58 | 0.597415 | [
"vector"
] |
cc48fa70a6a1b834e5b615779550b794d12aa43c | 837 | cpp | C++ | leetcode/cpp-version/16.cpp | tlming16/Projec_Euler | 797824c5159fae67493de9eba24c22cc7512d95d | [
"MIT"
] | 4 | 2018-11-14T12:03:05.000Z | 2019-09-03T14:33:28.000Z | leetcode/cpp-version/16.cpp | tlming16/Projec_Euler | 797824c5159fae67493de9eba24c22cc7512d95d | [
"MIT"
] | null | null | null | leetcode/cpp-version/16.cpp | tlming16/Projec_Euler | 797824c5159fae67493de9eba24c22cc7512d95d | [
"MIT"
] | 1 | 2018-11-17T14:39:22.000Z | 2018-11-17T14:39:22.000Z | /*
* author:tlming16
* email:tlming16@fudan.edu.cn
* all wrong reserved
*/
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
int diff=INT_MAX;
int ans=0;
for (int i=0;i<nums.size()-2;i++){
int j=i+1;
int k= nums.size()-1;
for ( ;j<k;) {
int sum = nums[i] +nums[j]+nums[k];
if ( abs(sum -target)<diff) {
diff = abs(sum-target);
ans =sum;
}
if (sum== target) {
return target;
}
else if (sum < target) {
j++;
}else {
k--;
}
}
}
return ans;
}
}; | 24.617647 | 56 | 0.37037 | [
"vector"
] |
cc4e55a3f8b7108049387abcd007214564ce3ae1 | 4,134 | cc | C++ | src/type_info/LF_STRUCTURE.cc | chp-io/libmspdb | 31283565f18fd32e27717e7e0180b9c27f44d824 | [
"Apache-2.0"
] | 1 | 2021-11-11T01:30:16.000Z | 2021-11-11T01:30:16.000Z | src/type_info/LF_STRUCTURE.cc | chp-io/libmspdb | 31283565f18fd32e27717e7e0180b9c27f44d824 | [
"Apache-2.0"
] | null | null | null | src/type_info/LF_STRUCTURE.cc | chp-io/libmspdb | 31283565f18fd32e27717e7e0180b9c27f44d824 | [
"Apache-2.0"
] | 3 | 2021-03-02T18:25:56.000Z | 2022-02-11T21:19:24.000Z | /*
* Copyright 2021 Assured Information Security, 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 "type_info/LF_STRUCTURE.hh"
#include "TypeInfoStream.hh"
#include "pdb_exception.hh"
#include "type_info/LF_FIELDLIST.hh"
#include "../builtin_expect.hh"
#include "../portable_endian.hh"
#include "CV_Property.hh"
#include "LF_VALUE.hh"
#include <cstring>
#include <iostream>
#include <mutex>
namespace mspdb {
#pragma pack(push, 1)
struct lfStructure {
le_uint16_t count;
CV_Property property;
le_uint32_t field_list;
le_uint32_t derived;
le_uint32_t vshape;
};
#pragma pack(pop)
class LF_STRUCTURE::IMPL {
public:
IMPL(const TypeInfoStream& tpi) : tpi(tpi) {}
public:
lfStructure entry;
int64_t size;
std::string name;
const TypeInfoStream& tpi;
std::vector<std::reference_wrapper<const LF_MEMBER>> field_list;
std::mutex mtx;
};
uint16_t LF_STRUCTURE::count() const { return pImpl->entry.count; }
const std::vector<std::reference_wrapper<const LF_MEMBER>>& LF_STRUCTURE::field_list() const {
std::lock_guard<std::mutex> lock(pImpl->mtx);
if (pImpl->field_list.empty()) {
if (unlikely(pImpl->entry.field_list == 0)) {
throw pdb_exception("No field list in structure. Forward declaration?");
}
const auto& field_list = static_cast<const LF_FIELDLIST&>(
pImpl->tpi.type(pImpl->entry.field_list, LEAF_TYPE::LF_FIELDLIST));
for (const LF_TYPE& substruct : field_list.substructs()) {
if (unlikely(substruct.type() != LEAF_TYPE::LF_MEMBER)) {
throw pdb_exception("Invalid type " + to_string(substruct.type()) +
" in LF_FIELDLIST");
}
pImpl->field_list.emplace_back(static_cast<const LF_MEMBER&>(substruct));
}
}
return pImpl->field_list;
}
uint32_t LF_STRUCTURE::derived() const { return pImpl->entry.derived; }
uint32_t LF_STRUCTURE::vshape() const { return pImpl->entry.vshape; }
int64_t LF_STRUCTURE::size() const { return pImpl->size; }
const std::string& LF_STRUCTURE::name() const { return pImpl->name; }
bool LF_STRUCTURE::packed() const { return pImpl->entry.property.packed(); }
bool LF_STRUCTURE::ctor() const { return pImpl->entry.property.ctor(); }
bool LF_STRUCTURE::ovlops() const { return pImpl->entry.property.ovlops(); }
bool LF_STRUCTURE::nested() const { return pImpl->entry.property.nested(); }
bool LF_STRUCTURE::cnested() const { return pImpl->entry.property.cnested(); }
bool LF_STRUCTURE::opassign() const { return pImpl->entry.property.opassign(); }
bool LF_STRUCTURE::opcast() const { return pImpl->entry.property.opcast(); }
bool LF_STRUCTURE::fwdref() const { return pImpl->entry.property.fwdref(); }
bool LF_STRUCTURE::scoped() const { return pImpl->entry.property.scoped(); }
LF_STRUCTURE::LF_STRUCTURE(const char* buffer, int32_t buffer_size, const TypeInfoStream& tpi)
: LF_FIELDLIST_CONTAINER(buffer, buffer_size), pImpl(std::make_unique<IMPL>(tpi)) {
// LF_TYPE advances our buffer/buffer_size past the "type" field (constructor takes references)
if (unlikely(buffer_size < sizeof(lfStructure))) {
throw pdb_exception("Buffer too small for LF_STRUCTURE");
}
pImpl->entry = *reinterpret_cast<const lfStructure*>(buffer);
buffer += sizeof(lfStructure);
buffer_size -= sizeof(lfStructure);
LF_VALUE lfValue(buffer, buffer_size);
pImpl->size = lfValue.value();
pImpl->name = std::string(buffer, strnlen(buffer, buffer_size));
}
LF_STRUCTURE::~LF_STRUCTURE() = default;
} /* namespace mspdb */
| 36.910714 | 99 | 0.701016 | [
"vector"
] |
cc573a3765c15453593594ee8a7532059a849f78 | 10,798 | cpp | C++ | cvdump/dumpsym6.cpp | AbhyudayaSharma/microsoft-pdb | c757660669073f3d98d392bf1f2b076ce74b9074 | [
"MIT"
] | 1,286 | 2015-10-30T02:39:40.000Z | 2019-05-06T09:24:53.000Z | cvdump/dumpsym6.cpp | maojun1998/microsoft-pdb | 082c5290e5aff028ae84e43affa8be717aa7af73 | [
"MIT"
] | 36 | 2015-10-30T03:59:17.000Z | 2019-04-27T11:03:04.000Z | cvdump/dumpsym6.cpp | maojun1998/microsoft-pdb | 082c5290e5aff028ae84e43affa8be717aa7af73 | [
"MIT"
] | 215 | 2015-10-30T02:17:09.000Z | 2019-04-29T10:22:06.000Z | /***********************************************************************
* Microsoft (R) Debugging Information Dumper
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
* File Comments:
*
*
***********************************************************************/
#include "cvdump.h"
#include "debsym.h" // SYMBOLS definitions
#include "symrec.h" // SYMBOLS definitions
void C6BlockSym();
void C6ProcSym();
void C6LabSym();
void C6WithSym();
void C6EntrySym();
void C6SkipSym();
void C6ChangeModel();
void C6CodeSegSym();
void C6EndSym();
void C6BpSym();
void C6RegSym();
void C6ConSym();
void C6CobolTypeDefSym();
void C6LocalSym();
void C6ChangeModelSym();
bool f386;
size_t cchIndent;
#define GetOffset() (f386 ? LGets() : (long) WGets())
typedef struct {
BYTE tsym;
void (*pfcn)();
} symfcn;
const symfcn SymFcnC6[] =
{
{ S_BLOCK, C6BlockSym },
{ S_PROC, C6ProcSym },
{ S_END, C6EndSym },
{ S_BPREL, C6BpSym },
{ S_LOCAL, C6LocalSym },
{ S_LABEL, C6LabSym },
{ S_WITH, C6WithSym },
{ S_REG, C6RegSym },
{ S_CONST, C6ConSym },
{ S_ENTRY, C6EntrySym },
{ S_NOOP, C6SkipSym },
{ S_CODSEG, C6CodeSegSym },
{ S_TYPEDEF, C6CobolTypeDefSym },
{ S_CHGMODEL, C6ChangeModelSym },
};
#define SYMCNT (sizeof SymFcnC6 / sizeof (SymFcnC6[0]))
/**
*
* Display SYMBOLS section.
*
*/
void DumpSym()
{
StdOutPuts(L"\n\n*** SYMBOLS section\n");
for (PMOD pMod = ModList; pMod != NULL; pMod = pMod->next) {
DWORD cbSym;
if (((cbSym = pMod->SymbolSize) != 0) &&
((iModToList == 0) || ((WORD)iModToList == pMod->iMod))) {
_lseek(exefile, lfoBase + pMod->SymbolsAddr, SEEK_SET);
cchIndent = 0;
char szName[256];
strcpy_s(szName, _countof(szName), pMod->ModName);
StdOutPrintf(L"%S\n", szName);
cbRec = 4;
DWORD ulSignature = LGets();
switch( ulSignature ){
case CV_SIGNATURE_C7:
case CV_SIGNATURE_C11:
// Dump C7 debug info
cbSym -= sizeof (DWORD); // Subtract size of signature
DumpModSymC7 (cbSym, sizeof(DWORD));
break;
default:
// Symbols are in C6 format
// M00 - seek could be eliminated for speed improvement
// Re-seek because first four bytes are not signature
_lseek(exefile, lfoBase + pMod->SymbolsAddr, SEEK_SET);
DumpModSymC6 (cbSym);
break;
}
}
}
StdOutPutc(L'\n');
}
void DumpModSymC6(size_t cbSym)
{
char sb[255]; // String buffer
WORD cbName; // Length of string
unsigned i;
while (cbSym > 0) {
WORD rect;
// Get record length
cbRec = 1;
cbRec = Gets();
cbSym -= cbRec + 1;
rect = Gets();
f386 = (rect & 0x80) != 0; // check for 32-bit sym
rect &= ~0x80;
for (i = 0; i < SYMCNT; i++) {
if (SymFcnC6[i].tsym == (BYTE) rect) {
SymFcnC6[i].pfcn ();
break;
}
}
if( i == SYMCNT ){
// Couldn't find symbol record type in the table
Fatal(L"Invalid symbol record type");
}
if (cbRec > 0) {
// display symbol name
cbName = Gets();
GetBytes(sb, (size_t) cbName);
sb[cbName] = '\0';
StdOutPrintf(L"\t%s", sb);
}
StdOutPutc(L'\n');
if (cbRec) {
Fatal(L"Invalid file");
}
StdOutPutc(L'\n');
}
}
void PrtIndent()
{
size_t n;
for (n = 0; n < cchIndent; n++) {
StdOutPutc(L' ');
}
}
void C6EndSym()
{
cchIndent--;
PrtIndent();
StdOutPuts(L"End");
}
void C6BpSym()
{
BPSYMTYPE bp;
bp.off = GetOffset ();
bp.typind = WGets();
PrtIndent();
if (f386) {
StdOutPrintf(L"BP-relative:\toff = %08lx, type %8s", bp.off, SzNameType(bp.typind));
}
else {
StdOutPrintf(L"BP-relative:\toff = %04lx, type %8s", bp.off, SzNameType(bp.typind));
}
}
void C6LocalSym()
{
LOCSYMTYPE loc;
loc.off = GetOffset ();
loc.seg = WGets();
loc.typind = WGets();
PrtIndent();
StdOutPrintf(L"Local:\tseg:off = %04x:%0*lx",
loc.seg,
f386? 8 : 4,
loc.off
);
StdOutPrintf(L", type %8s, ", SzNameType(loc.typind));
}
const wchar_t * const namereg[] =
{
L"AL", // 0
L"CL", // 1
L"DL", // 2
L"BL", // 3
L"AH", // 4
L"CH", // 5
L"DH", // 6
L"BH", // 7
L"AX", // 8
L"CX", // 9
L"DX", // 10
L"BX", // 11
L"SP", // 12
L"BP", // 13
L"SI", // 14
L"DI", // 15
L"EAX", // 16
L"ECX", // 17
L"EDX", // 18
L"EBX", // 19
L"ESP", // 20
L"EBP", // 21
L"ESI", // 22
L"EDI", // 23
L"ES", // 24
L"CS", // 25
L"SS", // 26
L"DS", // 27
L"FS", // 28
L"GS", // 29
L"???", // 30
L"???", // 31
L"DX:AX", // 32
L"ES:BX", // 33
L"IP", // 34
L"FLAGS", // 35
};
const wchar_t * const name87[] =
{
L"ST (0)",
L"ST (1)",
L"ST (2)",
L"ST (3)",
L"ST (4)",
L"ST (5)",
L"ST (6)",
L"ST (7)"
};
const wchar_t *SzNameReg(BYTE reg)
{
if (reg <= 37) {
return(namereg[reg]);
}
if (reg < 128 || reg > 135) {
return(L"???");
}
return(name87[reg - 128]);
}
void C6RegSym()
{
REGSYMTYPE regsym;
regsym.typind = WGets();
regsym.reg = (char) Gets();
PrtIndent();
StdOutPrintf(L"Register:\ttype %8s, register = %s, ",
SzNameType(regsym.typind),
SzNameReg(regsym.reg));
}
void C6ConSym()
{
long len;
WORD type;
WORD code;
static char buf[1024];
type = WGets();
PrtIndent();
StdOutPrintf(L"Constant:\ttype %8s, ", SzNameType(type));
code = Gets();
if (code < 128) {
len = code;
// skip value bytes
GetBytes(buf, (size_t) len);
} else {
switch (code) {
case 133: // unsigned word
case 137: // signed word
len = WGets();
StdOutPrintf(L"%x", (int) len);
break;
case 134: // signed long
case 138: // unsigned long
len = LGets();
StdOutPrintf(L"%lx", len);
break;
case 136: // signed byte
len = Gets();
StdOutPrintf(L"%x", (int) len);
break;
default:
StdOutPuts(L"??");
return;
break;
}
}
// now we should be at the name of the symbol
}
void C6BlockSym()
{
BLKSYMTYPE block;
int n;
block.off = GetOffset();
block.len = WGets();
PrtIndent();
cchIndent++;
n = f386? 8 : 4;
StdOutPrintf(L"Block Start : off = %0*lx, len = %04x",
n, block.off, block.len);
}
void C6ProcSym()
{
PROCSYMTYPE proc;
int n;
proc.off = GetOffset ();
proc.typind = WGets();
proc.len = WGets();
proc.startoff = WGets();
proc.endoff = WGets();
proc.res = WGets();
proc.rtntyp = (char) Gets();
PrtIndent();
cchIndent++;
n = f386? 8 : 4;
StdOutPrintf(L"Proc Start: off = %0*lx, type %8s, len = %04x\n",
n, proc.off, SzNameType(proc.typind), proc.len);
StdOutPrintf(L"\tDebug start = %04x, debug end = %04x, ",
proc.startoff, proc.endoff);
switch (proc.rtntyp) {
case S_NEAR:
StdOutPuts(L"NEAR,");
break;
case S_FAR:
StdOutPuts(L"FAR,");
break;
default:
StdOutPuts(L"???,");
}
}
void C6LabSym ()
{
LABSYMTYPE dat;
int n;
dat.off = GetOffset ();
dat.rtntyp = (char) Gets();
PrtIndent();
n = f386? 8 : 4;
StdOutPrintf(L"Code label: off = %0*lx,",
n, dat.off);
switch (dat.rtntyp) {
case S_NEAR:
StdOutPuts(L"NEAR,");
break;
case S_FAR:
StdOutPuts(L"FAR,");
break;
default:
StdOutPuts(L"???,");
}
}
void C6WithSym ()
{
WITHSYMTYPE dat;
int n;
dat.off = GetOffset ();
dat.len = WGets();
PrtIndent();
cchIndent++;
n = f386? 8 : 4;
StdOutPrintf(L"'With Start: off = %0*lx, len = %04x",
n, dat.off,dat.len);
}
void C6EntrySym()
{
PROCSYMTYPE proc;
int n;
proc.off = GetOffset ();
proc.typind = WGets();
proc.len = WGets();
proc.startoff = WGets();
proc.endoff = WGets();
proc.res = WGets();
proc.rtntyp = (char) Gets();
PrtIndent();
cchIndent++;
n = f386? 8 : 4;
StdOutPrintf(L"FORTARN Entry: off = %0*lx, type %8s, len = %04x\n",
n, proc.off, SzNameType(proc.typind), proc.len);
StdOutPrintf(L"\tDebug start = %04x, debug end = %04x, ",
proc.startoff, proc.endoff);
switch (proc.rtntyp) {
case S_NEAR:
StdOutPuts(L"NEAR,");
break;
case S_FAR:
StdOutPuts(L"FAR,");
break;
default:
StdOutPuts(L"???,");
}
}
void C6SkipSym()
{
StdOutPrintf(L"Skip: %d bytes\n", cbRec);
// skip the bytes in the skip record
while (cbRec > 0) {
Gets();
}
}
void C6CodeSegSym()
{
WORD seg;
WORD res;
seg = WGets();
res = WGets();
StdOutPrintf(L"Change Default Seg: seg = %04x\n", seg);
}
void C6CobolTypeDefSym()
{
CV_typ_t type;
// review
type = WGets();
StdOutPrintf(L"Cobol Typedef: type = %d,", type);
}
void C6ChangeModelSym()
{
WORD offset;
WORD model;
WORD byte1;
WORD byte2;
WORD byte3;
WORD byte4;
offset = WGets();
model= Gets();
byte1 = Gets();
byte2 = Gets();
byte3 = Gets();
byte4 = Gets();
StdOutPrintf(L"Change Model: offset = 0x%04x model = 0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x\n",
offset, model, byte1, byte2, byte3, byte4);
}
| 21.339921 | 99 | 0.460826 | [
"model"
] |
7fe299daac6bc6631f454bd95b33193143671ca4 | 59,733 | cpp | C++ | Inventory System/Inventory.cpp | Nicholas-Toh/MMU-Projects | ead57f8653d89e7f80c34c473eb29ed1ba3a5d3b | [
"MIT"
] | null | null | null | Inventory System/Inventory.cpp | Nicholas-Toh/MMU-Projects | ead57f8653d89e7f80c34c473eb29ed1ba3a5d3b | [
"MIT"
] | null | null | null | Inventory System/Inventory.cpp | Nicholas-Toh/MMU-Projects | ead57f8653d89e7f80c34c473eb29ed1ba3a5d3b | [
"MIT"
] | null | null | null | /**********|**********|**********|
Program: Inventory.cpp /StoreItem.cpp /StoreItem.h
Course: Programming Fundamentals
Year: 2017/2018 Trimester 2
Name: Nicholas Toh Zhern Hau
ID: 1161104589
Lecture Section: TC01
Tutorial Section: TT01
Email: tohnic1999@gmail.com
Phone: 019-6606712
*********|**********|**********/
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <iomanip>
#include <cstdlib> //stoi (older version)
#include <cstdio> //delete, rename
#include <cstring>
#include <math.h> //round
#include <utility> //iter_swap
#include "StoreItem.h"
using namespace std;
const int SIZE = 14; //The size of one record [key, recordName, values (2-13)]
int initFile (string filename); //Creates file if it doesn't exist yet
int readFile (string filename, vector<string>& storage); //Reads file and stores in a designated storage
int readFile (string filename, vector<StoreItem>& storage); //Reads file and stores in a designated storage
int deleteFile (const char * filename); //Deletes file, used in write file
int writeFile (string filename, vector <string> storage); //Writes into a file from a storage
int writeFile (string filename, vector <StoreItem> storage); //Writes into a file from a storage
int getInput(int lowerLimit, int upperLimit, string optionalText = "", string errorText = ""); //Used for conditioned int inputs
int getInput(vector <int> inputVector, int exitCondition, string optionalText = "", string errorText = ""); //Used for conditioned int inputs
char getInput(char lowerLimit, char upperLimit, string optionalText = "", string errorText= ""); //Used for conditioned char inputs
double getInput(double lowerLimit, double upperLimit, string optionalText = "", string errorText= ""); //Used for conditioned double inputs
string getStrInput(string optionalText = ""); //Used to get string inputs
void createRecord (string & name, vector <string> nameList, vector <string> & valueList); //Gets temporary record from user
void updateField (vector <string> nameList, StoreItem & record); //Updates a field
void deleteField (vector <string> nameList, StoreItem & record); //Deletes a field
int assignKey (vector <int> & keys); //Assigns a unique key from the keys vector
int validateKey (int inputKey, vector <int> keys); //Checks if a key is valid
int deleteKey (int inputKey, vector <int> & keys); //Deletes a key
int keyToRecord (int inputKey, vector <StoreItem> masterRecord); //Exchanges the key for the location of the record in the master record
void updateKeys (vector <int> & keys, vector <StoreItem> masterRecord); //Updates the keys vector after a record is sorted
vector <int> fullStringSearch (vector <StoreItem> masterRecord, vector <int> selectedKeys, int DFKey, string searchString); //Searches for a record that contains the string in a specified data field
vector <int> subStringSearch (vector <StoreItem> masterRecord, vector <int> selectedKeys, int DFKey, string searchString); //Searches for a record that contains the substring in a specified data field
vector <int> compareGreaterNumSearch (vector <StoreItem> masterRecord, vector <int> selectedKeys, int DFKey, int num); //Searches for a record that has a number greater than num in a specified data field
vector <int> compareSmallerNumSearch (vector <StoreItem> masterRecord, vector <int> selectedKeys, int DFKey, int num); //Searches for a record that has a number smaller than num in a specified data field
void ascendSortRecord (int DFKey, vector <StoreItem> & masterRecord); //Sorts records in ascending order
void descendingSortRecord (int DFKey, vector <StoreItem> & masterRecord); //Sorts records in descending order
void ascendSortRecordInt (int DFKey, vector <StoreItem> & masterRecord); //Sorts records in ascending order based on int
void descendingSortRecordInt (int DFKey, vector <StoreItem> & masterRecord); //Sorts records in descending order based on int
void ascendSortRecordDouble (int DFKey, vector <StoreItem> & masterRecord); //Sorts records in ascending order based on double
void descendingSortRecordDouble (int DFKey, vector <StoreItem> & masterRecord); //Sorts records in descending order based on double
void ascendSortRecordStr (int DFKey, vector <StoreItem> & masterRecord); //Sorts records in ascending order based on strings
void descendingSortRecordStr (int DFKey, vector <StoreItem> & masterRecord); //Sorts records in descending order based on strings
void ascKeySortRecord (vector <StoreItem> & masterRecord); //Sorts based on keys in ascending order
void dscKeySortRecord (vector <StoreItem> & masterRecord); //Sorts based on keys in descending order
int displayMainMenu(vector <StoreItem> masterRecord); //Main Menu
int displayShowRecordMenu (vector <StoreItem> masterRecord); //Show Record Menu
void searchByRecord (vector <string> nameList, vector <int> keys, vector <StoreItem> masterRecord); //Show data fields of individual records
vector <int> searchByDataField (vector <string> nameList, vector <int> keys, vector <StoreItem> masterRecord); //Show records based on data field
int editRecordMenu (vector <string> nameList, StoreItem record); //Edit Record Menu
int displaySortRecordMenu (vector <string> nameList, vector <StoreItem> masterRecord); //Sort Record Menu
void displayArray(vector <int> storage, string name); //DEBUGGING
void displayArray(vector <unsigned int> storage, string name); //DEBUGGING
void displayArray(vector <string> storage, string name); //DEBUGGING
void displayBlankRecord(vector <string> nameList); //Displays a blank record
void displayRecord(vector <string> nameList, StoreItem record); //Displays a record
void displayRecord(vector <string> nameList, StoreItem record, vector <bool> displayDataField); //Displays a record with visibility settings
void displayRecord(vector <string> nameList, vector <string> valueList); //Displays a pseudo record using an external array
void displayAvailableRecords(vector <StoreItem> masterRecord); //Displays all available records
void displayAvailableRecords(vector <StoreItem> masterRecord, vector <int> selectedKeys); //Displays selected available records
int main ()
{
const vector <string> nameList = {"Item Id", "Item Name", "Item Description", "Category", "Manufacturer", "Selling Price", "Cost Price", "Units in Store", "Units Sold", "Year of Date First Introduced", "Month of Date First Introduced", "Day of Date First Introduced"}; //names of data fields are constant
vector <StoreItem> masterRecord; //Master record that holds all of the records
vector <int> keys; //Holds all of the keys in the Master record
vector <string> valueList (SIZE-2, " "); //temporary storage
string databaseName = "database.txt";
int menuChoice;
bool mainMenuLoop = true, updateRecordLoop = true;
//Create database
initFile(databaseName);
//Read from database
readFile(databaseName, masterRecord);
//Create records from database
string tempRecordName;
int tempKey;
/*
for (int i = 0; i < masterArray.size(); i += SIZE)
{
for (int j = 0; j < SIZE; j++)
{
if (j % SIZE == 0)
{
tempKey = stoi(masterArray[j+i]);
}
else if (j % SIZE == 1)
{
tempRecordName = masterArray[j+i];
}
else
{
valueList[j-2] = masterArray[j+i];
}
}
StoreItem record(tempRecordName, tempKey, valueList);
masterRecord.push_back(record);
}
fill(valueList.begin(), valueList.end(), " "); //reset valueList
*/
//Gather all keys in one array
for (int i = 0; i < masterRecord.size(); i++) {
keys.push_back((masterRecord[i]).getKey());
}
//Display main menu
while (mainMenuLoop == true) {
int mainMenuChoice = displayMainMenu(masterRecord);
switch (mainMenuChoice)
{
case 1: //Create record
{
createRecord(tempRecordName, nameList, valueList);
tempKey = assignKey(keys);
StoreItem record(tempRecordName, tempKey, valueList);
masterRecord.push_back(record);
updateKeys(keys, masterRecord);
writeFile(databaseName, masterRecord);
break;
}
case 2: //Show record
{
displayBlankRecord(nameList);
vector <int> selectedKeys = searchByDataField(nameList, keys, masterRecord);
displayAvailableRecords(masterRecord, selectedKeys);
searchByRecord(nameList, selectedKeys, masterRecord);
/*
bool showRecordLoop = true;
while (showRecordLoop == true)
{
int showRecordMenuChoice = displayShowRecordMenu(masterRecord);
displayBlankRecord(nameList);
switch (showRecordMenuChoice)
{
case 1: //Search by record
{
searchByRecord (nameList, keys, masterRecord);
break;
}
case 2: //Search by data field
{
vector <int> selectedKeys = searchByDataField(nameList, masterRecord);
displayAvailableRecords(masterRecord, selectedKeys);
cout << "*****************" << endl;
break;
}
case 3: //Exit menu
{
showRecordLoop = false;
break;
}
default:
{
cout << "Something went wrong with showRecordMenuChoice ---> " << showRecordMenuChoice << endl;
break;
}
}
}
*/
break;
}
case 3: //Edit a record
{
int tempKey = getInput(keys, 0, "Please enter the record you wish to edit ('0' to exit): ", "Invalid key, please try again: ");
if (tempKey != 0)
{
int key = keyToRecord(tempKey, masterRecord);
int choice = editRecordMenu(nameList, masterRecord[key]);
switch (choice)
{
case 1: //Update field
{
updateField(nameList, masterRecord[key]);
break;
}
case 2: //Delete field
{
deleteField(nameList, masterRecord[key]);
break;
}
}
break;
}
else
{
break;
}
}
case 4: //Delete record
{
displayAvailableRecords(masterRecord);
int tempKey = getInput(keys, 0, "Please enter the record you wish to delete ('0' to exit): ", "Invalid key, please try again: ");
if (tempKey != 0)
{
int key = keyToRecord(tempKey, masterRecord);
deleteKey(tempKey, keys);
masterRecord.erase(masterRecord.begin()+key);
break;
}
else
{
break;
}
}
case 5: //Sort records
{
int choice = displaySortRecordMenu(nameList, masterRecord);
switch (choice)
{
case 1: //Sort alphabetically
{
int tempKey = getInput(0, 12, "Please enter the field that you wish to sort ('0' to exit): ", "Invalid key. Please try again: ");
int DFKey = tempKey - 1;
int choice = getInput(1, 2, "1 - Ascending, 2 - Descending: ", "Invalid input. Please try again: ");
switch (choice)
{
case 0: //Exit
{
break;
}
case 1: //Ascending
{
switch (tempKey)
{
case 0:
{
break;
}
case 1:
case 2:
case 3:
case 4:
case 5:
{
ascendSortRecordStr(DFKey, masterRecord);
break;
}
case 6:
case 7:
{
ascendSortRecordDouble(DFKey, masterRecord);
break;
}
case 8:
case 9:
case 10:
case 11:
case 12:
{
ascendSortRecordInt(DFKey, masterRecord);
break;
}
}
break;
}
case 2: //Descending
{
switch (tempKey)
{
case 0:
{
break;
}
case 1:
case 2:
case 3:
case 4:
case 5:
{
descendingSortRecordStr(DFKey, masterRecord);
break;
}
case 6:
case 7:
{
descendingSortRecordDouble(DFKey, masterRecord);
break;
}
case 8:
case 9:
case 10:
case 11:
case 12:
{
descendingSortRecordInt(DFKey, masterRecord);
break;
}
}
break;
}
}
break;
}
case 2: //Sort based on key
{
int choice = getInput(1, 2, "1 - Ascending, 2 - Descending: ", "Invalid input. Please try again: ");
switch (choice)
{
case 1: //Ascending
{
ascKeySortRecord(masterRecord);
break;
}
case 2: //Descending
{
dscKeySortRecord(masterRecord);
break;
}
}
break;
}
}
break;
}
case 6: //Exit program
{
mainMenuLoop = false;
break;
}
default:
{
cout << "Something went wrong. Shutting down...";
return 0;
}
}
fill(valueList.begin(), valueList.end(), " ");
}
//DEBUGGING
//displayArray (masterArray, "masterArray");
//cout << endl;
//displayArray (keys, "keys");
writeFile(databaseName, masterRecord);
return 0;
}
/*****************************************************
FILE I/O FUNCTIONS
******************************************************/
int initFile (string filename) //Creates file if none exists
{
fstream f;
f.open(filename);
if (!f.is_open())
{
f.open(filename, std::ios::out|std::ios::in|std::ios::trunc);
if (!f.is_open())
{
cout << "Error creating file " << filename << "!" << endl;
f.close();
return 1;
}
}
return 0;
}
int readFile(string filename, vector<string>& storage) //Reads file and stores in a designated storage
{
string temp;
int pos = 0;
fstream f;
f.open(filename);
if (!f.is_open())
{
cout << "Error reading file " << filename << "!" << endl;
f.close();
return 1;
}
else
{
while ( getline(f, temp) )
{
if (pos == storage.size())
{
storage.push_back(temp);
}
else
{
storage[pos] = temp;
}
pos++;
}
f.close();
}
return 0;
}
int readFile(string filename, vector<StoreItem>& storage) //Reads file and stores in a designated storage
{
string temp;
int pos = 0;
vector <string> tempStorage (SIZE-2, " ");
fstream f;
f.open(filename);
if (!f.is_open())
{
cout << "Error reading file " << filename << "!" << endl;
f.close();
return 1;
}
else
{
string tempRecordName;
int tempKey;
while ( getline(f, temp) ) //Reads the exact amount of data to create a StoreItem object each cycle
{
if (pos == 0)
{
tempKey = stoi(temp);
}
else if (pos == 1)
{
tempRecordName = temp;
}
else
{
tempStorage[pos-2] = temp;
if (pos == SIZE-1)
{
StoreItem record (tempRecordName, tempKey, tempStorage);
storage.push_back(record);
pos = -1;
}
}
pos++;
}
f.close();
}
return 0;
}
int deleteFile (const char * filename) //Deletes file
{
remove(filename);
fstream f;
f.open(filename);
if (f.is_open())
{
cout << "Error deleting file " << filename << "!" << endl;
f.close();
return 1;
}
return 0;
}
int writeFile (string filename, vector <string> storage) //Writes into a file from a storage
{
fstream f;
f.open(filename);
if (!f.is_open())
{
cout << "Error writing to file " << filename << "!" << endl;
f.close();
return 1;
}
f.close();
if (initFile("temp.txt"))
{
cout << "Error: temp file failed to be created while writing" << endl;
return 2;
}
f.open ("temp.txt");
for (int i = 0; i < storage.size(); i++)
{
f << storage[i] << endl;
}
f.close();
remove(filename.c_str());
rename("temp.txt", filename.c_str());
return 0;
}
int writeFile (string filename, vector <StoreItem> storage) //Writes into a file from a storage
{
fstream f;
f.open(filename);
if (!f.is_open())
{
cout << "Error writing to file " << filename << "!" << endl;
f.close();
return 1;
}
f.close();
if (initFile("temp.txt"))
{
cout << "Error: temp file failed to be created while writing" << endl;
return 2;
}
f.open ("temp.txt");
for (int i = 0; i < storage.size(); i++)
{
f << storage[i].getKey() << endl << storage[i].getRecordName() << endl; //Write each record into the file
for (int j = 0; j < (storage[i].getRecord()).size(); j++)
{
f << (storage[i].getRecord())[j] << endl;
}
}
f.close();
remove(filename.c_str());
rename("temp.txt", filename.c_str());
return 0;
}
/*****************************************************
MENU FUNCTIONS
******************************************************/
void displayAvailableRecords(vector <StoreItem> masterRecord) //Displays all record names and their keys in the Master Record
{
if (masterRecord.size() != 0)
{
cout << endl;
cout << "Available records\n";
cout << "*****************\n\n";
cout << setw(8) << left << "Key";
cout << setw(40) << left << "Record" << endl;
for (int i = 0; i < masterRecord.size(); i++)
{
cout << setw(8) << left << masterRecord[i].getKey(); //print key
cout << setw(40) << left << masterRecord[i].getRecordName() << endl; //print name
}
}
else
{
cout << left << "No records." << endl;
}
}
void displayAvailableRecords(vector <StoreItem> masterRecord, vector <int> selectedKeys) //Displays specific record names and their keys in the Master Record
{
if (masterRecord.size() != 0 && selectedKeys.size() != 0)
{
cout << endl;
cout << "Available records\n";
cout << "*****************\n\n";
cout << setw(8) << left << "Key";
cout << setw(40) << left << "Record" << endl;
for (int i = 0; i < masterRecord.size(); i++)
{
int tempKey = masterRecord[i].getKey();
string tempName = masterRecord[i].getRecordName();
if (!validateKey(tempKey, selectedKeys))
{
cout << setw(8) << left << tempKey; //print key
cout << setw(40) << left << tempName << endl; //print name
}
}
}
else
{
cout << left << "No records." << endl;
}
}
int displayMainMenu(vector <StoreItem> masterRecord) //Displays main menu
{
int userInput;
int tempKey;
string tempName;
cout << "Welcome to the Record Setter! We take, update and delete records!\n";
displayAvailableRecords(masterRecord);
cout << "\nNote: If you quit the program without exiting through this menu, all changes will not be saved.\n";
cout << "\n1 - Create a new record\n2 - Display record\n3 - Edit an existing record\n4 - Delete an existing record\n5 - Sort records\n6 - Exit the program\n";
cout << "Choice: ";
userInput = getInput(1, 6, "", "Please enter a number between 1 - 6: ");
return userInput;
}
int displayShowRecordMenu (vector <StoreItem> masterRecord) //Displays show record menu
{
int userInput;
int tempKey;
string tempName;
cout << endl << endl;
displayAvailableRecords(masterRecord);
cout << "\n1 - Search for a record\n2 - Search by data field\n3 - Exit the current menu\n";
cout << "Choice: ";
userInput = getInput (1, 3, "", "Please enter a number between 1 - 3: ");
return userInput;
}
int displayShowRecordMenu (vector <StoreItem> masterRecord, vector <int> selectedKeys) //Displays show record menu
{
int userInput;
int tempKey;
string tempName;
cout << endl << endl;
displayAvailableRecords(masterRecord, selectedKeys);
userInput = getInput(selectedKeys, 0, "", "Please enter the data field you wsh to display: ");
return userInput;
}
void searchByRecord (vector <string> nameList, vector <int> keys, vector <StoreItem> masterRecord) //Show data fields of individual records
{
int tempKey = -1;
int DFKey = -1;
vector <bool> displayDataField (SIZE-2, false); //Holds the visibility of each data field
vector <int> displayRecordKeys; //Holds the visibility (keys) of each record
do
{
cout << "Please enter the key of the record to be displayed ('0' to exit, '-1' to display all records): ";
while(!(cin >> tempKey))
{
cin.clear();
cin.ignore(99, '\n');
cout << "Only posititve integers are allowed: ";
}
while (validateKey(tempKey, keys) && tempKey != -1 && tempKey != 0)
{
cout << "Invalid key. Please try again: ";
while(!(cin >> tempKey))
{
cin.clear();
cin.ignore(99, '\n');
cout << "Only posititve integers are allowed: ";
}
}
cin.ignore();
if (tempKey != -1 && tempKey != 0)
{
if (validateKey(tempKey, displayRecordKeys))
{
displayRecordKeys.push_back(tempKey);
}
}
else if(tempKey == -1)
{
displayRecordKeys = keys;
}
//cout << displayRecordKeys.size() << " " << keys.size() << endl;
} while (tempKey != 0 && tempKey != -1 && displayRecordKeys.size() != keys.size());
if (displayRecordKeys.size() != 0)
{
do
{
tempKey = getInput(0, 14, "Please enter the key of the field that you wish to display (0 to exit, 13 to display everything, 14 to reset): ", "Invalid key. Please try again (0 to exit, 13 to display everything, 14 to reset): ");
DFKey = tempKey - 1;
while (tempKey != 0)
{
if (tempKey == 13) //Displays all data fields
{
fill(displayDataField.begin(), displayDataField.end(), true);
break;
}
else if (tempKey == 14) //Displays no data fields
{
fill(displayDataField.begin(), displayDataField.end(), false);
}
else
{
displayDataField[DFKey] = true; //Enables visibility on that data field
}
tempKey = getInput(0, 14, "Please enter the key of the field that you wish to display (0 to exit, 13 to display everything, 14 to reset): ", "Invalid key. Please try again (0 to exit, 13 to display everything, 14 to reset): ");
DFKey = tempKey - 1;
}
} while (tempKey != 0 && tempKey != 13 && tempKey != 14);
for (int i = 0; i < displayRecordKeys.size(); i++)
{
int key = keyToRecord(displayRecordKeys[i], masterRecord); //Convert key to position of the record in the masterRecord
displayRecord(nameList, masterRecord[key], displayDataField);
}
string dummyValue;
cout << "Press enter to continue: ";
getline(cin, dummyValue);
}
/*
if (tempKey != -1 && tempKey != 0)
{
while (validateKey(tempKey, keys) && tempKey != -1 && tempKey != 0)
{
cout << "Invalid key. Please try again: ";
cin >> tempKey;
}
int key = keyToRecord(tempKey, masterRecord); //Convert key to position of the record in the masterRecord
int tempKey = getInput(0, 14, "Please enter the key of the field that you wish to display (0 to exit, 13 to display everything, 14 to reset): ", "Invalid key. Please try again (0 to exit, 13 to display everything, 14 to reset): ");
int DFKey = tempKey -1;
while (tempKey != 0)
{
if (tempKey == 13) //Displays all data fields
{
fill(displayDataField.begin(), displayDataField.end(), true);
break;
}
else if (tempKey == 14) //Displays no data fields
{
fill(displayDataField.begin(), displayDataField.end(), false);
}
else
{
displayDataField[DFKey] = true; //Enables visibility on that data field
}
tempKey = getInput(0, 14, "Please enter the key of the field that you wish to display (0 to exit, 13 to display everything, 14 to reset): ");
DFKey = tempKey - 1;
}
displayRecord(nameList, masterRecord[key], displayDataField);
}
*/
}
vector <int> searchByDataField (vector <string> nameList, vector <int> keys, vector <StoreItem> masterRecord) //Show records based on data field
{
vector <int> selectedKeys = keys;
int tempKey = -1;
int counter = 0;
int DFKey;
while (tempKey != 0 && counter < 3) //Only 3 conditions can be stacked
{
tempKey = getInput(0, 12, "Please enter the key of the field that you wish to search ('0' to exit): ", "Invalid key. Please try again: ");
if (tempKey != 0)
{
counter++;
DFKey = tempKey - 1;
string userInput = getStrInput("Please enter the value that you wish to search (Enter '>' or '<' followed by numbers for comparison): ");
char * cstruserInput = new char [userInput.length()+1]; //Create new pointer that points to an array of char
strcpy (cstruserInput, userInput.c_str()); //Copy userinput to that new array of char
if (cstruserInput[0] != '>' && cstruserInput[0] != '<') //Not a numeric comparison search
{
int choice = getInput(1, 2, "Please enter 1 for full string search or 2 for sub-string search: ", "Please enter 1 for full string search or 2 for sub-string search: ");
if (choice == 1) //Full string search
{
selectedKeys = fullStringSearch(masterRecord, selectedKeys, DFKey, userInput);
}
else if (choice == 2) //Sub string search
{
selectedKeys = subStringSearch(masterRecord, selectedKeys, DFKey, userInput);
}
}
else if (cstruserInput[0] == '>') //Comparison search
{
if (DFKey < 5) //not a numeric field
{
cout << "Not a numeric field" << endl << endl;
counter--; //Not a condition
}
else
{
userInput.erase(userInput.begin()); //removes '>' from userInput so that it can be used to search
if (userInput != "")
{
int intUserInput = stoi(userInput); //Data field MUST be convertible to an integral type
selectedKeys = compareGreaterNumSearch(masterRecord, selectedKeys, DFKey, intUserInput);
}
else
{
cout << "Invalid search condition" << endl;
counter --;
}
}
}
else if (cstruserInput[0] == '<')
{
if (DFKey < 5) //not a numeric field
{
cout << "Not a numeric field" << endl << endl;
counter--;
}
else
{
userInput.erase(userInput.begin()); //removes '>' from userInput so that it can be used to search
if (userInput != "")
{
int intUserInput = stoi(userInput); //Data field MUST be convertible to an integral type
selectedKeys = compareSmallerNumSearch(masterRecord, selectedKeys, DFKey, intUserInput);
}
else
{
cout << "Invalid search condition" << endl;
counter --;
}
}
}
}
}
return selectedKeys;
}
int editRecordMenu (vector <string> nameList, StoreItem record) //Edit Record Menu
{
displayRecord(nameList, record);
cout << "\n1 - Update a field\n2 - Delete a field\n";
int choice = getInput(1, 2, "Choice: ", "Invalid choice. Please try again (1 - Update a field, 2 - Delete a field): ");
return choice;
}
int displaySortRecordMenu (vector <string> nameList, vector <StoreItem> masterRecord) //Sort Record Menu
{
displayAvailableRecords(masterRecord);
cout << "\n1 - Sort by data field\n2 - Sort by key\n";
int choice = getInput(1, 2, "Choice: ", "Invalid choice. Please try again (1 - Sort by data field, 3 - Sort by key): ");
return choice;
}
/*****************************************************
INPUT VALIDATION FUNCTIONS
******************************************************/
char getInput(char lowerLimit, char upperLimit, string optionalText, string errorText) //used for conditioned char inputs
{
char input;
cout << optionalText;
while(!(cin >> input))
{
cin.clear();
cin.ignore(99, '\n');
cout << "Only posititve integers are allowed: ";
}
while (input < lowerLimit || input > upperLimit && input != '0') //'0' will be an exit condition
{
cout << errorText;
while(!(cin >> input))
{
cin.clear();
cin.ignore(99, '\n');
cout << "Only posititve integers are allowed: ";
}
}
cin.ignore();
return input;
}
int getInput(int lowerLimit, int upperLimit, string optionalText, string errorText) //used for conditioned int inputs
{
int input;
cout << optionalText;
while(!(cin >> input))
{
cin.clear();
cin.ignore(99, '\n');
cout << "Only posititve integers are allowed: ";
}
while (input < lowerLimit || input > upperLimit && input != 0) //'0' will be an exit condition
{
cout << errorText;
while(!(cin >> input))
{
cin.clear();
cin.ignore(99, '\n');
cout << "Only posititve integers are allowed: ";
}
}
cin.ignore(99, '\n');
return input;
}
int getInput(vector <int> inputVector, int exitCondition, string optionalText, string errorText) //used for conditioned int inputs
{
int input;
bool match = false;
cout << optionalText;
while(!(cin >> input))
{
cin.clear();
cin.ignore(99, '\n');
cout << "Only posititve integers are allowed: ";
}
if (input == exitCondition) //If exit condition is met, exit the function
{
return input;
}
for (int i: inputVector) //Search through vector for a match
{
if (i == input)
{
match = true;
}
else
{
match = match || false;
}
}
while (match == false) //Keep getting new input until it satisfies the vector check
{
cout << errorText;
while(!(cin >> input))
{
cin.clear();
cin.ignore(99, '\n');
cout << "Only posititve integers are allowed: ";
}
if (input == exitCondition) //If exit condition is met, exit the function
{
return input;
}
for (int i: inputVector)
{
//cout << i << " ---> " << input << endl;
if (i == input)
{
match = true;
}
else
{
match = match || false;
}
}
}
cin.ignore(99, '\n');
return input;
}
double getInput(double lowerLimit, double upperLimit, string optionalText, string errorText) //used for conditioned int inputs
{
double input;
cout << optionalText;
while(!(cin >> input))
{
cin.clear();
cin.ignore(99, '\n');
cout << "Only posititve integers are allowed: ";
}
while (input < lowerLimit || input > upperLimit && input != 0) //'0' will be an exit condition
{
cout << errorText;
while(!(cin >> input))
{
cin.clear();
cin.ignore(99, '\n');
cout << "Only posititve integers are allowed: ";
}
}
cin.ignore(99, '\n');
return input;
}
string getStrInput(string optionalText) //Gets string input
{
string input;
cout << optionalText;
getline(cin, input);
return input;
}
/*****************************************************
DISPLAY FUNCTIONS
******************************************************/
void displayArray(vector <int> storage, string name) //Displays the vector with its name
{
if (storage.size() != 0)
{
cout << endl << name << endl;
for (int i = 0; i < storage.size(); ++i)
{
cout << i << " ---> " << storage[i] << endl;
}
}
else
{
cout << name <<" is empty" << endl;
}
}
void displayArray(vector <unsigned int> storage, string name) //Displays the vector with its name
{
if (storage.size() != 0)
{
cout << endl << name << endl;
for (int i = 0; i < storage.size(); ++i)
{
cout << i << " ---> " << storage[i] << endl;
}
}
else
{
cout << name <<" is empty" << endl;
}
}
void displayArray(vector <string> storage, string name) //Displays the vector with its name
{
if (storage.size() != 0)
{
cout << endl << name << endl;
for (int i = 0; i < storage.size(); ++i)
{
cout << i << " ---> " << storage[i] << endl;
}
}
else
{
cout << name <<" is empty" << endl;
}
}
void displayBlankRecord(vector <string> nameList) //Displays a blank record when the data held in a record is not important
{
cout << endl;
cout << setw(8) << left << "Key" ;
cout << setw(40) << left << "Data field " << endl;
for (int i = 0; i <= 11; i++)
{
cout << setw(8) << left << i+1;
cout << setw(40) << left << nameList[i] << endl;
}
cout << endl << endl;
}
void displayRecord(vector <string> nameList, StoreItem record) //Displays a record
{
cout << endl;
cout << "Record Name: " << record.getRecordName() << endl << endl;
cout << setw(8) << left << "Key" ;
cout << setw(40) << left << "Data field ";
cout << setw (20) << left << "Value" << endl;
for (int i = 0; i <= 11; i++)
{
cout << setw(8) << left << i+1;
cout << setw(40) << left << nameList[i];
cout << setw(20) << left << (record.getRecord())[i] << endl;
}
}
void displayRecord(vector <string> nameList, StoreItem record, vector <bool> displayDataField) //Displays a record with specified visibilities for each data field
{
cout << endl;
cout << "Record Name: " << record.getRecordName() << endl << endl;
cout << setw(8) << left << "Key" ;
cout << setw(40) << left << "Data field ";
cout << setw (20) << left << "Value" << endl;
for (int i = 0; i <= 11; i++)
{
if (displayDataField[i] == true) //If the data field is visible, display it
{
cout << setw(8) << left << i+1;
cout << setw(40) << left << nameList[i];
cout << setw(20) << left << (record.getRecord())[i] << endl;
}
}
}
void displayRecord(vector <string> nameList, vector <string> valueList) //Displays a record using external data fields
{
cout << endl;
cout << setw(8) << left << "Key" ;
cout << setw(40) << left << "Data field ";
cout << setw (20) << left << "Value" << endl;
for (int i = 0; i <= 11; i++)
{
cout << setw(8) << left << i+1;
cout << setw(40) << left << nameList[i];
cout << setw(20) << left << valueList[i] << endl;
}
}
/*****************************************************
RECORD RELATED FUNCTIONS
******************************************************/
void createRecord(string & name, vector <string> nameList, vector <string> & valueList) //Creates a new record and places it into the masterRecord
{
name = getStrInput("Please enter the name of your record: "); //Gets name for the new record
displayRecord(nameList, valueList);
unsigned int key = getInput(-1, valueList.size(), //Get DFKey
"Please enter the key of the field that you wish to insert ('-1' to exit to main menu, '0' when done): ",
"Please enter a number between 0 and " + to_string(valueList.size())),
DFKey = key - 1; //Vector starts from 0
if (key == -1)
{
return;
}
while (key != 0)
{
switch (key)
{
case 0:
{
break;
}
case 1:
case 2:
case 3: //First 5 fields are strings
case 4:
case 5:
{
valueList[DFKey] = getStrInput("Please enter the value that you want to enter: ");
break;
}
case 6:
case 7: //Next 2 fields are doubles
{
valueList[DFKey] = to_string(getInput(0.0, 1.8E+307, "Please enter a positive value of the field: ", "Please enter a non-negative number: "));
break;
}
case 8: //All other fields are int
case 9:
{
valueList[DFKey] = to_string(getInput(0, 2147483647, "Please enter a positive value of the field: ", "Please enter a non-negative number: "));
break;
}
case 10: //Next 3 fields are int (date)
{
if (valueList[9] != " ")
{
if (stoi(valueList[9]) % 4 == 0) //if the previous entry was a leap year, reset the day fields
{
valueList[11] = " ";
}
}
valueList[DFKey] = to_string(getInput(1900, 2019, //only 1900 to 2019 are supported
"Please enter the value of the field: (only 1900 - 2019) ",
"Please enter a number within 1900 - 2019: "));
break;
}
case 11:
{
valueList[DFKey] = to_string(getInput(1, 12,
"Please enter the value of the field: (only 1 - 12) ",
"Please enter a number within 1 - 12: "));
if (valueList[11] == "31" && (valueList[DFKey] == "2" || valueList[DFKey] == "4" || valueList[DFKey] == "6 "|| valueList[DFKey] == "9" || valueList[DFKey] == "11")) //If the new month doesnt have 31 days, reset the day field
{
valueList[11] = " ";
}
break;
}
case 12:
{ if (valueList[10] != " ")
{
switch (stoi(valueList[10]))
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
{
valueList[DFKey] = to_string(getInput(1, 31,
"Please enter the value of the field: (only 1 - 31) ",
"Please enter a number within 1 - 31: "));
break;
}
case 2:
{
if (stoi(valueList[9]) % 4 == 0) //test for leap year
{
valueList[DFKey] = to_string(getInput(1, 29,
"Please enter the value of the field: (only 1 - 29) ",
"Please enter a number within 1 - 29: "));
break;
}
else
{
valueList[DFKey] = to_string(getInput(1, 28,
"Please enter the value of the field: (only 1 - 28) ",
"Please enter a number within 1 - 28: "));
break;
}
}
case 4:
case 6:
case 9:
case 11:
{
valueList[DFKey] = to_string(getInput(1, 30,
"Please enter the value of the field: (only 1 - 30) ",
"Please enter a number within 1 - 30: "));
break;
}
default:
{
cout << "Day bounds checking error: invalid input at valueList[10] ---> " << valueList[10];
return;
}
}
break;
}
else
{
valueList[DFKey] = to_string(getInput(1, 31,
"Please enter the value of the field: (only 1 - 31) ",
"Please enter a number within 1 - 31: " ));
break;
}
}
default:
{
cout << "Error: invalid key ---> " << key;
return;
}
}
displayRecord(nameList, valueList);
key = getInput(0, valueList.size(),
"Please enter the key of the field that you wish to insert ('0' to exit): ",
"Please enter a number between 0 and ");
DFKey = key - 1;
}
}
void updateField (vector <string> nameList, StoreItem& record) //Updates a field - the conditions for each data field is the same as createRecord
{
displayRecord(nameList, record);
unsigned int key = getInput(0, (record.getRecord()).size(),
"Please enter the key of the field that you wish to update ('0' to exit): ",
"Please enter a number between 0 and " + to_string((record.getRecord()).size()) + ": "),
DFKey = key - 1;
string value;
while (key != 0)
{
switch (key)
{
case 0:
{
break;
}
case 1:
case 2:
case 3:
case 4:
case 5:
{
value = getStrInput("Please enter the value that you want to enter: ");
record.updateField(value, DFKey);
break;
}
case 6:
case 7:
{
value = to_string(getInput(0.0, 1.8E+307, "Please enter a positive value of the field: ", "Please enter a non-negative number: "));
record.updateField(value, DFKey);
break;
}
case 8:
case 9:
{
value = to_string(getInput(0, 2147483647, "Please enter a positive value of the field: ", "Please enter a non-negative number: "));
record.updateField(value, DFKey);
break;
}
case 10:
{
if ((record.getRecord())[9] != " ")
{
if (stoi((record.getRecord())[9]) % 4 == 0) //if the previous entry was a leap year, reset the day fields
{
record.deleteField(11);
}
}
value = to_string(getInput(1900, 2019,
"Please enter the value of the field: (only 1900 - 2019) ",
"Please enter a number within 1900 - 2019: "));
record.updateField(value, DFKey);
break;
}
case 11:
{
value = to_string(getInput(1, 12,
"Please enter the value of the field: (only 1 - 12) ",
"Please enter a number within 1 - 12: "));
record.updateField(value, DFKey);
if ((record.getRecord())[11] == "31" && ((record.getRecord())[DFKey] == "2" || (record.getRecord())[DFKey] == "4" || (record.getRecord())[DFKey] == "6 "|| (record.getRecord())[DFKey] == "9" || (record.getRecord())[DFKey] == "11")) //If the new month doesnt have 31 days, reset the day field
{
record.deleteField(11);
}
break;
}
case 12:
{ if ((record.getRecord())[10] != " ")
{
switch (stoi((record.getRecord())[10]))
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
{
value = to_string(getInput(1, 31,
"Please enter the value of the field: (only 1 - 31) ",
"Please enter a number within 1 - 31: "));
record.updateField(value, DFKey);
break;
}
case 2:
{
if (stoi((record.getRecord())[9]) % 4 == 0) //test for leap year
{
value = to_string(getInput(1, 29,
"Please enter the value of the field: (only 1 - 29) ",
"Please enter a number within 1 - 29: "));
record.updateField(value, DFKey);
break;
}
else
{
value = to_string(getInput(1, 28,
"Please enter the value of the field: (only 1 - 28) ",
"Please enter a number within 1 - 28: "));
record.updateField(value, DFKey);
break;
}
}
case 4:
case 6:
case 9:
case 11:
{
value = to_string(getInput(1, 30,
"Please enter the value of the field: (only 1 - 30) ",
"Please enter a number within 1 - 30: "));
record.updateField(value, DFKey);
break;
}
default:
{
cout << "Day bounds checking error: invalid input at valueList[10] ---> " << (record.getRecord())[10];
return;
}
}
break;
}
else
{
value = to_string(getInput(1, 31,
"Please enter the value of the field: (only 1 - 31) ",
"Please enter a number within 1 - 31: " ));
record.updateField(value, DFKey);
break;
}
}
default:
{
cout << "Error: invalid key ---> " << key;
return;
}
}
displayRecord(nameList, record);
key = getInput(0, (record.getRecord()).size(),
"Please enter the key of the field that you wish to update ('0' to exit): ",
"Please enter a number between 0 and ");
DFKey = key - 1;
}
}
void deleteField (vector <string> nameList, StoreItem & record) //Deletes a field
{
displayRecord(nameList, record);
unsigned int key = getInput(0, (record.getRecord()).size(),
"Please enter the key of the field that you wish to delete ('0' to exit): ",
"Please enter a number between 0 and " + to_string((record.getRecord()).size())),
DFKey = key - 1;
string value;
while (key != 0)
{
record.deleteField(DFKey);
displayRecord(nameList, record);
key = getInput(0, (record.getRecord()).size(),
"Please enter the key of the field that you wish to delete ('0' to exit): ",
"Please enter a number between 0 and ");
DFKey = key - 1;
}
}
int assignKey (vector <int> & keys) //Assigns a unique key based on the existing key vector
{
int tempKey;
bool match = true;
for (int i = 1; match != false; i++)
{
match = false;
for (int j = 0; j < keys.size(); j++)
{
if (i == keys[j])
{
match = true;
j = keys.size();
}
else
{
match = match || false;
}
}
if (match == false)
{
tempKey = i;
keys.push_back(i); //assigns a key to the new record starting from 1
}
}
return tempKey;
}
int validateKey (int inputKey, vector <int> keys) //Checks if a key is present in the key vector
{
for (int key : keys)
{
if (inputKey == key)
{
return 0; //Key is good
}
}
return 1; //If the loop managed to finish without a match being found, key is bad
}
int deleteKey (int inputKey, vector <int> & keys) //Deletes key when a record is deleteds
{
for (int i = 0; i < keys.size(); i++)
{
if (inputKey == keys[i])
{
keys.erase(keys.begin() + i);
return 0; //Delete successful
}
}
return 1; //Delete failed
}
int keyToRecord (int inputKey, vector <StoreItem> masterRecord) //Converts the key of a record to its position in the masterRecord
{
for (int i = 0; i < masterRecord.size(); i++)
{
if (inputKey == masterRecord[i].getKey())
{
return i;
}
}
return -1; //if no match is found at the end of the loop, return -1
}
void updateKeys (vector <int> & keys, vector <StoreItem> masterRecord) //Updates the keys vector after a record is sorted
{
for (int i = 0; i < masterRecord.size(); i++)
{
keys[i] = (masterRecord[i]).getKey();
}
}
vector <int> fullStringSearch (vector <StoreItem> masterRecord, vector <int> selectedKeys, int DFKey, string searchString) //Searches in a given list for records that have the exact string in the specific data field
{
if (selectedKeys.size() != 0) //Instead of pushing new keys into the vector, it deletes existing keys that do not have a match
{
for (int i = 0; i < selectedKeys.size(); i++)
{
int key = keyToRecord(selectedKeys[i], masterRecord); //convert input key to the position of the record in the master record
if (searchString != (masterRecord[key].getRecord())[DFKey])
{
selectedKeys.erase(selectedKeys.begin()+i);
i--; //Necessary because the no. of elements reduced by 1 and shifted to the left in the selectedKey vector
}
}
}
/*
else //If the input vector is empty, push keys instead
{
for (int i = 0; i < masterRecord.size(); i++)
{
if (searchString == (masterRecord[i].getRecord())[DFKey])
{
selectedKeys.push_back(masterRecord[i].getKey());
}
}
}
*/
return selectedKeys;
}
vector <int> subStringSearch (vector <StoreItem> masterRecord, vector <int> selectedKeys, int DFKey, string searchString) //Searches in a given list for records that include string in the specific data field
{
if (selectedKeys.size() != 0) //Instead of pushing new keys into the vector, it deletes existing keys that do not have a match
{
for (int i = 0; i < selectedKeys.size(); i++)
{
int key = keyToRecord(selectedKeys[i], masterRecord); //convert input key to the position of the record in th master record
if ((masterRecord[key].getRecord())[DFKey].find(searchString) == string::npos)
{
selectedKeys.erase(selectedKeys.begin()+i);
i--; //Necessary because the no. of elements reduced by 1 and shifted to the left in the selectedKey vector
}
}
}
/*
else //If the input vector is empty, push keys instead
{
for (int i = 0; i < masterRecord.size(); i++)
{
if ((masterRecord[i].getRecord())[DFKey].find(searchString) != string::npos) //first get record in master record at index i, then loop through the record vector with subscript j and look
//for the substring searchString
{
selectedKeys.push_back(masterRecord[i].getKey());
}
}
}
*/
return selectedKeys;
}
vector <int> compareGreaterNumSearch (vector <StoreItem> masterRecord, vector <int> selectedKeys, int DFKey, int num) //Searches for a record that has a number greater than num in a specified data field
{
if (selectedKeys.size() != 0)
{
for (int i = 0; i < selectedKeys.size(); i++)
{
int key = keyToRecord(selectedKeys[i], masterRecord); //convert input key to the position of the record in th master record
if ((masterRecord[key].getRecord())[DFKey] == " ")
{
selectedKeys.erase(selectedKeys.begin()+i);
i--;
}
else if (stoi(masterRecord[key].getRecord()[DFKey]) <= num) //first get record in master record at index i, then look at index DFKey and convert to int then compare
{
selectedKeys.erase(selectedKeys.begin()+i);
i--;
}
}
}
/*
else
{
for (int i = 0; i < masterRecord.size(); i++)
{
if ((masterRecord[i].getRecord())[DFKey] != " ")
{
if (stoi(masterRecord[i].getRecord()[DFKey]) > num) //first get record in master record at index i, then look at index DFKey and convert to int then compare
{
selectedKeys.push_back(masterRecord[i].getKey());
}
}
}
}
*/
return selectedKeys;
}
vector <int> compareSmallerNumSearch (vector <StoreItem> masterRecord, vector <int> selectedKeys, int DFKey, int num) //Searches for a record that has a number smaller than num in a specified data field
{
if (selectedKeys.size() != 0)
{
for (int i = 0; i < selectedKeys.size(); i++)
{
int key = keyToRecord(selectedKeys[i], masterRecord); //convert input key to the position of the record in th master record
if ((masterRecord[key].getRecord())[DFKey] == " ")
{
selectedKeys.erase(selectedKeys.begin()+i);
i--;
}
else if (stoi(masterRecord[key].getRecord()[DFKey]) >= num) //first get record in master record at index i, then look at index DFKey and convert to int then compare
{
selectedKeys.erase(selectedKeys.begin()+i);
i--;
}
}
}
/*
else
{
for (int i = 0; i < masterRecord.size(); i++)
{
if ((masterRecord[i].getRecord())[DFKey] != " ")
{
if (stoi(masterRecord[i].getRecord()[DFKey]) < num) //first get record in master record at index i, then look at index DFKey and convert to int then compare
{
selectedKeys.push_back(masterRecord[i].getKey());
}
}
}
}
*/
return selectedKeys;
}
void ascendSortRecord (int DFKey, vector <StoreItem> & masterRecord) //Sorts records in ascending order
{
int index, minIndex;
auto minValue = (masterRecord[0].getRecord())[DFKey]; //Determine automatically the data type of the data field
bool newMinFound = false;
for (index = 0; index < (masterRecord.size() - 1); index++)
{
minIndex = index;
minValue = (masterRecord[index].getRecord())[DFKey];
newMinFound = false;
for (int i = index + 1; i < masterRecord.size(); i++)
{
//cout << "At index = " << index << ", " << minValue << " compared to i: " << i << ", " << (masterRecord[i].getRecord())[DFKey] << endl;
if ((masterRecord[i].getRecord())[DFKey] < minValue)
{
minIndex = i;
minValue = (masterRecord[i].getRecord())[DFKey];
newMinFound = true; //Improvement on the previous algorithm, now it only swaps only if a new minimum is found
}
}
if (newMinFound)
{
iter_swap(masterRecord.begin()+minIndex, masterRecord.begin()+index);
}
}
}
void descendingSortRecord (int DFKey, vector <StoreItem> & masterRecord) //Sorts records in descending order
{
int index, maxIndex;
auto maxValue = (masterRecord[0].getRecord())[DFKey];
bool newMaxFound = false;
for (index = 0; index < (masterRecord.size() - 1); index++)
{
maxIndex = index;
maxValue = (masterRecord[index].getRecord())[DFKey];
newMaxFound = false;
for (int i = index + 1; i < masterRecord.size(); i++)
{
//cout << "At index = " << index << ", " << maxValue << " compared to i: " << i << ", " << (masterRecord[i].getRecord())[DFKey] << endl;
if ((masterRecord[i].getRecord())[DFKey] > maxValue)
{
maxIndex = i;
maxValue = (masterRecord[i].getRecord())[DFKey];
newMaxFound = true; //Improvement on the previous algorithm, now it only swaps only if a new maximum is found
}
}
if (newMaxFound)
{
iter_swap(masterRecord.begin()+maxIndex, masterRecord.begin()+index);
}
}
}
void ascendSortRecordInt (int DFKey, vector <StoreItem> & masterRecord) //Sorts records in ascending order based on int
{
int index, minIndex;
string temp;
int minValue;
bool newMinFound = false;
for (index = 0; index < (masterRecord.size() - 1); index++)
{
minIndex = index;
temp = (masterRecord[index].getRecord())[DFKey];
if (temp != " ")
{
minValue = stoi(temp);
}
else
{
minValue = -1;
}
newMinFound = false;
for (int i = index + 1; i < masterRecord.size(); i++)
{
//cout << "At index = " << index << ", " << minValue << " compared to i: " << i << ", " << (masterRecord[i].getRecord())[DFKey] << endl;
temp = (masterRecord[i].getRecord())[DFKey];
if (temp == " ")
{
temp = "-1";
}
if (stoi(temp) < minValue)
{
minIndex = i;
minValue = stoi(temp);
newMinFound = true;
}
}
if (newMinFound)
{
iter_swap(masterRecord.begin()+minIndex, masterRecord.begin()+index);
}
}
}
void descendingSortRecordInt (int DFKey, vector <StoreItem> & masterRecord) //Sorts records in descending order based on int
{
int index, maxIndex;
string temp;
int maxValue;
bool newMaxFound = false;
for (index = 0; index < (masterRecord.size() - 1); index++)
{
maxIndex = index;
temp = (masterRecord[index].getRecord())[DFKey];
if (temp != " ")
{
maxValue = stoi(temp);
}
else
{
maxValue = -1;
}
newMaxFound = false;
for (int i = index + 1; i < masterRecord.size(); i++)
{
//cout << "At index = " << index << ", " << maxValue << " compared to i: " << i << ", " << (masterRecord[i].getRecord())[DFKey] << endl;
temp = (masterRecord[i].getRecord())[DFKey];
if (temp == " ")
{
temp = "-1";
}
if (stoi(temp) > maxValue)
{
maxIndex = i;
maxValue = stoi(temp);
newMaxFound = true; //Improvement on the previous algorithm, now it only swaps only if a new minimum is found
}
}
if (newMaxFound)
{
iter_swap(masterRecord.begin()+maxIndex, masterRecord.begin()+index);
}
}
}
void ascendSortRecordDouble (int DFKey, vector <StoreItem> & masterRecord) //Sorts records in ascending order based on double
{
int index, minIndex;
string temp;
double minValue;
bool newMinFound = false;
for (index = 0; index < (masterRecord.size() - 1); index++)
{
minIndex = index;
temp = (masterRecord[index].getRecord())[DFKey];
if (temp != " ")
{
minValue = atof(temp.c_str());
}
else
{
minValue = -1.0;
}
newMinFound = false;
for (int i = index + 1; i < masterRecord.size(); i++)
{
//cout << "At index = " << index << ", " << minValue << " compared to i: " << i << ", " << (masterRecord[i].getRecord())[DFKey] << endl;
temp = (masterRecord[i].getRecord())[DFKey];
if (temp == " ")
{
temp = "-1.0";
}
if (atof(temp.c_str()) < minValue)
{
minIndex = i;
minValue = atof(temp.c_str());
newMinFound = true; //Improvement on the previous algorithm, now it only swaps only if a new minimum is found
}
}
if (newMinFound)
{
iter_swap(masterRecord.begin()+minIndex, masterRecord.begin()+index);
}
}
}
void descendingSortRecordDouble (int DFKey, vector <StoreItem> & masterRecord) //Sorts records in descending order based on double
{
int index, maxIndex;
string temp = (masterRecord[0].getRecord())[DFKey];
double maxValue = atof(temp.c_str());
bool newMaxFound = false;
for (index = 0; index < (masterRecord.size() - 1); index++)
{
maxIndex = index;
temp = (masterRecord[index].getRecord())[DFKey];
if (temp != " ")
{
maxValue = atof(temp.c_str());
}
else
{
maxValue = -1.0;
}
maxValue = atof(temp.c_str());
newMaxFound = false;
for (int i = index + 1; i < masterRecord.size(); i++)
{
//cout << "At index = " << index << ", " << maxValue << " compared to i: " << i << ", " << (masterRecord[i].getRecord())[DFKey] << endl;
temp = (masterRecord[i].getRecord())[DFKey];
if (temp == " ")
{
temp = "-1.0";
}
if (atof(temp.c_str()) > maxValue)
{
maxIndex = i;
maxValue = atof(temp.c_str());
newMaxFound = true; //Improvement on the previous algorithm, now it only swaps only if a new minimum is found
}
}
if (newMaxFound)
{
iter_swap(masterRecord.begin()+maxIndex, masterRecord.begin()+index);
}
}
}
void ascendSortRecordStr (int DFKey, vector <StoreItem> & masterRecord) //Sorts records in ascending order based on strings
{
int index, minIndex;
string minValue = (masterRecord[0].getRecord())[DFKey];
bool newMinFound = false;
for (index = 0; index < (masterRecord.size() - 1); index++)
{
minIndex = index;
minValue = (masterRecord[index].getRecord())[DFKey];
newMinFound = false;
for (int i = index + 1; i < masterRecord.size(); i++)
{
//cout << "At index = " << index << ", " << minValue << " compared to i: " << i << ", " << (masterRecord[i].getRecord())[DFKey] << endl;
if ((masterRecord[i].getRecord())[DFKey] < minValue)
{
minIndex = i;
minValue = (masterRecord[i].getRecord())[DFKey];
newMinFound = true; //Improvement on the previous algorithm, now it only swaps only if a new minimum is found
}
}
if (newMinFound)
{
iter_swap(masterRecord.begin()+minIndex, masterRecord.begin()+index);
}
}
}
void descendingSortRecordStr (int DFKey, vector <StoreItem> & masterRecord) //Sorts records in descending order based on strings
{
int index, maxIndex;
string maxValue = (masterRecord[0].getRecord())[DFKey];
bool newMinFound = false;
for (index = 0; index < (masterRecord.size() - 1); index++)
{
maxIndex = index;
maxValue = (masterRecord[index].getRecord())[DFKey];
newMinFound = false;
for (int i = index + 1; i < masterRecord.size(); i++)
{
//cout << "At index = " << index << ", " << maxValue << " compared to i: " << i << ", " << (masterRecord[i].getRecord())[DFKey] << endl;
if ((masterRecord[i].getRecord())[DFKey] < maxValue)
{
maxIndex = i;
maxValue = (masterRecord[i].getRecord())[DFKey];
newMinFound = true; //Improvement on the previous algorithm, now it only swaps only if a new minimum is found
}
}
if (newMinFound)
{
iter_swap(masterRecord.begin()+maxIndex, masterRecord.begin()+index);
}
}
}
void ascKeySortRecord (vector <StoreItem> & masterRecord) //Sorts based on keys in ascending order
{
int index, minIndex;
int minValue = masterRecord[0].getKey();
bool newMinFound = false;
for (index = 0; index < (masterRecord.size() - 1); index++)
{
minIndex = index;
minValue = masterRecord[index].getKey();
newMinFound = false;
for (int i = index + 1; i < masterRecord.size(); i++)
{
//cout << "At index = " << index << ", " << minValue << " compared to i: " << i << ", " << masterRecord[i].getKey() << endl;
if (masterRecord[i].getKey() < minValue)
{
minIndex = i;
minValue = masterRecord[i].getKey();
newMinFound = true;
}
}
if (newMinFound)
{
iter_swap(masterRecord.begin()+ minIndex, masterRecord.begin()+index);
}
}
}
void dscKeySortRecord (vector <StoreItem> & masterRecord) //Sorts based on keys in descending order
{
int index, maxIndex;
int maxValue = masterRecord[0].getKey();
bool newMaxFound = false;
for (index = 0; index < (masterRecord.size() - 1); index++)
{
maxIndex = index;
maxValue = masterRecord[index].getKey();
newMaxFound = false;
for (int i = index + 1; i < masterRecord.size(); i++)
{
if (masterRecord[i].getKey() > maxValue)
{
maxIndex = i;
maxValue = masterRecord[i].getKey();
newMaxFound = true;
}
}
if (newMaxFound)
{
iter_swap(masterRecord.begin()+maxIndex, masterRecord.begin()+index);
}
}
}
| 29.152269 | 306 | 0.590779 | [
"object",
"vector"
] |
7fe86a3fcb6c852c2109741f62d8781a96c7032d | 57,210 | cpp | C++ | src/comm/transports/ibrc/ibrc.cpp | shintaro-iwasaki/nvshmem | 295b40c2f1a00cea8ee2f791886713dd4abc6b0c | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | src/comm/transports/ibrc/ibrc.cpp | shintaro-iwasaki/nvshmem | 295b40c2f1a00cea8ee2f791886713dd4abc6b0c | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | src/comm/transports/ibrc/ibrc.cpp | shintaro-iwasaki/nvshmem | 295b40c2f1a00cea8ee2f791886713dd4abc6b0c | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | /*
* * Copyright (c) 2016-2018, NVIDIA CORPORATION. All rights reserved.
* *
* * See COPYRIGHT for license information
* */
#include "nvshmem.h"
#include "nvshmem_internal.h"
#include <string.h>
#include <assert.h>
#include <map>
#include <vector>
#include <deque>
#include <dlfcn.h>
#include "ibrc.h"
#include "nvshmemx_error.h"
#ifdef NVSHMEM_USE_GDRCOPY
#include "gdrapi.h"
#endif
#define IBRC_MAX_INLINE_SIZE 128
int ibrc_srq_depth;
#define IBRC_SRQ_MASK (ibrc_srq_depth - 1)
int ibrc_qp_depth;
#define IBRC_REQUEST_QUEUE_MASK (ibrc_qp_depth - 1)
#define IBRC_BUF_SIZE 64
#if defined(NVSHMEM_X86_64)
#define IBRC_CACHELINE 64
#elif defined(NVSHMEM_PPC64LE)
#define IBRC_CACHELINE 128
#else
#error Unknown cache line size
#endif
#define MAX_NUM_HCAS 16
#define MAX_NUM_PORTS 4
#define MAX_NUM_PES_PER_NODE 32
#ifdef NVSHMEM_USE_GDRCOPY
#define BAR_READ_BUFSIZE (2*1024*1024)
#else
#define BAR_READ_BUFSIZE (sizeof(uint64_t))
#endif
enum { WAIT_ANY = 0, WAIT_ALL = 1 };
int MAX_RD_ATOMIC; /* Maximum number of RDMA Read & Atomic operations that can be outstanding per QP */
typedef struct {
void *devices;
int *dev_ids;
int *port_ids;
int n_dev_ids;
} transport_ibrc_state_t;
struct ibrc_request {
struct ibv_send_wr sr;
struct ibv_send_wr *bad_sr;
struct ibv_sge sge;
};
struct ibrc_atomic_op {
nvshmemi_amo_t op;
void *addr;
void *retaddr;
uint32_t retrkey;
uint64_t retflag;
uint32_t elembytes;
uint64_t compare;
uint64_t swap_add;
};
typedef struct ibrc_buf {
struct ibv_recv_wr rwr;
struct ibv_recv_wr *bad_rwr;
struct ibv_sge sge;
int qp_num;
char buf[IBRC_BUF_SIZE];
} ibrc_buf_t;
ibrc_buf_t *bpool;
int bpool_size;
static std::vector<void *> bpool_free;
static std::deque<void *> bqueue_toprocess;
struct ibrc_device {
struct ibv_device *dev;
struct ibv_context *context;
struct ibv_pd *pd;
struct ibv_device_attr device_attr;
struct ibv_port_attr port_attr[MAX_NUM_PORTS];
//bpool information
struct ibv_srq *srq;
int srq_posted;
struct ibv_mr *bpool_mr;
struct ibv_cq *recv_cq;
struct ibv_cq *send_cq;
};
struct ibrc_ep {
int devid;
int portid;
struct ibv_qp *qp;
struct ibv_cq *send_cq;
struct ibv_cq *recv_cq;
struct ibrc_request *req;
volatile uint64_t head_op_id;
volatile uint64_t tail_op_id;
void *ibrc_state;
};
struct ibrc_ep_handle {
uint32_t qpn;
uint16_t lid;
};
struct ibrc_mem_handle {
uint32_t lkey;
uint32_t rkey;
void *mr;
};
typedef struct ibrc_mem_handle_info {
struct ibv_mr *mr;
void *ptr;
size_t size;
#ifdef NVSHMEM_USE_GDRCOPY
void *cpu_ptr;
void *cpu_ptr_base;
gdr_mh_t mh;
#endif
} ibrc_mem_handle_info_t;
ibrc_mem_handle_info_t *dummy_local_mem;
pthread_mutex_t ibrc_mutex_recv_progress;
pthread_mutex_t ibrc_mutex_send_progress;
static std::vector<ibrc_mem_handle_info_t> mem_handle_cache;
static std::map<unsigned int, long unsigned int> qp_map;
static uint64_t connected_qp_count;
struct ibrc_ep *ibrc_cst_ep;
static int use_ib_native_atomics = 1;
static int use_gdrcopy = 0;
#ifdef NVSHMEM_USE_GDRCOPY
static gdr_t gdr_desc;
struct gdrcopy_function_table {
gdr_t (*open)();
int (*close)(gdr_t g);
int (*pin_buffer)(gdr_t g, unsigned long addr, size_t size, uint64_t p2p_token, uint32_t va_space, gdr_mh_t *handle);
int (*unpin_buffer)(gdr_t g, gdr_mh_t handle);
int (*get_info)(gdr_t g, gdr_mh_t handle, gdr_info_t *info);
int (*map)(gdr_t g, gdr_mh_t handle, void **va, size_t size);
int (*unmap)(gdr_t g, gdr_mh_t handle, void *va, size_t size);
int (*copy_from_mapping)(gdr_mh_t handle, void *h_ptr, const void *map_d_ptr, size_t size);
int (*copy_to_mapping)(gdr_mh_t handle, const void *map_d_ptr, void *h_ptr, size_t size);
void (*runtime_get_version)(int *major, int *minor);
int (*driver_get_version)(gdr_t g, int *major, int *minor);
};
static struct gdrcopy_function_table gdrcopy_ftable;
static void *gdrcopy_handle = NULL;
static volatile uint64_t atomics_received = 0;
static volatile uint64_t atomics_processed = 0;
static volatile uint64_t atomics_issued = 0;
static volatile uint64_t atomics_completed = 0;
static volatile uint64_t atomics_acked = 0;
struct gdrmap_heap_info {
void *gpu_ptr;
gdr_mh_t mh;
void *mapped_ptr;
int size;
};
static struct gdrmap_heap_info gdrmap_heap;
#endif
static struct ibrc_function_table ftable;
static void *ibv_handle;
struct ibrc_hca_info {
char name[64];
int port;
int count;
int found;
};
int nvshmemt_ibrc_init(nvshmem_transport_t *transport);
int check_poll_avail(struct ibrc_ep *ep, int wait_predicate);
ibrc_mem_handle_info_t get_mem_handle_info(void* gpu_ptr) {
assert(!mem_handle_cache.empty());
//assuming there is only one region (shmem heap) that is registered with IB
ibrc_mem_handle_info_t mem_handle_info = mem_handle_cache.back();
return mem_handle_info;
}
inline int refill_srq(struct ibrc_device *device) {
int status = 0;
while ((device->srq_posted < ibrc_srq_depth) && !bpool_free.empty()) {
ibrc_buf_t* buf = (ibrc_buf_t *)bpool_free.back();
buf->rwr.next = NULL;
buf->rwr.wr_id = (uint64_t)buf;
buf->rwr.sg_list = &(buf->sge);
buf->rwr.num_sge = 1;
buf->sge.addr = (uint64_t)buf->buf;
buf->sge.length = IBRC_BUF_SIZE;
buf->sge.lkey = device->bpool_mr->lkey;
status = ibv_post_srq_recv(device->srq, &buf->rwr,
&buf->bad_rwr);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out,
"ibv_post_srq_recv failed \n");
bpool_free.pop_back();
device->srq_posted++;
}
out:
return status;
}
int parse_hca_list(const char *string, struct ibrc_hca_info *hca_list, int max_count) {
if (!string) return 0;
const char *ptr = string;
// Ignore "^" name, will be detected outside of this function
if (ptr[0] == '^') ptr++;
int if_num = 0;
int if_counter = 0;
int segment_counter = 0;
char c;
do {
c = *ptr;
if (c == ':') {
if (segment_counter == 0) {
if (if_counter > 0) {
hca_list[if_num].name[if_counter] = '\0';
hca_list[if_num].port = atoi(ptr + 1);
hca_list[if_num].found = 0;
if_num++;
if_counter = 0;
segment_counter++;
}
} else {
hca_list[if_num - 1].count = atoi(ptr + 1);
segment_counter = 0;
}
c = *(ptr + 1);
while (c != ',' && c != ':' && c != '\0') {
ptr++;
c = *(ptr + 1);
}
} else if (c == ',' || c == '\0') {
if (if_counter > 0) {
hca_list[if_num].name[if_counter] = '\0';
hca_list[if_num].found = 0;
if_num++;
if_counter = 0;
}
segment_counter = 0;
} else {
if (if_counter == 0) {
hca_list[if_num].port = -1;
hca_list[if_num].count = 1;
}
hca_list[if_num].name[if_counter] = c;
if_counter++;
}
ptr++;
} while (if_num < max_count && c);
INFO(NVSHMEM_INIT, "Begin - Parsed HCA list provided by user - ");
for (int i = 0; i < if_num; i++) {
INFO(NVSHMEM_INIT, "Parsed HCA list provided by user - i=%d (of %d), name=%s, port=%d, count=%d", \
i, if_num, hca_list[i].name, hca_list[i].port, hca_list[i].count);
}
INFO(NVSHMEM_INIT, "End - Parsed HCA list provided by user");
return if_num;
}
int nvshmemt_ibrc_show_info(nvshmem_mem_handle_t *mem_handles, int transport_id,
int transport_count, nvshmemt_ep_t *eps, int ep_count, int npes,
int mype) {
for (int i = 0; i < npes; ++i) {
INFO(NVSHMEM_TRANSPORT, "[%d] mem_handle %d : %p", mype, transport_id,
&mem_handles[i * transport_count + transport_id]);
struct ibrc_mem_handle *mem_handle =
(struct ibrc_mem_handle *)&mem_handles[i * transport_count + transport_id];
(struct ibrc_mem_handle *)&mem_handles[i * transport_count + transport_id];
INFO(NVSHMEM_TRANSPORT, "[%d] lkey %x rkey %x mr %p", mype, mem_handle->lkey,
mem_handle->rkey, mem_handle->mr);
if (i != mype) {
for (int j = 0; j < ep_count; ++j) {
/*XXX : not implemented*/
}
}
}
return 0;
}
int nvshmemt_ibrc_get_device_count(int *ndev, nvshmem_transport_t t) {
int status = 0;
struct nvshmem_transport *transport = (struct nvshmem_transport *)t;
transport_ibrc_state_t *ibrc_state = (transport_ibrc_state_t *)transport->state;
*ndev = ibrc_state->n_dev_ids;
out:
return status;
}
static int ib_iface_get_mlx_path(const char *ib_name, char **path) {
int status = NVSHMEMX_SUCCESS;
char device_path[MAXPATHSIZE];
snprintf(device_path, MAXPATHSIZE, "/sys/class/infiniband/%s/device", ib_name);
*path = realpath(device_path, NULL);
NULL_ERROR_JMP(*path, status, NVSHMEMX_ERROR_OUT_OF_MEMORY, out, "realpath failed \n");
out:
return status;
}
int nvshmemt_ibrc_get_pci_path(int dev, char **pci_path, nvshmem_transport_t t) {
int status = NVSHMEMX_SUCCESS;
struct nvshmem_transport *transport = (struct nvshmem_transport *)t;
transport_ibrc_state_t *ibrc_state = (transport_ibrc_state_t *)transport->state;
int dev_id = ibrc_state->dev_ids[dev];
const char *ib_name =
(const char *)((struct ibrc_device *)ibrc_state->devices)[dev_id].dev->name;
status = ib_iface_get_mlx_path(ib_name, pci_path);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "ib_iface_get_mlx_path failed \n");
out:
return status;
}
int nvshmemt_ibrc_can_reach_peer(int *access, struct nvshmem_transport_pe_info *peer_info,
nvshmem_transport_t t) {
int status = 0;
*access = NVSHMEM_TRANSPORT_CAP_CPU_WRITE | NVSHMEM_TRANSPORT_CAP_CPU_READ | NVSHMEM_TRANSPORT_CAP_CPU_ATOMICS;
out:
return status;
}
static int ep_create(struct ibrc_ep **ep_ptr, int devid, transport_ibrc_state_t *ibrc_state) {
int status = 0;
struct ibrc_ep *ep;
struct ibv_qp_init_attr init_attr;
struct ibv_qp_attr attr;
int flags;
struct ibrc_device *device =
((struct ibrc_device *)ibrc_state->devices + ibrc_state->dev_ids[devid]);
int portid = ibrc_state->port_ids[devid];
struct ibv_port_attr port_attr = device->port_attr[ibrc_state->port_ids[devid] - 1];
struct ibv_context *context = device->context;
struct ibv_pd *pd = device->pd;
//algining ep structure to prevent split tranactions when accessing head_op_id and
//tail_op_id which can be used in inter-thread synchronization
//TODO: use atomic variables instead to rely on language memory model guarantees
status = posix_memalign((void **)&ep, IBRC_CACHELINE, sizeof(struct ibrc_ep));
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_OUT_OF_MEMORY, out, "ep allocation failed \n");
memset((void *)ep, 0, sizeof(struct ibrc_ep));
if (!device->send_cq) {
device->send_cq = ftable.create_cq(context, device->device_attr.max_cqe, NULL, NULL, 0);
NULL_ERROR_JMP(device->send_cq, status, NVSHMEMX_ERROR_INTERNAL, out, "cq creation failed \n");
}
assert(device->send_cq != NULL);
ep->send_cq = device->send_cq;
if (!device->srq) {
struct ibv_srq_init_attr srq_init_attr;
memset(&srq_init_attr, 0, sizeof(srq_init_attr));
srq_init_attr.attr.max_wr = ibrc_srq_depth;
srq_init_attr.attr.max_sge = 1;
device->srq = ftable.create_srq(pd, &srq_init_attr);
NULL_ERROR_JMP(device->srq, status, NVSHMEMX_ERROR_INTERNAL, out, "srq creation failed \n");
device->recv_cq = ftable.create_cq(context, ibrc_srq_depth, NULL, NULL, 0);
NULL_ERROR_JMP(device->recv_cq, status, NVSHMEMX_ERROR_INTERNAL, out, "cq creation failed \n");
}
assert(device->recv_cq != NULL);
ep->recv_cq = device->recv_cq;
memset(&init_attr, 0, sizeof(struct ibv_qp_init_attr));
init_attr.srq = device->srq;
init_attr.send_cq = ep->send_cq;
init_attr.recv_cq = ep->recv_cq;
init_attr.qp_type = IBV_QPT_RC;
init_attr.cap.max_send_wr = ibrc_qp_depth;
init_attr.cap.max_recv_wr = 0;
init_attr.cap.max_send_sge = 1;
init_attr.cap.max_recv_sge = 0;
init_attr.cap.max_inline_data = IBRC_MAX_INLINE_SIZE;
ep->qp = ftable.create_qp(pd, &init_attr);
NULL_ERROR_JMP(ep->qp, status, NVSHMEMX_ERROR_INTERNAL, out, "qp creation failed \n");
memset(&attr, 0, sizeof(struct ibv_qp_attr));
attr.qp_state = IBV_QPS_INIT;
attr.pkey_index = 0;
attr.port_num = portid;
attr.qp_access_flags =
IBV_ACCESS_REMOTE_WRITE | IBV_ACCESS_REMOTE_READ | IBV_ACCESS_LOCAL_WRITE
| IBV_ACCESS_REMOTE_ATOMIC;
flags = IBV_QP_STATE | IBV_QP_PKEY_INDEX | IBV_QP_PORT | IBV_QP_ACCESS_FLAGS;
status = ftable.modify_qp(ep->qp, &attr, flags);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "ibv_modify_qp failed \n");
ep->req = (struct ibrc_request *)malloc(sizeof(struct ibrc_request) * ibrc_qp_depth);
NULL_ERROR_JMP(ep->req, status, NVSHMEMX_ERROR_OUT_OF_MEMORY, out, "req allocation failed \n");
ep->head_op_id = 0;
ep->tail_op_id = 0;
ep->ibrc_state = (void *)ibrc_state;
ep->devid = ibrc_state->dev_ids[devid];
ep->portid = portid;
//insert qp into map
qp_map.insert(std::make_pair((unsigned int)ep->qp->qp_num, (long unsigned int)ep));
*ep_ptr = ep;
out:
return status;
}
static int ep_connect(struct ibrc_ep *ep, struct ibrc_ep_handle *ep_handle) {
int status = 0;
struct ibv_qp_attr attr;
int flags;
int devid = ep->devid;
int portid = ep->portid;
transport_ibrc_state_t *ibrc_state = (transport_ibrc_state_t *)ep->ibrc_state;
struct ibrc_device *device = ((struct ibrc_device *)ibrc_state->devices + devid);
struct ibv_port_attr port_attr = device->port_attr[portid - 1];
memset(&attr, 0, sizeof(struct ibv_qp_attr));
attr.qp_state = IBV_QPS_RTR;
attr.path_mtu = port_attr.active_mtu;
attr.dest_qp_num = ep_handle->qpn;
attr.rq_psn = 0;
attr.ah_attr.dlid = ep_handle->lid;
attr.max_dest_rd_atomic = MAX_RD_ATOMIC;
attr.min_rnr_timer = 12;
attr.ah_attr.is_global = 0;
attr.ah_attr.sl = 0;
attr.ah_attr.src_path_bits = 0;
attr.ah_attr.port_num = portid;
flags = IBV_QP_STATE | IBV_QP_AV | IBV_QP_PATH_MTU | IBV_QP_DEST_QPN | IBV_QP_RQ_PSN |
IBV_QP_MIN_RNR_TIMER | IBV_QP_MAX_DEST_RD_ATOMIC;
status = ftable.modify_qp(ep->qp, &attr, flags);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "ibv_modify_qp failed \n");
memset(&attr, 0, sizeof(struct ibv_qp_attr));
attr.qp_state = IBV_QPS_RTS;
attr.sq_psn = 0;
attr.timeout = 20;
attr.retry_cnt = 7;
attr.rnr_retry = 7;
attr.max_rd_atomic = MAX_RD_ATOMIC;
flags = IBV_QP_STATE | IBV_QP_SQ_PSN | IBV_QP_TIMEOUT | IBV_QP_RETRY_CNT | IBV_QP_RNR_RETRY |
IBV_QP_MAX_QP_RD_ATOMIC;
status = ftable.modify_qp(ep->qp, &attr, flags);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "ibv_modify_qp failed \n");
//register and post receive buffer pool
if (!device->bpool_mr) {
device->bpool_mr = ftable.reg_mr(device->pd, bpool, bpool_size*sizeof(ibrc_buf_t),
IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE | IBV_ACCESS_REMOTE_READ);
NULL_ERROR_JMP(device->bpool_mr, status, NVSHMEMX_ERROR_OUT_OF_MEMORY, out,
"mem registration failed \n");
assert(device->srq != NULL);
status = refill_srq(device);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "refill_srq failed \n");
}
connected_qp_count++;
out:
return status;
}
int ep_get_handle(struct ibrc_ep_handle *ep_handle, struct ibrc_ep *ep) {
int status = 0;
transport_ibrc_state_t *ibrc_state = (transport_ibrc_state_t *)ep->ibrc_state;
struct ibrc_device *device = ((struct ibrc_device *)ibrc_state->devices + ep->devid);
assert(sizeof(struct ibrc_ep_handle) <= NVSHMEM_EP_HANDLE_SIZE);
ep_handle->lid = device->port_attr[ep->portid - 1].lid;
ep_handle->qpn = ep->qp->qp_num;
out:
return status;
}
int setup_cst_loopback (transport_ibrc_state_t *ibrc_state, int dev_id) {
int status = 0;
struct ibrc_device *device =
((struct ibrc_device *)ibrc_state->devices + ibrc_state->dev_ids[dev_id]);
struct ibrc_ep_handle cst_ep_handle;
status = ep_create(&ibrc_cst_ep, dev_id, ibrc_state);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "ep_create cst failed \n");
status = ep_get_handle(&cst_ep_handle, ibrc_cst_ep);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "ep_get_handle failed \n");
status = ep_connect(ibrc_cst_ep, &cst_ep_handle);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "ep_connect failed \n");
out:
return status;
}
int nvshmemt_ibrc_get_mem_handle(nvshmem_mem_handle_t *mem_handle, void *buf, size_t length,
int dev_id, nvshmem_transport_t t) {
int status = 0;
struct nvshmem_transport *transport = (struct nvshmem_transport *)t;
transport_ibrc_state_t *ibrc_state = (transport_ibrc_state_t *)transport->state;
struct ibrc_device *device =
((struct ibrc_device *)ibrc_state->devices + ibrc_state->dev_ids[dev_id]);
struct ibrc_mem_handle_info handle_info;
struct ibrc_mem_handle *handle = (struct ibrc_mem_handle *)mem_handle;
struct ibv_mr *mr = NULL;
assert(sizeof(struct ibrc_mem_handle) <= NVSHMEM_MEM_HANDLE_SIZE);
mr = ftable.reg_mr(device->pd, buf, length,
IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE | IBV_ACCESS_REMOTE_READ
| IBV_ACCESS_REMOTE_ATOMIC);
NULL_ERROR_JMP(mr, status, NVSHMEMX_ERROR_OUT_OF_MEMORY,
out, "mem registration failed \n");
handle->lkey = mr->lkey;
handle->rkey = mr->rkey;
handle->mr = (void *)mr;
handle_info.mr = mr;
handle_info.ptr = buf;
handle_info.size = length;
INFO(NVSHMEM_TRANSPORT, "ibv_reg_mr handle %p handle->mr %x", handle, handle->mr);
#ifdef NVSHMEM_USE_GDRCOPY
if (use_gdrcopy) {
status = gdrcopy_ftable.pin_buffer(gdr_desc, (unsigned long)buf,
length, 0, 0, &handle_info.mh);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "gdrcopy pin_buffer failed \n");
status = gdrcopy_ftable.map(gdr_desc, handle_info.mh,
&handle_info.cpu_ptr_base, length);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "gdrcopy map failed \n");
gdr_info_t info;
status = gdrcopy_ftable.get_info(gdr_desc, handle_info.mh, &info);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "gdrcopy get_info failed \n");
// remember that mappings start on a 64KB boundary, so let's
// calculate the offset from the head of the mapping to the
// beginning of the buffer
uintptr_t off;
off = (uintptr_t)buf - info.va;
handle_info.cpu_ptr = (void *)((uintptr_t)handle_info.cpu_ptr_base + off);
}
#endif
mem_handle_cache.push_back(handle_info);
if(!dummy_local_mem) {
dummy_local_mem = (ibrc_mem_handle_info_t *)malloc(sizeof(ibrc_mem_handle_info_t));
NULL_ERROR_JMP(dummy_local_mem, status, NVSHMEMX_ERROR_OUT_OF_MEMORY,
out, "dummy_local_mem allocation failed\n");
dummy_local_mem->ptr = malloc(sizeof(uint64_t));
NULL_ERROR_JMP(dummy_local_mem->ptr, status,
NVSHMEMX_ERROR_OUT_OF_MEMORY,
out, "dummy_mem allocation failed\n");
dummy_local_mem->mr = ftable.reg_mr(device->pd,
dummy_local_mem->ptr,
sizeof(uint64_t),
IBV_ACCESS_LOCAL_WRITE |
IBV_ACCESS_REMOTE_WRITE | IBV_ACCESS_REMOTE_READ
| IBV_ACCESS_REMOTE_ATOMIC);
NULL_ERROR_JMP(dummy_local_mem->mr, status,
NVSHMEMX_ERROR_OUT_OF_MEMORY,
out, "mem registration failed \n");
}
out:
return status;
}
int nvshmemt_ibrc_release_mem_handle(nvshmem_mem_handle_t mem_handle) {
int status = 0;
struct ibrc_mem_handle *handle = (struct ibrc_mem_handle *)&mem_handle;
INFO(NVSHMEM_TRANSPORT, "ibv_dereg_mr handle %p handle->mr %x", handle, handle->mr);
status = ftable.dereg_mr((struct ibv_mr *)handle->mr);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "ibv_dereg_mr failed \n");
out:
return status;
}
int nvshmemt_ibrc_finalize(nvshmem_transport_t transport) {
int status = 0;
struct nvshmem_transport *t = (struct nvshmem_transport *)transport;
transport_ibrc_state_t *ibrc_state = (transport_ibrc_state_t *)t->state;
while (!mem_handle_cache.empty()) {
ibrc_mem_handle_info_t handle_info = mem_handle_cache.back();
#ifdef NVSHMEM_USE_GDRCOPY
if (use_gdrcopy) {
status = gdrcopy_ftable.unmap(gdr_desc, handle_info.mh, handle_info.cpu_ptr_base,
handle_info.size);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "gdr_unmap failed\n");
status = gdrcopy_ftable.unpin_buffer(gdr_desc, handle_info.mh);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "gdr_unpin failed\n");
status = gdrcopy_ftable.close(gdr_desc);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "gdr_close failed\n");
}
#endif
mem_handle_cache.pop_back();
}
//clear qp map
qp_map.clear();
if (dummy_local_mem) {
status = ftable.dereg_mr(dummy_local_mem->mr);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "ibv_dereg_mr failed \n");
free(dummy_local_mem);
}
#ifdef NVSHMEM_USE_GDRCOPY
if (use_gdrcopy && gdrcopy_handle) {
status = dlclose(gdrcopy_handle);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "dlclose() failed\n");
}
#endif
if(bpool != NULL) {
while (!bpool_free.empty())
bpool_free.pop_back();
free(bpool);
}
status = dlclose(ibv_handle);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "dlclose() failed\n");
status = pthread_mutex_destroy(&ibrc_mutex_send_progress);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "pthread_mutex_destroy failed\n");
status = pthread_mutex_destroy(&ibrc_mutex_recv_progress);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "pthread_mutex_destroy failed\n");
out:
return status;
}
#ifdef NVSHMEM_USE_GDRCOPY
template <typename T>
int perform_gdrcopy_amo (struct ibrc_ep *ep, gdr_mh_t mh, struct ibrc_atomic_op *op,
void *ptr) {
int status = 0;
T old_value, new_value;
status = gdrcopy_ftable.copy_from_mapping(mh, &old_value, ptr, sizeof(T));
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "gdr copy to mapping failed\n");
switch (op->op) {
case NVSHMEMI_AMO_SIGNAL:
case NVSHMEMI_AMO_SET:
case NVSHMEMI_AMO_SWAP:
{
new_value = *((T *)&op->swap_add);
break;
}
case NVSHMEMI_AMO_ADD:
case NVSHMEMI_AMO_FETCH_ADD:
{
new_value = old_value + (*((T *)&op->swap_add));
break;
}
case NVSHMEMI_AMO_OR:
case NVSHMEMI_AMO_FETCH_OR:
{
new_value = old_value | (*((T *)&op->swap_add));
break;
}
case NVSHMEMI_AMO_AND:
case NVSHMEMI_AMO_FETCH_AND:
{
new_value = old_value & (*((T *)&op->swap_add));
break;
}
case NVSHMEMI_AMO_XOR:
case NVSHMEMI_AMO_FETCH_XOR:
{
new_value = old_value ^ (*((T *)&op->swap_add));
break;
}
case NVSHMEMI_AMO_COMPARE_SWAP:
{
new_value = (old_value == *((T *)&op->compare)) ? *((T *)&op->swap_add) : old_value;
break;
}
default:
{
ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "RMA/AMO verb %d not implemented\n", op->op);
}
}
status = gdrcopy_ftable.copy_to_mapping(mh, ptr, (void *)&new_value, sizeof(T));
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "gdr copy to mapping failed\n");
{
transport_ibrc_state_t *ibrc_state = (transport_ibrc_state_t *)ep->ibrc_state;
struct ibrc_device *device = ((struct ibrc_device *)ibrc_state->devices + ep->devid);
struct ibv_send_wr *sr, **bad_sr;
struct ibv_sge *sge;
struct ibrc_request *req;
int op_id;
nvshmemi_amo_t ack;
g_elem_t ret;
//wait for one send request to become avaialble on the ep
int outstanding_count = (ibrc_qp_depth - 1);
while ((ep->head_op_id - ep->tail_op_id) > outstanding_count) {
status = progress_send(ibrc_state);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "progress_send failed, outstanding_count: %d\n", outstanding_count);
//already in processing a recv request
//only poll recv cq
status = poll_recv(ibrc_state);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "poll_recv failed, outstanding_count: %d\n", outstanding_count);
}
op_id = ep->head_op_id & IBRC_REQUEST_QUEUE_MASK; // ep->head_op_id % ibrc_qp_depth
ep->head_op_id++;
sr = &(ep->req + op_id)->sr;
bad_sr = &(ep->req + op_id)->bad_sr;
sge = &(ep->req + op_id)->sge;
memset(sr, 0, sizeof(ibv_send_wr));
if (op->op > NVSHMEMI_AMO_END_OF_NONFETCH) {
ret.data = ret.flag = 0;
*((T *)&ret.data) = old_value;
ret.flag = op->retflag;
sr->next = NULL;
sr->opcode = IBV_WR_RDMA_WRITE_WITH_IMM;
sr->send_flags = IBV_SEND_SIGNALED | IBV_SEND_INLINE;
sr->wr_id = NVSHMEMI_AMO_END_OF_NONFETCH;
sr->num_sge = 1;
sr->sg_list = sge;
sr->imm_data = (uint32_t)NVSHMEMI_AMO_ACK;
sr->wr.rdma.remote_addr = (uint64_t)op->retaddr;
sr->wr.rdma.rkey = op->retrkey;
sge->length = sizeof(g_elem_t);
sge->addr = (uintptr_t)&ret;
sge->lkey = 0;
} else {
ack = NVSHMEMI_AMO_ACK;
sr->next = NULL;
sr->opcode = IBV_WR_SEND;
sr->send_flags = IBV_SEND_SIGNALED | IBV_SEND_INLINE;
sr->wr_id = NVSHMEMI_AMO_ACK;
sr->num_sge = 1;
sr->sg_list = sge;
//dummy send
sge->length = sizeof(nvshmemi_amo_t);
sge->addr = (uintptr_t)&ack;
sge->lkey = 0;
}
status = ibv_post_send(ep->qp, sr, bad_sr);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "ibv_poll_cq failed \n");
}
out:
return status;
}
int poll_recv(transport_ibrc_state_t *ibrc_state) {
int status = 0;
int n_devs = ibrc_state->n_dev_ids;
static int atomic_in_progress = 0;
//poll all CQs available
for (int i=0; i<n_devs; i++) {
struct ibv_wc wc;
int devid = ibrc_state->dev_ids[i];
struct ibrc_device *device = ((struct ibrc_device *)ibrc_state->devices + devid);
if (!device->recv_cq) continue;
int ne = ibv_poll_cq(device->recv_cq, 1, &wc);
if (ne < 0) {
status = ne;
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "ibv_poll_cq failed \n");
} else if (ne) {
uint64_t idx;
struct ibrc_atomic_op *op;
assert(ne == 1);
ibrc_buf_t *buf = (ibrc_buf_t *)wc.wr_id;
if(wc.wc_flags & IBV_WC_WITH_IMM) {
atomics_acked++;
TRACE(NVSHMEM_TRANSPORT, "[%d] atomic acked : %llu \n", getpid(), atomics_acked);
bpool_free.push_back((void *)buf);
} else {
struct ibrc_atomic_op *op = (struct ibrc_atomic_op *)buf->buf;
if (op->op == NVSHMEMI_AMO_ACK) {
atomics_acked++;
TRACE(NVSHMEM_TRANSPORT, "[%d] atomic acked : %llu \n", getpid(), atomics_acked);
bpool_free.push_back((void *)buf);
} else {
buf->qp_num = wc.qp_num;
atomics_received++;
TRACE(NVSHMEM_TRANSPORT, "[%d] atomic received, enqueued : %llu \n", getpid(), atomics_received);
bqueue_toprocess.push_back((void *)buf);
}
}
device->srq_posted--;
}
status = refill_srq(device);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "refill_sqr failed \n");
}
out:
return status;
}
int process_recv(transport_ibrc_state_t *ibrc_state) {
int status = 0;
if (!bqueue_toprocess.empty()) {
ibrc_buf_t *buf = (ibrc_buf_t *)bqueue_toprocess.front();
struct ibrc_ep *ep = (struct ibrc_ep *)qp_map.find((unsigned int)buf->qp_num)->second;
struct ibrc_atomic_op *op = (struct ibrc_atomic_op *)buf->buf;
ibrc_mem_handle_info_t mem_handle_info = get_mem_handle_info((void *)op->addr);
void *ptr = (void *)((uintptr_t)mem_handle_info.cpu_ptr
+ ((uintptr_t)op->addr - (uintptr_t)mem_handle_info.ptr));
switch(op->elembytes) {
case 2:
perform_gdrcopy_amo<uint16_t>(ep, mem_handle_info.mh, op, ptr);
break;
case 4:
perform_gdrcopy_amo<uint32_t>(ep, mem_handle_info.mh, op, ptr);
break;
case 8:
perform_gdrcopy_amo<uint64_t>(ep, mem_handle_info.mh, op, ptr);
break;
default:
ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "invalid element size encountered \n");
}
atomics_processed++;
TRACE(NVSHMEM_TRANSPORT, "[%d] atomic dequeued and processed : %llu \n", getpid(), atomics_processed);
bqueue_toprocess.pop_front();
bpool_free.push_back((void *)buf);
}
out:
return status;
}
int progress_recv(transport_ibrc_state_t *ibrc_state) {
int status = 0;
pthread_mutex_lock (&ibrc_mutex_recv_progress);
status = poll_recv(ibrc_state);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "poll recv failed \n");
status = process_recv(ibrc_state);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "process recv failed \n");
out:
pthread_mutex_unlock (&ibrc_mutex_recv_progress);
return status;
}
#endif
int progress_send(transport_ibrc_state_t *ibrc_state) {
int status = 0;
struct ibrc_ep *ep;
int n_devs = ibrc_state->n_dev_ids;
pthread_mutex_lock (&ibrc_mutex_send_progress);
for (int i=0; i<n_devs; i++) {
struct ibv_wc wc;
int devid = ibrc_state->dev_ids[i];
struct ibrc_device *device = ((struct ibrc_device *)ibrc_state->devices + devid);
if (!device->send_cq) continue;
int ne = ibv_poll_cq(device->send_cq, 1, &wc);
if (ne < 0) {
status = ne;
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "ibv_poll_cq failed \n");
} else if (ne) {
if (wc.status) {
status = wc.status;
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "ibv_poll_cq failed, status: %d\n", wc.status);
}
assert (ne == 1);
if (wc.wr_id == NVSHMEMI_OP_AMO) {
#ifdef NVSHMEM_USE_GDRCOPY
atomics_completed++;
TRACE(NVSHMEM_TRANSPORT, "[%d] atomic completed : %llu \n", getpid(), atomics_completed);
#else
ERROR_EXIT("unexpected atomic op received \n");
#endif
}
struct ibrc_ep *ep = (struct ibrc_ep *)qp_map.find((unsigned int)wc.qp_num)->second;
ep->tail_op_id += ne;
}
}
out:
pthread_mutex_unlock (&ibrc_mutex_send_progress);
return status;
}
int nvshmemt_ibrc_progress(nvshmem_transport_t t) {
int status = 0;
struct nvshmem_transport *transport = (struct nvshmem_transport *)t;
transport_ibrc_state_t *ibrc_state = (transport_ibrc_state_t *)transport->state;
status = progress_send(ibrc_state);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "progress_send failed, \n");
#ifdef NVSHMEM_USE_GDRCOPY
status = progress_recv(ibrc_state);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "progress failed \n");
#endif
out:
return status;
}
int check_poll_avail(struct ibrc_ep *ep, int wait_predicate) {
int status = 0;
int outstanding_count = (ibrc_qp_depth - 1);
if (wait_predicate == WAIT_ALL) outstanding_count = 0;
transport_ibrc_state_t *ibrc_state = (transport_ibrc_state_t *)ep->ibrc_state;
/* poll until space becomes in local send qp and space in receive qp at target for atomics
* assuming connected qp cout is symmetric across all processes,
* connected_qp_count+1 to avoid completely emptying the recv qp at target, leading to perf issues*/
while (((ep->head_op_id - ep->tail_op_id) > outstanding_count)
#ifdef NVSHMEM_USE_GDRCOPY
|| ((atomics_issued - atomics_acked) > (ibrc_srq_depth/(connected_qp_count + 1)))
#endif
) {
status = progress_send(ibrc_state);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "progress_send failed, outstanding_count: %d\n", outstanding_count);
#ifdef NVSHMEM_USE_GDRCOPY
status = progress_recv(ibrc_state);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "progress_recv failed \n");
#endif
}
out:
return status;
}
int nvshmemt_ibrc_rma(nvshmemt_ep_t tep, rma_verb_t verb, rma_memdesc_t remote, rma_memdesc_t local,
rma_bytesdesc_t bytesdesc) {
int status = 0;
struct ibrc_ep *ep = (struct ibrc_ep *)tep;
transport_ibrc_state_t *ibrc_state = (transport_ibrc_state_t *)ep->ibrc_state;
struct ibrc_device *device = ((struct ibrc_device *)ibrc_state->devices + ep->devid);
struct ibv_send_wr *sr, **bad_sr;
struct ibv_sge *sge;
struct ibrc_request *req;
int op_id;
status = check_poll_avail(ep, WAIT_ANY);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "check_poll failed \n");
op_id = ep->head_op_id & IBRC_REQUEST_QUEUE_MASK; // ep->head_op_id % ibrc_qp_depth
sr = &(ep->req + op_id)->sr;
bad_sr = &(ep->req + op_id)->bad_sr;
sge = &(ep->req + op_id)->sge;
memset(sr, 0, sizeof(ibv_send_wr));
sr->next = NULL;
sr->send_flags = IBV_SEND_SIGNALED;
sr->wr_id = NVSHMEMI_OP_PUT;
sr->num_sge = 1;
sr->sg_list = sge;
sr->wr.rdma.remote_addr = (uint64_t)remote.ptr;
sr->wr.rdma.rkey = ((struct ibrc_mem_handle *)&remote.handle)->rkey;
sge->length = bytesdesc.nelems * bytesdesc.elembytes;
sge->addr = (uintptr_t)local.ptr;
sge->lkey = ((struct ibrc_mem_handle *)&local.handle)->lkey;
if (verb.desc == NVSHMEMI_OP_P) {
sr->opcode = IBV_WR_RDMA_WRITE;
sr->send_flags |= IBV_SEND_INLINE;
TRACE(NVSHMEM_TRANSPORT, "[PUT] remote_addr %p addr %p rkey %d lkey %d length %lx",
sr->wr.rdma.remote_addr, sge->addr, sr->wr.rdma.rkey, sge->lkey, sge->length);
} else if (verb.desc == NVSHMEMI_OP_GET || verb.desc == NVSHMEMI_OP_G) {
sr->opcode = IBV_WR_RDMA_READ;
TRACE(NVSHMEM_TRANSPORT, "[GET] remote_addr %p addr %p rkey %d lkey %d length %lx",
sr->wr.rdma.remote_addr, sge->addr, sr->wr.rdma.rkey, sge->lkey, sge->length);
} else if (verb.desc == NVSHMEMI_OP_PUT) {
sr->opcode = IBV_WR_RDMA_WRITE;
TRACE(NVSHMEM_TRANSPORT, "[PUT] remote_addr %p addr %p rkey %d lkey %d length %lx",
sr->wr.rdma.remote_addr, sge->addr, sr->wr.rdma.rkey, sge->lkey, sge->length);
} else {
ERROR_PRINT("RMA/AMO verb not implemented\n");
exit(-1);
}
TRACE(NVSHMEM_TRANSPORT, "[%d] ibrc post_send dest handle %p rkey %x src handle %p lkey %x",
getpid(), remote.handle, sr->wr.rdma.rkey, local.handle, sge->lkey);
status = ibv_post_send(ep->qp, sr, bad_sr);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "ibv_poll_cq failed \n");
ep->head_op_id++;
if (unlikely(!verb.is_nbi && verb.desc != NVSHMEMI_OP_P)) {
check_poll_avail(ep, WAIT_ALL /*1*/);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "check_poll failed \n");
}
out:
return status;
}
int nvshmemt_ibrc_amo(nvshmemt_ep_t tep, void *curetptr, amo_verb_t verb,
amo_memdesc_t remote, amo_bytesdesc_t bytesdesc) {
int status = 0;
struct ibrc_ep *ep = (struct ibrc_ep *)tep;
transport_ibrc_state_t *ibrc_state = (transport_ibrc_state_t *)ep->ibrc_state;
struct ibrc_device *device = ((struct ibrc_device *)ibrc_state->devices + ep->devid);
struct ibv_send_wr *sr, **bad_sr;
struct ibv_sge *sge;
struct ibrc_request *req;
int op_id;
int op_prepared = 0;
struct ibrc_atomic_op op;
status = check_poll_avail(ep, WAIT_ANY);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "check_poll failed \n");
op_id = ep->head_op_id & IBRC_REQUEST_QUEUE_MASK; // ep->head_op_id % ibrc_qp_depth
sr = &(ep->req + op_id)->sr;
bad_sr = &(ep->req + op_id)->bad_sr;
sge = &(ep->req + op_id)->sge;
memset(sr, 0, sizeof(ibv_send_wr));
memset(sge, 0, sizeof(ibv_sge));
sr->num_sge = 1;
sr->sg_list = sge;
sr->wr_id = NVSHMEMI_OP_AMO;
sr->next = NULL;
#ifdef NVSHMEM_USE_GDRCOPY
//if gdrcopy is available, use it for all atomics to guarantee
//atomicity across different ops
if (use_gdrcopy) {
ibrc_mem_handle_info_t mem_handle_info;
//assuming GDRCopy availability is uniform on all nodes
op.op = verb.desc;
op.addr = remote.ptr;
op.retaddr = remote.retptr;
op.retflag = remote.retflag;
op.compare = remote.cmp;
op.swap_add = remote.val;
op.elembytes = bytesdesc.elembytes;
//send rkey info
assert(!mem_handle_cache.empty());
mem_handle_info = mem_handle_cache.back();
op.retrkey = mem_handle_info.mr->rkey;
sr->opcode = IBV_WR_SEND;
sr->send_flags = IBV_SEND_SIGNALED | IBV_SEND_INLINE;
sge->length = sizeof(struct ibrc_atomic_op);
assert(sge->length <= IBRC_BUF_SIZE);
sge->addr = (uintptr_t)&op;
sge->lkey = 0;
atomics_issued++;
TRACE(NVSHMEM_TRANSPORT, "[%d] atomic issued : %llu \n", getpid(), atomics_issued);
goto post_op;
}
#endif
if (use_ib_native_atomics) {
if (verb.desc == NVSHMEMI_AMO_ADD) {
if (bytesdesc.elembytes = 8) {
sr->opcode = IBV_WR_ATOMIC_FETCH_AND_ADD;
sr->send_flags = IBV_SEND_SIGNALED;
sr->wr.atomic.remote_addr = (uint64_t)remote.ptr;
sr->wr.atomic.rkey = ((struct ibrc_mem_handle *)&remote.handle)->rkey;
sr->wr.atomic.compare_add = remote.val;
sge->length = bytesdesc.elembytes;
sge->addr = (uintptr_t)dummy_local_mem->ptr;
sge->lkey = dummy_local_mem->mr->lkey;
goto post_op;
}
} else if (verb.desc == NVSHMEMI_AMO_SIGNAL) {
sr->opcode = IBV_WR_RDMA_WRITE;
sr->send_flags = IBV_SEND_SIGNALED;
sr->send_flags |= IBV_SEND_INLINE;
sr->wr.rdma.remote_addr = (uint64_t)remote.ptr;
sr->wr.rdma.rkey = ((struct ibrc_mem_handle *)&remote.handle)->rkey;
sge->length = bytesdesc.elembytes;
sge->addr = (uintptr_t)&remote.val;
sge->lkey = 0;
goto post_op;
}
}
ERROR_EXIT("RMA/AMO verb %d not implemented\n", verb.desc);
post_op:
status = ibv_post_send(ep->qp, sr, bad_sr);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "ibv_exp_post_send failed \n");
ep->head_op_id++;
out:
return status;
}
int nvshmemt_ibrc_enforce_cst_at_target() {
int status = 0;
ibrc_mem_handle_info_t mem_handle_info;
if (mem_handle_cache.empty()) return status;
//pick the last region that was inserted
mem_handle_info = mem_handle_cache.back();
#ifdef NVSHMEM_USE_GDRCOPY
if (use_gdrcopy) {
int temp;
gdrcopy_ftable.copy_from_mapping(mem_handle_info.mh,
&temp, mem_handle_info.cpu_ptr, sizeof(int));
return status;
}
#endif
struct ibrc_ep *ep = ibrc_cst_ep;
transport_ibrc_state_t *ibrc_state = (transport_ibrc_state_t *)ep->ibrc_state;
struct ibv_send_wr *sr, **bad_sr;
struct ibv_sge *sge;
struct ibrc_request *req;
int op_id;
op_id = ep->head_op_id & IBRC_REQUEST_QUEUE_MASK; // ep->head_op_id % ibrc_qp_depth
sr = &(ep->req + op_id)->sr;
bad_sr = &(ep->req + op_id)->bad_sr;
sge = &(ep->req + op_id)->sge;
sr->next = NULL;
sr->send_flags = IBV_SEND_SIGNALED;
sr->num_sge = 1;
sr->sg_list = sge;
sr->opcode = IBV_WR_RDMA_READ;
sr->wr.rdma.remote_addr = (uint64_t)mem_handle_info.ptr;
sr->wr.rdma.rkey = mem_handle_info.mr->rkey;
sge->length = sizeof(int);
sge->addr = (uintptr_t)mem_handle_info.ptr;
sge->lkey = mem_handle_info.mr->lkey;
status = ibv_post_send(ep->qp, sr, bad_sr);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "ibv_post_send failed \n");
ep->head_op_id++;
status = check_poll_avail(ep, WAIT_ALL);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "check_poll failed \n");
out:
return status;
}
int nvshmemt_ibrc_fence(nvshmemt_ep_t tep) {
int status = 0;
struct ibrc_ep *ep = (struct ibrc_ep *)tep;
out:
return status;
}
int nvshmemt_ibrc_quiet(nvshmemt_ep_t tep) {
int status = 0;
struct ibrc_ep *ep = (struct ibrc_ep *)tep;
static uint64_t quiet_count = 0;
status = check_poll_avail(ep, WAIT_ALL /*1*/);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "check_poll failed \n");
quiet_count++;
#ifdef NVSHMEM_USE_GDRCOPY
while(atomics_acked < atomics_issued) {
status = progress_recv((transport_ibrc_state_t *)ep->ibrc_state);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "progress failed \n");
}
#endif
out:
return status;
}
int nvshmemt_ibrc_ep_create(nvshmemt_ep_t *tep, int devid, nvshmem_transport_t t) {
int status = 0;
struct ibrc_ep *ep;
struct nvshmem_transport *transport = (struct nvshmem_transport *)t;
transport_ibrc_state_t *ibrc_state = (transport_ibrc_state_t *)transport->state;
status = ep_create(&ep, devid, ibrc_state);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "ep_create failed\n");
*tep = ep;
//setup loopback connection on the first device used.
if (!ibrc_cst_ep) {
status = setup_cst_loopback(ibrc_state, devid);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "cst setup failed \n");
}
out:
return status;
}
int nvshmemt_ibrc_ep_get_handle(nvshmemt_ep_handle_t *ep_handle, nvshmemt_ep_t tep) {
int status = 0;
struct ibrc_ep *ep = (struct ibrc_ep *)tep;
transport_ibrc_state_t *ibrc_state = (transport_ibrc_state_t *)ep->ibrc_state;
struct ibrc_device *device = ((struct ibrc_device *)ibrc_state->devices + ep->devid);
struct ibrc_ep_handle *ep_handle_ptr = (struct ibrc_ep_handle *)ep_handle;
assert(sizeof(struct ibrc_ep_handle) <= NVSHMEM_EP_HANDLE_SIZE);
status = ep_get_handle(ep_handle_ptr, ep);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "ep_get_handle failed \n");
out:
return status;
}
int nvshmemt_ibrc_ep_destroy(nvshmemt_ep_t tep) {
int status = 0;
struct ibrc_ep *ep = (struct ibrc_ep *)tep;
status = check_poll_avail(ep, WAIT_ALL /*1*/);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "check_poll failed \n");
// TODO: clean up qp, cq, etc.
out:
return status;
}
int nvshmemt_ibrc_ep_connect(nvshmemt_ep_t tep, nvshmemt_ep_handle_t remote_ep_handle) {
int status = 0;
struct ibrc_ep *ep = (struct ibrc_ep *)tep;
struct ibrc_ep_handle *ep_handle = (struct ibrc_ep_handle *)&remote_ep_handle;
status = ep_connect(ep, ep_handle);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "ep_connect failed \n");
out:
return status;
}
#define LOAD_SYM(handle, symbol, funcptr) \
do { \
void **cast = (void **)&funcptr; \
void *tmp = dlsym(handle, symbol); \
*cast = tmp; \
} while (0)
int nvshmemt_ibrc_init(nvshmem_transport_t *t) {
int status = 0;
struct nvshmem_transport *transport;
transport_ibrc_state_t *ibrc_state;
struct ibv_device **dev_list = NULL;
int num_devices;
struct ibrc_device *device;
char *value = NULL;
std::vector<std::string> nic_names_n_pes;
std::vector<std::string> nic_names;
int exclude_list = 0;
int pes_counted = 0;
struct ibrc_hca_info hca_list[MAX_NUM_HCAS];
struct ibrc_hca_info pe_hca_mapping[MAX_NUM_PES_PER_NODE];
int hca_list_count = 0, pe_hca_map_count = 0, user_selection = 0;
int offset = 0;
ibv_handle = dlopen("libibverbs.so", RTLD_LAZY);
NULL_ERROR_JMP(ibv_handle, status, NVSHMEMX_ERROR_INTERNAL, out, "dlopen() failed\n");
LOAD_SYM(ibv_handle, "ibv_get_device_list", ftable.get_device_list);
LOAD_SYM(ibv_handle, "ibv_get_device_name", ftable.get_device_name);
LOAD_SYM(ibv_handle, "ibv_open_device", ftable.open_device);
LOAD_SYM(ibv_handle, "ibv_close_device", ftable.close_device);
LOAD_SYM(ibv_handle, "ibv_query_port", ftable.query_port);
LOAD_SYM(ibv_handle, "ibv_query_device", ftable.query_device);
LOAD_SYM(ibv_handle, "ibv_alloc_pd", ftable.alloc_pd);
LOAD_SYM(ibv_handle, "ibv_reg_mr", ftable.reg_mr);
LOAD_SYM(ibv_handle, "ibv_dereg_mr", ftable.dereg_mr);
LOAD_SYM(ibv_handle, "ibv_create_cq", ftable.create_cq);
LOAD_SYM(ibv_handle, "ibv_create_qp", ftable.create_qp);
LOAD_SYM(ibv_handle, "ibv_create_srq", ftable.create_srq);
LOAD_SYM(ibv_handle, "ibv_modify_qp", ftable.modify_qp);
if (nvshmemi_options.DISABLE_IB_NATIVE_ATOMICS) {
use_ib_native_atomics = 0;
}
ibrc_srq_depth = nvshmemi_options.SRQ_DEPTH;
ibrc_qp_depth = nvshmemi_options.QP_DEPTH;
#ifdef NVSHMEM_USE_GDRCOPY
use_gdrcopy = 1;
if (nvshmemi_options.DISABLE_GDRCOPY) {
use_gdrcopy = 0;
}
gdrcopy_handle = dlopen("libgdrapi.so", RTLD_LAZY);
if (!gdrcopy_handle) use_gdrcopy = 0;
if (use_gdrcopy) {
LOAD_SYM(gdrcopy_handle, "gdr_runtime_get_version", gdrcopy_ftable.runtime_get_version);
if (!gdrcopy_ftable.runtime_get_version) {
WARN_PRINT("GDRCopy library found by version older than 2.0, skipping use \n");
use_gdrcopy = 0;
goto skip_gdrcopy_dlsym;
}
LOAD_SYM(gdrcopy_handle, "gdr_runtime_get_version", gdrcopy_ftable.driver_get_version);
LOAD_SYM(gdrcopy_handle, "gdr_open", gdrcopy_ftable.open);
LOAD_SYM(gdrcopy_handle, "gdr_close", gdrcopy_ftable.close);
LOAD_SYM(gdrcopy_handle, "gdr_pin_buffer", gdrcopy_ftable.pin_buffer);
LOAD_SYM(gdrcopy_handle, "gdr_unpin_buffer", gdrcopy_ftable.unpin_buffer);
LOAD_SYM(gdrcopy_handle, "gdr_map", gdrcopy_ftable.map);
LOAD_SYM(gdrcopy_handle, "gdr_unmap", gdrcopy_ftable.unmap);
LOAD_SYM(gdrcopy_handle, "gdr_get_info", gdrcopy_ftable.get_info);
LOAD_SYM(gdrcopy_handle, "gdr_copy_from_mapping", gdrcopy_ftable.copy_from_mapping);
LOAD_SYM(gdrcopy_handle, "gdr_copy_to_mapping", gdrcopy_ftable.copy_to_mapping);
gdr_desc = gdrcopy_ftable.open();
if(!gdr_desc) {
use_gdrcopy = 0;
WARN_PRINT("GDRCopy open call failed, falling back to not using GDRCopy \n");
}
}
skip_gdrcopy_dlsym:
#endif
transport = (struct nvshmem_transport *)malloc(sizeof(struct nvshmem_transport));
memset(transport, 0, sizeof(struct nvshmem_transport));
transport->is_successfully_initialized = false; /* set it to true after everything has been successfully initialized */
ibrc_state = (transport_ibrc_state_t *)malloc(sizeof(transport_ibrc_state_t));
NULL_ERROR_JMP(ibrc_state, status, NVSHMEMX_ERROR_OUT_OF_MEMORY, out,
"p2p state allocation failed \n");
dev_list = ftable.get_device_list(&num_devices);
NULL_ERROR_JMP(dev_list, status, NVSHMEMX_ERROR_INTERNAL, out, "get_device_list failed \n");
ibrc_state->devices = calloc(MAX_NUM_HCAS, sizeof(struct ibrc_device));
NULL_ERROR_JMP(ibrc_state->devices, status, NVSHMEMX_ERROR_OUT_OF_MEMORY, out,
"get_device_list failed \n");
ibrc_state->dev_ids = (int *)malloc(MAX_NUM_PES_PER_NODE * sizeof(int));
NULL_ERROR_JMP(ibrc_state->dev_ids, status, NVSHMEMX_ERROR_OUT_OF_MEMORY, out,
"malloc failed \n");
ibrc_state->port_ids = (int *)malloc(MAX_NUM_PES_PER_NODE * sizeof(int));
NULL_ERROR_JMP(ibrc_state->port_ids, status, NVSHMEMX_ERROR_OUT_OF_MEMORY, out,
"malloc failed \n");
status = pthread_mutex_init(&ibrc_mutex_send_progress, NULL);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "pthread_mutex_init failed \n");
status = pthread_mutex_init(&ibrc_mutex_recv_progress, NULL);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "pthread_mutex_init failed \n");
if (nvshmemi_options.HCA_LIST_provided) {
user_selection = 1;
exclude_list = (nvshmemi_options.HCA_LIST[0] == '^');
hca_list_count = parse_hca_list(nvshmemi_options.HCA_LIST, hca_list, MAX_NUM_HCAS);
}
if (nvshmemi_options.HCA_PE_MAPPING_provided) {
if (hca_list_count) {
WARN_PRINT(
"Found conflicting parameters NVSHMEM_HCA_LIST and NVSHMEM_HCA_PE_MAPPING, ignoring "
"NVSHMEM_HCA_PE_MAPPING \n");
} else {
user_selection = 1;
pe_hca_map_count = parse_hca_list(nvshmemi_options.HCA_PE_MAPPING,
pe_hca_mapping, MAX_NUM_PES_PER_NODE);
}
}
INFO(NVSHMEM_INIT, "Begin - Enumerating IB devices in the system ([<dev_id, device_name, num_ports>]) - ");
for (int i = 0; i < num_devices; i++) {
device = (struct ibrc_device *)ibrc_state->devices + i;
device->dev = dev_list[i];
device->context = ftable.open_device(device->dev);
if (!device->context){
INFO(NVSHMEM_INIT, "open_device failed for IB device at index %d \n", i);
continue;
}
const char *name = ftable.get_device_name(device->dev);
NULL_ERROR_JMP(name, status, NVSHMEMX_ERROR_INTERNAL, out, "ibv_get_device_name failed \n");
status = ftable.query_device(device->context, &device->device_attr);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "ibv_query_device failed \n");
MAX_RD_ATOMIC = (device->device_attr).max_qp_rd_atom;
INFO(NVSHMEM_INIT, "Enumerated IB devices in the system - device id=%d (of %d), name=%s, num_ports=%d", i, num_devices, name, device->device_attr.phys_port_cnt);
int device_used = 0;
for (int p = 1; p <= device->device_attr.phys_port_cnt; p++) {
int allowed_device = 1;
int replicate_count = 1;
if (hca_list_count) {
// filter out based on user hca list
allowed_device = exclude_list;
for (int j = 0; j < hca_list_count; j++) {
if (!strcmp(hca_list[j].name, name)) {
if (hca_list[j].port == -1 || hca_list[j].port == p) {
hca_list[j].found = 1;
allowed_device = !exclude_list;
}
}
}
} else if (pe_hca_map_count) {
// filter devices based on user hca-pe mapping
allowed_device = 0;
for (int j = 0; j < pe_hca_map_count; j++) {
if (!strcmp(pe_hca_mapping[j].name, name)) {
if (pe_hca_mapping[j].port == -1 || pe_hca_mapping[j].port == p) {
allowed_device = 1;
pe_hca_mapping[j].found = 1;
replicate_count = pe_hca_mapping[j].count;
}
}
}
}
if (!allowed_device) {
continue;
} else {
status = ftable.query_port(device->context, p, &device->port_attr[p - 1]);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "ibv_port_query failed \n");
if ((device->port_attr[p - 1].state != IBV_PORT_ACTIVE) ||
(device->port_attr[p - 1].link_layer != IBV_LINK_LAYER_INFINIBAND)) {
if (user_selection) {
WARN_PRINT(
"found inactive port or port with non-IB link layer protocol, "
"skipping...\n");
}
continue;
}
device->pd = ftable.alloc_pd(device->context);
NULL_ERROR_JMP(device->pd, status, NVSHMEMX_ERROR_INTERNAL, out,
"ibv_alloc_pd failed \n");
for (int k = 0; k < replicate_count; k++) {
ibrc_state->dev_ids[offset] = i;
ibrc_state->port_ids[offset] = p;
offset++;
}
device_used = 1;
}
}
if (!device_used) {
status = ftable.close_device(device->context);
NZ_ERROR_JMP(status, NVSHMEMX_ERROR_INTERNAL, out, "ibv_port_query failed \n");
}
}
INFO(NVSHMEM_INIT, "End - Enumerating IB devices in the system");
ibrc_state->n_dev_ids = offset;
INFO(NVSHMEM_INIT, "Begin - Ordered list of devices for assignment (after processing user provdied env vars (if any)) - ");
for (int i = 0; i < ibrc_state->n_dev_ids; i++) {
INFO(NVSHMEM_INIT, "Ordered list of devices for assignment - idx=%d (of %d), device id=%d, port_num=%d", \
i, ibrc_state->n_dev_ids, ibrc_state->dev_ids[i], ibrc_state->port_ids[i]);
}
INFO(NVSHMEM_INIT, "End - Ordered list of devices for assignment (after processing user provdied env vars (if any))");
if (!ibrc_state->n_dev_ids) {
INFO(NVSHMEM_INIT, "no active IB device found, exiting");
status = NVSHMEMX_ERROR_INTERNAL;
goto out;
}
// print devices that were not found
if (hca_list_count) {
for (int j = 0; j < hca_list_count; j++) {
if (hca_list[j].found != 1) {
WARN_PRINT("cound not find user specified HCA name: %s port: %d, skipping\n",
hca_list[j].name, hca_list[j].port);
}
}
} else if (pe_hca_map_count) {
// filter devices based on user hca-pe mapping
for (int j = 0; j < pe_hca_map_count; j++) {
if (pe_hca_mapping[j].found != 1) {
WARN_PRINT("cound not find user specified HCA name: %s port: %d, skipping\n",
pe_hca_mapping[j].name, pe_hca_mapping[j].port);
}
}
}
//allocate buffer pool
bpool_size = ibrc_srq_depth;
bpool = (ibrc_buf_t *)calloc(bpool_size, sizeof(ibrc_buf_t));
NULL_ERROR_JMP(bpool, status, NVSHMEMX_ERROR_OUT_OF_MEMORY, out, "buf poll allocation failed \n");
for (int i=0; i<bpool_size; i++) {
bpool_free.push_back((void *)(bpool + i));
}
transport->host_ops.get_device_count = nvshmemt_ibrc_get_device_count;
transport->host_ops.get_pci_path = nvshmemt_ibrc_get_pci_path;
transport->host_ops.can_reach_peer = nvshmemt_ibrc_can_reach_peer;
transport->host_ops.ep_create = nvshmemt_ibrc_ep_create;
transport->host_ops.ep_get_handle = nvshmemt_ibrc_ep_get_handle;
transport->host_ops.ep_connect = nvshmemt_ibrc_ep_connect;
transport->host_ops.ep_destroy = nvshmemt_ibrc_ep_destroy;
transport->host_ops.get_mem_handle = nvshmemt_ibrc_get_mem_handle;
transport->host_ops.release_mem_handle = nvshmemt_ibrc_release_mem_handle;
transport->host_ops.rma = nvshmemt_ibrc_rma;
transport->host_ops.amo = nvshmemt_ibrc_amo;
transport->host_ops.fence = nvshmemt_ibrc_fence;
transport->host_ops.quiet = nvshmemt_ibrc_quiet;
transport->host_ops.finalize = nvshmemt_ibrc_finalize;
transport->host_ops.show_info = nvshmemt_ibrc_show_info;
transport->host_ops.progress = nvshmemt_ibrc_progress;
transport->host_ops.enforce_cst = nvshmemt_ibrc_enforce_cst_at_target;
#ifndef NVSHMEM_PPC64LE
if (!use_gdrcopy)
#endif
transport->host_ops.enforce_cst_at_target = nvshmemt_ibrc_enforce_cst_at_target;
transport->attr = NVSHMEM_TRANSPORT_ATTR_CONNECTED;
transport->state = (void *)ibrc_state;
transport->is_successfully_initialized = true;
*t = transport;
out:
return status;
}
| 35.64486 | 169 | 0.650725 | [
"vector",
"model"
] |
7ff40347533142772b2e5d0b3ec99f4a7709964a | 14,166 | cpp | C++ | src/algorithm/sequential/cis_sequential_algorithm.cpp | GraphProcessor/LocalityBasedGraphAlgo | de6e48498eb43a106312f14149a3060501b8a49c | [
"MIT"
] | null | null | null | src/algorithm/sequential/cis_sequential_algorithm.cpp | GraphProcessor/LocalityBasedGraphAlgo | de6e48498eb43a106312f14149a3060501b8a49c | [
"MIT"
] | null | null | null | src/algorithm/sequential/cis_sequential_algorithm.cpp | GraphProcessor/LocalityBasedGraphAlgo | de6e48498eb43a106312f14149a3060501b8a49c | [
"MIT"
] | 1 | 2021-01-06T14:03:59.000Z | 2021-01-06T14:03:59.000Z | //
// Created by cheyulin on 12/20/16.
//
#include "cis_sequential_algorithm.h"
namespace yche {
Cis::Cis(unique_ptr<Cis::Graph> graph_ptr, double lambda) : lambda_(lambda), graph_ptr_(std::move(graph_ptr)) {
for (auto vp = vertices(*graph_ptr_); vp.first != vp.second; ++vp.first) { vertices_.emplace_back(*vp.first); }
}
double Cis::CalDensity(int size, double w_in, double w_out, double lambda) {
if (size < 1) {
return numeric_limits<double>::min();
}
double partA = ((1 - lambda) * (w_in / (w_in + w_out)));
double partB = (lambda * ((2 * w_in) / (size * (size - 1))));
if (size == 1)
partB = lambda;
return partA + partB;
}
double Cis::CalDensity(const Community &community) const {
return CalDensity(static_cast<int>(community.member_indices_.size()),
community.w_in_, community.w_out_, lambda_);
}
double Cis::CalDensity(const Community &community, const Entity &member, MutationType mutation_type) const {
if (mutation_type == MutationType::add_neighbor) {
return CalDensity(static_cast<int>(community.member_indices_.size() + 1),
community.w_in_ + member.w_in_, community.w_out_ + member.w_out_, lambda_);
}
return CalDensity(static_cast<int>(community.member_indices_.size() - 1),
community.w_in_ - member.w_in_, community.w_out_ - member.w_out_, lambda_);
}
void Cis::InitializeSeeds(const EntityIdxSet &seed, Community &community,
EntityDict &member_dict, EntityDict &neighbor_dict,
property_map<Graph, vertex_index_t>::type &vertex_index_map,
property_map<Graph, edge_weight_t>::type &edge_weight_map) const {
auto neighbor_indices = EntityIdxSet();
for (auto &seed_vertex_index :seed) {
community.member_indices_.emplace(seed_vertex_index);
auto member = Entity(seed_vertex_index);
auto seed_vertex = vertices_[seed_vertex_index];
for (auto vp = adjacent_vertices(seed_vertex, *graph_ptr_); vp.first != vp.second; ++vp.first) {
auto adjacent_vertex_index = static_cast<int>(vertex_index_map[*vp.first]);
auto edge_weight = edge_weight_map[edge(seed_vertex, vertices_[adjacent_vertex_index],
*graph_ptr_).first];
if (seed.find(adjacent_vertex_index) != seed.end()) {
member.w_in_ += edge_weight;
community.w_in_ += edge_weight;
} else {
member.w_out_ += edge_weight;
community.w_out_ += edge_weight;
neighbor_indices.emplace(adjacent_vertex_index);
}
}
member_dict.emplace(member.entity_index_, member);
}
for (auto &neighbor_vertex_index :neighbor_indices) {
auto neighbor = Entity(neighbor_vertex_index);
Vertex neighbor_vertex = vertices_[neighbor_vertex_index];
for (auto vp = adjacent_vertices(neighbor_vertex, *graph_ptr_); vp.first != vp.second; ++vp.first) {
auto adjacent_vertex_index = static_cast<int>(vertex_index_map[*vp.first]);
auto edge_weight = edge_weight_map[edge(neighbor_vertex, vertices_[adjacent_vertex_index],
*graph_ptr_).first];
if (seed.find(adjacent_vertex_index) != seed.end()) {
neighbor.w_in_ += edge_weight;
} else {
neighbor.w_out_ += edge_weight;
}
}
neighbor_dict.emplace(neighbor.entity_index_, neighbor);
}
}
void Cis::UpdateForAddNeighbor(const Cis::Vertex &mutate_vertex, Community &community,
EntityDict &member_dict, EntityDict &neighbor_dict,
property_map<Graph, vertex_index_t>::type &vertex_index_map,
property_map<Graph, edge_weight_t>::type &edge_weight_map) const {
//Update Member and Neighbor List
for (auto vp = adjacent_vertices(mutate_vertex, *graph_ptr_); vp.first != vp.second; ++vp.first) {
auto check_neighbor_vertex = *vp.first;
auto check_neighbor_vertex_index = static_cast<int>(vertex_index_map[check_neighbor_vertex]);
auto check_neighbor = Entity(check_neighbor_vertex_index);
auto edge_weight = edge_weight_map[edge(mutate_vertex, check_neighbor_vertex, *graph_ptr_).first];
auto iter = member_dict.find(check_neighbor.entity_index_);
if (iter != member_dict.end() ||
(iter = neighbor_dict.find(check_neighbor.entity_index_)) != neighbor_dict.end()) {
//Update Info In Members and Neighbors
iter->second.w_in_ += edge_weight;
iter->second.w_out_ -= edge_weight;
} else {
//Add New Neighbor
auto member = Entity(check_neighbor_vertex_index);
for (auto vp_inner = adjacent_vertices(check_neighbor_vertex, *graph_ptr_);
vp_inner.first != vp_inner.second; ++vp_inner.first) {
auto neighbor_neighbor_vertex_index = static_cast<int>(vertex_index_map[*vp_inner.first]);
edge_weight = edge_weight_map[edge(check_neighbor_vertex,
vertices_[neighbor_neighbor_vertex_index], *graph_ptr_).first];
if (community.member_indices_.find(neighbor_neighbor_vertex_index) !=
community.member_indices_.end()) {
member.w_in_ += edge_weight;
} else {
member.w_out_ += edge_weight;
}
}
neighbor_dict.emplace(member.entity_index_, member);
}
}
}
void Cis::UpdateForRemoveMember(const Cis::Vertex &mutate_vertex, Community &community,
EntityDict &member_dict, EntityDict &neighbor_dict,
property_map<Graph, vertex_index_t>::type &vertex_index_map,
property_map<Graph, edge_weight_t>::type &edge_weight_map) const {
//Update Member and Neighbor List
for (auto vp = adjacent_vertices(mutate_vertex, *graph_ptr_); vp.first != vp.second; ++vp.first) {
auto check_neighbor_vertex = *vp.first;
auto check_neighbor_vertex_index = static_cast<int>(vertex_index_map[check_neighbor_vertex]);
auto check_neighbor_ptr = Entity(check_neighbor_vertex_index);
auto edge_weight = edge_weight_map[edge(mutate_vertex, check_neighbor_vertex, *graph_ptr_).first];
auto iter = member_dict.find(check_neighbor_ptr.entity_index_);
if (iter != member_dict.end() ||
(iter = neighbor_dict.find(check_neighbor_ptr.entity_index_)) != neighbor_dict.end()) {
//Update Info In Members and Neighbors
iter->second.w_in_ -= edge_weight;
iter->second.w_out_ += edge_weight;
}
}
}
Community Cis::FindConnectedComponent(EntityIdxSet &member_set, EntityIdxSet &mark_set, int first_mem_idx,
property_map<Graph, vertex_index_t>::type &vertex_index_map,
property_map<Graph, edge_weight_t>::type &edge_weight_map) const {
auto community = Community();
auto frontier = queue<int>();
frontier.emplace(first_mem_idx);
mark_set.emplace(first_mem_idx);
while (!frontier.empty()) {
auto expand_vertex_index = frontier.front();
auto expand_vertex = vertices_[expand_vertex_index];
community.member_indices_.emplace(expand_vertex_index);
for (auto vp = adjacent_vertices(vertices_[expand_vertex_index], *graph_ptr_);
vp.first != vp.second; ++vp.first) {
auto neighbor_vertex = *vp.first;
auto adjacency_vertex_index = static_cast<int>(vertex_index_map[neighbor_vertex]);
auto edge_flag_pair = boost::edge(expand_vertex, neighbor_vertex, *graph_ptr_);
auto &my_edge = edge_flag_pair.first;
auto iter = member_set.find(adjacency_vertex_index);
if (mark_set.find(adjacency_vertex_index) == mark_set.end() && iter != member_set.end()) {
community.w_in_ += edge_weight_map[my_edge];
frontier.emplace(adjacency_vertex_index);
mark_set.emplace(adjacency_vertex_index);
} else {
community.w_out_ = edge_weight_map[my_edge];
}
}
member_set.erase(expand_vertex_index);
frontier.pop();
}
return community;
}
Community Cis::SplitAndChoose(EntityIdxSet &member_set) const {
auto community_vec = vector<Community>();
auto mark_set = std::unordered_set<int>();
auto vertex_index_map = boost::get(vertex_index, *graph_ptr_);
auto edge_weight_map = boost::get(edge_weight, *graph_ptr_);
while (!member_set.empty()) {
auto first_mem_idx = *member_set.begin();
community_vec.emplace_back(
FindConnectedComponent(member_set, mark_set, first_mem_idx, vertex_index_map, edge_weight_map));
}
sort(community_vec.begin(), community_vec.end(),
[this](auto &left_comm, auto &right_comm) {
double left_density = this->CalDensity(left_comm);
double right_density = this->CalDensity(right_comm);
if (left_density != right_density) {
return left_density > right_density;
}
return (left_comm.member_indices_).size() > (right_comm.member_indices_).size();
});
return community_vec[0];
}
EntityIdxVec Cis::ExpandSeed(EntityIdxSet &entity_idx_set) const {
auto community = Community();
auto member_dict = EntityDict();
auto neighbor_dict = EntityDict();
auto vertex_index_map = boost::get(vertex_index, *graph_ptr_);
auto edge_weight_map = boost::get(edge_weight, *graph_ptr_);
InitializeSeeds(entity_idx_set, community, member_dict, neighbor_dict, vertex_index_map, edge_weight_map);
auto degree_cmp_obj = [this](auto &left_member, auto &right_member) {
return degree(this->vertices_[left_member.entity_index_], *this->graph_ptr_) <
degree(this->vertices_[right_member.entity_index_], *this->graph_ptr_);
};
for (auto is_change = true; is_change;) {
is_change = false;
MutateStates(MutationType::add_neighbor, community, member_dict, neighbor_dict,
degree_cmp_obj, is_change, vertex_index_map, edge_weight_map);
MutateStates(MutationType::remove_member, community, neighbor_dict, member_dict,
degree_cmp_obj, is_change, vertex_index_map, edge_weight_map);
community = SplitAndChoose(community.member_indices_);
}
//For Later Merge Usage
auto member_vec = EntityIdxVec();
member_vec.reserve(community.member_indices_.size());
for (auto entity_index:community.member_indices_) { member_vec.emplace_back(entity_index); }
sort(member_vec.begin(), member_vec.end());
return member_vec;
}
double Cis::GetIntersectRatio(const EntityIdxVec &left_community, const EntityIdxVec &right_community) {
auto intersect_set = vector<int>(left_community.size() + right_community.size());
auto iter_end = set_intersection(left_community.begin(), left_community.end(),
right_community.begin(), right_community.end(), intersect_set.begin());
auto intersect_set_size = iter_end - intersect_set.begin();
auto rate = static_cast<double>(intersect_set_size) / min(left_community.size(), right_community.size());
return rate;
}
EntityIdxVec Cis::GetUnion(const EntityIdxVec &left_community, const EntityIdxVec &right_community) {
auto union_set = vector<int>(left_community.size() + right_community.size());
auto iter_end = set_union(left_community.begin(), left_community.end(),
right_community.begin(), right_community.end(), union_set.begin());
union_set.resize(iter_end - union_set.begin());
return union_set;
}
void Cis::MergeCommToGlobal(EntityIdxVec &result_community) {
if (overlap_community_vec_.empty()) {
overlap_community_vec_.emplace_back(std::move(result_community));
} else {
auto is_insert = true;
for (auto &community:overlap_community_vec_) {
if (GetIntersectRatio(community, result_community) > 1 - DOUBLE_ACCURACY) {
community = GetUnion(community, result_community);
is_insert = false;
break;
}
}
if (is_insert) { overlap_community_vec_.emplace_back(std::move(result_community)); }
}
}
Cis::CommunityVec Cis::ExecuteCis() {
auto vertex_index_map = boost::get(vertex_index, *graph_ptr_);
for (auto vp = vertices(*graph_ptr_); vp.first != vp.second; ++vp.first) {
auto vertex = *vp.first;
auto partial_comm_members = EntityIdxSet();
partial_comm_members.emplace(vertex_index_map[vertex]);
auto result_community = ExpandSeed(partial_comm_members);
MergeCommToGlobal(result_community);
}
return overlap_community_vec_;
}
}
| 50.592857 | 119 | 0.605605 | [
"vector"
] |
7ff9b04acce81479989571e5fcb1cc592cc47777 | 2,129 | cpp | C++ | services/safwk/src/system_ability_connection_callback_stub.cpp | openharmony-gitee-mirror/distributedschedule_safwk | 1de684cf8b9bd56e1302f3f9e67068c18639ac05 | [
"Apache-2.0"
] | null | null | null | services/safwk/src/system_ability_connection_callback_stub.cpp | openharmony-gitee-mirror/distributedschedule_safwk | 1de684cf8b9bd56e1302f3f9e67068c18639ac05 | [
"Apache-2.0"
] | null | null | null | services/safwk/src/system_ability_connection_callback_stub.cpp | openharmony-gitee-mirror/distributedschedule_safwk | 1de684cf8b9bd56e1302f3f9e67068c18639ac05 | [
"Apache-2.0"
] | 1 | 2021-09-13T11:18:08.000Z | 2021-09-13T11:18:08.000Z | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 "system_ability_connection_callback_stub.h"
#include "errors.h"
#include "ipc_skeleton.h"
#include "ipc_types.h"
#include "safwk_log.h"
namespace OHOS {
namespace {
const std::string TAG = "SystemAbilityConnectionCallbackStub";
const std::u16string SA_CONNECTION_CALLBACK_INTERFACE_TOKEN = u"ohos.distributedschedule.saconnectAccessToken";
}
int32_t SystemAbilityConnectionCallbackStub::OnRemoteRequest(uint32_t code,
MessageParcel& data, MessageParcel& reply, MessageOption& option)
{
HILOGI(TAG, "code:%{public}d, flags:%{public}d", code, option.GetFlags());
if (data.ReadInterfaceToken() != SA_CONNECTION_CALLBACK_INTERFACE_TOKEN) {
return ERR_PERMISSION_DENIED;
}
switch (code) {
case ON_CONNECTED_SYSTEM_ABILITY: {
auto object = data.ReadRemoteObject();
if (object == nullptr) {
HILOGW(TAG, "ReadRemoteObject failed!");
return ERR_NULL_OBJECT;
}
OnConnectedSystemAbility(object);
return ERR_OK;
}
case ON_DISCONNECTED_SYSTEM_ABILITY: {
int32_t systemAbilityId = data.ReadInt32();
if (systemAbilityId <= 0) {
HILOGW(TAG, "read saId failed!");
return ERR_NULL_OBJECT;
}
OnDisConnectedSystemAbility(systemAbilityId);
return ERR_OK;
}
default:
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
}
} // namespace OHOS
| 32.753846 | 111 | 0.674025 | [
"object"
] |
7ffbd0c24dd87dfee452b5d85437c05c64f34cfd | 2,724 | cpp | C++ | owGame/Renderer/RenderPass_WMOPortalDebug.cpp | Chaos192/OpenWow | 1d91a51fafeedadc67122a3e9372ec4637a48434 | [
"Apache-2.0"
] | 30 | 2017-09-02T20:25:47.000Z | 2021-12-31T10:12:07.000Z | owGame/Renderer/RenderPass_WMOPortalDebug.cpp | Chaos192/OpenWow | 1d91a51fafeedadc67122a3e9372ec4637a48434 | [
"Apache-2.0"
] | null | null | null | owGame/Renderer/RenderPass_WMOPortalDebug.cpp | Chaos192/OpenWow | 1d91a51fafeedadc67122a3e9372ec4637a48434 | [
"Apache-2.0"
] | 23 | 2018-02-04T17:18:33.000Z | 2022-03-22T09:45:36.000Z | #include "stdafx.h"
#ifdef USE_WMO_MODELS
// General
#include "RenderPass_WMOPortalDebug.h"
// Additional
#include "WMO/WMO_Base_Instance.h"
#include "WMO/WMO_Group_Instance.h"
#include "WMO/WMO_Part_Material.h"
CRenderPass_WMOPortalDebug::CRenderPass_WMOPortalDebug(IScene& Scene)
: Base3DPass(Scene)
{
SetPassName("WMOPortalDebug");
}
CRenderPass_WMOPortalDebug::~CRenderPass_WMOPortalDebug()
{}
//
// IRenderPassPipelined
//
std::shared_ptr<IRenderPassPipelined> CRenderPass_WMOPortalDebug::ConfigurePipeline(std::shared_ptr<IRenderTarget> RenderTarget)
{
__super::ConfigurePipeline(RenderTarget);
m_MaterialDebug = MakeShared(MaterialDebug, GetRenderDevice());
std::shared_ptr<IShader> vertexShader = GetRenderDevice().GetObjectsFactory().LoadShader(EShaderType::VertexShader, "3D/Debug.hlsl", "VS_main");
vertexShader->LoadInputLayoutFromReflector();
std::shared_ptr<IShader> pixelShader = GetRenderDevice().GetObjectsFactory().LoadShader(EShaderType::PixelShader, "3D/Debug.hlsl", "PS_main");
// PIPELINES
GetPipeline().GetDepthStencilState()->SetDepthMode(disableDepthWrites);
GetPipeline().SetRenderTarget(RenderTarget);
GetPipeline().SetShader(vertexShader);
GetPipeline().SetShader(pixelShader);
return shared_from_this();
}
//
// IVisitor
//
EVisitResult CRenderPass_WMOPortalDebug::Visit(const std::shared_ptr<ISceneNode>& SceneNode)
{
if (std::dynamic_pointer_cast<CWMO_Group_Instance>(SceneNode))
{
if (auto portalRoom = std::dynamic_pointer_cast<IPortalRoom>(SceneNode))
{
for (const auto& portal : portalRoom->GetPortals())
{
#ifdef USE_WMO_PORTALS_CULLING
if (auto portalCast = std::dynamic_pointer_cast<CWMOPortalInstance>(portal))
{
auto pointsXYZ = portalCast->GetVertices();
pointsXYZ.push_back(pointsXYZ[0]);
if (pointsXYZ.size() < 2)
return EVisitResult::AllowVisitChilds;
BindPerObjectData(PerObject());
if (portalCast->IsPositive(GetRenderEventArgs().CameraForCulling->GetPosition()))
m_MaterialDebug->SetDiffuseColor(ColorRGBA(0.0f, 1.0f, 0.0f, 1.0f));
else
m_MaterialDebug->SetDiffuseColor(ColorRGBA(1.0f, 0.0f, 0.0f, 1.0f));
m_WaypointGeometry = GetRenderDevice().GetPrimitivesFactory().CreateLines(pointsXYZ);
m_MaterialDebug->Bind(GetPipeline().GetPixelShaderPtr());
m_WaypointGeometry->Render(GetPipeline().GetVertexShaderPtr());
m_MaterialDebug->Unbind(GetPipeline().GetPixelShaderPtr());
}
#endif
}
}
}
return EVisitResult::AllowVisitChilds;
}
EVisitResult CRenderPass_WMOPortalDebug::Visit(const std::shared_ptr<IGeometry>& Geometry, const std::shared_ptr<IMaterial>& Material, SGeometryDrawArgs GeometryDrawArgs)
{
return EVisitResult::Block;
}
#endif | 28.673684 | 170 | 0.764317 | [
"geometry",
"render",
"3d"
] |
3d0e45c42b8215461b90310b8c20a42a0516e032 | 5,385 | cpp | C++ | src/worker/deprecated/io.cpp | chemspacelab/clockwork | 0956d8d29417a974809166857de9a978d7fac677 | [
"MIT"
] | null | null | null | src/worker/deprecated/io.cpp | chemspacelab/clockwork | 0956d8d29417a974809166857de9a978d7fac677 | [
"MIT"
] | 21 | 2019-01-04T10:55:39.000Z | 2019-09-23T11:02:59.000Z | src/worker/deprecated/io.cpp | chemspacelab/clockwork | 0956d8d29417a974809166857de9a978d7fac677 | [
"MIT"
] | 1 | 2019-02-23T15:15:00.000Z | 2019-02-23T15:15:00.000Z | #include <iostream>
#include <vector>
#include <map>
//#define DEBUG
class Archive {
public:
std::vector<unsigned int> molecule_ids;
std::map<unsigned int, unsigned int> number_of_atoms;
std::map<unsigned int, unsigned int*> element_numbers;
std::map<unsigned int, double*> coordinates;
std::map<unsigned int, unsigned int> number_of_bonds;
std::map<unsigned int, unsigned int*> bonds;
std::map<unsigned int, unsigned int*> bond_orders;
std::map<unsigned int, unsigned int> number_of_dihedrals;
std::map<unsigned int, unsigned int*> dihedrals;
int read_archive(const char * filename);
};
int Archive::read_archive(const char * filename) {
std::ifstream fh;
fh.open(filename, std::ios::in | std::ios::binary);
if (!fh.is_open()) {
std::cout << "Unable to open file " << filename << std::endl;
return 1;
}
char * buffer1 = new char[1];
char * buffer4 = new char[4];
char * buffer8 = new char[8];
unsigned int atomcount, elementid, bondcount, dihedralcount;
unsigned int molecule_id;
while (fh.read(buffer4, 4) && !fh.eof()) {
// read molecule id
molecule_id = *(unsigned int*)buffer4;
#ifdef DEBUG
std::cout << "Reading molecule " << molecule_id << std::endl;
#endif
this->molecule_ids.push_back(molecule_id);
// read number of atoms
fh.read(buffer1, 1);
atomcount = *(unsigned int*)buffer1;
#ifdef DEBUG
std::cout << " > has " << atomcount << " atoms" << std::endl;
#endif
number_of_atoms.insert(std::pair<unsigned int, unsigned int>(molecule_id, atomcount));
// read element numbers
unsigned int * numbers = new unsigned int[atomcount];
#ifdef DEBUG
std::cout << " > atoms have these atomic numbers:" << std::endl << " >> ";
#endif
for (unsigned int atom = 0; atom < atomcount; atom++) {
fh.read(buffer1, 1);
elementid = *(unsigned int*)buffer1;
#ifdef DEBUG
std::cout << elementid << ", ";
#endif
numbers[atom] = elementid;
}
#ifdef DEBUG
std::cout << std::endl;
#endif
element_numbers.insert(std::pair<unsigned int, unsigned int*>(molecule_id, numbers));
// read nuclear coordinates
double * mcoordinates = new double[atomcount * 3];
mcoordinates[0] = 0;
mcoordinates[1] = 0;
mcoordinates[2] = 0;
#ifdef DEBUG
std::cout << " > atoms have these coordinates: " << std::endl;
#endif
for (unsigned int atom = 1; atom < atomcount; atom++) {
for (unsigned int dimension = 0; dimension < 3; dimension++) {
fh.read(buffer8, 8);
mcoordinates[atom * 3 + dimension] = *(double*)buffer8;
}
#ifdef DEBUG
std::cout << " > atom " << atom << ": " << mcoordinates[atom * 3 + 0] << ", " << mcoordinates[atom * 3 + 1]<< ", " << mcoordinates[atom * 3 + 2] << std::endl;
#endif
}
coordinates.insert(std::pair<unsigned int, double*>(molecule_id, mcoordinates));
// read number of bonds
fh.read(buffer1, 1);
bondcount = *(unsigned int*)buffer1;
#ifdef DEBUG
std::cout << " > has " << bondcount << " bonds" << std::endl;
#endif
number_of_bonds.insert(std::pair<unsigned int, unsigned int>(molecule_id, bondcount));
// read bond indices
unsigned int * bondindices = new unsigned int[bondcount * 2];
#ifdef DEBUG
std::cout << " > bonds have these pairs: " << std::endl << " >> ";
#endif
for (unsigned int bond = 0; bond < bondcount; bond++) {
fh.read(buffer1, 1);
bondindices[bond * 2] = *(unsigned int*)buffer1;
fh.read(buffer1, 1);
bondindices[bond * 2 + 1] = *(unsigned int*)buffer1;
#ifdef DEBUG
std::cout << bondindices[bond * 2] << "-" << bondindices[bond * 2 + 1] << ", ";
#endif
}
#ifdef DEBUG
std::cout << std::endl;
#endif
bonds.insert(std::pair<unsigned int, unsigned int*>(molecule_id, bondindices));
// read bond orders
unsigned int * bondorders = new unsigned int[bondcount];
#ifdef DEBUG
std::cout << " > bonds have these orders: " << std::endl << " >> ";
#endif
for (unsigned int bond = 0; bond < bondcount; bond++) {
fh.read(buffer1, 1);
bondorders[bond] = *(unsigned int*)buffer1;
#ifdef DEBUG
std::cout << bondorders[bond] << ", ";
#endif
}
#ifdef DEBUG
std::cout << std::endl;
#endif
bond_orders.insert(std::pair<unsigned int, unsigned int*>(molecule_id, bondorders));
// read number of dihedrals
fh.read(buffer1, 1);
dihedralcount = *(unsigned int*)buffer1;
#ifdef DEBUG
std::cout << " > has " << dihedralcount << " dihedrals" << std::endl;
#endif
number_of_dihedrals.insert(std::pair<unsigned int, unsigned int>(molecule_id, dihedralcount));
// read dihedral indices
unsigned int * dihedralindices = new unsigned int[dihedralcount * 4];
#ifdef DEBUG
std::cout << " > dihedrals have these tuples: " << std::endl << " >> ";
#endif
for (unsigned int dihedral = 0; dihedral < dihedralcount; dihedral++) {
for (unsigned int pos = 0; pos < 4; pos++) {
fh.read(buffer1, 1);
dihedralindices[dihedral * 4 + pos] = *(unsigned int*)buffer1;
}
#ifdef DEBUG
std::cout << dihedralindices[dihedral * 4 + 0] << "-" << dihedralindices[dihedral * 4 + 1] << "-" << dihedralindices[dihedral * 4 + 2] << "-" << dihedralindices[dihedral * 4 + 3] << ", ";
#endif
}
#ifdef DEBUG
std::cout << std::endl;
#endif
dihedrals.insert(std::pair<unsigned int, unsigned int*>(molecule_id, dihedralindices));
}
delete[] buffer1;
delete[] buffer4;
delete[] buffer8;
fh.close();
return 0;
} | 32.053571 | 191 | 0.641226 | [
"vector"
] |
3d12df542fa92921c7cbbfed1b857c0892ff7631 | 6,309 | cc | C++ | src/asp/Core/AffineEpipolar.cc | lucasz93/StereoPipeline | 49a2e91b4502253cdd1a5583bf850d1a42eb79b0 | [
"Apache-2.0"
] | null | null | null | src/asp/Core/AffineEpipolar.cc | lucasz93/StereoPipeline | 49a2e91b4502253cdd1a5583bf850d1a42eb79b0 | [
"Apache-2.0"
] | null | null | null | src/asp/Core/AffineEpipolar.cc | lucasz93/StereoPipeline | 49a2e91b4502253cdd1a5583bf850d1a42eb79b0 | [
"Apache-2.0"
] | null | null | null | // __BEGIN_LICENSE__
// Copyright (c) 2009-2013, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NGT platform is licensed under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance with the
// License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// __END_LICENSE__
#include <asp/Core/AffineEpipolar.h>
#include <vw/Math/Vector.h>
#include <vw/Math/Matrix.h>
#include <vw/Math/LinearAlgebra.h>
#include <vw/InterestPoint/InterestData.h>
#include <vector>
using namespace vw;
namespace asp {
// Solves for Affine Fundamental Matrix as per instructions in
// Multiple View Geometry.
// TODO(oalexan1): Filter outliers here with RANSAC!
Matrix<double>
linear_affine_fundamental_matrix( std::vector<ip::InterestPoint> const& ip1,
std::vector<ip::InterestPoint> const& ip2 ) {
// (i) Compute the centroid of X and delta X
Matrix<double> delta_x(ip1.size(),4);
Vector4 mean_x;
for ( size_t i = 0; i < ip1.size(); i++ ) {
delta_x(i,0) = ip2[i].x;
delta_x(i,1) = ip2[i].y;
delta_x(i,2) = ip1[i].x;
delta_x(i,3) = ip1[i].y;
mean_x += select_row(delta_x,i) / double(ip1.size());
}
for ( size_t i = 0; i < ip1.size(); i++ ) {
select_row(delta_x,i) -= mean_x;
}
Matrix<double> U, VT;
Vector<double> S;
svd(transpose(delta_x),U,S,VT);
Vector<double> N = select_col( U, 3 );
double e = -transpose(N)*mean_x;
Matrix<double> f(3,3);
f(0,2) = N(0);
f(1,2) = N(1);
f(2,2) = e;
f(2,0) = N(2);
f(2,1) = N(3);
return f;
}
void solve_y_scaling( std::vector<ip::InterestPoint> const& ip1,
std::vector<ip::InterestPoint> const& ip2,
Matrix<double>& affine_left,
Matrix<double>& affine_right ) {
Matrix<double> a( ip1.size(), 2 );
Vector<double> b( ip1.size() );
for ( size_t i = 0; i < ip1.size(); i++ ) {
select_row(a,i) = subvector(affine_right*Vector3(ip2[i].x,ip2[i].y,1),1,2);
b[i] = (affine_left*Vector3(ip1[i].x,ip1[i].y,1))(1);
}
Vector<double> scaling = least_squares( a, b );
submatrix(affine_right,0,0,2,2) *= scaling[0];
affine_right(1,2) = scaling[1];
}
void solve_x_shear( std::vector<ip::InterestPoint> const& ip1,
std::vector<ip::InterestPoint> const& ip2,
Matrix<double>& affine_left,
Matrix<double>& affine_right ) {
Matrix<double> a( ip1.size(), 3 );
Vector<double> b( ip1.size() );
for ( size_t i = 0; i < ip1.size(); i++ ) {
select_row(a,i) = affine_right * Vector3(ip2[i].x,ip2[i].y,1);
b[i] = (affine_left*Vector3(ip1[i].x,ip1[i].y,1))(0);
}
Vector<double> shear = least_squares( a, b );
Matrix<double> interm = math::identity_matrix<3>();
interm(0,1) = -shear[1] / 2.0;
affine_left = interm * affine_left;
interm = math::identity_matrix<3>();
interm(0,0) = shear[0];
interm(0,1) = shear[1] / 2.0;
interm(0,2) = shear[2];
affine_right = interm * affine_right;
}
// Main function that other parts of ASP should use
Vector2i
affine_epipolar_rectification( Vector2i const& left_size,
Vector2i const& right_size,
std::vector<ip::InterestPoint> const& ip1,
std::vector<ip::InterestPoint> const& ip2,
Matrix<double>& left_matrix,
Matrix<double>& right_matrix ) {
// Create affine fundamental matrix
Matrix<double> fund = linear_affine_fundamental_matrix( ip1, ip2 );
// Solve for rotation matrices
double Hl = sqrt( fund(2,0)*fund(2,0) + fund(2,1)*fund(2,1) );
double Hr = sqrt( fund(0,2)*fund(0,2) + fund(1,2)*fund(1,2) );
Vector2 epipole(-fund(2,1),fund(2,0)), epipole_prime(-fund(1,2),fund(0,2));
if ( epipole.x() < 0 )
epipole = -epipole;
if ( epipole_prime.x() < 0 )
epipole_prime = -epipole_prime;
epipole.y() = -epipole.y();
epipole_prime.y() = -epipole_prime.y();
left_matrix = math::identity_matrix<3>();
right_matrix = math::identity_matrix<3>();
left_matrix(0,0) = epipole[0]/Hl;
left_matrix(0,1) = -epipole[1]/Hl;
left_matrix(1,0) = epipole[1]/Hl;
left_matrix(1,1) = epipole[0]/Hl;
right_matrix(0,0) = epipole_prime[0]/Hr;
right_matrix(0,1) = -epipole_prime[1]/Hr;
right_matrix(1,0) = epipole_prime[1]/Hr;
right_matrix(1,1) = epipole_prime[0]/Hr;
// Solve for ideal scaling and translation
solve_y_scaling( ip1, ip2, left_matrix, right_matrix );
// Solve for ideal shear, scale, and translation of X axis
solve_x_shear( ip1, ip2, left_matrix, right_matrix );
// Work out the ideal render size.
BBox2i output_bbox, right_bbox;
output_bbox.grow( subvector(left_matrix*Vector3(0,0,1),0,2) );
output_bbox.grow( subvector(left_matrix*Vector3(left_size.x(),0,1),0,2) );
output_bbox.grow( subvector(left_matrix*Vector3(left_size.x(),left_size.y(),1),0,2) );
output_bbox.grow( subvector(left_matrix*Vector3(0,left_size.y(),1),0,2) );
right_bbox.grow( subvector(right_matrix*Vector3(0,0,1),0,2) );
right_bbox.grow( subvector(right_matrix*Vector3(right_size.x(),0,1),0,2) );
right_bbox.grow( subvector(right_matrix*Vector3(right_size.x(),right_size.y(),1),0,2) );
right_bbox.grow( subvector(right_matrix*Vector3(0,right_size.y(),1),0,2) );
output_bbox.crop( right_bbox );
left_matrix(0,2) -= output_bbox.min().x();
right_matrix(0,2) -= output_bbox.min().x();
left_matrix(1,2) -= output_bbox.min().y();
right_matrix(1,2) -= output_bbox.min().y();
return Vector2i( output_bbox.width(), output_bbox.height() );
}
}
| 38.705521 | 92 | 0.619433 | [
"geometry",
"render",
"vector"
] |
3d162f310d4cdd8e18181c72c50f3433619faf5a | 7,709 | cpp | C++ | OpenGL-Rendering-Engine/Exalted/src/Core/Renderer/EditorCamera.cpp | Kney-Delach/OpenGL-Rendering | 5a144ab06ba767028ee27eec5d3f92db7986bdaa | [
"MIT"
] | null | null | null | OpenGL-Rendering-Engine/Exalted/src/Core/Renderer/EditorCamera.cpp | Kney-Delach/OpenGL-Rendering | 5a144ab06ba767028ee27eec5d3f92db7986bdaa | [
"MIT"
] | null | null | null | OpenGL-Rendering-Engine/Exalted/src/Core/Renderer/EditorCamera.cpp | Kney-Delach/OpenGL-Rendering | 5a144ab06ba767028ee27eec5d3f92db7986bdaa | [
"MIT"
] | 1 | 2020-03-10T17:39:56.000Z | 2020-03-10T17:39:56.000Z | /***************************************************************************
* Filename : EditorCamera.cpp
* Name : Ori Lazar
* Date : 05/11/2019
* Description : Contains an implementation for an FPS camera used in the
* editor.
.---.
.'_:___".
|__ --==|
[ ] :[|
|__| I=[|
/ / ____|
|-/.____.'
/___\ /___\
***************************************************************************/
#include "expch.h"
#include "EditorCamera.h"
#include "Core/SceneGraph/Scene.h"
#include "Core/Input.h"
#include "Core/KeyCodes.h"
#include "Core/MouseButtonCodes.h"
#include "Core/Events/ApplicationEvent.h"
#include "Core/Events/MouseEvent.h"
#include "imgui.h"
#include "imgui_internal.h"
#include "UniformBuffer.h"
#include "glm/gtc/type_ptr.hpp"
namespace Exalted
{
void EditorCamera::UpdateCamera(Timestep deltaTime)
{
if (Input::IsKeyPressed(EX_KEY_W))
ProcessKeyboardEvent(CameraMovement::FORWARD, deltaTime);
if (Input::IsKeyPressed(EX_KEY_A))
ProcessKeyboardEvent(CameraMovement::LEFT, deltaTime);
if (Input::IsKeyPressed(EX_KEY_S))
ProcessKeyboardEvent(CameraMovement::BACKWARD, deltaTime);
if (Input::IsKeyPressed(EX_KEY_D))
ProcessKeyboardEvent(CameraMovement::RIGHT, deltaTime);
if (Input::IsKeyPressed(EX_KEY_Q))
ProcessKeyboardEvent(CameraMovement::UP, deltaTime);
if (Input::IsKeyPressed(EX_KEY_E))
ProcessKeyboardEvent(CameraMovement::DOWN, deltaTime);
UpdateUBO();
}
void EditorCamera::UpdateTrack(Timestep deltaTime)
{
EX_CORE_ASSERT(m_CurrentTrack, " Attempting to update the camera track with no currently set track! Set a track first!", true);
if(m_CurrentTrack->Update(deltaTime, m_Position, m_Yaw, m_Pitch) == -1)
{
Scene::s_IsCameraFree = true;
ResetMovementVariables();
}
UpdateCameraVectors();
RecalculateViewMatrix();
UpdateUBO(); // update ubo with camera data
}
void EditorCamera::SetTrack(const int index)
{
EX_CORE_ASSERT(index < m_CameraTracks.size(), " Attempting to set camera track to invalid index! {0}", 0, true);
m_CurrentTrack = m_CameraTracks[index];
m_CurrentTrack->PrepareTrack();
m_FOV = 45.f; // note, this manually assigns the field of view of the camera to 45 degrees for every track, set this configurable eventually...
RecalculateProjectionMatrix();
}
// this was used for debugging camera positions
void EditorCamera::OnImGuiRender()
{
ImGui::Begin("Camera Transform");
ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true);
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.6f);
ImGui::InputFloat3("Position", (float*)& m_Position);
ImGui::InputFloat("Yaw", &m_Yaw);
ImGui::InputFloat("Pitch", &m_Pitch);
ImGui::PopItemFlag();
ImGui::PopStyleVar();
ImGui::InputFloat("Movement Speed", &m_MovementSpeed, 0.01f, 10.f);
ImGui::InputFloat("Mouse Sensitivity", &m_MouseSensitivity, 0.01f, 10.f);
ImGui::End();
}
void EditorCamera::UpdateCameraVectors()
{
glm::vec3 front;
front.x = cos(glm::radians(m_Pitch)) * cos(glm::radians(m_Yaw));
front.y = sin(glm::radians(m_Pitch));
front.z = cos(glm::radians(m_Pitch)) * sin(glm::radians(m_Yaw));
m_Front = glm::normalize(front);
m_Right = glm::normalize(glm::cross(m_Front, m_WorldUp));
m_Up = glm::normalize(glm::cross(m_Right, m_Front));
}
void EditorCamera::RecalculateViewMatrix()
{
m_ViewMatrix = glm::lookAt(m_Position, m_Position + m_Front, m_Up);;
RecalculateViewProjectionMatrix();
}
void EditorCamera::OnEvent(Exalted::Event& event)
{
if ((event.GetEventType() == Exalted::EventType::MouseButtonPressed) && !m_MouseMoving)
{
auto& e = dynamic_cast<Exalted::MouseButtonPressedEvent&>(event);
if (e.GetMouseButton() == EX_MOUSE_BUTTON_2)
{
m_FirstMouseMovement = true;
m_ProcessingMouseMovement = true;
m_MouseMoving = true;
}
}
if (event.GetEventType() == Exalted::EventType::MouseButtonReleased)
{
auto& e = dynamic_cast<Exalted::MouseButtonReleasedEvent&>(event);
if (e.GetMouseButton() == EX_MOUSE_BUTTON_2)
{
m_ProcessingMouseMovement = false;
m_MouseMoving = false;
}
}
if (event.GetEventType() == Exalted::EventType::MouseScrolled)
{
auto& e = dynamic_cast<Exalted::MouseScrolledEvent&>(event);
ProcessMouseScrollEvent(e.GetYOffset());
}
if (m_ProcessingMouseMovement && (event.GetEventType() == Exalted::EventType::MouseMoved))
{
auto& e = dynamic_cast<Exalted::MouseMovedEvent&>(event);
if (m_FirstMouseMovement)
{
m_LastMouseX = e.GetX();
m_LastMouseY = e.GetY();
m_FirstMouseMovement = false;
}
float xOffset = e.GetX() - m_LastMouseX;
float yOffset = m_LastMouseY - e.GetY();
m_LastMouseX = e.GetX();
m_LastMouseY = e.GetY();
ProcessRotationEvent(xOffset, yOffset);
}
}
void EditorCamera::UpdateUBO(Ref<UniformBuffer>& ubo) const //todo: exists only for backwards compatibility with previous example scenes
{
ubo->Bind();
Bytes offset = 0;
Bytes size = sizeof(glm::mat4);
Bytes sizeofVec4 = sizeof(glm::vec4);
ubo->SetBufferSubData(offset, size, glm::value_ptr(GetViewMatrix()));
offset += sizeof(glm::mat4);
ubo->SetBufferSubData(offset, size, glm::value_ptr(glm::mat4(glm::mat3(GetViewMatrix()))));
offset += sizeof(glm::mat4);
ubo->SetBufferSubData(offset, size, glm::value_ptr(GetProjectionMatrix()));
offset += sizeof(glm::mat4);
ubo->SetBufferSubData(offset, size, glm::value_ptr(GetViewProjectionMatrix()));
offset += sizeof(glm::mat4);
ubo->SetBufferSubData(offset, sizeofVec4, glm::value_ptr(GetPosition()));
offset += sizeof(glm::vec4);
ubo->Unbind();
}
void EditorCamera::UpdateUBO() const
{
m_CameraUniformBuffer->Bind();
Bytes offset = 0;
Bytes size = sizeof(glm::mat4);
Bytes sizeofVec4 = sizeof(glm::vec4);
m_CameraUniformBuffer->SetBufferSubData(offset, size, glm::value_ptr(GetViewMatrix()));
offset += sizeof(glm::mat4);
m_CameraUniformBuffer->SetBufferSubData(offset, size, glm::value_ptr(glm::mat4(glm::mat3(GetViewMatrix()))));
offset += sizeof(glm::mat4);
m_CameraUniformBuffer->SetBufferSubData(offset, size, glm::value_ptr(GetProjectionMatrix()));
offset += sizeof(glm::mat4);
m_CameraUniformBuffer->SetBufferSubData(offset, size, glm::value_ptr(GetViewProjectionMatrix()));
offset += sizeof(glm::mat4);
m_CameraUniformBuffer->SetBufferSubData(offset, sizeofVec4, glm::value_ptr(GetPosition()));
offset += sizeof(glm::vec4);
m_CameraUniformBuffer->Unbind();
}
void EditorCamera::ProcessRotationEvent(float xOffset, float yOffset)
{
xOffset *= m_MouseSensitivity;
yOffset *= m_MouseSensitivity;
m_Yaw = glm::mod(m_Yaw + xOffset, 360.0f);
m_Pitch += yOffset;
if (m_Pitch > 89.f)
m_Pitch = 89.f;
else if (m_Pitch < -89.f)
m_Pitch = -89.f;
UpdateCameraVectors();
RecalculateViewMatrix();
}
void EditorCamera::ProcessMouseScrollEvent(float yOffset)
{
if (m_FOV >= 1.0f && m_FOV <= 90.0f)
m_FOV -= yOffset;
if (m_FOV <= 1.0f)
m_FOV = 1.0f;
if (m_FOV >= 90.0f)
m_FOV = 90.0f;
RecalculateProjectionMatrix();
}
void EditorCamera::ProcessKeyboardEvent(CameraMovement direction, const float deltaTime)
{
const float velocity = m_MovementSpeed * deltaTime;
if (direction == CameraMovement::FORWARD)
m_Position += m_Front * velocity;
if (direction == CameraMovement::BACKWARD)
m_Position -= m_Front * velocity;
if (direction == CameraMovement::LEFT)
m_Position -= m_Right * velocity;
if (direction == CameraMovement::RIGHT)
m_Position += m_Right * velocity;
if (direction == CameraMovement::UP)
m_Position += m_WorldUp * velocity;
if (direction == CameraMovement::DOWN)
m_Position -= m_WorldUp * velocity;
RecalculateViewMatrix();
}
} | 33.372294 | 145 | 0.694253 | [
"transform"
] |
3d1a73d09ae2d1cbf75290fd5c99d4b25837f108 | 6,191 | cpp | C++ | Drivers/UnitTests/EnergyUnitTest.cpp | gustavo-castillo-bautista/Mercury | eeb402ccec8e487652229d4595c46ec84f6aefbb | [
"BSD-3-Clause"
] | null | null | null | Drivers/UnitTests/EnergyUnitTest.cpp | gustavo-castillo-bautista/Mercury | eeb402ccec8e487652229d4595c46ec84f6aefbb | [
"BSD-3-Clause"
] | null | null | null | Drivers/UnitTests/EnergyUnitTest.cpp | gustavo-castillo-bautista/Mercury | eeb402ccec8e487652229d4595c46ec84f6aefbb | [
"BSD-3-Clause"
] | null | null | null | //Copyright (c) 2013-2020, The MercuryDPM Developers Team. All rights reserved.
//For the list of developers, see <http://www.MercuryDPM.org/Team>.
//
//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 MercuryDPM nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//DISCLAIMED. IN NO EVENT SHALL THE MERCURYDPM DEVELOPERS TEAM 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 "Species/LinearViscoelasticIrreversibleAdhesiveSpecies.h"
#include "Species/LinearViscoelasticReversibleAdhesiveSpecies.h"
#include "DPMBase.h"
#include "Logger.h"
#include "Species/LinearPlasticViscoelasticReversibleAdhesiveSpecies.h"
/*!
* A simple test where two adhesive particles collide; two adhesive force models are tested here,
* LinearViscoelasticIrreversibleAdhesiveInteraction and LinearViscoelasticReversibleAdhesiveInteraction.
* The focus of this test is to see if energy is conserved during the collision; for the elastic force model,
* no energy should be lost, whereas the irreversible force model should loose a fixed amount of energy.
*/
class EnergyUnitTest : public DPMBase
{
public:
void setupInitialConditions() override {
setFileType(FileType::NO_FILE);
//to see the behaviour of elastic and kinetic energy, comment the line above and plot in gnuplot
//p 'ReversibleAdhesiveEnergyUnitTest.ene' u 1:3 w lp, 'ReversibleAdhesiveEnergyUnitTest.ene' u 1:5 w lp, 'ReversibleAdhesiveEnergyUnitTest.ene' u 1:($3+$5) w lp
//p 'IrreversibleAdhesiveEnergyUnitTest.ene' u 1:3 w lp, 'IrreversibleAdhesiveEnergyUnitTest.ene' u 1:5 w lp, 'IrreversibleAdhesiveEnergyUnitTest.ene' u 1:($3+$5) w lp
setDimension(3);
setGravity({0.0, 0.0, 0.0});
setXMax(1.0);
setYMax(0.5);
setZMax(0.5);
setXMin(-1.0);
setYMin(-0.5);
setZMin(-0.5);
particleHandler.clear();
SphericalParticle P;
P.setSpecies(speciesHandler.getObject(0));
P.setRadius(0.5);
P.setPosition({-0.551, 0.0, 0.0});
P.setVelocity({0.7, 0.0, 0.0});
particleHandler.copyAndAddObject(P);
P.setPosition({0.551, 0.0, 0.0});
P.setVelocity({-0.7, 0.0, 0.0});
particleHandler.copyAndAddObject(P);
}
};
int main(int argc UNUSED, char *argv[] UNUSED)
{
std::cout << "Test if the LinearViscoelasticReversibleAdhesiveInteraction conserves energy" << std::endl;
EnergyUnitTest energyUnitTest;
energyUnitTest.setName("ReversibleAdhesiveEnergyUnitTest");
LinearViscoelasticReversibleAdhesiveSpecies species1;
species1.setDensity(6.0 / constants::pi);
species1.setStiffness(500);
species1.setAdhesionStiffness(100);
species1.setAdhesionForceMax(10);
//std::cout << "maxVelocity=" << species1.getMaximumVelocity(0.5, 1.0) << std::endl;
energyUnitTest.setTimeStep(0.002 * species1.getCollisionTime(1.0));
//std::cout << "timeStep=" << energyUnitTest.getTimeStep() << std::endl;
energyUnitTest.setSaveCount(3);
energyUnitTest.setTimeMax(0.4);
energyUnitTest.speciesHandler.copyAndAddObject(species1);
energyUnitTest.solve();
Mdouble lostEnergy = mathsFunc::square(0.7)-energyUnitTest.getElasticEnergy()-energyUnitTest.getKineticEnergy();
if (!mathsFunc::isEqual(lostEnergy, 0.0, 1e-6))
{
logger(ERROR, "energy loss is %, but should be %", lostEnergy, 0.0);
}
std::cout << "Test if the LinearViscoelasticIrreversibleAdhesiveInteraction looses the right amount of energy" << std::endl;
EnergyUnitTest energyUnitTest2;
energyUnitTest2.setName("IrreversibleAdhesiveEnergyUnitTest");
LinearViscoelasticIrreversibleAdhesiveSpecies species2;
species2.setDensity(6.0 / constants::pi);
species2.setStiffness(500);
species2.setAdhesionStiffness(100);
species2.setAdhesionForceMax(10);
std::cout << "maxVelocity=" << species2.getMaximumVelocity(0.5, 1.0) << std::endl;
//this test is 10 times more accurate than the previous one, as the error is so much bigger.
energyUnitTest2.setTimeStep(0.0002 * species2.getCollisionTime(1.0));
std::cout << "timeStep=" << energyUnitTest2.getTimeStep() << std::endl;
energyUnitTest2.setSaveCount(3);
energyUnitTest2.setTimeMax(0.2);
energyUnitTest2.speciesHandler.copyAndAddObject(species2);
energyUnitTest2.solve();
lostEnergy = mathsFunc::square(0.7)-energyUnitTest2.getElasticEnergy()-energyUnitTest2.getKineticEnergy();
/*!
* \todo TW The inaccuracy of the calculation is much worse for the
* irreversible force model, as there is a jump in force at zero overlap;
* we should correct for that in the time stepping algorithm
* (i.e. find out what the mean force was over the duration of the time step,
* not using a left Riemann sum.
*/
if (!mathsFunc::isEqual(lostEnergy, 0.5, 1e-4))
{
logger(ERROR, "energy loss is %, but should be %", lostEnergy, 0.5);
}
return 0;
}
| 49.528 | 175 | 0.7267 | [
"model"
] |
3d213bc7ee739fbf0d2a5ed9f3dedd1b4da44f7d | 8,507 | cpp | C++ | lib/spatial/xregFitPlane.cpp | rg2/xreg | c06440d7995f8a441420e311bb7b6524452843d3 | [
"MIT"
] | 30 | 2020-09-29T18:36:13.000Z | 2022-03-28T09:25:13.000Z | lib/spatial/xregFitPlane.cpp | gaocong13/Orthopedic-Robot-Navigation | bf36f7de116c1c99b86c9ba50f111c3796336af0 | [
"MIT"
] | 3 | 2020-10-09T01:21:27.000Z | 2020-12-10T15:39:44.000Z | lib/spatial/xregFitPlane.cpp | rg2/xreg | c06440d7995f8a441420e311bb7b6524452843d3 | [
"MIT"
] | 8 | 2021-05-25T05:14:48.000Z | 2022-02-26T12:29:50.000Z | /*
* MIT License
*
* Copyright (c) 2020 Robert Grupp
*
* 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 "xregFitPlane.h"
#include "xregExceptionUtils.h"
#include "xregSampleUtils.h"
#include "xregAssert.h"
#include "xregCMAESInterface.h"
std::tuple<xreg::Plane3,xreg::Pt3>
xreg::FitPlaneToPoints(const Pt3List& pts)
{
const size_type num_pts = pts.size();
Pt3 mean_pt = Pt3::Zero();
for (size_type i = 0; i < num_pts; ++i)
{
mean_pt += pts[i];
}
mean_pt /= num_pts;
MatMxN data_mat(3,num_pts);
for (size_type i = 0; i < num_pts; ++i)
{
data_mat.col(i) = pts[i] - mean_pt;
}
Eigen::JacobiSVD<MatMxN> svd(data_mat, Eigen::ComputeFullU);
Plane3 plane;
plane.normal = svd.matrixU().col(2);
plane.scalar = plane.normal.dot(mean_pt);
return std::make_tuple(plane, mean_pt);
}
xreg::Plane3 xreg::FitPlaneToPoints(const Pt3& x1, const Pt3& x2, const Pt3& x3,
const bool checked)
{
Pt3 n = (x2 - x1).cross(x3 - x1);
const CoordScalar n_norm = n.norm();
if (checked && (n_norm < 1.0e-8))
{
xregThrow("Points are colinear!");
}
n /= n_norm;
return Plane3{n, n.dot(x1)};
}
std::tuple<xreg::Plane3,xreg::Pt3,xreg::Pt3List>
xreg::FitPlaneToPointsRANSAC(const Pt3List& pts,
const double consensus_ratio_min_thresh,
const size_type max_num_its)
{
const size_type num_pts = pts.size();
xregASSERT(num_pts > 4);
const size_type consensus_num_pts_min = std::lround(num_pts * consensus_ratio_min_thresh);
std::mt19937 rng_eng;
SeedRNGEngWithRandDev(&rng_eng);
std::uniform_int_distribution<size_type> uni_dist(0, num_pts - 1);
auto sample_inlier_inds = [&rng_eng,&uni_dist]()
{
std::array<size_type,3> inds;
inds[0] = uni_dist(rng_eng);
inds[1] = uni_dist(rng_eng);
while (inds[1] == inds[0])
{
inds[1] = uni_dist(rng_eng);
}
inds[2] = uni_dist(rng_eng);
while ((inds[2] == inds[0]) || (inds[2] == inds[1]))
{
inds[2] = uni_dist(rng_eng);
}
return inds;
};
std::vector<CoordScalar> all_dists(num_pts);
std::vector<size_type> poss_inlier_inds;
poss_inlier_inds.reserve(num_pts);
Pt3List cur_model_pts;
cur_model_pts.reserve(num_pts);
Pt3List best_model_pts;
best_model_pts.reserve(num_pts);
std::array<size_type,3> cur_inliers;
auto is_not_inlier = [&cur_inliers] (const size_type i)
{
return (i != cur_inliers[0]) && (i != cur_inliers[1]) && (i != cur_inliers[2]);
};
Plane3 best_plane = { Pt3::Zero(), 0 };
CoordScalar best_avg_dist = std::numeric_limits<CoordScalar>::max();
Pt3 best_pt_on_plane;
bool at_least_one_consensus_found = false;
bool should_stop = false;
size_type iter = 0;
while (!should_stop)
{
cur_inliers = sample_inlier_inds();
auto cur_plane = FitPlaneToPoints(pts[cur_inliers[0]], pts[cur_inliers[1]],
pts[cur_inliers[2]]);
if (cur_plane.normal.norm() > 1.0e-8)
{
// compute the standard deviation of non-inlier distances to the current plane
// we'll ignore points more than some number of standard deviations away from
// the mean
CoordScalar sum = 0;
for (size_type i = 0; i < num_pts; ++i)
{
if (is_not_inlier(i))
{
all_dists[i] = DistToPlane(pts[i], cur_plane);
sum += all_dists[i];
}
}
const CoordScalar mean = sum / (num_pts - 3);
sum = 0;
for (size_type i = 0; i < num_pts; ++i)
{
if (is_not_inlier(i))
{
const CoordScalar a = all_dists[i] - mean;
sum += a * a;
}
}
const CoordScalar std_dev = std::sqrt(sum / (num_pts - 4));
const CoordScalar poss_inlier_thresh = mean + (1 * std_dev);
// threshold to get the possible inliers
poss_inlier_inds.clear();
for (size_type i = 0; i < num_pts; ++i)
{
if (is_not_inlier(i) && (all_dists[i] < poss_inlier_thresh))
{
poss_inlier_inds.push_back(i);
}
}
// see if we have a sufficient number of possible inliers
if (poss_inlier_inds.size() >= consensus_num_pts_min)
{
at_least_one_consensus_found = true;
// we have a consensus, now fit a plane using the consensus set union
// the current inliers
poss_inlier_inds.push_back(cur_inliers[0]);
poss_inlier_inds.push_back(cur_inliers[1]);
poss_inlier_inds.push_back(cur_inliers[2]);
cur_model_pts.clear();
for (const auto& i : poss_inlier_inds)
{
cur_model_pts.push_back(pts[i]);
}
Pt3 pt_on_plane;
std::tie(cur_plane,pt_on_plane) = FitPlaneToPoints(cur_model_pts);
// compute the average error of this new model
sum = 0;
for (const auto& p : cur_model_pts)
{
sum += DistToPlane(p, cur_plane);
}
sum /= cur_model_pts.size();
if (sum < best_avg_dist)
{
// the current model is a better bit to inliers/consensus than
// the previous best model, update the best
best_plane = cur_plane;
best_pt_on_plane = pt_on_plane;
best_avg_dist = sum;
best_model_pts = cur_model_pts;
if (sum < 1.0e-3)
{
should_stop = true;
}
}
}
}
++iter;
if (!should_stop && (iter == max_num_its))
{
should_stop = true;
}
}
return std::make_tuple(best_plane, best_pt_on_plane, best_model_pts);
}
namespace
{
using namespace xreg;
class PlaneFitMAPCMAES : public CmaesOptimizer
{
public:
PlaneFitMAPCMAES(const Pt3List& pts, const Plane3& p0)
: CmaesOptimizer(3,50), pts_(pts), p0_(p0)
{
this->obj_fn_exec_type_ = CmaesOptimizer::kPARALLEL_OBJ_FN_EVAL;
set_sigma(Pt3({0.3,0.3,2}));
}
protected:
double obj_fn(const Pt& plane_params) override
{
const auto p = PlaneSphericalToNormalScalar(plane_params[0], plane_params[1], plane_params[2]);
double f = 0;
for (const auto& x : pts_)
{
const double tmp = p.normal.dot(x) - p.scalar;
f += tmp * tmp;
}
f /= (2 * pts_.size());
f += -p0_.normal.dot(p.normal) * 2;
return f;
}
private:
const Pt3List& pts_;
const Plane3 p0_;
};
} // un-named
std::tuple<xreg::Plane3,xreg::Pt3>
xreg::FitPlaneToPointsMAP(const Pt3List& pts, const Plane3& p0)
{
const size_type num_pts = pts.size();
xregASSERT(num_pts > 4);
constexpr bool use_mle_as_init = true;
Plane3 init_plane;
Pt3 pt_on_plane;
std::tie(init_plane,pt_on_plane) = FitPlaneToPoints(pts);
CoordScalar init_theta;
CoordScalar init_phi;
CoordScalar init_r;
if (use_mle_as_init)
{
std::tie(init_theta,init_phi,init_r) = PlaneNormalScalarToSpherical(init_plane);
}
else
{
std::tie(init_theta,init_phi,init_r) = PlaneNormalScalarToSpherical(p0);
}
PlaneFitMAPCMAES map_fit(pts, p0);
map_fit.set_init_guess(Pt3({ init_theta, init_phi, init_r }));
map_fit.run();
const auto fit_params = map_fit.solution();
const auto fit_plane = PlaneSphericalToNormalScalar(fit_params[0], fit_params[1], fit_params[2]);
return std::make_tuple(fit_plane, FindClosestOnPlane(pt_on_plane, fit_plane));
}
| 25.318452 | 99 | 0.631127 | [
"vector",
"model"
] |
3d225d384219854ba4a96358f2fc9d0dbe8adb58 | 665 | cpp | C++ | src/renderViewController.cpp | dalewzm/IceRayTracer | ba26e44a88fb6ff37106707ccfd3e73e123d0d60 | [
"Apache-1.1"
] | null | null | null | src/renderViewController.cpp | dalewzm/IceRayTracer | ba26e44a88fb6ff37106707ccfd3e73e123d0d60 | [
"Apache-1.1"
] | null | null | null | src/renderViewController.cpp | dalewzm/IceRayTracer | ba26e44a88fb6ff37106707ccfd3e73e123d0d60 | [
"Apache-1.1"
] | null | null | null | #include "renderViewController.h"
#include <cstdio>
RenderViewController::RenderViewController(MainWindow* mainWindow)
{
rayTracerPtr = new RayTracer;
mainWindowPtr = mainWindow;
QObject::connect(rayTracerPtr, SIGNAL(calculatedApixel(int ,int ,QColor)),this, SLOT(getApixelValue(int ,int ,QColor)));
}
RenderViewController::~RenderViewController()
{
if(rayTracerPtr)
delete rayTracerPtr;
}
void RenderViewController::getApixelValue(int x,int y,QColor rgb)
{
mainWindowPtr->setPixel(x,y,rgb);
}
bool RenderViewController::renderScene()
{
printf("enter view controller render scene\n");
rayTracerPtr->start();
return true;
}
| 22.931034 | 124 | 0.742857 | [
"render"
] |
3d23c857f8662333de688cfd3aff49894048baa2 | 9,755 | hpp | C++ | apps/kmeans/kmeans_helper.hpp | RickAi/csci5570 | 2814c0a6bf608c73bf81d015d13e63443470e457 | [
"Apache-2.0"
] | 7 | 2019-04-09T16:25:49.000Z | 2021-12-07T10:29:52.000Z | apps/kmeans/kmeans_helper.hpp | RickAi/csci5570 | 2814c0a6bf608c73bf81d015d13e63443470e457 | [
"Apache-2.0"
] | null | null | null | apps/kmeans/kmeans_helper.hpp | RickAi/csci5570 | 2814c0a6bf608c73bf81d015d13e63443470e457 | [
"Apache-2.0"
] | 4 | 2019-08-07T07:43:27.000Z | 2021-05-21T07:54:14.000Z | #include <utility>
#include <vector>
namespace minips {
template<typename T>
double dist(T &point1, T &point2, int num_features) {
std::vector<double> diff(num_features);
auto &x1 = point1.first;
auto &x2 = point2.first;
for (auto field : x1)
diff[field.first] = field.second; // first:fea, second:val
for (auto field : x2)
diff[field.first] = field.second; // first:fea, second:val
return std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
}
template<typename T>
void random_init(int K, int num_features, const std::vector<T> &data, std::vector<std::vector<double>> ¶ms) {
// LOG(INFO)<<"inside random";
std::vector<int> prohibited_indexes;
int index;
for (int i = 0; i < K; i++) {
while (true) {
srand(time(NULL));
index = rand() % data.size();
if (find(prohibited_indexes.begin(), prohibited_indexes.end(), index) ==
prohibited_indexes.end()) // not found, this index can be used
{
prohibited_indexes.push_back(index);
auto &x = data[index].first;
for (auto field : x)
params[i][field.first] = field.second; // first:fea, second:val
break;
}
}
params[K][i] += 1;
}
}
// return ID of cluster whose center is the nearest (uses euclidean distance), and the distance
std::pair<int, double>
get_nearest_center(const std::pair<std::vector<std::pair<int, double>>, double> &point, int K,
const std::vector<std::vector<double>> ¶ms, int num_features) {
double square_dist, min_square_dist = std::numeric_limits<double>::max();
int id_cluster_center = -1;
auto &x = point.first;
for (int i = 0; i < K; i++) // calculate the dist between point and clusters[i]
{
std::vector<double> diff = params[i];
for (auto field : x)
diff[field.first] -= field.second; // first:fea, second:val
square_dist = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
if (square_dist < min_square_dist) {
min_square_dist = square_dist;
id_cluster_center = i;
}
}
return std::make_pair(id_cluster_center, min_square_dist);
}
template<typename T>
void kmeans_plus_plus_init(int K, int num_features, const std::vector<T> &data,
std::vector<std::vector<double>> ¶ms) {
// LOG(INFO)<<"inside kmeans ++";
auto X = data;
std::vector<double> dist(X.size());
int index;
index = rand() % X.size();
auto &x = X[index].first;
for (auto field : x)
params[0][field.first] = field.second; // first:fea, second:val
params[K][0] += 1;
X.erase(X.begin() + index);
double sum;
int id_nearest_center;
for (int i = 1; i < K; i++) {
sum = 0;
for (int j = 0; j < X.size(); j++) {
dist[j] = get_nearest_center(X[j], i, params, num_features).second;
sum += dist[j];
}
sum = sum * rand() / (RAND_MAX - 1.);
for (int j = 0; j < X.size(); j++) {
sum -= dist[j];
if (sum > 0)
continue;
auto &x = X[j].first;
for (auto field : x)
params[i][field.first] = field.second; // first:fea, second:val
X.erase(X.begin() + j);
break;
}
params[K][i] += 1;
}
}
template<typename T>
void kmeans_parallel_init(int K, int num_features, const std::vector<T> &data,
std::vector<std::vector<double>> ¶ms) {
// LOG(INFO)<<"inside kmeans ||";
int index;
std::vector<T> C;
// std::vector<LabeledPointHObj<double, int, true>> C;
auto X = data;
index = rand() % X.size();
C.push_back(X[index]);
X.erase(X.begin() + index);
double square_dist, min_dist;
/*double sum_square_dist = 0; // original K-Means|| algorithms
for(int i = 0; i < X.size(); i++)
sum_square_dist += dist(C[0], X[i], num_features);
int sample_time = log(sum_square_dist), l = 2;*/
int sample_time = 5, l = 2; // empiric value, sampe_time: time of sampling l: oversample coefficient
for (int i = 0; i < sample_time; i++) {
// compute d^2 for each x_i
std::vector<double> psi(X.size());
for (int j = 0; j < X.size(); j++) {
min_dist = std::numeric_limits<double>::max();
for (int k = 0; k < C.size(); k++) {
square_dist = dist(X[j], C[k], num_features);
if (square_dist < min_dist)
min_dist = square_dist;
}
psi[j] = min_dist;
}
double phi = 0;
for (int i = 0; i < psi.size(); i++)
phi += psi[i];
// do the drawings
for (int i = 0; i < psi.size(); i++) {
double p_x = l * psi[i] / phi;
if (p_x >= rand() / (RAND_MAX - 1.)) {
C.push_back(X[i]);
X.erase(X.begin() + i);
}
}
}
std::vector<double> w(C.size()); // by default all are zero
for (int i = 0; i < X.size(); i++) {
min_dist = std::numeric_limits<double>::max();
for (int j = 0; j < C.size(); j++) {
square_dist = dist(X[i], C[j], num_features);
if (square_dist < min_dist) {
min_dist = square_dist;
index = j;
}
}
// we found the minimum index, so we increment corresp. weight
w[index]++;
}
// repeat kmeans++ on C
index = rand() % C.size();
auto &x = C[index].first;
for (auto field : x)
params[0][field.first] = field.second; // first:fea, second:val
params[K][0] += 1;
C.erase(C.begin() + index);
double sum;
for (int i = 1; i < K; i++) {
sum = 0;
std::vector<double> dist(C.size());
for (int j = 0; j < C.size(); j++) {
dist[j] = get_nearest_center(C[j], i, params, num_features).second;
sum += dist[j];
}
sum = sum * rand() / (RAND_MAX - 1.);
for (int j = 0; j < C.size(); j++) {
sum -= dist[j];
if (sum > 0)
continue;
auto &x = C[j].first;
for (auto field : x)
params[i][field.first] = field.second; // first:fea, second:val
C.erase(C.begin() + j);
break;
}
params[K][i] += 1;
}
}
template<typename T>
void init_centers(int K, int num_features, std::vector<T> data, std::vector<std::vector<double>> ¶ms,
std::string init_mode) {
if (init_mode == "random") // K-means: choose K distinct values for the centers of the clusters randomly
random_init(K, num_features, data, params);
else if (init_mode == "kmeans++") // K-means++
kmeans_plus_plus_init(K, num_features, data, params);
else if (init_mode ==
"kmeans_parallel") { // K-means||, reference: http://theory.stanford.edu/~sergei/papers/vldb12-kmpar.pdf
kmeans_parallel_init(K, num_features, data, params);
}
}
int random(int min, int max) {
int intervalLen = max - min + 1;
int ceilingPowerOf2 = pow(2, ceil(log2(intervalLen)));
int randomNumber = rand() % ceilingPowerOf2;
if (randomNumber < intervalLen) {
return min + randomNumber;
}
return random(min, max);
}
// test the Sum of Square Error of the model
template<typename T>
double test_error(const std::vector<std::vector<double>> ¶ms, const std::vector<T> &data, int iter, int K,
int num_features, int cluster_id) {
LOG(INFO) << "Current iteration=" + std::to_string(iter) << ", start test_error";
double sum = 0; // sum of square error
std::pair<int, double> id_dist;
std::vector<int> count(K);
auto start_time = std::chrono::steady_clock::now();
LOG(INFO) << "Start test KMeans error";
// only test top `test_count` since it time consuming
double test_count = data.size() > 50 ? 50 : data.size();
// double test_count = data.size();
double ratio = test_count / data.size();
for (int i = 0; i < test_count; i++) {
// get next data
int index = random(0, data.size());
id_dist = get_nearest_center(data[index], K, params, num_features);
sum += id_dist.second;
count[id_dist.first]++;
}
sum = sum / ratio;
auto end_time = std::chrono::steady_clock::now();
auto total_time = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count();
LOG(INFO) << "Current iteration=" + std::to_string(iter) << ", Sum of Squared Errors=" << std::to_string(sum)
<< ", Cost time=" << total_time << " ms";
return sum;
}
}
| 36.263941 | 122 | 0.494413 | [
"vector",
"model"
] |
3d26c47eaf42a9fd3608134143355db75bd2877a | 2,886 | cpp | C++ | source/sill/components/ui-area-component.cpp | Breush/lava | 1b1b1f0785300b93b4a9f35fca4490502fea6552 | [
"MIT"
] | 15 | 2018-02-26T08:20:03.000Z | 2022-03-06T03:25:46.000Z | source/sill/components/ui-area-component.cpp | Breush/lava | 1b1b1f0785300b93b4a9f35fca4490502fea6552 | [
"MIT"
] | 32 | 2018-02-26T08:26:38.000Z | 2020-09-12T17:09:38.000Z | source/sill/components/ui-area-component.cpp | Breush/lava | 1b1b1f0785300b93b4a9f35fca4490502fea6552 | [
"MIT"
] | null | null | null | #include <lava/sill/components/ui-area-component.hpp>
#include <lava/sill/components/transform-component.hpp>
using namespace lava::sill;
UiAreaComponent::UiAreaComponent(Entity& entity)
: UiAreaComponent(entity, {0.f, 0.f})
{
}
UiAreaComponent::UiAreaComponent(Entity& entity, const glm::vec2& extent)
: IUiComponent(entity)
{
m_extent = extent;
m_hoveringExtent = m_extent;
updateFromAnchor();
}
// ----- IUiComponent
void UiAreaComponent::verticallyScrolled(float delta, bool& propagate)
{
propagate = false;
glm::vec2 offset{0.f, -m_scrollSensibility * delta};
if (m_scrollOffset.y + offset.y > m_scrollMaxOffset.y) {
offset.y = m_scrollMaxOffset.y - m_scrollOffset.y;
}
if (m_scrollOffset.y + offset.y < m_scrollMinOffset.y) {
offset.y = m_scrollMinOffset.y - m_scrollOffset.y;
}
m_transformComponent.translate2d(-offset);
m_hoveringOffset += offset;
m_scrollOffset += offset;
}
// ----- Configuration
void UiAreaComponent::scrollOffset(const glm::vec2& scrollOffset)
{
m_transformComponent.translate2d(m_scrollOffset);
m_hoveringOffset -= m_scrollOffset;
m_scrollOffset = scrollOffset;
if (m_scrollOffset.y > m_scrollMaxOffset.y) {
m_scrollOffset.y = m_scrollMaxOffset.y;
}
if (m_scrollOffset.y < m_scrollMinOffset.y) {
m_scrollOffset.y = m_scrollMinOffset.y;
}
m_hoveringOffset += m_scrollOffset;
m_transformComponent.translate2d(-m_scrollOffset);
}
// ----- Internal
void UiAreaComponent::updateFromAnchor()
{
m_transformComponent.translate2d(m_scrollOffset);
m_hoveringOffset.x = 0.f;
m_hoveringOffset.y = 0.f;
switch (m_anchor) {
case Anchor::TopLeft:
m_hoveringOffset = {m_hoveringExtent.x / 2.f, m_hoveringExtent.y / 2.f};
break;
case Anchor::Top:
m_hoveringOffset = {0.f, m_hoveringExtent.y / 2.f};
break;
case Anchor::TopRight:
m_hoveringOffset = {-m_hoveringExtent.x / 2.f, m_hoveringExtent.y / 2.f};
break;
case Anchor::Left:
m_hoveringOffset = {m_hoveringExtent.x / 2.f, 0.f};
break;
case Anchor::Center:
m_hoveringOffset = {0.f, 0.f};
break;
case Anchor::Right:
m_hoveringOffset = {-m_hoveringExtent.x / 2.f, 0.f};
break;
case Anchor::BottomLeft:
m_hoveringOffset = {m_hoveringExtent.x / 2.f, -m_hoveringExtent.y / 2.f};
break;
case Anchor::Bottom:
m_hoveringOffset = {0.f, -m_hoveringExtent.y / 2.f};
break;
case Anchor::BottomRight:
m_hoveringOffset = {-m_hoveringExtent.x / 2.f, -m_hoveringExtent.y / 2.f};
break;
}
m_transformComponent.translate2d(-m_scrollOffset);
m_hoveringOffset += m_scrollOffset;
}
| 28.019417 | 86 | 0.641719 | [
"transform"
] |
3d277fc58a3594055985506215876556f9893f6a | 823 | hpp | C++ | visual_studio/visual_studio/oxi/scene/object/spawn_mock_enemy.hpp | collus-corn/oxi | 93e00c51c00f78cb3d09aa9c890e98c1a572af3a | [
"MIT"
] | null | null | null | visual_studio/visual_studio/oxi/scene/object/spawn_mock_enemy.hpp | collus-corn/oxi | 93e00c51c00f78cb3d09aa9c890e98c1a572af3a | [
"MIT"
] | null | null | null | visual_studio/visual_studio/oxi/scene/object/spawn_mock_enemy.hpp | collus-corn/oxi | 93e00c51c00f78cb3d09aa9c890e98c1a572af3a | [
"MIT"
] | null | null | null | #pragma once
#include "../i_spawn.hpp"
#include <vector>
namespace oxi
{
namespace scene
{
namespace object
{
class SpawnMockEnemy :public ISpawn
{
private:
int kind_;
int frame_{0};
bool creatable_{ true };
std::shared_ptr<IPosition> position_;
std::shared_ptr<std::vector<std::shared_ptr<IPosition>>> enemy_positions_;
public:
explicit SpawnMockEnemy(std::shared_ptr<IPosition> position, std::shared_ptr<std::vector<std::shared_ptr<IPosition>>> enemy_positions);
std::shared_ptr<IPosition> getPosition() override { return position_; }
void run() override;
int getKind() override { return kind_; }
bool isDisposable() override { return false; }
bool isCreatable() override { return creatable_; }
std::shared_ptr<IObject> create() override;
};
}
}
} | 26.548387 | 139 | 0.693803 | [
"object",
"vector"
] |
3d2b49eb1ac17180bf47218b18f28a510416ad05 | 909 | cc | C++ | PID/thread/sleep.cc | Incipe-win/linux_code | 808ede88505caccfdd8efb295b8be8d5bc85f856 | [
"Apache-2.0"
] | 1 | 2021-07-14T07:41:59.000Z | 2021-07-14T07:41:59.000Z | PID/thread/sleep.cc | Incipe-win/linux_code | 808ede88505caccfdd8efb295b8be8d5bc85f856 | [
"Apache-2.0"
] | null | null | null | PID/thread/sleep.cc | Incipe-win/linux_code | 808ede88505caccfdd8efb295b8be8d5bc85f856 | [
"Apache-2.0"
] | null | null | null | #include <unistd.h>
#include <ctime>
#include <iostream>
#include <thread>
#include <vector>
using namespace std;
vector<int> vec;
vector<int> ans;
int sum = 0;
template <class T>
void print(const T &array) {
for (int num : array) {
cout << num << " ";
}
cout << endl;
}
void create_numbers(int cnt) {
for (int i = 0; i < cnt; ++i) {
int tmp = rand() % 10 + 1;
sum += tmp;
vec.emplace_back(tmp);
}
cout << "before sort: ";
print(vec);
}
void *func(void *arg) {
sleep(*(int *)arg);
ans.emplace_back(*(int *)arg);
return NULL;
}
int main() {
srand((unsigned int)time(nullptr));
int cnt = 10;
create_numbers(cnt);
pthread_t tid[cnt];
int i;
for (i = 0; i < cnt; ++i) {
int *argc = new int(vec[i]);
pthread_create(&tid[i], NULL, func, (void *)argc);
pthread_detach(tid[i]);
}
sleep(sum);
cout << "sort after: ";
print(ans);
return 0;
}
| 16.833333 | 54 | 0.576458 | [
"vector"
] |
3d2f019483b34fec3a9a8839d0dee3ab4563c437 | 13,228 | cpp | C++ | third_party/WebKit/Source/web/tests/ScrollMetricsTest.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/web/tests/ScrollMetricsTest.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/web/tests/ScrollMetricsTest.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "core/frame/LocalFrameView.h"
#include "core/frame/WebLocalFrameBase.h"
#include "core/geometry/DOMRect.h"
#include "core/input/EventHandler.h"
#include "core/layout/LayoutView.h"
#include "core/paint/PaintLayerScrollableArea.h"
#include "core/testing/sim/SimDisplayItemList.h"
#include "core/testing/sim/SimRequest.h"
#include "core/testing/sim/SimTest.h"
#include "platform/scroll/MainThreadScrollingReason.h"
#include "platform/scroll/ScrollerSizeMetrics.h"
#include "platform/testing/HistogramTester.h"
#include "platform/testing/TestingPlatformSupport.h"
#include "platform/testing/UnitTestHelpers.h"
#define EXPECT_WHEEL_BUCKET(reason, count) \
histogram_tester.ExpectBucketCount( \
"Renderer4.MainThreadWheelScrollReason", \
GetBucketIndex(MainThreadScrollingReason::reason), count);
#define EXPECT_TOUCH_BUCKET(reason, count) \
histogram_tester.ExpectBucketCount( \
"Renderer4.MainThreadGestureScrollReason", \
GetBucketIndex(MainThreadScrollingReason::reason), count);
#define EXPECT_WHEEL_TOTAL(count) \
histogram_tester.ExpectTotalCount("Renderer4.MainThreadWheelScrollReason", \
count);
#define EXPECT_TOUCH_TOTAL(count) \
histogram_tester.ExpectTotalCount("Renderer4.MainThreadGestureScrollReason", \
count);
namespace blink {
namespace {
class ScrollMetricsTest : public SimTest {
public:
void SetUpHtml(const char*);
void Scroll(Element*, const WebGestureDevice);
};
class NonCompositedMainThreadScrollingReasonRecordTest
: public ScrollMetricsTest {
protected:
int GetBucketIndex(uint32_t reason);
};
class ScrollBeginEventBuilder : public WebGestureEvent {
public:
ScrollBeginEventBuilder(IntPoint position,
FloatPoint delta,
WebGestureDevice device)
: WebGestureEvent() {
type_ = WebInputEvent::kGestureScrollBegin;
x = global_x = position.X();
y = global_y = position.Y();
data.scroll_begin.delta_y_hint = delta.Y();
source_device = device;
frame_scale_ = 1;
}
};
class ScrollUpdateEventBuilder : public WebGestureEvent {
public:
ScrollUpdateEventBuilder() : WebGestureEvent() {
type_ = WebInputEvent::kGestureScrollUpdate;
data.scroll_update.delta_x = 0.0f;
data.scroll_update.delta_y = 1.0f;
data.scroll_update.velocity_x = 0;
data.scroll_update.velocity_y = 1;
frame_scale_ = 1;
}
};
class ScrollEndEventBuilder : public WebGestureEvent {
public:
ScrollEndEventBuilder() : WebGestureEvent() {
type_ = WebInputEvent::kGestureScrollEnd;
frame_scale_ = 1;
}
};
int NonCompositedMainThreadScrollingReasonRecordTest::GetBucketIndex(
uint32_t reason) {
int index = 1;
while (!(reason & 1)) {
reason >>= 1;
++index;
}
DCHECK_EQ(reason, 1u);
return index;
}
void ScrollMetricsTest::Scroll(Element* element,
const WebGestureDevice device) {
DCHECK(element);
DCHECK(element->getBoundingClientRect());
DOMRect* rect = element->getBoundingClientRect();
ScrollBeginEventBuilder scroll_begin(
IntPoint(rect->left() + rect->width() / 2,
rect->top() + rect->height() / 2),
FloatPoint(0.f, 1.f), device);
ScrollUpdateEventBuilder scroll_update;
ScrollEndEventBuilder scroll_end;
GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent(scroll_begin);
GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent(scroll_update);
GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent(scroll_end);
ASSERT_GT(scroll_update.DeltaYInRootFrame(), 0);
}
void ScrollMetricsTest::SetUpHtml(const char* html_content) {
WebView().Resize(WebSize(800, 600));
SimRequest request("https://example.com/test.html", "text/html");
LoadURL("https://example.com/test.html");
request.Complete(html_content);
Compositor().BeginFrame();
}
TEST_F(ScrollMetricsTest, ScrollerSizeOnPageLoadHistogramRecordingTest) {
HistogramTester histogram_tester;
SetUpHtml(
"<!DOCTYPE html>"
"<style>"
" .smallBox { overflow: scroll; width: 100px; height: 100px; }"
" .largeBox { overflow: auto; width: 500px; height: 500px; }"
" .nonScrollableBox { overflow: auto; width: 200px; height: 200px; }"
" .spacer { height: 1000px; }"
" body { height: 2000px; width: 1000px; }"
"</style>"
"<div class='smallBox'><div class='spacer'></div></div>"
"<div class='largeBox'><div class='spacer'></div></div>"
"<div class='notScrollableBox'></div>"
"<div style='width: 300px; height: 300px;'>"
" <div class='spacer'></div>"
"</div>");
testing::RunPendingTasks();
// SmallBox added to count.
histogram_tester.ExpectBucketCount("Event.Scroll.ScrollerSize.OnLoad", 10000,
1);
// LargeBox added to count.
histogram_tester.ExpectBucketCount("Event.Scroll.ScrollerSize.OnLoad",
kScrollerSizeLargestBucket, 1);
// Non-scrollable box is not added to count.
histogram_tester.ExpectBucketCount("Event.Scroll.ScrollerSize.OnLoad", 40000,
0);
// The fourth div without "overflow: scroll" is not supposed to be added to
// count.
histogram_tester.ExpectBucketCount("Event.Scroll.ScrollerSize.OnLoad", 90000,
0);
// Root scroller is not added to count.
histogram_tester.ExpectBucketCount("Event.Scroll.ScrollerSize.OnLoad",
kScrollerSizeLargestBucket, 1);
histogram_tester.ExpectTotalCount("Event.Scroll.ScrollerSize.OnLoad", 2);
}
TEST_F(ScrollMetricsTest,
ScrollerSizeOfMainThreadScrollingHistogramRecordingTest) {
HistogramTester histogram_tester;
SetUpHtml(
"<!DOCTYPE html>"
"<style>"
" .container { width: 200px; height: 200px; overflow: scroll; }"
" .box { width: 100px; height: 100px; overflow: scroll; }"
" .spacer { height: 1000px; }"
" .target { width: 200px; height: 200px; }"
" body { height: 2000px; }"
"</style>"
"<div class='container'>"
" <div id='box' class='box'>"
" <div id='content' class='spacer'></div>"
" </div>"
"</div>"
"<div id='target' class='target'></div>");
Element* box = GetDocument().getElementById("box");
// Test wheel scroll on the box.
Scroll(box, kWebGestureDeviceTouchpad);
histogram_tester.ExpectBucketCount("Event.Scroll.ScrollerSize.OnScroll_Wheel",
10000, 1);
// Only the first scrollable area is recorded.
histogram_tester.ExpectBucketCount("Event.Scroll.ScrollerSize.OnScroll_Wheel",
40000, 0);
histogram_tester.ExpectTotalCount("Event.Scroll.ScrollerSize.OnScroll_Wheel",
1);
// Test touch scroll.
Scroll(box, kWebGestureDeviceTouchscreen);
histogram_tester.ExpectBucketCount("Event.Scroll.ScrollerSize.OnScroll_Touch",
10000, 1);
histogram_tester.ExpectTotalCount("Event.Scroll.ScrollerSize.OnScroll_Touch",
1);
// Scrolling the non-scrollable target leads to scroll the root layer which
// doesn't add to count.
Element* body_scroll_target = GetDocument().getElementById("target");
Scroll(body_scroll_target, kWebGestureDeviceTouchscreen);
histogram_tester.ExpectBucketCount("Event.Scroll.ScrollerSize.OnScroll_Touch",
kScrollerSizeLargestBucket, 0);
histogram_tester.ExpectTotalCount("Event.Scroll.ScrollerSize.OnScroll_Touch",
1);
}
TEST_F(NonCompositedMainThreadScrollingReasonRecordTest,
TouchAndWheelGeneralTest) {
SetUpHtml(
"<style>"
" .box { overflow:scroll; width: 100px; height: 100px; }"
" .translucent { opacity: 0.5; }"
" .spacer { height: 1000px; }"
"</style>"
"<div id='box' class='translucent box'>"
" <div class='spacer'></div>"
"</div>");
GetDocument().View()->UpdateAllLifecyclePhases();
Element* box = GetDocument().getElementById("box");
HistogramTester histogram_tester;
// Test touch scroll.
Scroll(box, kWebGestureDeviceTouchscreen);
EXPECT_TOUCH_BUCKET(kHasOpacityAndLCDText, 1);
EXPECT_TOUCH_BUCKET(kBackgroundNotOpaqueInRectAndLCDText, 1);
Scroll(box, kWebGestureDeviceTouchscreen);
EXPECT_TOUCH_BUCKET(kHasOpacityAndLCDText, 2);
EXPECT_TOUCH_BUCKET(kBackgroundNotOpaqueInRectAndLCDText, 2);
EXPECT_TOUCH_TOTAL(4);
// Test wheel scroll.
Scroll(box, kWebGestureDeviceTouchpad);
EXPECT_WHEEL_BUCKET(kHasOpacityAndLCDText, 1);
EXPECT_WHEEL_BUCKET(kBackgroundNotOpaqueInRectAndLCDText, 1);
EXPECT_WHEEL_TOTAL(2);
}
TEST_F(NonCompositedMainThreadScrollingReasonRecordTest,
CompositedScrollableAreaTest) {
SetUpHtml(
"<style>"
" .box { overflow:scroll; width: 100px; height: 100px; }"
" .translucent { opacity: 0.5; }"
" .composited { will-change: transform; }"
" .spacer { height: 1000px; }"
"</style>"
"<div id='box' class='translucent box'>"
" <div class='spacer'></div>"
"</div>");
WebView().GetSettings()->SetAcceleratedCompositingEnabled(true);
GetDocument().View()->SetParentVisible(true);
GetDocument().View()->SetSelfVisible(true);
GetDocument().View()->UpdateAllLifecyclePhases();
Element* box = GetDocument().getElementById("box");
HistogramTester histogram_tester;
Scroll(box, kWebGestureDeviceTouchpad);
EXPECT_WHEEL_BUCKET(kHasOpacityAndLCDText, 1);
EXPECT_WHEEL_BUCKET(kBackgroundNotOpaqueInRectAndLCDText, 1);
EXPECT_WHEEL_TOTAL(2);
box->setAttribute("class", "composited translucent box");
GetDocument().View()->UpdateAllLifecyclePhases();
Scroll(box, kWebGestureDeviceTouchpad);
EXPECT_FALSE(ToLayoutBox(box->GetLayoutObject())
->GetScrollableArea()
->GetNonCompositedMainThreadScrollingReasons());
EXPECT_WHEEL_BUCKET(kHasOpacityAndLCDText, 1);
EXPECT_WHEEL_BUCKET(kBackgroundNotOpaqueInRectAndLCDText, 1);
EXPECT_WHEEL_TOTAL(2);
}
TEST_F(NonCompositedMainThreadScrollingReasonRecordTest,
NotScrollableAreaTest) {
SetUpHtml(
"<style>.box { overflow:scroll; width: 100px; height: 100px; }"
" .translucent { opacity: 0.5; }"
" .hidden { overflow: hidden; }"
" .spacer { height: 1000px; }"
"</style>"
"<div id='box' class='translucent box'>"
" <div class='spacer'></div>"
"</div>");
GetDocument().View()->UpdateAllLifecyclePhases();
Element* box = GetDocument().getElementById("box");
HistogramTester histogram_tester;
Scroll(box, kWebGestureDeviceTouchpad);
EXPECT_WHEEL_BUCKET(kHasOpacityAndLCDText, 1);
EXPECT_WHEEL_BUCKET(kBackgroundNotOpaqueInRectAndLCDText, 1);
EXPECT_WHEEL_TOTAL(2);
box->setAttribute("class", "hidden translucent box");
GetDocument().View()->UpdateAllLifecyclePhases();
Scroll(box, kWebGestureDeviceTouchpad);
EXPECT_WHEEL_BUCKET(kHasOpacityAndLCDText, 1);
EXPECT_WHEEL_BUCKET(kBackgroundNotOpaqueInRectAndLCDText, 1);
EXPECT_WHEEL_TOTAL(2);
}
TEST_F(NonCompositedMainThreadScrollingReasonRecordTest, NestedScrollersTest) {
SetUpHtml(
"<style>"
" .container { overflow:scroll; width: 200px; height: 200px; }"
" .box { overflow:scroll; width: 100px; height: 100px; }"
" .translucent { opacity: 0.5; }"
" .transform { transform: scale(0.8); }"
" .with-border-radius { border: 5px solid; border-radius: 5px; }"
" .spacer { height: 1000px; }"
" .composited { will-change: transform; }"
"</style>"
"<div id='container' class='container with-border-radius'>"
" <div class='translucent box'>"
" <div id='inner' class='composited transform box'>"
" <div class='spacer'></div>"
" </div>"
" <div class='spacer'></div>"
" </div>"
" <div class='spacer'></div>"
"</div>");
WebView().GetSettings()->SetAcceleratedCompositingEnabled(true);
GetDocument().View()->SetParentVisible(true);
GetDocument().View()->SetSelfVisible(true);
GetDocument().View()->UpdateAllLifecyclePhases();
Element* box = GetDocument().getElementById("inner");
HistogramTester histogram_tester;
Scroll(box, kWebGestureDeviceTouchpad);
// Scrolling the inner box will gather reasons from the scrolling chain. The
// inner box itself has no reason because it's composited. Other scrollable
// areas from the chain have corresponding reasons.
EXPECT_WHEEL_BUCKET(kHasOpacityAndLCDText, 1);
EXPECT_WHEEL_BUCKET(kBackgroundNotOpaqueInRectAndLCDText, 1);
EXPECT_WHEEL_BUCKET(kIsNotStackingContextAndLCDText, 1);
EXPECT_WHEEL_BUCKET(kHasBorderRadius, 1);
EXPECT_WHEEL_BUCKET(kHasTransformAndLCDText, 0);
EXPECT_WHEEL_TOTAL(4);
}
} // namespace
} // namespace blink
| 36.846797 | 80 | 0.678107 | [
"geometry",
"transform",
"solid"
] |
3d35102776976ae8f2c5d471d33c1531dc73ab79 | 3,673 | hpp | C++ | Quartz/Engine/Include/Quartz/Graphics/RHI/InputLayout.hpp | tobyplowy/quartz-engine | d08ff18330c9bb59ab8739b40d5a4781750697c1 | [
"BSD-3-Clause"
] | null | null | null | Quartz/Engine/Include/Quartz/Graphics/RHI/InputLayout.hpp | tobyplowy/quartz-engine | d08ff18330c9bb59ab8739b40d5a4781750697c1 | [
"BSD-3-Clause"
] | null | null | null | Quartz/Engine/Include/Quartz/Graphics/RHI/InputLayout.hpp | tobyplowy/quartz-engine | d08ff18330c9bb59ab8739b40d5a4781750697c1 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 Genten Studios
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include <Quartz/Graphics/RHI/DataTypes.hpp>
#include <initializer_list>
#include <string>
#include <vector>
namespace qz
{
namespace gfx
{
namespace rhi
{
/// @brief Represents the type of a vertex element in a shader
/// InputLayout.
struct VertexElementType
{
/// @brief The type of the entry.
DataType type;
// #todo: This could probably be inferred from the type.
/// @brief The number of components of this entry (e.g. Vec3 has
/// 3, Vec2 has 1, float has 1 etc...)
int numComponents;
/// @brief Represents a vertex element that is a 2 component
/// vector of floats.
static const VertexElementType Vec2f;
/// @brief Represents a vertex element that is a 3 component
/// vector of floats.
static const VertexElementType Vec3f;
/// @brief Represents a vertex element that is a 4 component
/// vector of floats.
static const VertexElementType Vec4f;
};
/// @brief Represents a vertex element in a shader input
/// layout/buffer layout.
struct VertexElement
{
/// @brief The type of this element.
VertexElementType type;
/// @brief The (index of) the vertex stream that this element
/// sits in.
int streamIndex;
/// @brief The shader attribute index of this element.
int attributeIndex;
/// @brief The offset of this element in the buffer (in bytes).
int offset;
// #todo: Maybe this is too OpenGL specific?
/// @brief Is this element normalized or not?
bool normalized;
};
/// @brief Describes the layout of data that will be sent to a
/// shader.
class InputLayout
{
public:
/**
* @brief Constructs the InputLayout, copying the elements from
* the given initalizer list.
*/
InputLayout(std::initializer_list<VertexElement> init);
/**
* @brief Default constructs this InputLayout to have to vertex
* elements.
*/
InputLayout() {}
/// @brief The list of elements in this input layout.
std::vector<VertexElement> elements;
};
} // namespace rhi
} // namespace gfx
} // namespace qz
| 32.504425 | 80 | 0.706507 | [
"vector"
] |
3d38560150f3a8fbd6c16751cae8fa91cab4573e | 16,594 | cpp | C++ | cpp/graph_2D.cpp | amstremblay/OmegaMaxEnt | bbb8a7fa8520e3e8a5a57dd662ab93ff6809b369 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 8 | 2017-01-12T14:18:50.000Z | 2021-02-18T14:44:33.000Z | cpp/graph_2D.cpp | amstremblay/OmegaMaxEnt | bbb8a7fa8520e3e8a5a57dd662ab93ff6809b369 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | cpp/graph_2D.cpp | amstremblay/OmegaMaxEnt | bbb8a7fa8520e3e8a5a57dd662ab93ff6809b369 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 5 | 2018-12-17T22:31:23.000Z | 2019-12-07T11:11:12.000Z | /*
file graph_2D.cpp
functions definitions for class "graph_2D" defined in file graph_2D.h
It is part of the program OmegaMaxEnt (other source files: OmegaMaxEnt_main.cpp, OmegaMaxEnt_data.h, OmegaMaxEnt_data.cpp, generique.h, generique.cpp)
Copyright (C) 2015 Dominic Bergeron (dominic.bergeron@usherbrooke.ca)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "graph_2D.h"
FILE *graph_2D::plot_pipe=NULL;
FILE *graph_2D::file_pipe=NULL;
bool graph_2D::display_figures=true;
bool graph_2D::print_to_file=true;
int graph_2D::ind_file=0;
int graph_2D::fig_ind_max=0;
char graph_2D::program_name[100];
char graph_2D::config_command[200];
char graph_2D::fig_command_format[100];
char graph_2D::plot_function[100];
char graph_2D::load_data_command_format[100];
char graph_2D::plot_data_command_format[100];
char graph_2D::plot_data_command_separator[100];
char graph_2D::xlabel_command_format[100];
char graph_2D::ylabel_command_format[100];
char graph_2D::title_command_format[100];
char graph_2D::xlims_command_format[100];
char graph_2D::ylims_command_format[100];
char graph_2D::legend_function[100];
char graph_2D::plot_closing_command[100];
char graph_2D::show_figures_command[100];
char graph_2D::close_figures_command[100];
char graph_2D::close_figures_command_format[100];
char graph_2D::tmp_file_name_format[100];
bool graph_2D::show_command=false;
plot_prog graph_2D::plotting_program=PYPLOT;
char graph_2D::file_name[100];
char graph_2D::file_name_format[100];
char graph_2D::figs_dir[100];
//char graph_2D::scripts_dir[100];
//ofstream graph_2D::figs_ind_file(figs_ind_file_name);
ofstream graph_2D::figs_ind_file;
graph_2D::graph_2D(plot_prog plot_prog_init, int fig_ind_p)
{
if (fig_ind_p>0)
fig_ind=fig_ind_p;
else
{
fig_ind_max++;
fig_ind=fig_ind_max;
}
if (figs_ind_file)
{
figs_ind_file<<setiosflags(ios::left);
}
labels_fontsize=20;
legend_fontsize=20;
title_fontsize=20;
legend_loc=0;
xlims[0]=0;
xlims[1]=0;
ylims[0]=0;
ylims[1]=0;
// fig_name[0]='\0';
title[0]='\0';
xlabel[0]='\0';
ylabel[0]='\0';
plotting_program=plot_prog_init;
switch (plotting_program)
{
case PYPLOT:
strcpy(figs_dir,"OmegaMaxEnt_figs_data");
strcpy(file_name_format,"OmegaMaxEnt_figs_%d.py");
strcpy(program_name,"python");
strcpy(config_command,"from matplotlib import pyplot\nfrom numpy import loadtxt\n");
strcpy(load_data_command_format,"x%d,y%d=loadtxt(\"%s\",unpack=True)\n");
strcpy(fig_command_format,"pyplot.figure(%d)\n");
strcpy(plot_function,"pyplot.plot(");
strcpy(plot_data_command_format,"x%d,y%d");
strcpy(plot_data_command_separator,",");
strcpy(xlabel_command_format,"pyplot.xlabel(\"%s\",fontsize=%g)\n");
strcpy(ylabel_command_format,"pyplot.ylabel(\"%s\",fontsize=%g)\n");
strcpy(title_command_format,"pyplot.title(\"%s\",fontsize=%g)\n");
strcpy(xlims_command_format,"pyplot.xlim(%g,%g)\n");
strcpy(ylims_command_format,"pyplot.ylim(%g,%g)\n");
strcpy(legend_function,"pyplot.legend(");
strcpy(plot_closing_command,")\n");
strcpy(tmp_file_name_format,figs_dir);
strcat(tmp_file_name_format,"/fig_file_%d.dat");
strcpy(show_figures_command,"pyplot.show()\n");
strcpy(close_figures_command,"pyplot.close(\"all\")\n");
strcpy(close_figures_command_format,"pyplot.close(%d)\n");
break;
case GNUPLOT:
strcpy(program_name,"gnuplot");
strcpy(config_command,"set terminal x11\n");
strcpy(plot_function,"plot");
strcpy(plot_data_command_format," \"%s\" with lines");
strcpy(plot_data_command_separator,",");
strcpy(tmp_file_name_format,"fig_file_%d.dat");
strcpy(show_figures_command,"\n");
break;
default:
break;
}
struct stat file_stat;
if (stat(figs_dir,&file_stat))
mkdir(figs_dir, S_IRWXU | S_IRWXG | S_IRWXO);
}
void graph_2D::open_pipe()
{
if (display_figures && !plot_pipe)
{
plot_pipe=popen(program_name,"w");
fputs(config_command,plot_pipe);
}
if (print_to_file && !file_pipe)
{
sprintf(file_name,file_name_format,ind_file);
file_pipe=fopen(file_name,"w");
if (figs_ind_file)
{
figs_ind_file<<setw(10)<<ind_file;
}
fputs(config_command,file_pipe);
}
if (show_command) cout<<config_command;
}
void graph_2D::close_pipe()
{
if (plot_pipe)
{
fflush(plot_pipe);
pclose(plot_pipe);
plot_pipe=NULL;
}
if (file_pipe)
{
fflush(file_pipe);
fclose(file_pipe);
file_pipe=NULL;
}
}
graph_2D::~graph_2D()
{
close_pipe();
}
void graph_2D::set_axes_lims(double *xlims_par, double *ylims_par)
{
if (xlims_par)
{
xlims[0]=xlims_par[0];
xlims[1]=xlims_par[1];
}
if (ylims_par)
{
ylims[0]=ylims_par[0];
ylims[1]=ylims_par[1];
}
}
void graph_2D::set_axes_labels(const char *xlabel_par, const char *ylabel_par)
{
if (xlabel_par) strcpy(xlabel,xlabel_par);
if (ylabel_par) strcpy(ylabel,ylabel_par);
}
void graph_2D::add_to_legend(const char *lgd_entry)
{
string str(lgd_entry);
curves_names.push_back(str);
}
void graph_2D::add_attribute(const char *attr)
{
string str(attr);
curves_attributes.push_back(str);
}
void graph_2D::close_figures()
{
char close_command[100];
sprintf(close_command,close_figures_command_format,fig_ind_max);
if (plot_pipe) fputs(close_command,plot_pipe);
if (file_pipe) fputs(close_command,file_pipe);
// fputs(close_figures_command,plot_pipe);
// pclose(plot_pipe);
// plot_pipe=NULL;
}
void graph_2D::show_figures()
{
if (plot_pipe)
{
fputs(show_figures_command,plot_pipe);
fflush(plot_pipe);
}
if (file_pipe)
{
fputs(show_figures_command,file_pipe);
fflush(file_pipe);
}
close_pipe();
if (!print_to_file)
{
char tmp_file_name[100];
for (int j=0; j<ind_file; ++j)
{
sprintf(tmp_file_name,tmp_file_name_format,j);
remove(tmp_file_name);
}
ind_file=0;
}
}
void graph_2D::add_data(double *x, double *y, int size_data)
{
vector<point> vtmp(size_data);
for (int i=0; i<size_data; i++)
{
vtmp[i][0]=x[i];
vtmp[i][1]=y[i];
}
list_curves.push_back(vtmp);
}
void graph_2D::add_title(const char *ttl)
{
strcpy(title,ttl);
}
void graph_2D::print_data()
{
cout<<"size of list_curves: "<<list_curves.size()<<'\n';
for (auto list_ptr=list_curves.begin(); list_ptr!=list_curves.end(); list_ptr++)
{
cout<<"size of element: "<<list_ptr->size()<<'\n';
cout<<setiosflags(ios::left);
for (int i=0; i<list_ptr->size(); i++)
{
cout<<setw(30)<<(*list_ptr)[i][0]<<(*list_ptr)[i][1]<<'\n';
}
}
}
void graph_2D::curve_plot(double *x, double *y, int size_data, char *extra_commands, int fig_ind_p)
{
add_data(x, y, size_data);
curve_plot(extra_commands, fig_ind_p);
}
void graph_2D::curve_plot(char *extra_commands, int fig_ind_p)
{
switch (plotting_program)
{
case PYPLOT:
plot_with_pyplot(extra_commands, fig_ind_p);
break;
case GNUPLOT:
plot_with_gnuplot(extra_commands, fig_ind_p);
break;
default:
plot_with_pyplot(extra_commands, fig_ind_p);
break;
}
}
void graph_2D::plot_with_pyplot(char *extra_commands, int fig_ind_p)
{
fstream data_file;
char tmp_file_name[100];
char file_name[200];
char load_data_command[200];
char fig_command[100];
char plot_command[10000];
char data_plot_command[100];
char legend_command[10000];
char legend_loc_command[10];
char xlabel_command[100];
char ylabel_command[100];
char xlims_command[100];
char ylims_command[100];
char title_command[400];
if (fig_ind_p>0)
fig_ind=fig_ind_p;
if (fig_ind>fig_ind_max)
fig_ind_max=fig_ind;
sprintf(fig_command,fig_command_format,fig_ind);
open_pipe();
if (!plot_pipe && !file_pipe)
{
cout<<"plot_with_pyplot(): no pipe open\n";
return;
}
strcpy(plot_command,plot_function);
strcpy(legend_command,legend_function);
sprintf(legend_loc_command,",loc=%d",legend_loc);
sprintf(title_command, title_command_format, title, title_fontsize);
sprintf(xlabel_command,xlabel_command_format,xlabel,labels_fontsize);
sprintf(ylabel_command,ylabel_command_format,ylabel,labels_fontsize);
sprintf(xlims_command,xlims_command_format,xlims[0],xlims[1]);
sprintf(ylims_command,ylims_command_format,ylims[0],ylims[1]);
auto list_ptr=list_curves.begin();
auto lgd_ptr=curves_names.begin();
auto attr_ptr=curves_attributes.begin();
int j=ind_file;
/*
strcpy(file_name,figs_dir);
sprintf(tmp_file_name,tmp_file_name_format,j);
strcat(file_name,"/");
strcat(file_name,tmp_file_name);
cout<<"tmp_file_name: "<<tmp_file_name<<endl;
cout<<"file_name: "<<file_name<<endl;
data_file.open(file_name,ios::out);
*/
sprintf(tmp_file_name,tmp_file_name_format,j);
data_file.open(tmp_file_name,ios::out);
if (data_file && (plot_pipe || file_pipe))
{
data_file<<setprecision(16)<<setiosflags(ios::left)<<setiosflags(ios::scientific);
for (int i=0; i<list_ptr->size(); i++)
{
data_file<<setw(30)<<(*list_ptr)[i][0]<<(*list_ptr)[i][1]<<'\n';
}
data_file.close();
sprintf(load_data_command,load_data_command_format,j,j,tmp_file_name);
if (show_command) cout<<load_data_command;
if (plot_pipe) fputs(load_data_command,plot_pipe);
if (file_pipe) fputs(load_data_command,file_pipe);
sprintf(data_plot_command,plot_data_command_format,j,j);
strcat(plot_command,data_plot_command);
if (curves_attributes.size()>0)
{
strcat(plot_command,plot_data_command_separator);
strcat(plot_command,attr_ptr->data());
}
if (curves_names.size()>0)
{
if (list_curves.size()>1) strcat(legend_command,"(");
strcat(legend_command,"\'");
strcat(legend_command,(*lgd_ptr).data());
strcat(legend_command,"\'");
}
strcat(plot_command,")\n");
}
else
{
if (!data_file)
cout<<"curve_plot: file "<<tmp_file_name<<" could not be opened\n";
else
cout<<"curve_plot: plotting program not found\n";
}
list_ptr++;
lgd_ptr++;
attr_ptr++;
j++;
while (list_ptr!=list_curves.end())
{
/*
strcpy(file_name,figs_dir);
sprintf(tmp_file_name,tmp_file_name_format,j);
strcat(file_name,"/");
strcat(file_name,tmp_file_name);
data_file.open(file_name,ios::out);
*/
sprintf(tmp_file_name,tmp_file_name_format,j);
data_file.open(tmp_file_name,ios::out);
if (data_file && (plot_pipe || file_pipe))
{
strcat(plot_command,plot_function);
data_file<<setprecision(16)<<setiosflags(ios::left)<<setiosflags(ios::scientific);
for (int i=0; i<list_ptr->size(); i++)
{
data_file<<setw(30)<<(*list_ptr)[i][0]<<(*list_ptr)[i][1]<<'\n';
}
data_file.close();
sprintf(load_data_command,load_data_command_format,j,j,tmp_file_name);
if (show_command) cout<<load_data_command;
if (plot_pipe) fputs(load_data_command,plot_pipe);
if (file_pipe) fputs(load_data_command,file_pipe);
// strcat(plot_command,plot_data_command_separator);
sprintf(data_plot_command,plot_data_command_format,j,j);
strcat(plot_command,data_plot_command);
if (curves_attributes.size()>(j-ind_file))
{
strcat(plot_command,plot_data_command_separator);
strcat(plot_command,attr_ptr->data());
}
if (curves_names.size()>(j-ind_file))
{
strcat(legend_command,",\'");
strcat(legend_command,(*lgd_ptr).data());
strcat(legend_command,"\'");
}
strcat(plot_command,")\n");
}
else
{
if (!data_file)
cout<<"curve_plot: file "<<tmp_file_name<<" could not be opened\n";
else
cout<<"curve_plot: plotting program not found\n";
}
list_ptr++;
lgd_ptr++;
attr_ptr++;
j++;
}
if (list_curves.size()>1) strcat(legend_command,")");
strcat(legend_command,legend_loc_command);
strcat(legend_command,")\n");
ind_file=j;
if (plot_pipe) fputs(fig_command, plot_pipe);
if (file_pipe) fputs(fig_command, file_pipe);
if (show_command) cout<<fig_command;
// strcat(plot_command,plot_closing_command);
if (show_command) cout<<plot_command;
if (plot_pipe) fputs(plot_command,plot_pipe);
if (file_pipe) fputs(plot_command,file_pipe);
if (curves_names.size()>0)
{
if (plot_pipe) fputs(legend_command,plot_pipe);
if (file_pipe) fputs(legend_command,file_pipe);
if (show_command) cout<<legend_command;
}
if (title[0])
{
if (plot_pipe) fputs(title_command,plot_pipe);
if (file_pipe) fputs(title_command,file_pipe);
}
if (xlabel[0])
{
if (plot_pipe) fputs(xlabel_command,plot_pipe);
if (file_pipe) fputs(xlabel_command,file_pipe);
}
if (ylabel[0])
{
if (plot_pipe) fputs(ylabel_command,plot_pipe);
if (file_pipe) fputs(ylabel_command,file_pipe);
}
if (xlims[0]!=xlims[1])
{
if (plot_pipe) fputs(xlims_command,plot_pipe);
if (file_pipe) fputs(xlims_command,file_pipe);
}
if (ylims[0]!=ylims[1])
{
if (plot_pipe) fputs(ylims_command,plot_pipe);
if (file_pipe) fputs(ylims_command,file_pipe);
}
if (extra_commands)
{
if (plot_pipe) fputs(extra_commands,plot_pipe);
if (file_pipe) fputs(extra_commands,file_pipe);
}
if (plot_pipe) fflush(plot_pipe);
if (file_pipe) fflush(file_pipe);
}
void graph_2D::plot_with_gnuplot(char *extra_commands, int fig_ind_p)
{
fstream data_file;
char tmp_file_name[100];
char plot_command[10000];
char data_plot_command[100];
open_pipe();
strcpy(plot_command,plot_function);
auto list_ptr=list_curves.begin();
int j=ind_file;
sprintf(tmp_file_name,tmp_file_name_format,j);
data_file.open(tmp_file_name,ios::out);
if (data_file && plot_pipe)
{
data_file<<setprecision(16)<<setiosflags(ios::left)<<setiosflags(ios::scientific);
for (int i=0; i<list_ptr->size(); i++)
{
data_file<<setw(30)<<(*list_ptr)[i][0]<<(*list_ptr)[i][1]<<'\n';
}
data_file.close();
sprintf(data_plot_command,plot_data_command_format,tmp_file_name);
strcat(plot_command,data_plot_command);
}
else
{
if (!data_file)
cout<<"curve_plot: open file failed\n";
else
cout<<"curve_plot: plotting program not found\n";
}
list_ptr++;
j++;
while (list_ptr!=list_curves.end())
{
sprintf(tmp_file_name,tmp_file_name_format,j);
data_file.open(tmp_file_name,ios::out);
if (data_file && plot_pipe)
{
data_file<<setprecision(16)<<setiosflags(ios::left)<<setiosflags(ios::scientific);
for (int i=0; i<list_ptr->size(); i++)
{
data_file<<setw(30)<<(*list_ptr)[i][0]<<(*list_ptr)[i][1]<<'\n';
}
data_file.close();
strcat(plot_command,plot_data_command_separator);
sprintf(data_plot_command,plot_data_command_format,tmp_file_name);
strcat(plot_command,data_plot_command);
}
else
{
if (!data_file)
cout<<"curve_plot: open file failed\n";
else
cout<<"curve_plot: plotting program not found\n";
}
list_ptr++;
j++;
}
ind_file=j;
strcat(plot_command,"\n");
if (show_command) cout<<plot_command<<'\n';
fputs(plot_command,plot_pipe);
fflush(plot_pipe);
getchar();
// fflush(plot_pipe);
// pclose(plot_pipe);
/*
for (int j=0; j<list_curves.size(); ++j)
{
sprintf(tmp_file_name,tmp_file_name_format,j);
remove(tmp_file_name);
}
*/
}
| 28.659758 | 151 | 0.667771 | [
"vector"
] |
3d3adaf7840964c9aff08eb3b308ac8203b3f19d | 1,601 | cpp | C++ | WeirdEngine/src/WeirdEngine/Source Files/SoundComponent.cpp | jeramauni/Proyecto-3 | 2dbdba99ef2899e498dea3eb9a085417773686d7 | [
"Apache-2.0"
] | null | null | null | WeirdEngine/src/WeirdEngine/Source Files/SoundComponent.cpp | jeramauni/Proyecto-3 | 2dbdba99ef2899e498dea3eb9a085417773686d7 | [
"Apache-2.0"
] | null | null | null | WeirdEngine/src/WeirdEngine/Source Files/SoundComponent.cpp | jeramauni/Proyecto-3 | 2dbdba99ef2899e498dea3eb9a085417773686d7 | [
"Apache-2.0"
] | null | null | null | #include "SoundComponent.h"
#include "ComponentFactory.h"
#include <AudioManager.h>
#include <iostream>
//CREATE_REGISTER(SoundComponent);
SoundComponent::SoundComponent(Container* e) {
_name = "Sound";
_parent = e;
audioManager = _parent->getWEManager()->getAudioManager();
}
void SoundComponent::Init(std::unordered_map<std::string, std::string>& param) {
//nombre
audioName = param.at("name");
fileName = param.at("filename");
//volumen
std::vector<std::string> aux;
aux = GetWords(param.at("volume"));
Vector3 collSize = Vector3(std::stof(aux[0]),
std::stof(aux[1]) ,
std::stof(aux[2]));
volume = collSize.x + collSize.y * 0.1 + collSize.z * 0.01;
//loop
if (param.at("loop") == "0") loop = false;
else loop = true;
//playStart
if (param.at("playStart") == "0") playStart = false;
else playStart = true;
//playEvent
if (param.at("playEvent") == "0") playEvent = false;
else playEvent = true;
audioManager->createSound(audioName, fileName);
}
void SoundComponent::receive(Container* c, const msg::Message& msg) {
switch (msg.type_) {
case msg::SWITCH_COMP: {
//_parent->activeComponent(_name);
break;
}
case msg::SCENE_OVER: {
audioManager->stop(ch);
//audioManager->releaseChannel();
break;
}
case msg::SCENE_START: {
if (playStart) ch = audioManager->play(audioName, volume, 1.0, loop);
break;
}
case msg::PLAY_SOUND: {
const msg::PlaySound _m = static_cast<const msg::PlaySound&>(msg);
if (_m._name == audioName) {
if (playEvent)
ch = audioManager->play(audioName, volume, 1.0, loop);
}
break;
}
default:
break;
}
}
| 22.549296 | 80 | 0.669582 | [
"vector"
] |
3d40d8deee3dad0cc17a7c41158d558aa4501261 | 11,538 | cpp | C++ | src/serializestruct/SerializerStruct.cpp | mnaveedb/finalmq | 3c3b2b213fa07bb5427a1364796b19d732890ed2 | [
"MIT"
] | 11 | 2020-10-13T11:50:29.000Z | 2022-02-27T11:47:34.000Z | src/serializestruct/SerializerStruct.cpp | mnaveedb/finalmq | 3c3b2b213fa07bb5427a1364796b19d732890ed2 | [
"MIT"
] | 15 | 2020-10-07T18:01:27.000Z | 2021-07-08T09:09:13.000Z | src/serializestruct/SerializerStruct.cpp | mnaveedb/finalmq | 3c3b2b213fa07bb5427a1364796b19d732890ed2 | [
"MIT"
] | 2 | 2020-10-07T21:29:06.000Z | 2020-10-14T18:02:17.000Z | //MIT License
//Copyright (c) 2020 bexoft GmbH (mail@bexoft.de)
//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 "finalmq/serializestruct/SerializerStruct.h"
#include "finalmq/serializevariant/VarValueToVariant.h"
#include "finalmq/serialize/ParserProcessDefaultValues.h"
#include "finalmq/metadata/MetaData.h"
#include "finalmq/variant/VariantValueStruct.h"
#include "finalmq/variant/VariantValueList.h"
#include "finalmq/variant/VariantValues.h"
#include <assert.h>
#include <algorithm>
namespace finalmq {
static const std::string STR_VARVALUE = "finalmq.variant.VarValue";
SerializerStruct::SerializerStruct(StructBase& root)
: ParserConverter()
, m_internal(*this, root)
{
setVisitor(m_internal);
}
void SerializerStruct::setExitNotification(std::function<void()> funcExit)
{
m_internal.setExitNotification(std::move(funcExit));
}
SerializerStruct::Internal::Internal(SerializerStruct& outer, StructBase& root)
: m_root(root)
, m_outer(outer)
{
m_root.clear();
m_stack.push_back({ &m_root, -1 });
m_current = &m_stack.back();
}
void SerializerStruct::Internal::setExitNotification(std::function<void()> funcExit)
{
m_funcExit = std::move(funcExit);
}
// IParserVisitor
void SerializerStruct::Internal::notifyError(const char* /*str*/, const char* /*message*/)
{
}
void SerializerStruct::Internal::startStruct(const MetaStruct& /*stru*/)
{
m_wasStartStructCalled = true;
}
void SerializerStruct::Internal::finished()
{
}
void SerializerStruct::Internal::enterStruct(const MetaField& field)
{
assert(!m_stack.empty());
assert(m_current);
if (m_wasStartStructCalled && field.typeName == STR_VARVALUE)
{
m_varValueToVariant = nullptr;
Variant* variant = nullptr;
if (m_current->structBase)
{
variant = m_current->structBase->getData<Variant>(field);
}
if (variant)
{
m_varValueToVariant = std::make_shared<VarValueToVariant>(*variant);
m_outer.ParserConverter::setVisitor(m_varValueToVariant->getVisitor());
m_varValueToVariant->setExitNotification([this, &field]() {
assert(m_varValueToVariant);
m_outer.ParserConverter::setVisitor(*this);
m_varValueToVariant->convert();
m_varValueToVariant->setExitNotification(nullptr);
});
}
else
{
m_current->structBase = nullptr;
}
}
else
{
StructBase* sub = nullptr;
if (m_current->structBase)
{
if (m_current->structArrayIndex == -1)
{
sub = m_current->structBase->getData<StructBase>(field);
}
else
{
sub = m_current->structBase->add(m_current->structArrayIndex);
}
}
m_stack.push_back({ sub, -1 });
m_current = &m_stack.back();
}
}
void SerializerStruct::Internal::exitStruct(const MetaField& /*field*/)
{
if (!m_stack.empty())
{
m_stack.pop_back();
if (!m_stack.empty())
{
m_current = &m_stack.back();
}
else
{
m_current = nullptr;
if (m_funcExit)
{
m_funcExit();
}
}
}
}
void SerializerStruct::Internal::enterArrayStruct(const MetaField& field)
{
assert(m_current);
m_current->structArrayIndex = field.index;
}
void SerializerStruct::Internal::exitArrayStruct(const MetaField& /*field*/)
{
assert(m_current);
m_current->structArrayIndex = -1;
}
template <class T>
void SerializerStruct::Internal::setValue(const MetaField& field, const T& value)
{
assert(m_current);
if (m_current->structBase)
{
T* pval = m_current->structBase->getData<T>(field);
if (pval)
{
*pval = value;
}
}
}
template <class T>
void SerializerStruct::Internal::setValue(const MetaField& field, T&& value)
{
assert(m_current);
if (m_current->structBase)
{
T* pval = m_current->structBase->getData<T>(field);
if (pval)
{
*pval = std::move(value);
}
}
}
void SerializerStruct::Internal::enterBool(const MetaField& field, bool value)
{
setValue<bool>(field, value);
}
void SerializerStruct::Internal::enterInt32(const MetaField& field, std::int32_t value)
{
setValue<std::int32_t>(field, value);
}
void SerializerStruct::Internal::enterUInt32(const MetaField& field, std::uint32_t value)
{
setValue<std::uint32_t>(field, value);
}
void SerializerStruct::Internal::enterInt64(const MetaField& field, std::int64_t value)
{
setValue<std::int64_t>(field, value);
}
void SerializerStruct::Internal::enterUInt64(const MetaField& field, std::uint64_t value)
{
setValue<std::uint64_t>(field, value);
}
void SerializerStruct::Internal::enterFloat(const MetaField& field, float value)
{
setValue<float>(field, value);
}
void SerializerStruct::Internal::enterDouble(const MetaField& field, double value)
{
setValue<double>(field, value);
}
void SerializerStruct::Internal::enterString(const MetaField& field, std::string&& value)
{
setValue(field, std::move(value));
}
void SerializerStruct::Internal::enterString(const MetaField& field, const char* value, ssize_t size)
{
setValue(field, std::string(value, size));
}
void SerializerStruct::Internal::enterBytes(const MetaField& field, Bytes&& value)
{
setValue(field, std::move(value));
}
void SerializerStruct::Internal::enterBytes(const MetaField& field, const BytesElement* value, ssize_t size)
{
setValue(field, Bytes(value, value + size));
}
void SerializerStruct::Internal::enterEnum(const MetaField& field, std::int32_t value)
{
bool validEnum = MetaDataGlobal::instance().isEnumValue(field, value);
setValue<std::int32_t>(field, validEnum ? value : 0);
}
void SerializerStruct::Internal::enterEnum(const MetaField& field, std::string&& value)
{
std::int32_t v = MetaDataGlobal::instance().getEnumValueByName(field, value);
setValue<std::int32_t>(field, v);
}
void SerializerStruct::Internal::enterEnum(const MetaField& field, const char* value, ssize_t size)
{
std::int32_t v = MetaDataGlobal::instance().getEnumValueByName(field, std::string(value, size));
setValue<std::int32_t>(field, v);
}
void SerializerStruct::Internal::enterArrayBoolMove(const MetaField& field, std::vector<bool>&& value)
{
setValue(field, std::move(value));
}
void SerializerStruct::Internal::enterArrayBool(const MetaField& field, const std::vector<bool>& value)
{
setValue(field, value);
}
void SerializerStruct::Internal::enterArrayInt32(const MetaField& field, std::vector<std::int32_t>&& value)
{
setValue(field, std::move(value));
}
void SerializerStruct::Internal::enterArrayInt32(const MetaField& field, const std::int32_t* value, ssize_t size)
{
setValue(field, std::vector<std::int32_t>(value, value + size));
}
void SerializerStruct::Internal::enterArrayUInt32(const MetaField& field, std::vector<std::uint32_t>&& value)
{
setValue(field, std::move(value));
}
void SerializerStruct::Internal::enterArrayUInt32(const MetaField& field, const std::uint32_t* value, ssize_t size)
{
setValue(field, std::vector<std::uint32_t>(value, value + size));
}
void SerializerStruct::Internal::enterArrayInt64(const MetaField& field, std::vector<std::int64_t>&& value)
{
setValue(field, std::move(value));
}
void SerializerStruct::Internal::enterArrayInt64(const MetaField& field, const std::int64_t* value, ssize_t size)
{
setValue(field, std::vector<std::int64_t>(value, value + size));
}
void SerializerStruct::Internal::enterArrayUInt64(const MetaField& field, std::vector<std::uint64_t>&& value)
{
setValue(field, std::move(value));
}
void SerializerStruct::Internal::enterArrayUInt64(const MetaField& field, const std::uint64_t* value, ssize_t size)
{
setValue(field, std::vector<std::uint64_t>(value, value + size));
}
void SerializerStruct::Internal::enterArrayFloat(const MetaField& field, std::vector<float>&& value)
{
setValue(field, std::move(value));
}
void SerializerStruct::Internal::enterArrayFloat(const MetaField& field, const float* value, ssize_t size)
{
setValue(field, std::vector<float>(value, value + size));
}
void SerializerStruct::Internal::enterArrayDouble(const MetaField& field, std::vector<double>&& value)
{
setValue(field, std::move(value));
}
void SerializerStruct::Internal::enterArrayDouble(const MetaField& field, const double* value, ssize_t size)
{
setValue(field, std::vector<double>(value, value + size));
}
void SerializerStruct::Internal::enterArrayStringMove(const MetaField& field, std::vector<std::string>&& value)
{
setValue(field, std::move(value));
}
void SerializerStruct::Internal::enterArrayString(const MetaField& field, const std::vector<std::string>& value)
{
setValue(field, value);
}
void SerializerStruct::Internal::enterArrayBytesMove(const MetaField& field, std::vector<Bytes>&& value)
{
setValue(field, std::move(value));
}
void SerializerStruct::Internal::enterArrayBytes(const MetaField& field, const std::vector<Bytes>& value)
{
setValue(field, value);
}
void SerializerStruct::Internal::enterArrayEnum(const MetaField& field, std::vector<std::int32_t>&& value)
{
enterArrayEnum(field, value.data(), value.size());
}
void SerializerStruct::Internal::enterArrayEnum(const MetaField& field, const std::int32_t* value, ssize_t size)
{
std::vector<std::int32_t> enums;
enums.reserve(size);
std::for_each(value, value + size, [this, &field, &enums] (const std::int32_t& entry) {
bool validEnum = MetaDataGlobal::instance().isEnumValue(field, entry);
enums.push_back(validEnum ? entry : 0);
});
setValue(field, std::move(enums));
}
void SerializerStruct::Internal::enterArrayEnumMove(const MetaField& field, std::vector<std::string>&& value)
{
enterArrayEnum(field, value);
}
void SerializerStruct::Internal::enterArrayEnum(const MetaField& field, const std::vector<std::string>& value)
{
std::vector<std::int32_t> enums;
enums.reserve(value.size());
std::for_each(value.begin(), value.end(), [this, &field, &enums] (const std::string& entry) {
std::int32_t v = MetaDataGlobal::instance().getEnumValueByName(field, entry);
enums.push_back(v);
});
setValue(field, std::move(enums));
}
} // namespace finalmq
| 28.98995 | 115 | 0.693448 | [
"vector"
] |
3d43e2a77aeec56cff1fc45409606f526503e2d7 | 2,518 | cpp | C++ | src/runtime_src/core/common/api/xrt_pipeline.cpp | mariodruiz/XRT | c2fe15ff3c3b3d329645d40073cf9f71b8222e15 | [
"Apache-2.0"
] | 359 | 2018-10-05T03:05:08.000Z | 2022-03-31T06:28:16.000Z | src/runtime_src/core/common/api/xrt_pipeline.cpp | mariodruiz/XRT | c2fe15ff3c3b3d329645d40073cf9f71b8222e15 | [
"Apache-2.0"
] | 5,832 | 2018-10-02T22:43:29.000Z | 2022-03-31T22:28:05.000Z | src/runtime_src/core/common/api/xrt_pipeline.cpp | mariodruiz/XRT | c2fe15ff3c3b3d329645d40073cf9f71b8222e15 | [
"Apache-2.0"
] | 442 | 2018-10-02T23:06:29.000Z | 2022-03-21T08:34:44.000Z | /*
* Copyright (C) 2020, Xilinx Inc - All rights reserved
* Xilinx Runtime (XRT) Experimental APIs
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may
* not use this file except in compliance with the License. A copy of the
* License is located 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.
*/
// This file implements XRT xclbin APIs as declared in
// core/include/experimental/xrt_enqueue.h
#define XCL_DRIVER_DLL_EXPORT // exporting xrt_pipeline.h
#define XRT_CORE_COMMON_SOURCE // in same dll as core_common
#include "core/include/experimental/xrt_pipeline.h"
#include "core/common/debug.h"
#include <memory>
#include <vector>
#include <functional>
#include <algorithm>
#ifdef _WIN32
# pragma warning( disable : 4244 )
#endif
namespace {
}
namespace xrt {
class pipeline_impl : public std::enable_shared_from_this<pipeline_impl>
{
event_queue m_queue;
unsigned long m_uid;
std::vector<pipeline::stage> m_stages;
public:
// Construct the pipeline implementation
pipeline_impl(const xrt::event_queue& q)
: m_queue(q)
{
static unsigned int count = 0;
m_uid = count++;
XRT_DEBUGF("pipeline_impl::pipeline_impl(%d)\n", m_uid);
}
// Event destructor added for debuggability.
~pipeline_impl()
{
XRT_DEBUGF("pipeline_impl::~pipeline_impl(%d)\n", m_uid);
}
xrt::event
execute(xrt::event event)
{
for (auto& s : m_stages)
event = s.enqueue(m_queue, {event});
return event;
}
const pipeline::stage&
add_stage(pipeline::stage&& s)
{
m_stages.push_back(std::move(s));
return m_stages.back(); // bug, cannot return reference (vector resize)
}
};
} // xrt
////////////////////////////////////////////////////////////////
// xrt_enqueue C++ API implmentations (xrt_pipeline.h)
////////////////////////////////////////////////////////////////
namespace xrt {
pipeline::
pipeline(const xrt::event_queue& q)
: m_impl(std::make_shared<pipeline_impl>(q))
{}
xrt::event
pipeline::
execute(xrt::event event)
{
return m_impl->execute(event);
}
const pipeline::stage&
pipeline::
add_stage(pipeline::stage&& s)
{
return m_impl->add_stage(std::move(s));
}
} // xrt
| 23.100917 | 76 | 0.672359 | [
"vector"
] |
3d585ba79a50653a83e2651d8e2c8e8088635607 | 6,135 | cpp | C++ | examples/particles/utils.cpp | dalihub/dali-demo | cd0ea861acbc3e25dc18571de3e82db61ea85fae | [
"Apache-2.0"
] | 8 | 2016-11-18T10:26:56.000Z | 2021-05-03T10:26:30.000Z | examples/particles/utils.cpp | dalihub/dali-demo | cd0ea861acbc3e25dc18571de3e82db61ea85fae | [
"Apache-2.0"
] | 2 | 2020-07-26T11:54:24.000Z | 2021-06-06T19:37:36.000Z | examples/particles/utils.cpp | dalihub/dali-demo | cd0ea861acbc3e25dc18571de3e82db61ea85fae | [
"Apache-2.0"
] | 6 | 2019-05-24T11:59:15.000Z | 2021-05-24T07:34:39.000Z | /*
* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* 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 "utils.h"
using namespace Dali;
Vector3 ToHueSaturationLightness(Vector3 rgb)
{
float min = std::min(rgb.r, std::min(rgb.g, rgb.b));
float max = std::max(rgb.r, std::max(rgb.g, rgb.b));
Vector3 hsl(max - min, 0.f, (max + min) * .5f);
if(hsl.x * hsl.x > .0f)
{
hsl.y = hsl.x / max;
if(max == rgb.r)
{
hsl.x = (rgb.g - rgb.b) / hsl.x;
}
else if(max == rgb.g)
{
hsl.x = 2.f + (rgb.b - rgb.r) / hsl.x;
}
else
{
hsl.x = 4.f + (rgb.r - rgb.g) / hsl.x;
}
hsl.x *= 60.f;
if(hsl.x < 0.f)
{
hsl.x += 360.f;
}
}
else
{
hsl.y = 0.f;
}
return hsl;
}
Vector3 FromHueSaturationLightness(Vector3 hsl)
{
Vector3 rgb;
if(hsl.y * hsl.y > 0.f)
{
if(hsl.x >= 360.f)
{
hsl.x -= 360.f;
}
hsl.x /= 60.f;
int i = FastFloor(hsl.x);
float ff = hsl.x - i;
float p = hsl.z * (1.0 - hsl.y);
float q = hsl.z * (1.0 - (hsl.y * ff));
float t = hsl.z * (1.0 - (hsl.y * (1.f - ff)));
switch(i)
{
case 0:
rgb.r = hsl.z;
rgb.g = t;
rgb.b = p;
break;
case 1:
rgb.r = q;
rgb.g = hsl.z;
rgb.b = p;
break;
case 2:
rgb.r = p;
rgb.g = hsl.z;
rgb.b = t;
break;
case 3:
rgb.r = p;
rgb.g = q;
rgb.b = hsl.z;
break;
case 4:
rgb.r = t;
rgb.g = p;
rgb.b = hsl.z;
break;
case 5:
default:
rgb.r = hsl.z;
rgb.g = p;
rgb.b = q;
break;
}
}
else
{
rgb = Vector3::ONE * hsl.z;
}
return rgb;
}
Geometry CreateCuboidWireframeGeometry()
{
//
// 2---3
// |- |-
// | 6---7
// | | | |
// 0-|-1 |
// -| -|
// 4---5
//
Vector3 vertexData[] = {
Vector3(-.5, -.5, -.5),
Vector3(.5, -.5, -.5),
Vector3(-.5, .5, -.5),
Vector3(.5, .5, -.5),
Vector3(-.5, -.5, .5),
Vector3(.5, -.5, .5),
Vector3(-.5, .5, .5),
Vector3(.5, .5, .5),
};
uint16_t indices[] = {
0, 1, 1, 3, 3, 2, 2, 0, 0, 4, 1, 5, 3, 7, 2, 6, 4, 5, 5, 7, 7, 6, 6, 4};
VertexBuffer vertexBuffer = VertexBuffer::New(Property::Map()
.Add("aPosition", Property::VECTOR3));
vertexBuffer.SetData(vertexData, std::extent<decltype(vertexData)>::value);
Geometry geometry = Geometry::New();
geometry.AddVertexBuffer(vertexBuffer);
geometry.SetIndexBuffer(indices, std::extent<decltype(indices)>::value);
geometry.SetType(Geometry::LINES);
return geometry;
}
Renderer CreateRenderer(TextureSet textures, Geometry geometry, Shader shader, uint32_t options)
{
Renderer renderer = Renderer::New(geometry, shader);
renderer.SetProperty(Renderer::Property::BLEND_MODE,
(options & OPTION_BLEND) ? BlendMode::ON : BlendMode::OFF);
renderer.SetProperty(Renderer::Property::DEPTH_TEST_MODE,
(options & OPTION_DEPTH_TEST) ? DepthTestMode::ON : DepthTestMode::OFF);
renderer.SetProperty(Renderer::Property::DEPTH_WRITE_MODE,
(options & OPTION_DEPTH_WRITE) ? DepthWriteMode::ON : DepthWriteMode::OFF);
renderer.SetProperty(Renderer::Property::FACE_CULLING_MODE, FaceCullingMode::BACK);
if(!textures)
{
textures = TextureSet::New();
}
renderer.SetTextures(textures);
return renderer;
}
void CenterActor(Actor actor)
{
actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
actor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
}
Actor CreateActor()
{
auto actor = Actor::New();
CenterActor(actor);
return actor;
}
Renderer CloneRenderer(Renderer original)
{
Geometry geom = original.GetGeometry();
Shader shader = original.GetShader();
Renderer clone = Renderer::New(geom, shader);
// Copy properties.
Property::IndexContainer indices;
original.GetPropertyIndices(indices);
for(auto& i : indices)
{
auto actualIndex = PropertyRanges::DEFAULT_RENDERER_PROPERTY_START_INDEX + i;
clone.SetProperty(actualIndex, original.GetProperty(actualIndex));
}
// Copy texture references (and create TextureSet, if there's any textures).
TextureSet ts = original.GetTextures();
clone.SetTextures(ts);
return clone;
}
Actor CloneActor(Actor original)
{
using namespace Dali;
auto clone = Actor::New();
clone.SetProperty(Actor::Property::NAME, original.GetProperty(Actor::Property::NAME));
// Copy properties.
// Don't copy every single one of them.
// Definitely don't copy resize policy related things, which will internally enable
// relayout, which in turn will result in losing the ability to set Z size.
for(auto i : {
Actor::Property::PARENT_ORIGIN,
Actor::Property::ANCHOR_POINT,
Actor::Property::SIZE,
Actor::Property::POSITION,
Actor::Property::ORIENTATION,
Actor::Property::SCALE,
Actor::Property::VISIBLE,
Actor::Property::COLOR,
Actor::Property::NAME,
})
{
clone.SetProperty(i, original.GetProperty(i));
}
// Clone renderers.
for(unsigned int i = 0; i < original.GetRendererCount(); ++i)
{
auto rClone = CloneRenderer(original.GetRendererAt(i));
clone.AddRenderer(rClone);
}
// Recurse into children.
for(unsigned int i = 0; i < original.GetChildCount(); ++i)
{
Actor newChild = CloneActor(original.GetChildAt(i));
clone.Add(newChild);
}
return clone;
}
| 24.153543 | 98 | 0.593317 | [
"geometry"
] |
3d5e63934f828be818770647a079e777210d37b0 | 1,146 | cpp | C++ | cradle/tests/alia/geometry.cpp | dotdecimal/open-cradle | f8b06f8d40b0f17ac8d2bf845a32fcd57bf5ce1d | [
"MIT"
] | null | null | null | cradle/tests/alia/geometry.cpp | dotdecimal/open-cradle | f8b06f8d40b0f17ac8d2bf845a32fcd57bf5ce1d | [
"MIT"
] | null | null | null | cradle/tests/alia/geometry.cpp | dotdecimal/open-cradle | f8b06f8d40b0f17ac8d2bf845a32fcd57bf5ce1d | [
"MIT"
] | 4 | 2018-09-28T17:12:54.000Z | 2022-03-20T14:22:29.000Z | #include <alia/geometry.hpp>
#define BOOST_TEST_MODULE id
#include "test.hpp"
BOOST_AUTO_TEST_CASE(id_test)
{
using namespace alia;
double epsilon = 0.00001;
double tolerance = 0.00011;
unit_cubic_bezier linear(
make_vector<double>(0, 0),
make_vector<double>(1, 1));
for (int i = 0; i <= 10; ++i)
{
BOOST_CHECK_SMALL(
eval_curve_at_x(linear, 0.1 * i, epsilon) - 0.1 * i,
tolerance);
}
unit_cubic_bezier nonlinear(
make_vector<double>(0.25, 0.1),
make_vector<double>(0.25, 1));
float test_values[11][2] = {
{ 1.0000f, 1.0000f },
{ 0.7965f, 0.9747f },
{ 0.6320f, 0.9056f },
{ 0.5005f, 0.8029f },
{ 0.3960f, 0.6768f },
{ 0.3125f, 0.5375f },
{ 0.2440f, 0.3952f },
{ 0.1845f, 0.2601f },
{ 0.1280f, 0.1424f },
{ 0.0685f, 0.0523f },
{ 0.0000f, 0.0000f } };
for (int i = 0; i != 11; ++i)
{
BOOST_CHECK_SMALL(
eval_curve_at_x(nonlinear, test_values[i][0], epsilon) -
test_values[i][1],
tolerance);
}
}
| 24.913043 | 68 | 0.518325 | [
"geometry"
] |
87dd8a13eceaaa9687f0cd3f26dc7404573b7f82 | 49,802 | hpp | C++ | cisco-ios-xe/ydk/models/cisco_ios_xe/DOCS_CABLE_DEVICE_MIB.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2016-12-02T05:45:49.000Z | 2022-02-10T19:32:54.000Z | cisco-ios-xe/ydk/models/cisco_ios_xe/DOCS_CABLE_DEVICE_MIB.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2017-03-27T15:22:38.000Z | 2019-11-05T08:30:16.000Z | cisco-ios-xe/ydk/models/cisco_ios_xe/DOCS_CABLE_DEVICE_MIB.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 11 | 2016-12-02T05:45:52.000Z | 2019-11-07T08:28:17.000Z | #ifndef _DOCS_CABLE_DEVICE_MIB_
#define _DOCS_CABLE_DEVICE_MIB_
#include <memory>
#include <vector>
#include <string>
#include <ydk/types.hpp>
#include <ydk/errors.hpp>
namespace cisco_ios_xe {
namespace DOCS_CABLE_DEVICE_MIB {
class DOCSCABLEDEVICEMIB : public ydk::Entity
{
public:
DOCSCABLEDEVICEMIB();
~DOCSCABLEDEVICEMIB();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::shared_ptr<ydk::Entity> clone_ptr() const override;
ydk::augment_capabilities_function get_augment_capabilities_function() const override;
std::string get_bundle_yang_models_location() const override;
std::string get_bundle_name() const override;
std::map<std::pair<std::string, std::string>, std::string> get_namespace_identity_lookup() const override;
class DocsDevBase; //type: DOCSCABLEDEVICEMIB::DocsDevBase
class DocsDevSoftware; //type: DOCSCABLEDEVICEMIB::DocsDevSoftware
class DocsDevServer; //type: DOCSCABLEDEVICEMIB::DocsDevServer
class DocsDevEvent; //type: DOCSCABLEDEVICEMIB::DocsDevEvent
class DocsDevFilter; //type: DOCSCABLEDEVICEMIB::DocsDevFilter
class DocsDevCpe; //type: DOCSCABLEDEVICEMIB::DocsDevCpe
class DocsDevNmAccessTable; //type: DOCSCABLEDEVICEMIB::DocsDevNmAccessTable
class DocsDevEvControlTable; //type: DOCSCABLEDEVICEMIB::DocsDevEvControlTable
class DocsDevEventTable; //type: DOCSCABLEDEVICEMIB::DocsDevEventTable
class DocsDevFilterLLCTable; //type: DOCSCABLEDEVICEMIB::DocsDevFilterLLCTable
class DocsDevFilterIpTable; //type: DOCSCABLEDEVICEMIB::DocsDevFilterIpTable
class DocsDevFilterPolicyTable; //type: DOCSCABLEDEVICEMIB::DocsDevFilterPolicyTable
class DocsDevFilterTosTable; //type: DOCSCABLEDEVICEMIB::DocsDevFilterTosTable
class DocsDevCpeTable; //type: DOCSCABLEDEVICEMIB::DocsDevCpeTable
class DocsDevCpeInetTable; //type: DOCSCABLEDEVICEMIB::DocsDevCpeInetTable
std::shared_ptr<cisco_ios_xe::DOCS_CABLE_DEVICE_MIB::DOCSCABLEDEVICEMIB::DocsDevBase> docsdevbase;
std::shared_ptr<cisco_ios_xe::DOCS_CABLE_DEVICE_MIB::DOCSCABLEDEVICEMIB::DocsDevSoftware> docsdevsoftware;
std::shared_ptr<cisco_ios_xe::DOCS_CABLE_DEVICE_MIB::DOCSCABLEDEVICEMIB::DocsDevServer> docsdevserver;
std::shared_ptr<cisco_ios_xe::DOCS_CABLE_DEVICE_MIB::DOCSCABLEDEVICEMIB::DocsDevEvent> docsdevevent;
std::shared_ptr<cisco_ios_xe::DOCS_CABLE_DEVICE_MIB::DOCSCABLEDEVICEMIB::DocsDevFilter> docsdevfilter;
std::shared_ptr<cisco_ios_xe::DOCS_CABLE_DEVICE_MIB::DOCSCABLEDEVICEMIB::DocsDevCpe> docsdevcpe;
std::shared_ptr<cisco_ios_xe::DOCS_CABLE_DEVICE_MIB::DOCSCABLEDEVICEMIB::DocsDevNmAccessTable> docsdevnmaccesstable;
std::shared_ptr<cisco_ios_xe::DOCS_CABLE_DEVICE_MIB::DOCSCABLEDEVICEMIB::DocsDevEvControlTable> docsdevevcontroltable;
std::shared_ptr<cisco_ios_xe::DOCS_CABLE_DEVICE_MIB::DOCSCABLEDEVICEMIB::DocsDevEventTable> docsdeveventtable;
std::shared_ptr<cisco_ios_xe::DOCS_CABLE_DEVICE_MIB::DOCSCABLEDEVICEMIB::DocsDevFilterLLCTable> docsdevfilterllctable;
std::shared_ptr<cisco_ios_xe::DOCS_CABLE_DEVICE_MIB::DOCSCABLEDEVICEMIB::DocsDevFilterIpTable> docsdevfilteriptable;
std::shared_ptr<cisco_ios_xe::DOCS_CABLE_DEVICE_MIB::DOCSCABLEDEVICEMIB::DocsDevFilterPolicyTable> docsdevfilterpolicytable;
std::shared_ptr<cisco_ios_xe::DOCS_CABLE_DEVICE_MIB::DOCSCABLEDEVICEMIB::DocsDevFilterTosTable> docsdevfiltertostable;
std::shared_ptr<cisco_ios_xe::DOCS_CABLE_DEVICE_MIB::DOCSCABLEDEVICEMIB::DocsDevCpeTable> docsdevcpetable;
std::shared_ptr<cisco_ios_xe::DOCS_CABLE_DEVICE_MIB::DOCSCABLEDEVICEMIB::DocsDevCpeInetTable> docsdevcpeinettable;
}; // DOCSCABLEDEVICEMIB
class DOCSCABLEDEVICEMIB::DocsDevBase : public ydk::Entity
{
public:
DocsDevBase();
~DocsDevBase();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf docsdevrole; //type: DocsDevRole
ydk::YLeaf docsdevdatetime; //type: string
ydk::YLeaf docsdevresetnow; //type: boolean
ydk::YLeaf docsdevserialnumber; //type: string
ydk::YLeaf docsdevstpcontrol; //type: DocsDevSTPControl
ydk::YLeaf docsdevigmpmodecontrol; //type: DocsDevIgmpModeControl
ydk::YLeaf docsdevmaxcpe; //type: uint32
class DocsDevRole;
class DocsDevSTPControl;
class DocsDevIgmpModeControl;
}; // DOCSCABLEDEVICEMIB::DocsDevBase
class DOCSCABLEDEVICEMIB::DocsDevSoftware : public ydk::Entity
{
public:
DocsDevSoftware();
~DocsDevSoftware();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf docsdevswserver; //type: string
ydk::YLeaf docsdevswfilename; //type: string
ydk::YLeaf docsdevswadminstatus; //type: DocsDevSwAdminStatus
ydk::YLeaf docsdevswoperstatus; //type: DocsDevSwOperStatus
ydk::YLeaf docsdevswcurrentvers; //type: string
ydk::YLeaf docsdevswserveraddresstype; //type: InetAddressType
ydk::YLeaf docsdevswserveraddress; //type: binary
ydk::YLeaf docsdevswservertransportprotocol; //type: DocsDevSwServerTransportProtocol
class DocsDevSwAdminStatus;
class DocsDevSwOperStatus;
class DocsDevSwServerTransportProtocol;
}; // DOCSCABLEDEVICEMIB::DocsDevSoftware
class DOCSCABLEDEVICEMIB::DocsDevServer : public ydk::Entity
{
public:
DocsDevServer();
~DocsDevServer();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf docsdevserverbootstate; //type: DocsDevServerBootState
ydk::YLeaf docsdevserverdhcp; //type: string
ydk::YLeaf docsdevservertime; //type: string
ydk::YLeaf docsdevservertftp; //type: string
ydk::YLeaf docsdevserverconfigfile; //type: string
ydk::YLeaf docsdevserverdhcpaddresstype; //type: InetAddressType
ydk::YLeaf docsdevserverdhcpaddress; //type: binary
ydk::YLeaf docsdevservertimeaddresstype; //type: InetAddressType
ydk::YLeaf docsdevservertimeaddress; //type: binary
ydk::YLeaf docsdevserverconfigtftpaddresstype; //type: InetAddressType
ydk::YLeaf docsdevserverconfigtftpaddress; //type: binary
class DocsDevServerBootState;
}; // DOCSCABLEDEVICEMIB::DocsDevServer
class DOCSCABLEDEVICEMIB::DocsDevEvent : public ydk::Entity
{
public:
DocsDevEvent();
~DocsDevEvent();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf docsdevevcontrol; //type: DocsDevEvControl
ydk::YLeaf docsdevevsyslog; //type: string
ydk::YLeaf docsdevevthrottleadminstatus; //type: DocsDevEvThrottleAdminStatus
ydk::YLeaf docsdevevthrottleinhibited; //type: boolean
ydk::YLeaf docsdevevthrottlethreshold; //type: uint32
ydk::YLeaf docsdevevthrottleinterval; //type: int32
ydk::YLeaf docsdevevsyslogaddresstype; //type: InetAddressType
ydk::YLeaf docsdevevsyslogaddress; //type: binary
ydk::YLeaf docsdevevthrottlethresholdexceeded; //type: boolean
class DocsDevEvControl;
class DocsDevEvThrottleAdminStatus;
}; // DOCSCABLEDEVICEMIB::DocsDevEvent
class DOCSCABLEDEVICEMIB::DocsDevFilter : public ydk::Entity
{
public:
DocsDevFilter();
~DocsDevFilter();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf docsdevfilterllcunmatchedaction; //type: DocsDevFilterLLCUnmatchedAction
ydk::YLeaf docsdevfilteripdefault; //type: DocsDevFilterIpDefault
class DocsDevFilterLLCUnmatchedAction;
class DocsDevFilterIpDefault;
}; // DOCSCABLEDEVICEMIB::DocsDevFilter
class DOCSCABLEDEVICEMIB::DocsDevCpe : public ydk::Entity
{
public:
DocsDevCpe();
~DocsDevCpe();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf docsdevcpeenroll; //type: DocsDevCpeEnroll
ydk::YLeaf docsdevcpeipmax; //type: int32
class DocsDevCpeEnroll;
}; // DOCSCABLEDEVICEMIB::DocsDevCpe
class DOCSCABLEDEVICEMIB::DocsDevNmAccessTable : public ydk::Entity
{
public:
DocsDevNmAccessTable();
~DocsDevNmAccessTable();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class DocsDevNmAccessEntry; //type: DOCSCABLEDEVICEMIB::DocsDevNmAccessTable::DocsDevNmAccessEntry
ydk::YList docsdevnmaccessentry;
}; // DOCSCABLEDEVICEMIB::DocsDevNmAccessTable
class DOCSCABLEDEVICEMIB::DocsDevNmAccessTable::DocsDevNmAccessEntry : public ydk::Entity
{
public:
DocsDevNmAccessEntry();
~DocsDevNmAccessEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf docsdevnmaccessindex; //type: int32
ydk::YLeaf docsdevnmaccessip; //type: string
ydk::YLeaf docsdevnmaccessipmask; //type: string
ydk::YLeaf docsdevnmaccesscommunity; //type: binary
ydk::YLeaf docsdevnmaccesscontrol; //type: DocsDevNmAccessControl
ydk::YLeaf docsdevnmaccessinterfaces; //type: binary
ydk::YLeaf docsdevnmaccessstatus; //type: RowStatus
ydk::YLeaf docsdevnmaccesstrapversion; //type: DocsDevNmAccessTrapVersion
class DocsDevNmAccessControl;
class DocsDevNmAccessTrapVersion;
}; // DOCSCABLEDEVICEMIB::DocsDevNmAccessTable::DocsDevNmAccessEntry
class DOCSCABLEDEVICEMIB::DocsDevEvControlTable : public ydk::Entity
{
public:
DocsDevEvControlTable();
~DocsDevEvControlTable();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class DocsDevEvControlEntry; //type: DOCSCABLEDEVICEMIB::DocsDevEvControlTable::DocsDevEvControlEntry
ydk::YList docsdevevcontrolentry;
}; // DOCSCABLEDEVICEMIB::DocsDevEvControlTable
class DOCSCABLEDEVICEMIB::DocsDevEvControlTable::DocsDevEvControlEntry : public ydk::Entity
{
public:
DocsDevEvControlEntry();
~DocsDevEvControlEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf docsdevevpriority; //type: DocsDevEvPriority
ydk::YLeaf docsdevevreporting; //type: binary
class DocsDevEvPriority;
}; // DOCSCABLEDEVICEMIB::DocsDevEvControlTable::DocsDevEvControlEntry
class DOCSCABLEDEVICEMIB::DocsDevEventTable : public ydk::Entity
{
public:
DocsDevEventTable();
~DocsDevEventTable();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class DocsDevEventEntry; //type: DOCSCABLEDEVICEMIB::DocsDevEventTable::DocsDevEventEntry
ydk::YList docsdevevententry;
}; // DOCSCABLEDEVICEMIB::DocsDevEventTable
class DOCSCABLEDEVICEMIB::DocsDevEventTable::DocsDevEventEntry : public ydk::Entity
{
public:
DocsDevEventEntry();
~DocsDevEventEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf docsdevevindex; //type: int32
ydk::YLeaf docsdevevfirsttime; //type: string
ydk::YLeaf docsdevevlasttime; //type: string
ydk::YLeaf docsdevevcounts; //type: uint32
ydk::YLeaf docsdevevlevel; //type: DocsDevEvLevel
ydk::YLeaf docsdevevid; //type: uint32
ydk::YLeaf docsdevevtext; //type: string
class DocsDevEvLevel;
}; // DOCSCABLEDEVICEMIB::DocsDevEventTable::DocsDevEventEntry
class DOCSCABLEDEVICEMIB::DocsDevFilterLLCTable : public ydk::Entity
{
public:
DocsDevFilterLLCTable();
~DocsDevFilterLLCTable();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class DocsDevFilterLLCEntry; //type: DOCSCABLEDEVICEMIB::DocsDevFilterLLCTable::DocsDevFilterLLCEntry
ydk::YList docsdevfilterllcentry;
}; // DOCSCABLEDEVICEMIB::DocsDevFilterLLCTable
class DOCSCABLEDEVICEMIB::DocsDevFilterLLCTable::DocsDevFilterLLCEntry : public ydk::Entity
{
public:
DocsDevFilterLLCEntry();
~DocsDevFilterLLCEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf docsdevfilterllcindex; //type: int32
ydk::YLeaf docsdevfilterllcstatus; //type: RowStatus
ydk::YLeaf docsdevfilterllcifindex; //type: int32
ydk::YLeaf docsdevfilterllcprotocoltype; //type: DocsDevFilterLLCProtocolType
ydk::YLeaf docsdevfilterllcprotocol; //type: int32
ydk::YLeaf docsdevfilterllcmatches; //type: uint32
class DocsDevFilterLLCProtocolType;
}; // DOCSCABLEDEVICEMIB::DocsDevFilterLLCTable::DocsDevFilterLLCEntry
class DOCSCABLEDEVICEMIB::DocsDevFilterIpTable : public ydk::Entity
{
public:
DocsDevFilterIpTable();
~DocsDevFilterIpTable();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class DocsDevFilterIpEntry; //type: DOCSCABLEDEVICEMIB::DocsDevFilterIpTable::DocsDevFilterIpEntry
ydk::YList docsdevfilteripentry;
}; // DOCSCABLEDEVICEMIB::DocsDevFilterIpTable
class DOCSCABLEDEVICEMIB::DocsDevFilterIpTable::DocsDevFilterIpEntry : public ydk::Entity
{
public:
DocsDevFilterIpEntry();
~DocsDevFilterIpEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf docsdevfilteripindex; //type: int32
ydk::YLeaf docsdevfilteripstatus; //type: RowStatus
ydk::YLeaf docsdevfilteripcontrol; //type: DocsDevFilterIpControl
ydk::YLeaf docsdevfilteripifindex; //type: int32
ydk::YLeaf docsdevfilteripdirection; //type: DocsDevFilterIpDirection
ydk::YLeaf docsdevfilteripbroadcast; //type: boolean
ydk::YLeaf docsdevfilteripsaddr; //type: string
ydk::YLeaf docsdevfilteripsmask; //type: string
ydk::YLeaf docsdevfilteripdaddr; //type: string
ydk::YLeaf docsdevfilteripdmask; //type: string
ydk::YLeaf docsdevfilteripprotocol; //type: int32
ydk::YLeaf docsdevfilteripsourceportlow; //type: int32
ydk::YLeaf docsdevfilteripsourceporthigh; //type: int32
ydk::YLeaf docsdevfilteripdestportlow; //type: int32
ydk::YLeaf docsdevfilteripdestporthigh; //type: int32
ydk::YLeaf docsdevfilteripmatches; //type: uint32
ydk::YLeaf docsdevfilteriptos; //type: binary
ydk::YLeaf docsdevfilteriptosmask; //type: binary
ydk::YLeaf docsdevfilteripcontinue; //type: boolean
ydk::YLeaf docsdevfilterippolicyid; //type: int32
class DocsDevFilterIpControl;
class DocsDevFilterIpDirection;
}; // DOCSCABLEDEVICEMIB::DocsDevFilterIpTable::DocsDevFilterIpEntry
class DOCSCABLEDEVICEMIB::DocsDevFilterPolicyTable : public ydk::Entity
{
public:
DocsDevFilterPolicyTable();
~DocsDevFilterPolicyTable();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class DocsDevFilterPolicyEntry; //type: DOCSCABLEDEVICEMIB::DocsDevFilterPolicyTable::DocsDevFilterPolicyEntry
ydk::YList docsdevfilterpolicyentry;
}; // DOCSCABLEDEVICEMIB::DocsDevFilterPolicyTable
class DOCSCABLEDEVICEMIB::DocsDevFilterPolicyTable::DocsDevFilterPolicyEntry : public ydk::Entity
{
public:
DocsDevFilterPolicyEntry();
~DocsDevFilterPolicyEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf docsdevfilterpolicyindex; //type: int32
ydk::YLeaf docsdevfilterpolicyid; //type: int32
ydk::YLeaf docsdevfilterpolicystatus; //type: RowStatus
ydk::YLeaf docsdevfilterpolicyptr; //type: string
}; // DOCSCABLEDEVICEMIB::DocsDevFilterPolicyTable::DocsDevFilterPolicyEntry
class DOCSCABLEDEVICEMIB::DocsDevFilterTosTable : public ydk::Entity
{
public:
DocsDevFilterTosTable();
~DocsDevFilterTosTable();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class DocsDevFilterTosEntry; //type: DOCSCABLEDEVICEMIB::DocsDevFilterTosTable::DocsDevFilterTosEntry
ydk::YList docsdevfiltertosentry;
}; // DOCSCABLEDEVICEMIB::DocsDevFilterTosTable
class DOCSCABLEDEVICEMIB::DocsDevFilterTosTable::DocsDevFilterTosEntry : public ydk::Entity
{
public:
DocsDevFilterTosEntry();
~DocsDevFilterTosEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf docsdevfiltertosindex; //type: int32
ydk::YLeaf docsdevfiltertosstatus; //type: RowStatus
ydk::YLeaf docsdevfiltertosandmask; //type: binary
ydk::YLeaf docsdevfiltertosormask; //type: binary
}; // DOCSCABLEDEVICEMIB::DocsDevFilterTosTable::DocsDevFilterTosEntry
class DOCSCABLEDEVICEMIB::DocsDevCpeTable : public ydk::Entity
{
public:
DocsDevCpeTable();
~DocsDevCpeTable();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class DocsDevCpeEntry; //type: DOCSCABLEDEVICEMIB::DocsDevCpeTable::DocsDevCpeEntry
ydk::YList docsdevcpeentry;
}; // DOCSCABLEDEVICEMIB::DocsDevCpeTable
class DOCSCABLEDEVICEMIB::DocsDevCpeTable::DocsDevCpeEntry : public ydk::Entity
{
public:
DocsDevCpeEntry();
~DocsDevCpeEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf docsdevcpeip; //type: string
ydk::YLeaf docsdevcpesource; //type: DocsDevCpeSource
ydk::YLeaf docsdevcpestatus; //type: RowStatus
class DocsDevCpeSource;
}; // DOCSCABLEDEVICEMIB::DocsDevCpeTable::DocsDevCpeEntry
class DOCSCABLEDEVICEMIB::DocsDevCpeInetTable : public ydk::Entity
{
public:
DocsDevCpeInetTable();
~DocsDevCpeInetTable();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class DocsDevCpeInetEntry; //type: DOCSCABLEDEVICEMIB::DocsDevCpeInetTable::DocsDevCpeInetEntry
ydk::YList docsdevcpeinetentry;
}; // DOCSCABLEDEVICEMIB::DocsDevCpeInetTable
class DOCSCABLEDEVICEMIB::DocsDevCpeInetTable::DocsDevCpeInetEntry : public ydk::Entity
{
public:
DocsDevCpeInetEntry();
~DocsDevCpeInetEntry();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf docsdevcpeinettype; //type: InetAddressType
ydk::YLeaf docsdevcpeinetaddr; //type: binary
ydk::YLeaf docsdevcpeinetsource; //type: DocsDevCpeInetSource
ydk::YLeaf docsdevcpeinetrowstatus; //type: RowStatus
class DocsDevCpeInetSource;
}; // DOCSCABLEDEVICEMIB::DocsDevCpeInetTable::DocsDevCpeInetEntry
class DOCSCABLEDEVICEMIB::DocsDevBase::DocsDevRole : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf cm;
static const ydk::Enum::YLeaf cmtsActive;
static const ydk::Enum::YLeaf cmtsBackup;
static int get_enum_value(const std::string & name) {
if (name == "cm") return 1;
if (name == "cmtsActive") return 2;
if (name == "cmtsBackup") return 3;
return -1;
}
};
class DOCSCABLEDEVICEMIB::DocsDevBase::DocsDevSTPControl : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf stEnabled;
static const ydk::Enum::YLeaf noStFilterBpdu;
static const ydk::Enum::YLeaf noStPassBpdu;
static int get_enum_value(const std::string & name) {
if (name == "stEnabled") return 1;
if (name == "noStFilterBpdu") return 2;
if (name == "noStPassBpdu") return 3;
return -1;
}
};
class DOCSCABLEDEVICEMIB::DocsDevBase::DocsDevIgmpModeControl : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf passive;
static const ydk::Enum::YLeaf active;
static int get_enum_value(const std::string & name) {
if (name == "passive") return 1;
if (name == "active") return 2;
return -1;
}
};
class DOCSCABLEDEVICEMIB::DocsDevSoftware::DocsDevSwAdminStatus : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf upgradeFromMgt;
static const ydk::Enum::YLeaf allowProvisioningUpgrade;
static const ydk::Enum::YLeaf ignoreProvisioningUpgrade;
static int get_enum_value(const std::string & name) {
if (name == "upgradeFromMgt") return 1;
if (name == "allowProvisioningUpgrade") return 2;
if (name == "ignoreProvisioningUpgrade") return 3;
return -1;
}
};
class DOCSCABLEDEVICEMIB::DocsDevSoftware::DocsDevSwOperStatus : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf inProgress;
static const ydk::Enum::YLeaf completeFromProvisioning;
static const ydk::Enum::YLeaf completeFromMgt;
static const ydk::Enum::YLeaf failed;
static const ydk::Enum::YLeaf other;
static int get_enum_value(const std::string & name) {
if (name == "inProgress") return 1;
if (name == "completeFromProvisioning") return 2;
if (name == "completeFromMgt") return 3;
if (name == "failed") return 4;
if (name == "other") return 5;
return -1;
}
};
class DOCSCABLEDEVICEMIB::DocsDevSoftware::DocsDevSwServerTransportProtocol : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf tftp;
static const ydk::Enum::YLeaf http;
static int get_enum_value(const std::string & name) {
if (name == "tftp") return 1;
if (name == "http") return 2;
return -1;
}
};
class DOCSCABLEDEVICEMIB::DocsDevServer::DocsDevServerBootState : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf operational;
static const ydk::Enum::YLeaf disabled;
static const ydk::Enum::YLeaf waitingForDhcpOffer;
static const ydk::Enum::YLeaf waitingForDhcpResponse;
static const ydk::Enum::YLeaf waitingForTimeServer;
static const ydk::Enum::YLeaf waitingForTftp;
static const ydk::Enum::YLeaf refusedByCmts;
static const ydk::Enum::YLeaf forwardingDenied;
static const ydk::Enum::YLeaf other;
static const ydk::Enum::YLeaf unknown;
static int get_enum_value(const std::string & name) {
if (name == "operational") return 1;
if (name == "disabled") return 2;
if (name == "waitingForDhcpOffer") return 3;
if (name == "waitingForDhcpResponse") return 4;
if (name == "waitingForTimeServer") return 5;
if (name == "waitingForTftp") return 6;
if (name == "refusedByCmts") return 7;
if (name == "forwardingDenied") return 8;
if (name == "other") return 9;
if (name == "unknown") return 10;
return -1;
}
};
class DOCSCABLEDEVICEMIB::DocsDevEvent::DocsDevEvControl : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf resetLog;
static const ydk::Enum::YLeaf useDefaultReporting;
static int get_enum_value(const std::string & name) {
if (name == "resetLog") return 1;
if (name == "useDefaultReporting") return 2;
return -1;
}
};
class DOCSCABLEDEVICEMIB::DocsDevEvent::DocsDevEvThrottleAdminStatus : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf unconstrained;
static const ydk::Enum::YLeaf maintainBelowThreshold;
static const ydk::Enum::YLeaf stopAtThreshold;
static const ydk::Enum::YLeaf inhibited;
static int get_enum_value(const std::string & name) {
if (name == "unconstrained") return 1;
if (name == "maintainBelowThreshold") return 2;
if (name == "stopAtThreshold") return 3;
if (name == "inhibited") return 4;
return -1;
}
};
class DOCSCABLEDEVICEMIB::DocsDevFilter::DocsDevFilterLLCUnmatchedAction : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf discard;
static const ydk::Enum::YLeaf accept;
static int get_enum_value(const std::string & name) {
if (name == "discard") return 1;
if (name == "accept") return 2;
return -1;
}
};
class DOCSCABLEDEVICEMIB::DocsDevFilter::DocsDevFilterIpDefault : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf discard;
static const ydk::Enum::YLeaf accept;
static int get_enum_value(const std::string & name) {
if (name == "discard") return 1;
if (name == "accept") return 2;
return -1;
}
};
class DOCSCABLEDEVICEMIB::DocsDevCpe::DocsDevCpeEnroll : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf none;
static const ydk::Enum::YLeaf any;
static int get_enum_value(const std::string & name) {
if (name == "none") return 1;
if (name == "any") return 2;
return -1;
}
};
class DOCSCABLEDEVICEMIB::DocsDevNmAccessTable::DocsDevNmAccessEntry::DocsDevNmAccessControl : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf none;
static const ydk::Enum::YLeaf read;
static const ydk::Enum::YLeaf readWrite;
static const ydk::Enum::YLeaf roWithTraps;
static const ydk::Enum::YLeaf rwWithTraps;
static const ydk::Enum::YLeaf trapsOnly;
static int get_enum_value(const std::string & name) {
if (name == "none") return 1;
if (name == "read") return 2;
if (name == "readWrite") return 3;
if (name == "roWithTraps") return 4;
if (name == "rwWithTraps") return 5;
if (name == "trapsOnly") return 6;
return -1;
}
};
class DOCSCABLEDEVICEMIB::DocsDevNmAccessTable::DocsDevNmAccessEntry::DocsDevNmAccessTrapVersion : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf disableSNMPv2trap;
static const ydk::Enum::YLeaf enableSNMPv2trap;
static int get_enum_value(const std::string & name) {
if (name == "disableSNMPv2trap") return 1;
if (name == "enableSNMPv2trap") return 2;
return -1;
}
};
class DOCSCABLEDEVICEMIB::DocsDevEvControlTable::DocsDevEvControlEntry::DocsDevEvPriority : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf emergency;
static const ydk::Enum::YLeaf alert;
static const ydk::Enum::YLeaf critical;
static const ydk::Enum::YLeaf error;
static const ydk::Enum::YLeaf warning;
static const ydk::Enum::YLeaf notice;
static const ydk::Enum::YLeaf information;
static const ydk::Enum::YLeaf debug;
static int get_enum_value(const std::string & name) {
if (name == "emergency") return 1;
if (name == "alert") return 2;
if (name == "critical") return 3;
if (name == "error") return 4;
if (name == "warning") return 5;
if (name == "notice") return 6;
if (name == "information") return 7;
if (name == "debug") return 8;
return -1;
}
};
class DOCSCABLEDEVICEMIB::DocsDevEventTable::DocsDevEventEntry::DocsDevEvLevel : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf emergency;
static const ydk::Enum::YLeaf alert;
static const ydk::Enum::YLeaf critical;
static const ydk::Enum::YLeaf error;
static const ydk::Enum::YLeaf warning;
static const ydk::Enum::YLeaf notice;
static const ydk::Enum::YLeaf information;
static const ydk::Enum::YLeaf debug;
static int get_enum_value(const std::string & name) {
if (name == "emergency") return 1;
if (name == "alert") return 2;
if (name == "critical") return 3;
if (name == "error") return 4;
if (name == "warning") return 5;
if (name == "notice") return 6;
if (name == "information") return 7;
if (name == "debug") return 8;
return -1;
}
};
class DOCSCABLEDEVICEMIB::DocsDevFilterLLCTable::DocsDevFilterLLCEntry::DocsDevFilterLLCProtocolType : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf ethertype;
static const ydk::Enum::YLeaf dsap;
static int get_enum_value(const std::string & name) {
if (name == "ethertype") return 1;
if (name == "dsap") return 2;
return -1;
}
};
class DOCSCABLEDEVICEMIB::DocsDevFilterIpTable::DocsDevFilterIpEntry::DocsDevFilterIpControl : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf discard;
static const ydk::Enum::YLeaf accept;
static const ydk::Enum::YLeaf policy;
static int get_enum_value(const std::string & name) {
if (name == "discard") return 1;
if (name == "accept") return 2;
if (name == "policy") return 3;
return -1;
}
};
class DOCSCABLEDEVICEMIB::DocsDevFilterIpTable::DocsDevFilterIpEntry::DocsDevFilterIpDirection : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf inbound;
static const ydk::Enum::YLeaf outbound;
static const ydk::Enum::YLeaf both;
static int get_enum_value(const std::string & name) {
if (name == "inbound") return 1;
if (name == "outbound") return 2;
if (name == "both") return 3;
return -1;
}
};
class DOCSCABLEDEVICEMIB::DocsDevCpeTable::DocsDevCpeEntry::DocsDevCpeSource : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf other;
static const ydk::Enum::YLeaf manual;
static const ydk::Enum::YLeaf learned;
static int get_enum_value(const std::string & name) {
if (name == "other") return 1;
if (name == "manual") return 2;
if (name == "learned") return 3;
return -1;
}
};
class DOCSCABLEDEVICEMIB::DocsDevCpeInetTable::DocsDevCpeInetEntry::DocsDevCpeInetSource : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf manual;
static const ydk::Enum::YLeaf learned;
static int get_enum_value(const std::string & name) {
if (name == "manual") return 2;
if (name == "learned") return 3;
return -1;
}
};
}
}
#endif /* _DOCS_CABLE_DEVICE_MIB_ */
| 46.674789 | 162 | 0.688868 | [
"vector"
] |
87ddd11a57ae137d4ff52f3c4d73b09642456bc5 | 15,795 | cpp | C++ | example/main.cpp | jamesu/libDTShape | d6bd9a705fb45ac1dc95a04ac0096fc724fd14b5 | [
"MIT"
] | 2 | 2019-05-14T07:55:45.000Z | 2020-12-31T11:06:27.000Z | example/main.cpp | jamesu/libDTShape | d6bd9a705fb45ac1dc95a04ac0096fc724fd14b5 | [
"MIT"
] | null | null | null | example/main.cpp | jamesu/libDTShape | d6bd9a705fb45ac1dc95a04ac0096fc724fd14b5 | [
"MIT"
] | 3 | 2016-09-11T03:08:56.000Z | 2019-05-14T07:55:48.000Z | /*
Copyright (C) 2019 James S Urquhart
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 "platform/platform.h"
#define GL_GLEXT_PROTOTYPES
#include "SDL.h"
#include <stdio.h>
#include "libdtshape.h"
#include "ts/tsShape.h"
#include "ts/tsShapeInstance.h"
#include "ts/tsRenderState.h"
#include "ts/tsMaterialManager.h"
#include "core/color.h"
#include "math/mMath.h"
#include "math/util/frustum.h"
#include "core/stream/fileStream.h"
extern "C"
{
#include "soil/SOIL.h"
}
#include "main.h"
using namespace DTShape;
bool gUseMetal;
// Generic interface which provides scene info to the rendering code
class GenericTSSceneRenderState : public TSSceneRenderState
{
public:
MatrixF mWorldMatrix;
MatrixF mViewMatrix;
MatrixF mProjectionMatrix;
GenericTSSceneRenderState()
{
mWorldMatrix = MatrixF(1);
mViewMatrix = MatrixF(1);
mProjectionMatrix = MatrixF(1);
}
~GenericTSSceneRenderState()
{
}
virtual TSMaterialInstance *getOverrideMaterial( TSMaterialInstance *inst ) const
{
return inst;
}
virtual Point3F getCameraPosition() const
{
return mViewMatrix.getPosition();
}
virtual Point3F getDiffuseCameraPosition() const
{
return mViewMatrix.getPosition();
}
virtual RectF getViewport() const
{
return RectF(0,0,800,600);
}
virtual Point2F getWorldToScreenScale() const
{
return Point2F(1,1);
}
virtual const MatrixF *getWorldMatrix() const
{
return &mWorldMatrix;
}
virtual bool isShadowPass() const
{
return false;
}
// Shared matrix stuff
virtual const MatrixF *getViewMatrix() const
{
return &mViewMatrix;
}
virtual const MatrixF *getProjectionMatrix() const
{
return &mProjectionMatrix;
}
};
#define TICK_TIME 15
const char* GetAssetPath(const char *file);
// DTS Sequences for sample shape
const char* sTSAppSequenceNames[] = {
"Root",
"Forward",
"Crouch_Backward",
"Side",
"Jump",
"invalid"
};
AnimSequenceInfo sAppSequenceInfos[] = {
{50, 109, true},
{150, 169, true},
{460, 489, true},
{200, 219, true},
{1000, 1010, false}
};
AppState *AppState::sInstance = NULL;
using namespace DTShape;
TSMaterialManager *TSMaterialManager::instance()
{
return AppState::getInstance()->mMaterialManager;
}
AppState::AppState()
{
running = false;
mWindow = NULL;
dStrcpy(shapeToLoad, "cube.dae");
sInstance = this;
sShape = NULL;
sShapeInstance = NULL;
sThread = NULL;
sCurrentSequenceIdx = 0;
for (int i=0; i<kNumTSAppSequences; i++)
sSequences[i] = -1;
sRot = 180.0f;
sDeltaRot = 0.0f;
sCameraPosition = Point3F(0,-10,1);
sModelPosition = Point3F(0,0,0);
deltaCameraPos = Point3F(0,0,0);
sOldTicks = 0;
mFrame = 0;
sRenderState = NULL;
}
AppState::~AppState()
{
if (sRenderState)
delete sRenderState;
if (mMaterialManager)
delete mMaterialManager;
CleanupShape();
if (mRenderer)
delete mRenderer;
if (mSDLRenderer)
{
SDL_DestroyRenderer(mSDLRenderer);
}
if (mWindow)
{
SDL_DestroyWindow(mWindow);
}
sInstance = NULL;
}
void AppState::onKeyChanged(int key, int state)
{
switch (key)
{
case SDLK_ESCAPE:
SDL_Quit();
break;
case SDLK_w:
deltaCameraPos.y = state == 1 ? 1.0 : 0.0;
break;
case SDLK_a:
deltaCameraPos.x = state == 1 ? -1.0 : 0.0;
break;
case SDLK_s:
deltaCameraPos.y = state == 1 ? -1.0 : 0.0;
break;
case SDLK_d:
deltaCameraPos.x = state == 1 ? 1.0 : 0.0;
break;
case SDLK_q:
sDeltaRot = state == 1 ? -30 : 0.0;
break;
case SDLK_e:
sDeltaRot = state == 1 ? 30 : 0.0;
break;
case SDLK_k:
// Rotate shape left
if (sShape && state == 0)
{
if (sCurrentSequenceIdx == 0)
sCurrentSequenceIdx = kNumTSAppSequences-1;
else
sCurrentSequenceIdx--;
if (sSequences[sCurrentSequenceIdx] != -1)
SwitchToSequence(sSequences[sCurrentSequenceIdx], 0.5f, true);
}
break;
case SDLK_l:
// Rotate shape right
if (sShape && state == 0)
{
if (sCurrentSequenceIdx == kNumTSAppSequences-1)
sCurrentSequenceIdx = 0;
else
sCurrentSequenceIdx++;
if (sSequences[sCurrentSequenceIdx] != -1)
SwitchToSequence(sSequences[sCurrentSequenceIdx], 0.5f, true);
}
break;
}
}
void AppState::mainLoop()
{
// Process events
U32 tickTime = SDL_GetTicks();
U32 deltaTick = (tickTime - sOldTicks);
if (deltaTick > 1000)
deltaTick = 1000;
F32 deltaTime = deltaTick / 1000.0f;
sOldTicks = tickTime;
SDL_Event e;
// Check input
while (SDL_PollEvent(&e))
{
switch (e.type)
{
case SDL_QUIT:
running = false;
return;
break;
case SDL_KEYDOWN:
onKeyChanged(e.key.keysym.sym, 1);
break;
case SDL_KEYUP:
onKeyChanged(e.key.keysym.sym, 0);
break;
}
}
// Draw scene
SetupProjection();
if (mRenderer->BeginFrame())
{
sRenderState->reset();
PrepShape(deltaTime);
ComputeShapeMeshes(); // mesh info is setup in PrepShape
mRenderer->BeginRasterPass();
DrawShapes();
mRenderer->EndFrame();
}
// Slow down if we're going too fast
U32 tickEnd = SDL_GetTicks();
deltaTick = (tickEnd - tickTime);
if (deltaTick < TICK_TIME)
SDL_Delay(TICK_TIME - deltaTick);
mFrame++;
}
bool AppState::LoadShape()
{
TSMaterialManager::instance()->allocateAndRegister("Soldier_Dif");
TSMaterialManager::instance()->allocateAndRegister("Soldier_Dazzle");
TSMaterialManager::instance()->mapMaterial("base_Soldier_Main", "Soldier_Dif");
TSMaterialManager::instance()->mapMaterial("base_Soldier_Dazzle", "Soldier_Dazzle");
//TSMaterialManager::instance()->mapMaterial("player_blue", "Soldier_Dazzle");
TSMaterial *cubeMat = TSMaterialManager::instance()->allocateAndRegister("cube");
TSMaterialManager::instance()->mapMaterial("Cube", "cube");
TSMaterialManager::instance()->allocateAndRegister("player");
TSMaterialManager::instance()->mapMaterial("Player", "player");
const char* fullPath = GetAssetPath(shapeToLoad);
sShape = TSShape::createFromPath(fullPath);
if (!sShape)
{
return false;
}
sShapeInstance = new TSShapeInstance(sShape, sRenderState, true);
// Load all dsq files
for (int i=0; i<kNumTSAppSequences; i++)
{
FileStream dsqFile;
char pathName[64];
dSprintf(pathName, 64, "player_%s.dsq", sTSAppSequenceNames[i]);
Log::printf("Attempting to load sequence file %s", pathName);
if (dsqFile.open(GetAssetPath(pathName), FileStream::Read) && sShape->importSequences(&dsqFile, ""))
{
Log::printf("Sequence file %s loaded", pathName);
}
if (sShape->addSequence(GetAssetPath(pathName), "", sTSAppSequenceNames[i], sAppSequenceInfos[i].start, sAppSequenceInfos[i].end, true, false))
{
Log::printf("Sequence file %s loaded", pathName);
}
}
// Resolve all sequences
for (int i=0; i<kNumTSAppSequences; i++)
{
sSequences[i] = sShape->findSequence(sTSAppSequenceNames[i]);
if (sSequences[i] != -1)
{
if (sAppSequenceInfos[i].cyclic)
sShape->sequences[sSequences[i]].flags |= TSShape::Cyclic;
else
sShape->sequences[sSequences[i]].flags &= ~TSShape::Cyclic;
}
}
sThread = sShapeInstance->addThread();
if (sSequences[kTSRootAnim] != -1)
{
sShapeInstance->setSequence(sThread, sSequences[kTSForwardAnim], 0);
sShapeInstance->setTimeScale(sThread, 1.0f);
}
// Load DTS
sShape->initRender();
return true;
}
void AppState::CleanupShape()
{
if (sShapeInstance)
{
delete sShapeInstance;
}
if (sShape)
{
delete sShape;
}
}
void AppState::PrepShape(F32 dt)
{
GenericTSSceneRenderState *dummyScene = sRenderState->allocCustom<GenericTSSceneRenderState>();
constructInPlace(dummyScene);
sCameraPosition += deltaCameraPos * dt;
sRot += sDeltaRot * dt;
MatrixF calc(1);
// Set render transform
dummyScene->mProjectionMatrix = sProjectionMatrix;
dummyScene->mViewMatrix = MatrixF(1);
dummyScene->mWorldMatrix = MatrixF(1);
dummyScene->mWorldMatrix.setPosition(sModelPosition);
// Apply model rotation
calc = MatrixF(1);
AngAxisF rot2 = AngAxisF(Point3F(0,0,1), mDegToRad(sRot));
rot2.setMatrix(&calc);
dummyScene->mWorldMatrix *= calc;
// Set camera position
calc = MatrixF(1);
calc.setPosition(sCameraPosition);
dummyScene->mViewMatrix *= calc;
// Rotate camera
rot2 = AngAxisF(Point3F(1,0,0), mDegToRad(-90.0f));
calc = MatrixF(1);
rot2.setMatrix(&calc);
dummyScene->mViewMatrix *= calc;
// Calculate lighting vector
mLightPos = sCameraPosition;
// Set base shader uniforms
setLightPosition(mLightPos);
setLightColor(ColorF(1,1,1,1));
mRenderer->SetPushConstants(renderConstants);
// Now we can render
sRenderState->setSceneState(dummyScene);
// Animate & render shape to the renderState
sShapeInstance->beginUpdate(sRenderState);
sShapeInstance->advanceTime(dt);
sShapeInstance->setCurrentDetail(0);
sShapeInstance->animateNodeSubtrees(true);
sShapeInstance->animate();
sShapeInstance->render(*sRenderState);
}
void AppState::ComputeShapeMeshes()
{
if (!TSShape::smUseComputeSkinning)
return;
mRenderer->BeginComputePass();
mRenderer->DoComputeSkinning(sShapeInstance);
mRenderer->EndComputePass();
}
void AppState::DrawShapes()
{
// Ensure generated primitives are in the right z-order
sRenderState->sortRenderInsts();
// Render solid stuff
for (int i=0; i<sRenderState->mRenderInsts.size(); i++)
{
sRenderState->mRenderInsts[i]->render(sRenderState);
}
// Render translucent stuff
/*for (int i=0; i<sRenderState->mTranslucentRenderInsts.size(); i++)
{
// Update transform, & render buffers
sRenderState->mTranslucentRenderInsts[i]->render(sRenderState);
}*/
}
void AppState::SwitchToSequence(U32 seqIdx, F32 transitionTime, bool doTransition)
{
Log::printf("Changing to sequence %s", sTSAppSequenceNames[seqIdx]);
if (doTransition)
{
// Smoothly transition to new sequence
if (sSequences[seqIdx] != -1)
{
F32 pos = 0.0f;
if (sThread->getSeqIndex() == sSequences[seqIdx])
{
// Keep existing position if same sequence
pos = sShapeInstance->getPos(sThread);
}
sShapeInstance->transitionToSequence(sThread,sSequences[seqIdx],
pos, transitionTime, true);
}
}
else
{
// Reset to new sequence
if (sSequences[seqIdx] != -1)
{
sShapeInstance->setSequence(sThread, sSequences[seqIdx], 0.0f);
}
}
}
void AppState::SetupProjection()
{
F32 viewportWidth = 800;
F32 viewportHeight = 600;
int viewportWidthI, viewportHeightI;
SDL_GetWindowSize(mWindow, &viewportWidthI, &viewportHeightI);
viewportWidth = viewportWidthI;
viewportHeight = viewportHeightI;
F32 viewportFOV = 70.0f;
F32 aspectRatio = viewportWidth / viewportHeight;
F32 viewportNear = 0.1f;
F32 viewportFar = 200.0f;
F32 wheight = viewportNear * mTan(viewportFOV / 2.0f);
F32 wwidth = aspectRatio * wheight;
F32 hscale = wwidth * 2.0f / viewportWidth;
F32 vscale = wheight * 2.0f / viewportHeight;
F32 left = (0) * hscale - wwidth;
F32 right = (viewportWidth) * hscale - wwidth;
F32 top = wheight - vscale * (0);
F32 bottom = wheight - vscale * (viewportHeight);
// Set & grab frustum
Frustum frustum;
frustum.set( false, left, right, top, bottom, viewportNear, viewportFar );
frustum.getProjectionMatrix(&sProjectionMatrix, false);
}
SDL_Renderer* SetupMetalSDL(SDL_Window* window);
int AppState::main(int argc, char **argv)
{
DTShapeInit::init();
Log::addConsumer(OnAppLog);
for (int i=0; i<argc; i++)
{
if (strcmp(argv[i], "-metal") == 0)
{
gUseMetal = true;
}
}
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
Log::errorf("Couldn't initialize SDL: %s\n", SDL_GetError());
return (1);
}
int screenW = 800;
int screenH = 600;
SDL_DisplayMode mode;
int windowFlags = 0;
windowFlags = SDL_WINDOW_RESIZABLE;
SDL_GetCurrentDisplayMode(0, &mode);
if (mode.w < screenW)
screenW = mode.w;
if (mode.h < screenH)
screenH = mode.h;
mWindow = SDL_CreateWindow("libDTShape Example", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screenW, screenH, windowFlags);
#if defined(USE_BOTH_RENDER)
mSDLRenderer = gUseMetal ? SetupMetalSDL(mWindow) : NULL;
#else
#if defined(USE_METAL)
mSDLRenderer = SetupMetalSDL(mWindow);
#else
mSDLRenderer = NULL;
#endif
#endif
SDL_ShowWindow(mWindow);
createRenderer();
mRenderer->Init(mWindow, mSDLRenderer);
// Init render state
sRenderState = new TSRenderState();
bool loaded = LoadShape();
if (!loaded)
{
Log::errorf("Couldn't load shape %s", shapeToLoad);
return false;
}
running = true;
return true;
}
void AppState::OnAppLog(U32 level, LogEntry *logEntry)
{
switch (logEntry->mLevel)
{
case LogEntry::Normal:
fprintf(stdout, "%s\n", logEntry->mData);
break;
case LogEntry::Warning:
fprintf(stdout, "%s\n", logEntry->mData);
break;
case LogEntry::Error:
fprintf(stderr, "%s\n", logEntry->mData);
break;
default:
break;
}
}
void AppState::setLightPosition(const DTShape::Point3F &pos)
{
renderConstants.lightPos = simd_make_float3(pos.x, pos.y, pos.z);
}
void AppState::setLightColor(const DTShape::ColorF &color)
{
renderConstants.lightColor = simd_make_float3(color.red, color.green, color.blue);
}
AppState *AppState::getInstance()
{
return sInstance;
}
int main(int argc, char *argv[])
{
AppState *app = new AppState();
if (app->main(argc, argv))
{
while (app->running)
app->mainLoop();
}
delete app;
SDL_Quit();
return (0);
}
| 24.262673 | 149 | 0.637733 | [
"mesh",
"render",
"shape",
"vector",
"model",
"transform",
"solid"
] |
87e326be3e11f0f93ee967bbecf446015ec8ec82 | 2,461 | cpp | C++ | addons/ofxGuido/lib/guidolib-code/src/abstract/ARTStem.cpp | k4rm/AscoGraph | 9038ae785b6f4f144a3ab5c4c5520761c0cd08f2 | [
"MIT"
] | 18 | 2015-01-18T22:34:22.000Z | 2020-09-06T20:30:30.000Z | addons/ofxGuido/lib/guidolib-code/src/abstract/ARTStem.cpp | k4rm/AscoGraph | 9038ae785b6f4f144a3ab5c4c5520761c0cd08f2 | [
"MIT"
] | 2 | 2015-08-04T00:07:46.000Z | 2017-05-10T15:53:51.000Z | addons/ofxGuido/lib/guidolib-code/src/abstract/ARTStem.cpp | k4rm/AscoGraph | 9038ae785b6f4f144a3ab5c4c5520761c0cd08f2 | [
"MIT"
] | 10 | 2015-01-18T23:46:10.000Z | 2019-08-25T12:10:04.000Z | /*
GUIDO Library
Copyright (C) 2002 Holger Hoos, Juergen Kilian, Kai Renz
Copyright (C) 2002-2013 Grame
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Grame Research Laboratory, 11, cours de Verdun Gensoul 69002 Lyon - France
research@grame.fr
*/
#include <iostream>
#include "ARTStem.h"
#include "TagParameterList.h"
#include "TagParameterFloat.h"
#include "ListOfStrings.h"
ListOfTPLs ARTStem::ltpls(1);
ARTStem::ARTStem(int st , ARTStem * p_savestem, ARTStem * p_copystem )
: ARMTParameter(-1,p_copystem)
{
rangesetting = RANGEDC;
mStemState = (ARTStem::STEMSTATE) st;
mSaveStem = p_savestem;
mTpfLength = NULL;
if (p_copystem)
{
mStemState = p_copystem->getStemState();
if (p_copystem->getLength())
mTpfLength = TagParameterFloat::cast(
p_copystem->getLength()->getCopy());
}
}
ARTStem::ARTStem(const ARTStem * tstem) : ARMTParameter(-1,tstem)
{
mSaveStem = NULL;
mStemState = tstem->mStemState;
mTpfLength = NULL;
if (tstem->mTpfLength)
{
mTpfLength = TagParameterFloat::cast
(tstem->mTpfLength->getCopy());
}
}
ARTStem::~ARTStem()
{
delete mTpfLength;
}
ARMusicalObject * ARTStem::Copy() const
{
return new ARTStem(this);
}
void ARTStem::PrintName(std::ostream & os) const
{
switch (mStemState)
{
case UP: os << "\\stemsUp"; break;
case DOWN: os << "\\stemsDown"; break;
case AUTO: os << "\\stemsAuto"; break;
case OFF: os << "\\stemsOff"; break;
}
}
void ARTStem::PrintParameters(std::ostream & os) const
{
if (mTpfLength && mTpfLength->TagIsSet())
{
os << "<" << mTpfLength->getUnitValue() <<
mTpfLength->getUnit() << ">";
}
}
void ARTStem::setTagParameterList(TagParameterList & tpl)
{
if (ltpls.GetCount() == 0)
{
// create a list of string ...
ListOfStrings lstrs; // (1); std::vector test impl
lstrs.AddTail(( "U,length,7.0,o"));
CreateListOfTPLs(ltpls,lstrs);
}
TagParameterList * rtpl = NULL;
const int ret = MatchListOfTPLsWithTPL(ltpls,tpl,&rtpl);
if (ret>=0 && rtpl)
{
// we found a match!
if (ret == 0)
{
// then, we now the match for
// the first ParameterList
// w, h, ml, mt, mr, mb
//GuidoPos pos = rtpl->GetHeadPosition();
mTpfLength = TagParameterFloat::cast( rtpl->RemoveHead());
}
delete rtpl;
}
else
{
// failure...
}
tpl.RemoveAll();
}
| 20.855932 | 76 | 0.66477 | [
"vector"
] |
87ec44acd9dd7783d7732de4b82034d62451bc74 | 14,726 | cc | C++ | src/pass/inject_transfer_buffer_scope.cc | KnowingNothing/akg-test | 114d8626b824b9a31af50a482afc07ab7121862b | [
"Apache-2.0"
] | 286 | 2020-06-23T06:40:44.000Z | 2022-03-30T01:27:49.000Z | src/pass/inject_transfer_buffer_scope.cc | KnowingNothing/akg-test | 114d8626b824b9a31af50a482afc07ab7121862b | [
"Apache-2.0"
] | 10 | 2020-07-31T03:26:59.000Z | 2021-12-27T15:00:54.000Z | src/pass/inject_transfer_buffer_scope.cc | KnowingNothing/akg-test | 114d8626b824b9a31af50a482afc07ab7121862b | [
"Apache-2.0"
] | 30 | 2020-07-17T01:04:14.000Z | 2021-12-27T14:05:19.000Z | /**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* 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 <tvm/ir.h>
#include <tvm/ir_visitor.h>
#include <tvm/ir_mutator.h>
#include <tvm/ir_pass.h>
#include <arithmetic/compute_expr.h>
#include <ir_pass.h>
#include "build_module.h"
#include "utils.h"
#include "common/common_util.h"
namespace akg {
namespace ir {
constexpr auto PREFETCH_SCOPE = "double_buffer_scope";
constexpr auto THREAD_GROUP_OFFSET = "thread_group_offset";
constexpr auto WMMA_FACTOR_AB = 16;
constexpr auto WMMA_FACTOR_C = 32;
constexpr int REGISTER_FILE_SIZE_PER_SM = 256 * 1024;
constexpr int TOTAL_THREAD_NUM_PER_BLOCK = 1024;
constexpr int MIN_OUTER_LOOP = 2;
constexpr int MAX_OUTER_LOOP = 64;
class IfTensorCore : public IRVisitor {
public:
const bool IfUseTensorCore(Stmt stmt) {
this->Visit(stmt);
return if_use_tensor_core_;
}
void Visit_(const AttrStmt *op) {
if (op->attr_key == "pragma_tensor_core") {
if_use_tensor_core_ = true;
return;
} else {
return IRVisitor::Visit_(op);
}
}
private:
bool if_use_tensor_core_{false};
};
class PrefetchScopeInjector : public IRMutator {
public:
bool HasShared(const Stmt &s) {
if (auto store = s.as<Store>()) {
is_nested_block_ = true;
auto it = touched_.find(store->buffer_var.get());
if (it != touched_.end()) {
prefetch_var_ = store->buffer_var;
return true;
}
} else if (auto loop = s.as<For>()) {
if (HasShared(loop->body)) {
return true;
}
} else if (auto attr = s.as<AttrStmt>()) {
if (HasShared(attr->body)) {
return true;
}
} else if (auto cond = s.as<IfThenElse>()) {
if (HasShared(cond->then_case)) {
return true;
}
}
return false;
}
bool HasConstantOuterLoop() {
return ((!loop_nest_.empty()) && (loop_nest_.back()->extent.as<IntImm>() != nullptr));
}
bool IsPrefetchBlock(const Stmt &s) {
return (HasShared(s) && HasConstantOuterLoop());
}
Stmt Mutate_(const AttrStmt *op, const Stmt &s) final {
if (op->attr_key == air::ir::attr::storage_scope && op->value.as<StringImm>()->value == "shared") {
touched_.insert(op->node.as<Variable>());
} else if (op->attr_key == "shared_mem_promoted_complete") {
if_shared_promoted_ = true;
} else if (op->attr_key == "promote_register_to_global" || op->attr_key == "promote_register_to_shared") {
if_shared_finished_ = true;
} else if (op->attr_key == "promote_vectorization") {
if (IsPrefetchBlock(s)) {
prefetch_outer_loop_ = (loop_nest_.back()->extent).as<IntImm>()->value;
if_prefetch_injected_ = true;
return AttrStmt::make(prefetch_var_, PREFETCH_SCOPE, 1, s);
}
return s;
}
return IRMutator::Mutate_(op, s);
}
Stmt Mutate_(const For *op, const Stmt &s) final {
if (IsPrefetchBlock(s)) {
prefetch_outer_loop_ = (loop_nest_.back()->extent).as<IntImm>()->value;
if_prefetch_injected_ = true;
return AttrStmt::make(prefetch_var_, PREFETCH_SCOPE, 1, s);
} else if (is_nested_block_) {
return s;
} else {
loop_nest_.push_back(op);
auto stmt = IRMutator::Mutate_(op, s);
loop_nest_.pop_back();
return stmt;
}
}
Stmt Mutate_(const Store *op, const Stmt &s) final {
if (IsPrefetchBlock(s)) {
prefetch_outer_loop_ = (loop_nest_.back()->extent).as<IntImm>()->value;
if_prefetch_injected_ = true;
return AttrStmt::make(prefetch_var_, PREFETCH_SCOPE, 1, s);
}
return IRMutator::Mutate_(op, s);
}
Stmt Mutate_(const Evaluate *op, const Stmt &s) final {
if (is_const(op->value)) {
return IRMutator::Mutate_(op, s);
}
if (const auto call = op->value.as<Call>()) {
if (call->is_intrinsic(air::ir::intrinsic::tvm_storage_sync)) {
if (if_prefetch_injected_ && (!if_shared_promoted_)) {
return AttrStmt::make(Var(""), "delete_this_sync", 1, s);
} else if (if_shared_promoted_ && (!if_shared_finished_)) {
return AttrStmt::make(Var(""), "delete_this_sync_for_db", 1, s);
}
}
}
return IRMutator::Mutate_(op, s);
}
Stmt Mutate_(const IfThenElse *op, const Stmt &s) final {
Stmt stmt = IRMutator::Mutate_(op, s);
if (const auto ifthenelse = stmt.as<IfThenElse>()) {
if (auto attr = ifthenelse->then_case.as<AttrStmt>()) {
if (attr->attr_key == PREFETCH_SCOPE) {
Stmt rotated_stmt = IfThenElse::make(ifthenelse->condition, attr->body, ifthenelse->else_case);
rotated_stmt = AttrStmt::make(attr->node, attr->attr_key, attr->value, rotated_stmt);
return rotated_stmt;
}
}
}
return stmt;
}
const bool GetIfPrefetchInjected() { return if_prefetch_injected_; }
const int GetPrefetchOuterLoop() { return prefetch_outer_loop_; }
private:
std::unordered_set<const Variable *> touched_;
VarExpr prefetch_var_;
std::vector<const For *> loop_nest_;
bool need_prefetch_{false};
bool is_vectorize_{false};
bool if_prefetch_injected_{false};
bool if_shared_promoted_{false};
bool if_shared_finished_{false};
bool is_nested_block_{false};
int prefetch_outer_loop_;
};
class IfResouceIsEnough : public IRVisitor {
public:
void Visit_(const AttrStmt *op) final {
if (op->attr_key == "bind_thread_x") {
use_thread_y_ = false;
return IRVisitor::Visit_(op);
} else if (op->attr_key == air::ir::attr::thread_extent) {
IterVar iv = Downcast<IterVar>(op->node);
if (iv->var->name_hint == "threadIdx.x") {
thread_x_var_ = iv->var;
thread_x_value_ = op->value;
}
if (iv->var->name_hint == "threadIdx.y") {
thread_y_var_ = iv->var;
thread_y_value_ = op->value;
}
return IRVisitor::Visit_(op);
} else if (op->attr_key == air::ir::attr::storage_scope) {
if (auto alloc = op->body.as<Allocate>()) {
if (!promote_local_usage_.defined()) {
promote_local_usage_ = make_const(alloc->extents[0].type(), 0);
}
if (op->value.as<StringImm>()->value == "shared") {
if (!shared_usage_.defined()) {
shared_usage_ = make_const(alloc->extents[0].type(), 0);
}
shared_usage_ +=
air::arith::ComputeReduce<Mul>(alloc->extents, Expr()) * alloc->type.lanes() * alloc->type.bytes();
} else if (op->value.as<StringImm>()->value == "local") {
promote_local_usage_ +=
air::arith::ComputeReduce<Mul>(alloc->extents, Expr()) * alloc->type.lanes() * alloc->type.bytes();
} else if (op->value.as<StringImm>()->value == "wmma.accumulator") {
promote_local_usage_ += air::arith::ComputeReduce<Mul>(alloc->extents, Expr()) * alloc->type.lanes() /
Expr(WMMA_FACTOR_C) * alloc->type.bytes();
} else if (op->value.as<StringImm>()->value == "wmma.matrix_b" ||
op->value.as<StringImm>()->value == "wmma.matrix_a") {
promote_local_usage_ += air::arith::ComputeReduce<Mul>(alloc->extents, Expr()) * alloc->type.lanes() /
Expr(WMMA_FACTOR_AB) * alloc->type.bytes();
}
}
return IRVisitor::Visit_(op);
} else if (op->attr_key == PREFETCH_SCOPE) {
in_prefetch_buffer_scope_ = true;
Visit(op->body);
if (!prefetch_local_usage_.defined()) {
prefetch_local_usage_ = make_const(transfer_loop_nest_[0]->extent.type(), 0);
}
Expr current_local_usage = make_const(transfer_loop_nest_[0]->extent.type(), 1);
for (unsigned i = 0; i < transfer_loop_nest_.size(); i++) {
current_local_usage *= transfer_loop_nest_[i]->extent - transfer_loop_nest_[i]->min;
}
prefetch_local_usage_ += current_local_usage * prefetch_data_type_.bytes();
transfer_loop_nest_.clear();
in_prefetch_buffer_scope_ = false;
} else {
return IRVisitor::Visit_(op);
}
}
void Visit_(const For *op) {
if (in_prefetch_buffer_scope_) transfer_loop_nest_.push_back(op);
return IRVisitor::Visit_(op);
}
void Visit_(const Store *op) {
if (in_prefetch_buffer_scope_) {
if (const auto load = op->value.as<Load>()) {
prefetch_data_type_ = load->type;
}
}
return IRVisitor::Visit_(op);
}
const int GetBindThreadNum() { return (thread_x_value_ * thread_y_value_).as<IntImm>()->value; }
const Var GetThreadGroupVar() {
if (use_thread_y_)
return thread_y_var_;
else
return thread_x_var_;
}
const Expr GetThreadGoupOffset() {
if (use_thread_y_)
return thread_y_value_;
else
return thread_x_value_;
}
const int GetTotalSharedUsage() { return shared_usage_.as<IntImm>()->value; }
const int GetTotalLocalUsage() { return (promote_local_usage_ + prefetch_local_usage_).as<IntImm>()->value; }
private:
bool use_thread_y_{true};
bool in_prefetch_buffer_scope_{false};
Var thread_x_var_, thread_y_var_;
Expr thread_x_value_, thread_y_value_;
Expr shared_usage_, promote_local_usage_, prefetch_local_usage_;
std::vector<const For *> transfer_loop_nest_;
air::DataType prefetch_data_type_;
};
class ThreadGroupScopeInjector : public IRMutator {
public:
Stmt Inject(Stmt stmt, int thread_group, Var thread_var, Expr thread_offset) {
thread_group_ = thread_group;
thread_var_ = thread_var;
thread_offset_ = thread_offset;
return this->Mutate(stmt);
}
Stmt Mutate_(const AttrStmt *op, const Stmt &s) final {
if (op->attr_key == air::ir::attr::thread_extent) {
thread_extent_count_ += 1;
Stmt body = Mutate(op->body);
thread_extent_count_ -= 1;
if (thread_extent_count_ == 0) {
return AttrStmt::make(thread_var_, "use_thread_group", make_const(thread_offset_.type(), thread_group_),
AttrStmt::make(op->node, op->attr_key, op->value, body));
} else {
return AttrStmt::make(op->node, op->attr_key, op->value, body);
}
} else if (op->attr_key == PREFETCH_SCOPE) {
Stmt body = Mutate(op->body);
return AttrStmt::make(op->node, op->attr_key, op->value,
AttrStmt::make(thread_var_, THREAD_GROUP_OFFSET, thread_offset_, body));
} else if (op->attr_key == "promote_register_to_shared" || op->attr_key == "promote_shared_to_global" ||
op->attr_key == "promote_register_to_global" || op->attr_key == "shared_mem_promoted_complete") {
Stmt body = Mutate(op->body);
return AttrStmt::make(
op->node, op->attr_key, op->value,
AttrStmt::make(thread_var_, THREAD_GROUP_OFFSET, make_const(thread_offset_.type(), 0), body));
} else {
return IRMutator::Mutate_(op, s);
}
}
private:
int thread_group_;
int thread_extent_count_ = 0;
Var thread_var_;
Expr thread_offset_;
};
Stmt InjectTransferBufferScope(Stmt stmt) {
if (!IfTensorCore().IfUseTensorCore(stmt)) return stmt;
PrefetchScopeInjector prefetch_injector;
Stmt new_stmt = prefetch_injector.Mutate(stmt);
const bool if_prefetch_injected = prefetch_injector.GetIfPrefetchInjected();
if (!if_prefetch_injected) return stmt;
const int thread_group = 2;
const bool tuning{true};
bool enable_double_buffer{false};
bool enable_transfer_buffer{false};
bool enable_thread_group{false};
IfResouceIsEnough resource_calc;
resource_calc.Visit(new_stmt);
if (tuning) {
// tuning: manually control by attrs
enable_double_buffer = g_attrs.GetBool(kEnableDoubleBuffer, false);
enable_transfer_buffer = g_attrs.GetBool(kEnableTransferBuffer, true);
enable_thread_group = g_attrs.GetBool(kEnableThreadGroup, false);
} else {
// not tuning: auto-analyse
const int total_shared_usage = resource_calc.GetTotalSharedUsage();
float shared_mem_rate = float(total_shared_usage * 2) / float(common::ADVANCED_SHARED_MEMORY_SIZE);
const int bind_thread_num = resource_calc.GetBindThreadNum();
const int total_local_usage = resource_calc.GetTotalLocalUsage();
float local_mem_rate = float(total_local_usage * bind_thread_num) / float(REGISTER_FILE_SIZE_PER_SM);
if (shared_mem_rate >= 1 && local_mem_rate >= 1) return stmt;
if (shared_mem_rate <= local_mem_rate) return new_stmt;
int max_bind_thread_num = TOTAL_THREAD_NUM_PER_BLOCK / thread_group;
const int prefetch_outer_loop = prefetch_injector.GetPrefetchOuterLoop();
if ((prefetch_outer_loop > MIN_OUTER_LOOP) && (local_mem_rate < 1) &&
((bind_thread_num < max_bind_thread_num / 2) || (prefetch_outer_loop < MAX_OUTER_LOOP))) {
enable_transfer_buffer = true;
g_attrs.Set(kEnableTransferBuffer, air::make_const(Int(32), true));
if ((local_mem_rate < (1.0 / float(thread_group) / 2.0)) && (bind_thread_num < max_bind_thread_num)) {
enable_thread_group = true;
}
}
}
// avoid enabling two modes
if (enable_double_buffer) {
enable_transfer_buffer = false;
}
Stmt stmt_after_prefetch = stmt;
if (enable_transfer_buffer || enable_double_buffer) {
if (enable_thread_group) {
const Var thread_group_var = resource_calc.GetThreadGroupVar();
const Expr thread_group_offset = resource_calc.GetThreadGoupOffset();
stmt_after_prefetch =
ThreadGroupScopeInjector().Inject(new_stmt, thread_group, thread_group_var, thread_group_offset);
} else {
stmt_after_prefetch = new_stmt;
}
}
// add an attr of prefetch_mode
int prefetch_mode = static_cast<int>(PrefetchMode::DEFAULT);
if (enable_double_buffer && enable_thread_group) {
prefetch_mode = static_cast<int>(PrefetchMode::DOUBLEBUFFER_THREADGROUP);
} else if (enable_transfer_buffer && enable_thread_group) {
prefetch_mode = static_cast<int>(PrefetchMode::TRANSFERBUFFER_THREADGROUP);
} else if (enable_double_buffer) {
prefetch_mode = static_cast<int>(PrefetchMode::DOUBLEBUFFER);
} else if (enable_transfer_buffer) {
prefetch_mode = static_cast<int>(PrefetchMode::TRANSFERBUFFER);
}
return AttrStmt::make(Expr("INFO"), ATTR_PREFETCH_MODE, prefetch_mode, stmt_after_prefetch);
}
} // namespace ir
} // namespace akg | 37.566327 | 112 | 0.669292 | [
"vector"
] |
87faddaf16c500298dbca73ee39fb011fa664975 | 8,120 | cpp | C++ | Handles.cpp | katahiromz/Handles | a353d9aefdbb3d6af3f17a6aa14474af1ac5c1b6 | [
"MIT"
] | 1 | 2020-05-03T08:27:33.000Z | 2020-05-03T08:27:33.000Z | Handles.cpp | katahiromz/Handles | a353d9aefdbb3d6af3f17a6aa14474af1ac5c1b6 | [
"MIT"
] | null | null | null | Handles.cpp | katahiromz/Handles | a353d9aefdbb3d6af3f17a6aa14474af1ac5c1b6 | [
"MIT"
] | 1 | 2020-05-03T08:27:35.000Z | 2020-05-03T08:27:35.000Z | // Handles.c --- List the kernel handles of the process
// Copyright (C) 2020 Katayama Hirofumi MZ <katayama.hirofumi.mz@gmail.com>
// This file is public domain software.
#ifndef UNICODE
#define UNICODE
#endif
#include <windows.h>
#include <cstdio>
#include "Auto.hpp"
static void
show_help(void)
{
printf("Shows the kernel handles of the specified process\n");
printf("\n");
printf("Usage: handles [pid]\n");
}
static void
show_version(void)
{
printf("handles ver.0.6 by katahiromz\n");
}
#define NT_SUCCESS(x) ((x) >= 0)
#define STATUS_INFO_LENGTH_MISMATCH 0xc0000004
#define SystemHandleInformation 16
#define ObjectBasicInformation 0
#define ObjectNameInformation 1
#define ObjectTypeInformation 2
typedef LONG NTSTATUS;
#define NTAPI __stdcall
typedef NTSTATUS (NTAPI *FN_NtQuerySystemInformation)(
ULONG SystemInformationClass,
PVOID SystemInformation,
ULONG SystemInformationLength,
PULONG ReturnLength);
typedef NTSTATUS (NTAPI *FN_NtDuplicateObject)(
HANDLE SourceProcessHandle,
HANDLE SourceHandle,
HANDLE TargetProcessHandle,
PHANDLE TargetHandle,
ACCESS_MASK DesiredAccess,
ULONG Attributes,
ULONG Options);
typedef NTSTATUS (NTAPI *FN_NtQueryObject)(
HANDLE ObjectHandle,
ULONG ObjectInformationClass,
PVOID ObjectInformation,
ULONG ObjectInformationLength,
PULONG ReturnLength);
typedef struct _UNICODE_STRING
{
USHORT Length;
USHORT MaximumLength;
PWSTR Buffer;
} UNICODE_STRING, *PUNICODE_STRING;
typedef struct _SYSTEM_HANDLE
{
ULONG ProcessId;
BYTE ObjectTypeNumber;
BYTE Flags;
USHORT Handle;
PVOID Object;
ACCESS_MASK GrantedAccess;
} SYSTEM_HANDLE, *PSYSTEM_HANDLE;
typedef struct _SYSTEM_HANDLE_INFORMATION
{
ULONG HandleCount;
SYSTEM_HANDLE Handles[1];
} SYSTEM_HANDLE_INFORMATION, *PSYSTEM_HANDLE_INFORMATION;
typedef enum _POOL_TYPE
{
NonPagedPool,
PagedPool,
NonPagedPoolMustSucceed,
DontUseThisType,
NonPagedPoolCacheAligned,
PagedPoolCacheAligned,
NonPagedPoolCacheAlignedMustS
} POOL_TYPE, *PPOOL_TYPE;
typedef struct _OBJECT_TYPE_INFORMATION
{
UNICODE_STRING Name;
ULONG TotalNumberOfObjects;
ULONG TotalNumberOfHandles;
ULONG TotalPagedPoolUsage;
ULONG TotalNonPagedPoolUsage;
ULONG TotalNamePoolUsage;
ULONG TotalHandleTableUsage;
ULONG HighWaterNumberOfObjects;
ULONG HighWaterNumberOfHandles;
ULONG HighWaterPagedPoolUsage;
ULONG HighWaterNonPagedPoolUsage;
ULONG HighWaterNamePoolUsage;
ULONG HighWaterHandleTableUsage;
ULONG InvalidAttributes;
GENERIC_MAPPING GenericMapping;
ULONG ValidAccess;
BOOLEAN SecurityRequired;
BOOLEAN MaintainHandleCount;
USHORT MaintainTypeList;
POOL_TYPE PoolType;
ULONG PagedPoolUsage;
ULONG NonPagedPoolUsage;
} OBJECT_TYPE_INFORMATION, *POBJECT_TYPE_INFORMATION;
template <typename T>
T DoGetProc(T& fn, HINSTANCE hInst, LPCSTR name)
{
fn = reinterpret_cast<T>(GetProcAddress(hInst, name));
return fn;
}
static FN_NtQuerySystemInformation s_pNtQuerySystemInformation;
static FN_NtDuplicateObject s_pNtDuplicateObject;
static FN_NtQueryObject s_pNtQueryObject;
#define NtQuerySystemInformation (*s_pNtQuerySystemInformation)
#define NtDuplicateObject (*s_pNtDuplicateObject)
#define NtQueryObject (*s_pNtQueryObject)
int DoMain(int argc, wchar_t **wargv)
{
if (argc < 2 || lstrcmpW(wargv[1], L"--help") == 0)
{
show_help();
return EXIT_SUCCESS;
}
if (lstrcmpW(wargv[1], L"--version") == 0)
{
show_version();
return EXIT_SUCCESS;
}
ULONG pid = wcstoul(wargv[1], NULL, 0);
AutoCloseHandle hProcess(OpenProcess(PROCESS_DUP_HANDLE, FALSE, pid));
if (!hProcess)
{
printf("Cannot open process %lu", pid);
return EXIT_FAILURE;
}
NTSTATUS status;
AutoFree<SYSTEM_HANDLE_INFORMATION> pHandleInfo(0x10000);
for (;;)
{
status = NtQuerySystemInformation(SystemHandleInformation, pHandleInfo, pHandleInfo.size(), NULL);
if (status != STATUS_INFO_LENGTH_MISMATCH)
break;
if (!pHandleInfo.resize(pHandleInfo.size() * 2))
{
printf("Out of memory\n");
return EXIT_FAILURE;
}
}
if (!NT_SUCCESS(status))
{
printf("NtQuerySystemInformation failed!\n");
return EXIT_FAILURE;
}
for (ULONG i = 0; i < pHandleInfo->HandleCount; i++)
{
SYSTEM_HANDLE SystemHandle = pHandleInfo->Handles[i];
if (SystemHandle.ProcessId != pid)
continue;
AutoCloseHandle hDuplicate(NULL);
status = NtDuplicateObject(hProcess,
(HANDLE)(ULONG_PTR)SystemHandle.Handle,
GetCurrentProcess(),
&hDuplicate, 0, 0, 0);
if (!NT_SUCCESS(status))
{
if (status == 0xC00000BB)
printf("[%#x] (not supported)\n", SystemHandle.Handle);
else
printf("[%#x] error: status: 0x%08lX\n", SystemHandle.Handle, status);
continue;
}
AutoFree<OBJECT_TYPE_INFORMATION> TypeInfo(0x1000);
status = NtQueryObject(hDuplicate, ObjectTypeInformation, TypeInfo, TypeInfo.size(), NULL);
if (!NT_SUCCESS(status))
{
if (status == 0xC00000BB)
printf("[%#x] (not supported)\n", SystemHandle.Handle);
else
printf("[%#x] error: status: 0x%08lX\n", SystemHandle.Handle, status);
continue;
}
if (SystemHandle.GrantedAccess == 0x0012019f)
{
printf("[%#x] %.*S: (did not get name)\n", SystemHandle.Handle,
TypeInfo->Name.Length / 2, TypeInfo->Name.Buffer);
continue;
}
ULONG cbLength = 0x1000;
AutoFree<UNICODE_STRING> NameInfo(cbLength);
status = NtQueryObject(hDuplicate, ObjectNameInformation, NameInfo, cbLength, &cbLength);
if (!NT_SUCCESS(status))
{
NameInfo.resize(cbLength);
status = NtQueryObject(hDuplicate, ObjectNameInformation, NameInfo, cbLength, NULL);
if (!NT_SUCCESS(status))
{
printf("[%#x] %.*S: (could not get name)\n", SystemHandle.Handle,
TypeInfo->Name.Length / 2, TypeInfo->Name.Buffer);
continue;
}
}
UNICODE_STRING Name = *(PUNICODE_STRING)NameInfo;
if (Name.Length)
{
/* The object has a name. */
printf("[%#x] %.*S: %.*S\n", SystemHandle.Handle,
TypeInfo->Name.Length / 2, TypeInfo->Name.Buffer,
Name.Length / 2, Name.Buffer);
}
else
{
/* No name. */
printf("[%#x] %.*S: (unnamed)\n", SystemHandle.Handle,
TypeInfo->Name.Length / 2, TypeInfo->Name.Buffer);
}
}
return EXIT_SUCCESS;
}
int wmain(int argc, wchar_t **wargv)
{
HINSTANCE hNTDLL = LoadLibraryA("ntdll.dll");
if (!hNTDLL)
{
printf("Cannot load ntdll.dll\n");
return EXIT_FAILURE;
}
if (!DoGetProc(s_pNtQuerySystemInformation, hNTDLL, "NtQuerySystemInformation") ||
!DoGetProc(s_pNtDuplicateObject, hNTDLL, "NtDuplicateObject") ||
!DoGetProc(s_pNtQueryObject, hNTDLL, "NtQueryObject"))
{
printf("Cannot get procedures of ntdll.dll\n");
return EXIT_FAILURE;
}
int ret = DoMain(argc, wargv);
FreeLibrary(hNTDLL);
return ret;
}
int main(int argc, char **argv)
{
int argc_ = 0;
LPWSTR *wargv_ = CommandLineToArgvW(GetCommandLineW(), &argc_);
int ret = wmain(argc_, wargv_);
LocalFree(wargv_);
return ret;
}
| 28.69258 | 107 | 0.62303 | [
"object"
] |
87fb604e087aee1c939677653fd076366afcc810 | 2,325 | cpp | C++ | src/main.cpp | ilya-guseynov/computing-node | c3213c1ff55d5597f950ce4fbb749e5dec931d3b | [
"MIT"
] | null | null | null | src/main.cpp | ilya-guseynov/computing-node | c3213c1ff55d5597f950ce4fbb749e5dec931d3b | [
"MIT"
] | null | null | null | src/main.cpp | ilya-guseynov/computing-node | c3213c1ff55d5597f950ce4fbb749e5dec931d3b | [
"MIT"
] | null | null | null | #include "nan.h"
#include "nan_algorithm.hpp"
#include "nan_basic.hpp"
#include "nan_matrix.hpp"
#include "nan_sorting.hpp"
void init_basic(v8::Local<v8::Object> target) {
Nan::Set(
target,
Nan::New("bubbleSort").ToLocalChecked(),
Nan::GetFunction(
Nan::New<v8::FunctionTemplate>(nan_bubble_sort)
).ToLocalChecked()
);
Nan::Set(
target,
Nan::New("fibonacci").ToLocalChecked(),
Nan::GetFunction(
Nan::New<v8::FunctionTemplate>(nan_fibonacci)
).ToLocalChecked()
);
Nan::Set(
target,
Nan::New("catalan").ToLocalChecked(),
Nan::GetFunction(
Nan::New<v8::FunctionTemplate>(nan_catalan)
).ToLocalChecked()
);
Nan::Set(
target,
Nan::New("eulerTotient").ToLocalChecked(),
Nan::GetFunction(
Nan::New<v8::FunctionTemplate>(nan_euler_totient)
).ToLocalChecked()
);
Nan::Set(
target,
Nan::New("binomialCoeff").ToLocalChecked(),
Nan::GetFunction(
Nan::New<v8::FunctionTemplate>(nan_binomial_coeff)
).ToLocalChecked()
);
Nan::Set(
target,
Nan::New("newmanConway").ToLocalChecked(),
Nan::GetFunction(
Nan::New<v8::FunctionTemplate>(nan_newman_conway)
).ToLocalChecked()
);
Nan::Set(
target,
Nan::New("isPrime").ToLocalChecked(),
Nan::GetFunction(
Nan::New<v8::FunctionTemplate>(nan_is_prime)
).ToLocalChecked()
);
Nan::Set(
target,
Nan::New("estimatePiNumber").ToLocalChecked(),
Nan::GetFunction(
Nan::New<v8::FunctionTemplate>(nan_estimate_pi_number)
).ToLocalChecked()
);
Nan::Set(
target,
Nan::New("createCollatzSequence").ToLocalChecked(),
Nan::GetFunction(
Nan::New<v8::FunctionTemplate>(nan_collatz_sequence)
).ToLocalChecked()
);
Nan::Set(
target,
Nan::New("sumList").ToLocalChecked(),
Nan::GetFunction(
Nan::New<v8::FunctionTemplate>(nan_list_sum)
).ToLocalChecked()
);
Nan::Set(
target,
Nan::New("isMatrixSquare").ToLocalChecked(),
Nan::GetFunction(
Nan::New<v8::FunctionTemplate>(nan_is_matrix_square)
).ToLocalChecked()
);
Nan::Set(
target,
Nan::New("matrixSum").ToLocalChecked(),
Nan::GetFunction(
Nan::New<v8::FunctionTemplate>(nan_matrix_sum)
).ToLocalChecked()
);
}
NODE_MODULE(basic, init_basic)
| 21.330275 | 60 | 0.64129 | [
"object"
] |
87fe2c6934899792737e4b25d4e0ab4a42994c6f | 595 | hh | C++ | src/ast/Block.hh | walecome/seal | 204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1 | [
"MIT"
] | 1 | 2020-01-06T09:43:56.000Z | 2020-01-06T09:43:56.000Z | src/ast/Block.hh | walecome/seal | 204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1 | [
"MIT"
] | null | null | null | src/ast/Block.hh | walecome/seal | 204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1 | [
"MIT"
] | null | null | null | #pragma once
#include "Node.hh"
#include "Statement.hh"
#include <sstream>
#include <vector>
class Block : public Statement {
MAKE_DEFAULT_CONSTRUCTABLE(Block)
MAKE_NONMOVABLE(Block)
MAKE_NONCOPYABLE(Block)
AST_NODE_NAME(Block)
AST_DUMPABLE()
AST_ANALYZABLE()
public:
template <class Callback>
void for_each_node(Callback cb) const {
for (auto &x : m_nodes) {
cb(x.get());
}
};
void add_node(ptr_t<Node> &node);
const auto &nodes() const { return m_nodes; }
private:
std::vector<ptr_t<Node>> m_nodes {};
}; | 19.193548 | 49 | 0.635294 | [
"vector"
] |
87ffecba23538636c0805b49c802e00630e525bd | 18,800 | cpp | C++ | examples/05.rin/shaders.cpp | newpolaris/Ren | 9ce444e0d5e85ce60e6c7cf083ad53a6a8f32410 | [
"Apache-2.0"
] | null | null | null | examples/05.rin/shaders.cpp | newpolaris/Ren | 9ce444e0d5e85ce60e6c7cf083ad53a6a8f32410 | [
"Apache-2.0"
] | null | null | null | examples/05.rin/shaders.cpp | newpolaris/Ren | 9ce444e0d5e85ce60e6c7cf083ad53a6a8f32410 | [
"Apache-2.0"
] | null | null | null | #include "shaders.h"
#include "filesystem.h"
#include "macro.h"
#include <algorithm>
#include "spirv-reflect.h"
#include "macro.h"
#include "resources.h"
#include <string_view>
constexpr auto main = "main";
struct InputInterfaceAttribute
{
VkFormat format;
uint32_t location;
uint32_t stride;
std::string name;
};
using InputInterfaceAttributeList = std::vector<InputInterfaceAttribute>;
VkShaderStageFlagBits GetShaderStageBit(SpvExecutionModel model)
{
switch (model)
{
case SpvExecutionModelVertex:
return VK_SHADER_STAGE_VERTEX_BIT;
case SpvExecutionModelFragment:
return VK_SHADER_STAGE_FRAGMENT_BIT;
case SpvExecutionModelGLCompute:
return VK_SHADER_STAGE_COMPUTE_BIT;
case SpvExecutionModelTaskNV:
return VK_SHADER_STAGE_TASK_BIT_NV;
case SpvExecutionModelMeshNV:
return VK_SHADER_STAGE_MESH_BIT_NV;
}
ASSERT(FALSE);
}
uint32_t GetPrimitiveStride(const spirv::PrimitiveType& type) {
return type.width.value() * type.component_count[0] * type.component_count[1] / 8;
}
uint32_t GetPrimitiveStride(const spirv::SpirvReflections& reflections, const uint32_t& type_id) {
const auto& primitive = reflections.primitive_types.at(type_id);
return GetPrimitiveStride(primitive);
}
uint32_t GetStride(const spirv::SpirvReflections& reflections, const uint32_t& type_id) {
auto sit = reflections.struct_types.find(type_id);
if (sit != reflections.struct_types.end()) {
// last one's offset + length
const auto& last = sit->second.members.back();
return last.offset + GetStride(reflections, last.type_id);
}
auto ait = reflections.array_types.find(type_id);
if (ait != reflections.array_types.end()) {
const auto& arr = ait->second;
uint32_t element_stride = GetStride(reflections, arr.element_type_id);
auto cit = reflections.constants.find(arr.length_id);
ASSERT(cit != reflections.constants.end());
uint32_t length = cit->second.value;
ASSERT(length >= 1);
return element_stride * length;
}
// parse others
auto pit = reflections.primitive_types.find(type_id);
ASSERT(pit != reflections.primitive_types.end());
return GetPrimitiveStride(pit->second);
}
VkFormat GetPrimitiveFormat(const spirv::PrimitiveType& type) {
ASSERT(type.component_count[1] == 1);
switch (type.primitive_type) {
case SpvOpTypeInt:
switch (type.width.value()) {
case 8:
switch (type.component_count[0]) {
case 1: return type.signedness ? VK_FORMAT_R8_SINT : VK_FORMAT_R8_UINT;
case 2: return type.signedness ? VK_FORMAT_R8G8_SINT : VK_FORMAT_R8G8_UINT;
case 3: return type.signedness ? VK_FORMAT_R8G8B8_SINT : VK_FORMAT_R8G8B8_UINT;
case 4: return type.signedness ? VK_FORMAT_R8G8B8A8_SINT : VK_FORMAT_R8G8B8A8_UINT;
}
case 16:
switch (type.component_count[0]) {
case 1: return type.signedness ? VK_FORMAT_R16_SINT : VK_FORMAT_R16_UINT;
case 2: return type.signedness ? VK_FORMAT_R16G16_SINT : VK_FORMAT_R16G16_UINT;
case 3: return type.signedness ? VK_FORMAT_R16G16B16_SINT : VK_FORMAT_R16G16B16_UINT;
case 4: return type.signedness ? VK_FORMAT_R16G16B16A16_SINT : VK_FORMAT_R16G16B16A16_UINT;
}
case 32:
switch (type.component_count[0]) {
case 1: return type.signedness ? VK_FORMAT_R32_SINT : VK_FORMAT_R32_UINT;
case 2: return type.signedness ? VK_FORMAT_R32G32_SINT : VK_FORMAT_R32G32_UINT;
case 3: return type.signedness ? VK_FORMAT_R32G32B32_SINT : VK_FORMAT_R32G32B32_UINT;
case 4: return type.signedness ? VK_FORMAT_R32G32B32A32_SINT : VK_FORMAT_R32G32B32A32_UINT;
}
}
case SpvOpTypeFloat:
switch (type.width.value()) {
case 16:
switch (type.component_count[0]) {
case 1: return VK_FORMAT_R16_SFLOAT;
case 2: return VK_FORMAT_R16G16_SFLOAT;
case 3: return VK_FORMAT_R16G16B16_SFLOAT;
case 4: return VK_FORMAT_R16G16B16A16_SFLOAT;
}
case 32:
switch (type.component_count[0]) {
case 1: return VK_FORMAT_R32_SFLOAT;
case 2: return VK_FORMAT_R32G32_SFLOAT;
case 3: return VK_FORMAT_R32G32B32_SFLOAT;
case 4: return VK_FORMAT_R32G32B32A32_SFLOAT;
}
}
}
return VK_FORMAT_UNDEFINED;
}
// TODO: can't handle - f16vec2, float16_t case
//
// In input attribute declared as VK_FORMAT_R16G16B16A16, in vertex (vec4)
// so, result always 32
InputInterfaceAttributeList GetInputInterfaceVariables(const ShaderModule& shader, const std::string& name)
{
const auto& entries = shader.reflections.entry_points;
auto it = std::find_if(entries.begin(), entries.end(),
[&name](const auto& pts) { return name == pts.name; });
ASSERT(it != entries.end());
InputInterfaceAttributeList list;
const auto& EntryPoint(*it);
for (auto id : EntryPoint.interfaces_ids) {
const auto& var = shader.reflections.variables.at(id);
if (var.storage_class != SpvStorageClassInput)
continue;
if (var.builtin.has_value())
continue;
const auto& primitive = shader.reflections.primitive_types.at(var.type_id);
VkFormat format = GetPrimitiveFormat(primitive);
uint32_t stride = GetPrimitiveStride(primitive);
InputInterfaceAttribute att{format, var.location.value(), stride, var.name.value()};
list.emplace_back(std::move(att));
}
std::sort(list.begin(), list.end(), [](const auto& a, const auto& b) { return a.location < b.location; });
return std::move(list);
}
const spirv::EntryPoint& GetEntryPoint(const ShaderModule& shader, const std::string_view& name) {
const auto& entries = shader.reflections.entry_points;
auto it = std::find_if(entries.begin(), entries.end(), [&name](const auto& pts) { return name == pts.name; });
ASSERT(it != entries.end());
const auto& EntryPoint(*it);
return EntryPoint;
}
VkPipelineShaderStageCreateInfo GetPipelineShaderStageCreateInfo(const ShaderModule& shader,
const std::string_view& name) {
auto& entriy_point = GetEntryPoint(shader, name);
VkPipelineShaderStageCreateInfo info = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO };
info.stage = GetShaderStageBit(entriy_point.execution_model);
info.module = shader.module;
info.pName = name.data();
return std::move(info);
}
VkPushConstantRange GetPushConstantRangeUnion(ShaderModules shaders) {
VkPushConstantRange range = {};
for (const auto& shader : shaders) {
auto& reflection = shader.reflections;
auto& entry_point = GetEntryPoint(shader, main);
for (auto& v : reflection.variables) {
auto& var = v.second;
if (var.storage_class != SpvStorageClassPushConstant)
continue;
auto& st = reflection.struct_types.at(var.type_id);
// to calc range, use first one's offset
auto size = GetStride(reflection, var.type_id);
range.stageFlags |= GetShaderStageBit(entry_point.execution_model);
range.size = std::max(range.size, size);
}
}
return range;
}
std::vector<VkPushConstantRange> GetPushConstantRange(ShaderModules shaders) {
std::vector<VkPushConstantRange> ranges;
for (auto& shader : shaders) {
auto& reflection = shader.reflections;
auto& entry_point = GetEntryPoint(shader, main);
for (auto& v : reflection.variables) {
auto& var = v.second;
if (var.storage_class != SpvStorageClassPushConstant)
continue;
auto& st = reflection.struct_types.at(var.type_id);
// to calc range, use first one's offset
auto offset = st.members.front().offset;
auto size = GetStride(reflection, var.type_id);
VkPushConstantRange range = {};
range.stageFlags = GetShaderStageBit(entry_point.execution_model);
range.size = size;
range.offset = offset;
ranges.push_back(range);
}
}
// overlapping region requires both stage's flag in vkCmdPushConstants
// so prohibit it
#if _DEBUG
std::vector<std::pair<uint32_t, uint32_t>> intervals;
for (auto r : ranges)
intervals.push_back({r.offset, r.size});
std::sort(intervals.begin(), intervals.end());
for (size_t i = 1; i < intervals.size(); i++) {
uint32_t range_end = intervals[i-1].first + intervals[i-1].second;
uint32_t next_range_start = intervals[i].first;
ASSERT(range_end <= next_range_start);
}
#endif
return std::move(ranges);
}
struct PushDescriptorBinding {
VkShaderStageFlags flags;
VkDescriptorType type;
};
std::vector<PushDescriptorBinding> GetPushDesciptorBindingStages(ShaderModules shaders) {
// 32 seems to enough
std::vector<PushDescriptorBinding> stages(32);
for (const auto& shader : shaders) {
auto& entry_point = GetEntryPoint(shader, main);
auto flag = GetShaderStageBit(entry_point.execution_model);
for (auto& var : shader.reflections.variables) {
if (var.second.storage_class != SpvStorageClassUniform)
continue;
auto& binding = stages[var.second.binding.value()];
// check dupliated binding
ASSERT((binding.flags & flag) == binding.flags);
binding.flags |= flag;
if (var.second.storage_class == SpvStorageClassUniform)
binding.type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
}
}
return stages;
}
PushDescriptorSets::PushDescriptorSets(const Buffer& buffer) {
buffer_.buffer = buffer.buffer;
buffer_.offset = 0; // TODO: offset
// TODO: requested vs allocated ?
buffer_.range = buffer.info.size;
// buffer_.range = buffer.size;
}
ShaderModule CreateShaderModule(VkDevice device, const char* filepath) {
auto code = FileRead(filepath);
VkShaderModuleCreateInfo info = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO };
info.codeSize = code.size();
info.pCode = reinterpret_cast<uint32_t*>(code.data());
VkShaderModule module = VK_NULL_HANDLE;
VK_ASSERT(vkCreateShaderModule(device, &info, nullptr, &module));
spirv::SpirvReflections reflections = spirv::ReflectShader(code.data(), code.size());
return ShaderModule {
module,
std::move(reflections)
};
}
VkPipelineLayout CreatePipelineLayout(VkDevice device,
ShaderModules shaders,
const std::vector<VkPushConstantRange>& ranges,
const std::vector<PushDescriptorBinding>& stages) {
std::vector<VkDescriptorSetLayoutBinding> bindings;
for (size_t i = 0; i < stages.size(); i++) {
if (!stages[i].flags)
continue;
VkDescriptorSetLayoutBinding binding = {};
binding.binding = i;
binding.descriptorType = stages[i].type;
binding.descriptorCount = 1;
binding.stageFlags = stages[i].flags;
bindings.push_back(binding);
}
VkDescriptorSetLayoutCreateInfo set_create_info = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };
set_create_info.flags = VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR;
set_create_info.bindingCount = static_cast<uint32_t>(bindings.size());
set_create_info.pBindings = bindings.data();
VkDescriptorSetLayout set_layout = VK_NULL_HANDLE;
VK_ASSERT(vkCreateDescriptorSetLayout(device, &set_create_info, nullptr, &set_layout));
VkPipelineLayoutCreateInfo info = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO };
info.setLayoutCount = 1;
info.pSetLayouts = &set_layout;
info.pushConstantRangeCount = static_cast<uint32_t>(ranges.size());
info.pPushConstantRanges = ranges.data();
VkPipelineLayout layout = VK_NULL_HANDLE;
VK_ASSERT(vkCreatePipelineLayout(device, &info, nullptr, &layout));
vkDestroyDescriptorSetLayout(device, set_layout, nullptr);
return layout;
}
VkPipeline CreateComputePipeline(VkDevice device, VkPipelineLayout layout, ShaderModule shader) {
VkPipelineShaderStageCreateInfo stage = GetPipelineShaderStageCreateInfo(shader, main);
VkComputePipelineCreateInfo info = { VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO };
info.stage = stage;
info.layout = layout;
VkPipelineCache pipeline_cache = VK_NULL_HANDLE;
VkPipeline pipeline = VK_NULL_HANDLE;
VK_ASSERT(vkCreateComputePipelines(device, pipeline_cache, 1, &info, nullptr, &pipeline));
return pipeline;
}
VkPipeline CreateGraphicsPipeline(VkDevice device, VkPipelineLayout layout, VkRenderPass pass, ShaderModules shaders) {
std::vector<VkPipelineShaderStageCreateInfo> stages;
for (const auto& shader : shaders)
stages.push_back(GetPipelineShaderStageCreateInfo(shader, main));
VkPipelineVertexInputStateCreateInfo vertex_input_info {
VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO
};
VkPipelineInputAssemblyStateCreateInfo input_info {
VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO
};
input_info.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
VkPipelineViewportStateCreateInfo viewport_info { VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO };
viewport_info.viewportCount = 1;
viewport_info.scissorCount = 1;
VkPipelineRasterizationStateCreateInfo raster_info = { VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO };
raster_info.lineWidth = 1.0;
raster_info.polygonMode = VK_POLYGON_MODE_FILL;
raster_info.cullMode = VK_CULL_MODE_BACK_BIT;
raster_info.frontFace = VK_FRONT_FACE_CLOCKWISE;
VkPipelineMultisampleStateCreateInfo multisample_info = { VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO };
multisample_info.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
VkPipelineDepthStencilStateCreateInfo depth_info = { VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO };
depth_info.depthTestEnable = VK_TRUE;
depth_info.depthWriteEnable = VK_TRUE;
depth_info.depthCompareOp = VK_COMPARE_OP_GREATER;
VkPipelineColorBlendAttachmentState blendstate = {};
blendstate.blendEnable = VK_FALSE;
blendstate.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
VkPipelineColorBlendStateCreateInfo blend_info = { VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO };
blend_info.attachmentCount = 1;
blend_info.pAttachments = &blendstate;
VkDynamicState dynamic_state[] { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
VkPipelineDynamicStateCreateInfo dynamic_info = { VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO };
dynamic_info.dynamicStateCount = ARRAY_SIZE(dynamic_state);
dynamic_info.pDynamicStates = dynamic_state;
VkGraphicsPipelineCreateInfo info = { VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO };
info.stageCount = static_cast<uint32_t>(stages.size());
info.pStages = stages.data();
info.pVertexInputState = &vertex_input_info;
info.pInputAssemblyState = &input_info;
info.pViewportState = &viewport_info;
info.pRasterizationState = &raster_info;
info.pMultisampleState = &multisample_info;
info.pDepthStencilState = &depth_info;
info.pColorBlendState = &blend_info;
info.pDynamicState = &dynamic_info;
info.layout = layout;
info.renderPass = pass;
info.subpass = 0;
VkPipelineCache pipeline_cache = VK_NULL_HANDLE;
VkPipeline pipeline = VK_NULL_HANDLE;
VK_ASSERT(vkCreateGraphicsPipelines(device, pipeline_cache, 1, &info, nullptr, &pipeline));
return pipeline;
}
VkDescriptorUpdateTemplate CreateDescriptorUpdateTemplate(VkDevice device,
VkPipelineBindPoint bindpoint,
VkPipelineLayout layout,
ShaderModules shaders) {
std::vector<VkDescriptorType> bindings(32, VK_DESCRIPTOR_TYPE_MAX_ENUM);
for (auto& shader : shaders)
for (auto& var : shader.reflections.variables)
if (var.second.storage_class == SpvStorageClassUniform)
bindings[var.second.binding.value()] = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
std::vector<VkDescriptorUpdateTemplateEntry> entries;
for (size_t i = 0; i < bindings.size(); i++) {
if (bindings[i] == VK_DESCRIPTOR_TYPE_MAX_ENUM)
continue;
VkDescriptorUpdateTemplateEntry entry = {};
entry.dstBinding = static_cast<uint32_t>(i);
entry.descriptorCount = 1;
entry.descriptorType = bindings[i];
entry.offset = entries.size() * sizeof(PushDescriptorSets);
entry.stride = sizeof(PushDescriptorSets);
entries.push_back(entry);
}
VkDescriptorUpdateTemplateCreateInfo info = { VK_STRUCTURE_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_CREATE_INFO };
info.descriptorUpdateEntryCount = static_cast<uint32_t>(entries.size());
info.pDescriptorUpdateEntries = entries.data();
info.templateType = VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_PUSH_DESCRIPTORS_KHR;
info.descriptorSetLayout = VK_NULL_HANDLE;
info.pipelineBindPoint = bindpoint;
info.pipelineLayout = layout;
info.set = 0;
VkDescriptorUpdateTemplate descriptorUpdateTemplate = VK_NULL_HANDLE;
VK_ASSERT(vkCreateDescriptorUpdateTemplate(device, &info, nullptr, &descriptorUpdateTemplate));
return descriptorUpdateTemplate;
}
Program CreateProgram(VkDevice device, VkPipelineBindPoint bindpoint, ShaderModules shaders) {
auto stages = GetPushDesciptorBindingStages(shaders);
auto range = GetPushConstantRangeUnion(shaders);
std::vector<VkPushConstantRange> ranges;
if (range.size > 0) ranges.push_back(range);
auto layout = CreatePipelineLayout(device, shaders, ranges, stages);
auto update = CreateDescriptorUpdateTemplate(device, bindpoint, layout, shaders);
return Program { layout, update, range.stageFlags };
}
void DestroyProgram(VkDevice device, Program* program) {
vkDestroyPipelineLayout(device, program->layout, nullptr);
program->layout = VK_NULL_HANDLE;
vkDestroyDescriptorUpdateTemplate(device, program->update, nullptr);
program->update = VK_NULL_HANDLE;
}
| 41.048035 | 138 | 0.697021 | [
"vector",
"model"
] |
e2124fbaa025debc7be2a2b1e8932e76a5d270ed | 1,544 | hpp | C++ | src/ast/function.hpp | lsaos/pld-comp | 500e88684cccf8becd54ad13df18cde06ad093ac | [
"MIT"
] | null | null | null | src/ast/function.hpp | lsaos/pld-comp | 500e88684cccf8becd54ad13df18cde06ad093ac | [
"MIT"
] | null | null | null | src/ast/function.hpp | lsaos/pld-comp | 500e88684cccf8becd54ad13df18cde06ad093ac | [
"MIT"
] | null | null | null | //
// (c) 2019 The Super 4404 C Compiler
// A.Belin, A.Nahid, L.Ohl, L.Saos, A.Verrier, I.Zemmouri
// INSA Lyon
//
#pragma once
#include <string>
using namespace std;
#include "type.hpp"
#include "block.hpp"
#include "identifiable.hpp"
namespace ast
{
class Block;
// Represents a C function.
// It has a block of code and is an identifiable.
class Function : public Block, public Identifiable
{
public:
// Create a function.
Function(const ItemPosition& position);
public:
// Add the specified variable as a parameter of the function.
void addParameter(Variable* var);
// Mark the function as extern.
void setIsExtern();
public:
// Get the list of parameters.
vector<Variable*> getParameters() const;
// Get the number of parameters.
size_t getParametersCount() const;
// Return true if the variable is extern.
bool isExtern() const { return isExternal; }
public:
// Get a textual representation of the AST tree
virtual void toTextualRepresentation(ostream& out, size_t i) const;
// Get the symbol or the constant associated to an instruction, used for warning messages
virtual string getStringRepresentation() const;
public:
virtual bool isFunction() const { return true; }
virtual void generateAssembly(ofstream& f, unordered_map<ast::Variable*, int>& addressTable, string curReg = "%eax");
virtual string buildIR(ir::CFG*) { return string(); }
private:
bool isExternal; // True if the variable if extern.
};
}
| 24.507937 | 120 | 0.686528 | [
"vector"
] |
e215cc19c137d4f35be265a5a94ad599b2fe8efc | 2,591 | cpp | C++ | src/prod/src/Transport/RequestTable.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/Transport/RequestTable.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/Transport/RequestTable.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace Transport;
using namespace Common;
static Common::StringLiteral const TraceType("RequestTable");
RequestTable::RequestTable() : table_()
{
}
ErrorCode RequestTable::TryInsertEntry(Transport::MessageId const & messageId, RequestAsyncOperationSPtr & entry)
{
auto error = this->table_.TryAdd(messageId, entry);
if (!error.IsSuccess())
{
if (error.IsError(ErrorCodeValue::ObjectClosed))
{
WriteInfo(TraceType, "TryInsertEntry: dropping message {0}, failed to insert: {1}", messageId, error);
}
else
{
WriteError(TraceType, "TryInsertEntry: dropping message {0}, failed to insert: {1}", messageId, error);
Assert::TestAssert();
}
}
return error;
}
bool RequestTable::TryRemoveEntry(Transport::MessageId const & messageId, RequestAsyncOperationSPtr & operation)
{
return this->table_.TryGetAndRemove(messageId, operation);
}
std::vector<std::pair<Transport::MessageId, RequestAsyncOperationSPtr>> RequestTable::RemoveIf(std::function<bool(std::pair<MessageId, RequestAsyncOperationSPtr> const&)> const & predicate)
{
return table_.RemoveIf(predicate);
}
bool RequestTable::OnReplyMessage(Transport::Message & reply)
{
// If this method fails to remove from the table or complete the request, that means it has already been completed (most likely with a timeout)
RequestAsyncOperationSPtr operation;
if (!this->TryRemoveEntry(reply.RelatesTo, operation))
{
return false;
}
// Create an error with the fault value of the message and complete it. This will bubble up the fault code.
ErrorCode error(reply.FaultErrorCodeValue);
if (error.IsSuccess())
{
operation->SetReply(reply.Clone()); // todo, leikong, consider avoiding unnecessary cloning
}
else if (reply.HasFaultBody)
{
RejectFaultBody body;
if (reply.GetBody(body) && body.HasErrorMessage())
{
error.Overwrite(body.TakeError());
}
}
return operation->TryComplete(operation, error);
}
void RequestTable::Close()
{
auto tableCopy = this->table_.Close();
for(auto iter = tableCopy.begin(); iter != tableCopy.end(); ++ iter)
{
iter->second->Cancel();
}
}
| 31.987654 | 189 | 0.649942 | [
"vector"
] |
e21bb3fa5b8eca7d8a785d107cf5ca7868246b1f | 1,101 | cpp | C++ | FunctionTest.cpp | Boid-team/Boid | 944350fa72cd6a0ce6332ec9b5320fa0691a91dd | [
"MIT"
] | null | null | null | FunctionTest.cpp | Boid-team/Boid | 944350fa72cd6a0ce6332ec9b5320fa0691a91dd | [
"MIT"
] | null | null | null | FunctionTest.cpp | Boid-team/Boid | 944350fa72cd6a0ce6332ec9b5320fa0691a91dd | [
"MIT"
] | null | null | null | #include <ncurses.h>
#include <stdlib.h>
#include <time.h>
#include "Object.h"
#include "Bird.h"
#include "Functions.cpp"
using namespace std;
int main(){
srand(time(NULL));
int n = 25;
Object *array = new Bird[n];
char ch;
int frameCount = 0;
initscr();
halfdelay(2);
int height = 30;
int width = 100;
while(1){
if(ch == 'q' | ch == 'Q'){
break;
}else{
clear();
move(0,0);
hline('-',width);
move(0,width);
vline('|',height);
move(height,0);
hline('-',width);
steerWithinBounds(array,n,width,height);
steerTowardsCentre(array,n,0.03);
avoidOtherObjects(array,n,0.01);
matchVelocity(array,n,0.01);
for(int i = 0; i < n; i++){//loop through object array
array[i].setDirection(frameCount);
array[i].updatePos();
array[i].keepInBounds(width,height);
mvaddch(array[i].getY(), array[i].getX(), array[i].getDirection());
}
// mvaddch(getAverageY(array,n,&array[1]), getAverageX(array,n,&array[1]),'o');//draw centre of mass
frameCount++;
move(height,width);
ch = getch();
}
}
endwin();
delete[] array;
return 0;
}
| 14.878378 | 102 | 0.615804 | [
"object"
] |
e2239c3d02926f55f7f34db32d4093864955d131 | 2,717 | cpp | C++ | Templates/BiConnectedComponents_Bridges.cpp | Shahraaz/CP_S5 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | [
"MIT"
] | 3 | 2020-02-08T10:34:16.000Z | 2020-02-09T10:23:19.000Z | Templates/BiConnectedComponents_Bridges.cpp | Shahraaz/CP_S5 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | [
"MIT"
] | null | null | null | Templates/BiConnectedComponents_Bridges.cpp | Shahraaz/CP_S5 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | [
"MIT"
] | 2 | 2020-10-02T19:05:32.000Z | 2021-09-08T07:01:49.000Z | // Optimise
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
struct BiConnectedComponents
{
int n, m, T, cmpCnt;
vector<int> U, V, arr, compId;
vector<bool> isBridge, vis;
vector<vector<int>> adj_mytype, Tree;
vector<queue<int>> Q;
int getNode(int e, int node)
{
return U[e] == node ? V[e] : U[e];
}
int dfsBridge(int u, int edge)
{
vis[u] = 1;
arr[u] = T++;
int dbe = arr[u];
for (auto &e : adj_mytype[u])
{
int v = getNode(e, u);
if (!vis[v])
dbe = min(dbe, dfsBridge(v, e));
else if (e != edge)
dbe = min(dbe, arr[v]);
}
if (dbe == arr[u] && edge != -1)
isBridge[edge] = true;
return dbe;
}
void dfsBridgeTree(int node)
{
int currCmp = cmpCnt;
Q[currCmp].push(node);
vis[node] = true;
while (!Q[currCmp].empty())
{
int u = Q[currCmp].front();
Q[currCmp].pop();
compId[u] = currCmp;
for (auto &edge : adj_mytype[u])
{
int v = getNode(edge, u);
if (vis[v])
continue;
if (isBridge[edge])
{
cmpCnt++;
Tree[cmpCnt].push_back(currCmp);
Tree[currCmp].push_back(cmpCnt);
dfsBridgeTree(v);
}
else
{
Q[currCmp].push(v);
vis[v] = true;
}
}
}
}
void build_tree(vector<vector<int>> &adj)
{
n = adj.size();
m = 0;
adj_mytype.assign(n, vector<int>());
U.clear();
V.clear();
for (int i = 0; i < n; i++)
{
for (int j = 0; j < adj[i].size(); j++)
{
if (i < adj[i][j])
{
U.push_back(i);
V.push_back(adj[i][j]);
adj_mytype[i].push_back(m);
adj_mytype[adj[i][j]].push_back(m);
m++;
}
}
}
// db(m);
isBridge.assign(m, false);
vis.assign(n, false);
arr.assign(n, 0);
T = 0;
dfsBridge(0, -1);
fill(vis.begin(), vis.end(), false);
Tree.assign(n, vector<int>());
cmpCnt = 0;
compId.assign(n, 0);
Q.assign(n, queue<int>());
dfsBridgeTree(0);
Tree.resize(cmpCnt + 1);
}
};
| 25.392523 | 55 | 0.406699 | [
"vector"
] |
e22619fd8771cc625e1a7d5755609ecdd6ce73ee | 6,628 | cc | C++ | libgraph/planargraph-io.cc | jamesavery/spiralcode-reference | bb2f02e01447c3f3772eb5f2d7bad4d06c8ce29b | [
"BSD-2-Clause"
] | null | null | null | libgraph/planargraph-io.cc | jamesavery/spiralcode-reference | bb2f02e01447c3f3772eb5f2d7bad4d06c8ce29b | [
"BSD-2-Clause"
] | null | null | null | libgraph/planargraph-io.cc | jamesavery/spiralcode-reference | bb2f02e01447c3f3772eb5f2d7bad4d06c8ce29b | [
"BSD-2-Clause"
] | 1 | 2021-08-04T22:44:06.000Z | 2021-08-04T22:44:06.000Z | #include "planargraph.hh"
#include "polyhedron.hh"
#include <stdio.h>
//////////////////////////// FORMAT MULTIPLEXING ////////////////////////////
vector<string> PlanarGraph::formats{{"ascii","planarcode","xyz","mol2","mathematica","latex"}};
vector<string> PlanarGraph::input_formats{{"planarcode","xyz","mol2"}}; // TODO: Add ASCII
vector<string> PlanarGraph::output_formats{{"ascii","planarcode"}}; // TODO: Add LaTeX, Mathematica
int PlanarGraph::format_id(string name)
{
for(int i=0;i<formats.size();i++) if(name == formats[i]) return i;
return -1;
}
PlanarGraph PlanarGraph::from_file(FILE *file, string format, int index)
{
switch(format_id(format)){
case PLANARCODE:
return from_planarcode(file,index);
case XYZ:
return Polyhedron::from_xyz(file);
case MOL2:
return Polyhedron::from_mol2(file);
default:
cerr << "Input format is '" << format << "'; must be one of: " << input_formats << "\n";
abort();
}
}
bool PlanarGraph::to_file(const PlanarGraph &G, FILE *file, string format)
{
switch(format_id(format)){
case ASCII:
return PlanarGraph::to_ascii(G,file);
case PLANARCODE:
return PlanarGraph::to_planarcode(G,file);
default:
cerr << "Output format is '" << format << "'; must be one of: " << output_formats << "\n";
return false;
}
}
PlanarGraph PlanarGraph::from_file(string filename, int index)
{
FILE *file = fopen(filename.c_str(),"rb");
string extension = filename_extension(filename);
PlanarGraph G = from_file(file,extension);
fclose(file);
return G;
}
bool PlanarGraph::to_file(const PlanarGraph &G, string filename)
{
FILE *file = fopen(filename.c_str(),"wb");
string extension = filename_extension(filename);
to_file(G,file,extension);
fclose(file);
}
////////////////////////////// OUTPUT ROUTINES //////////////////////////////
// TODO: Where does this belong?
// Assumes file is at position of a graph start
PlanarGraph PlanarGraph::read_hog_planarcode(FILE *file)
{
// Read the number N of vertices per graph.
int number_length=1, N=0;
auto read_int = [&]() -> int {
int x = fgetc(file);
if(number_length==2) x |= (fgetc(file) << 8);
return x;
};
N = read_int();
if(N == 0){ number_length=2; N = read_int(); }
Graph g(N,true);
for(node_t u=0; u<N && !feof(file); ++u){
int v=0;
do{
v = read_int();
if(v!=0) g.neighbours[u].push_back(v-1); // In oriented order
} while(v!=0 && !feof(file));
}
// Check graph. TODO: does this belong here?
// for(node_t u=0;u<N;u++){
// for(auto v: g.neighbours[u]){
// bool found_vu = false;
// for(node_t w: g.neighbours[v])
// if(w == u) found_vu = true;
// if(!found_vu){
// fprintf(stderr,"Graph is not symmetric: (u,v) = (%d,%d) has\n",u,v);
// cerr << "neighbours["<<u<<"] = " << g.neighbours[u] <<";\n";
// cerr << "neighbours["<<v<<"] = " << g.neighbours[v] <<";\n";
// abort();
// }
// }
//}
return g;
}
bool PlanarGraph::read_hog_metadata(FILE *file, size_t &graph_count, size_t &graph_size)
{
const int header_size = 15;
// Get file size
size_t file_pos = ftell(file);
fseek(file, 0, SEEK_END);
size_t file_size = ftell(file);
//find number of vertices per graph
//this only works for files with graphs of equal size
fseek(file, header_size, SEEK_SET);
//Assumes planarcode files containing only graphs of equal size
Graph first(read_hog_planarcode(file));
graph_size = ftell(file)-header_size;
//check if selected graphnumber is valid
graph_count = (file_size - header_size ) / graph_size;
fseek(file,file_pos,SEEK_SET); // Back to where we started
return (ferror(file) == 0);
}
// TODO: Read only a range
vector<PlanarGraph> PlanarGraph::read_hog_planarcodes(FILE *file) {
const int header_size = 15;
vector<PlanarGraph> graph_list;
//the actual parsing of the selected graph:
//go to the beginning of the selected graph
fseek(file, header_size, SEEK_SET);
// int i = 1;
while(!feof(file)){
// cerr << "Reading graph " << (i++) << ".\n";
Graph g = read_hog_planarcode(file);
// cerr << "Got graph on " << g.N << " vertices.\n";
if(g.N != 0){
graph_list.push_back(g);
}
}
return graph_list;
}
// Write House of Graphs planarcode
bool PlanarGraph::to_planarcode(const PlanarGraph &G, FILE *file)
{
auto write_int = [&](uint16_t x){ fputc(x&0xff,file); if(G.N>255) fputc((x>>8)&0xff,file); };
fputs(">>planar_code<<",file);
if(G.N>255) fputc(0,file);
write_int(G.N);
for(uint16_t u=0;u<G.N;u++){
for(uint16_t v: G.neighbours[u])
write_int(v);
write_int(0);
}
return ferror(file) == 0;
}
bool PlanarGraph::to_ascii(const PlanarGraph &G, FILE *file)
{
// Neighbour list is unique representation of graph that preserves orientation.
// N is length of list.
string s = to_string(G.neighbours);
fputs(s.c_str(),file);
return ferror(file) == 0;
}
bool PlanarGraph::to_mathematica(const PlanarGraph &G, FILE *file)
{
ostringstream s;
s << G << "\n";
fputs(s.str().c_str(),file);
return ferror(file) == 0;
}
////////////////////////////// INPUT ROUTINES //////////////////////////////
// Parse House of Graphs planarcode (not restricted to cubic graphs)
PlanarGraph PlanarGraph::from_planarcode(FILE* file, const size_t index){
const int header_size = 15;
size_t graph_count = 0, graph_size = 0;
read_hog_metadata(file,graph_count,graph_size);
size_t address = header_size + graph_size * index;
//check if selected graphnumber is valid
if(graph_count-1 < index){
cerr << "You asked for the " << index+1 << (index==0?"st":(index==1?"nd":"th"))<<" graph, but there "
<<(graph_count==1?"is":"are")<<" only"
<< graph_count << " stored in this file." << std::endl;
abort();
}
//Find the beginning of the selected graph and read it
fseek(file, address, SEEK_SET);
return read_hog_planarcode(file);
}
////////////////////////////// AUXILIARY //////////////////////////////
string filename_extension(const string& filename)
{
size_t i = filename.rfind(".");
bool found = i != string::npos;
if(found)
return filename.substr(i+1,filename.size());
else
return "";
}
bool getline(FILE *file, string& str){
char *line_ptr = 0;
size_t line_length = 0;
ssize_t error = getline(&line_ptr,&line_length,file);
// fprintf(stderr,"error = %ld, line_length = %ld, line = %s\n",error,line_length,line_ptr);
// str = string(line_ptr,line_length);
str = string(line_ptr);
free(line_ptr);
return error > 0;
}
| 27.502075 | 105 | 0.621907 | [
"vector"
] |
e226f2c0f00b2c095886b30a316c71c85342b6ce | 5,478 | cpp | C++ | src/qt/qtwebkit/Source/WebCore/html/shadow/ContentDistributor.cpp | viewdy/phantomjs | eddb0db1d253fd0c546060a4555554c8ee08c13c | [
"BSD-3-Clause"
] | 1 | 2015-05-27T13:52:20.000Z | 2015-05-27T13:52:20.000Z | src/qt/qtwebkit/Source/WebCore/html/shadow/ContentDistributor.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtwebkit/Source/WebCore/html/shadow/ContentDistributor.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | 1 | 2022-02-18T10:41:38.000Z | 2022-02-18T10:41:38.000Z | /*
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "ContentDistributor.h"
#include "ElementShadow.h"
#include "HTMLContentElement.h"
#include "NodeTraversal.h"
#include "ShadowRoot.h"
namespace WebCore {
ContentDistributor::ContentDistributor()
: m_insertionPointListIsValid(true)
, m_validity(Undetermined)
{
}
ContentDistributor::~ContentDistributor()
{
}
void ContentDistributor::invalidateInsertionPointList()
{
m_insertionPointListIsValid = false;
m_insertionPointList.clear();
}
const Vector<RefPtr<InsertionPoint> >& ContentDistributor::ensureInsertionPointList(ShadowRoot* shadowRoot)
{
if (m_insertionPointListIsValid)
return m_insertionPointList;
m_insertionPointListIsValid = true;
ASSERT(m_insertionPointList.isEmpty());
for (Element* element = ElementTraversal::firstWithin(shadowRoot); element; element = ElementTraversal::next(element, shadowRoot)) {
if (element->isInsertionPoint())
m_insertionPointList.append(toInsertionPoint(element));
}
return m_insertionPointList;
}
InsertionPoint* ContentDistributor::findInsertionPointFor(const Node* key) const
{
return m_nodeToInsertionPoint.get(key);
}
void ContentDistributor::distribute(Element* host)
{
ASSERT(needsDistribution());
ASSERT(m_nodeToInsertionPoint.isEmpty());
ASSERT(!host->containingShadowRoot() || host->containingShadowRoot()->owner()->distributor().isValid());
m_validity = Valid;
if (ShadowRoot* root = host->shadowRoot()) {
const Vector<RefPtr<InsertionPoint> >& insertionPoints = ensureInsertionPointList(root);
for (size_t i = 0; i < insertionPoints.size(); ++i) {
InsertionPoint* point = insertionPoints[i].get();
if (!point->isActive())
continue;
distributeSelectionsTo(point, host);
}
}
}
bool ContentDistributor::invalidate(Element* host)
{
ASSERT(needsInvalidation());
bool needsReattach = (m_validity == Undetermined) || !m_nodeToInsertionPoint.isEmpty();
if (ShadowRoot* root = host->shadowRoot()) {
const Vector<RefPtr<InsertionPoint> >& insertionPoints = ensureInsertionPointList(root);
for (size_t i = 0; i < insertionPoints.size(); ++i) {
needsReattach = true;
insertionPoints[i]->clearDistribution();
}
}
m_validity = Invalidating;
m_nodeToInsertionPoint.clear();
return needsReattach;
}
void ContentDistributor::distributeSelectionsTo(InsertionPoint* insertionPoint, Element* host)
{
for (Node* child = host->firstChild(); child; child = child->nextSibling()) {
ASSERT(!child->isInsertionPoint());
if (insertionPoint->matchTypeFor(child) != InsertionPoint::AlwaysMatches)
continue;
m_nodeToInsertionPoint.add(child, insertionPoint);
}
if (m_nodeToInsertionPoint.isEmpty())
return;
insertionPoint->setHasDistribution();
}
void ContentDistributor::ensureDistribution(ShadowRoot* shadowRoot)
{
ASSERT(shadowRoot);
Vector<ElementShadow*, 8> elementShadows;
for (Element* current = shadowRoot->host(); current; current = current->shadowHost()) {
ElementShadow* elementShadow = current->shadow();
if (!elementShadow->distributor().needsDistribution())
break;
elementShadows.append(elementShadow);
}
for (size_t i = elementShadows.size(); i > 0; --i)
elementShadows[i - 1]->distributor().distribute(elementShadows[i - 1]->host());
}
void ContentDistributor::invalidateDistribution(Element* host)
{
bool didNeedInvalidation = needsInvalidation();
bool needsReattach = didNeedInvalidation ? invalidate(host) : false;
if (needsReattach && host->attached()) {
for (Node* n = host->firstChild(); n; n = n->nextSibling())
n->lazyReattach();
host->setNeedsStyleRecalc();
}
if (didNeedInvalidation) {
ASSERT(m_validity == Invalidating);
m_validity = Invalidated;
}
}
void ContentDistributor::didShadowBoundaryChange(Element* host)
{
setValidity(Undetermined);
invalidateDistribution(host);
}
}
| 32.035088 | 136 | 0.707558 | [
"vector"
] |
e226fd4e2c8402c69f97d8818a13d4da6ab9ace9 | 12,043 | cpp | C++ | lidardet/ops/lidar_bev/bev.cpp | Jiaolong/trajectory-prediction | 3fd4e6253b44dfdc86e7c08e93c002baf66f2e46 | [
"Apache-2.0"
] | 6 | 2021-05-10T09:42:01.000Z | 2022-01-04T08:03:42.000Z | lidardet/ops/lidar_bev/bev.cpp | Jiaolong/trajectory-prediction | 3fd4e6253b44dfdc86e7c08e93c002baf66f2e46 | [
"Apache-2.0"
] | 3 | 2021-08-16T02:19:10.000Z | 2022-01-10T02:05:48.000Z | lidardet/ops/lidar_bev/bev.cpp | Jiaolong/trajectory-prediction | 3fd4e6253b44dfdc86e7c08e93c002baf66f2e46 | [
"Apache-2.0"
] | 1 | 2021-07-15T00:51:58.000Z | 2021-07-15T00:51:58.000Z | // pybind libraries
#include <pybind11/eigen.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
// C/C++ includes
#include <cfloat>
#include <chrono>
#include <cmath>
#include <vector>
namespace py = pybind11;
using namespace std;
/*
* @brief returns all the voxels that are traversed by a ray going from start to end
* @param start : continous world position where the ray starts
* @param end : continous world position where the ray end
* @return vector of voxel ids hit by the ray in temporal order
*
* J. Amanatides, A. Woo. A Fast Voxel Traversal Algorithm for Ray Tracing. Eurographics '87
*
* Code adapted from: https://github.com/francisengelmann/fast_voxel_traversal
*
* Warning:
* This is not production-level code.
*/
inline void _voxel_traversal(std::vector<Eigen::Vector3i>& visited_voxels,
const Eigen::Vector3d& ray_start,
const Eigen::Vector3d& ray_end,
const Eigen::VectorXf lidar_range,
const double voxel_size)
{
int xmin = floor(lidar_range[0] / voxel_size);
int xmax = floor(lidar_range[1] / voxel_size);
int ymin = floor(lidar_range[2] / voxel_size);
int ymax = floor(lidar_range[3] / voxel_size);
int zmin = floor(lidar_range[4] / voxel_size);
int zmax = floor(lidar_range[5] / voxel_size);
// Compute normalized ray direction.
Eigen::Vector3d ray = ray_end - ray_start;
// ray.normalize();
// This id of the first/current voxel hit by the ray.
// Using floor (round down) is actually very important,
// the implicit int-casting will round up for negative numbers.
Eigen::Vector3i current_voxel(floor(ray_start[0] / voxel_size),
floor(ray_start[1] / voxel_size),
floor(ray_start[2] / voxel_size));
// create aliases for indices of the current voxel
int &vx = current_voxel[0], &vy = current_voxel[1], &vz = current_voxel[2];
// The id of the last voxel hit by the ray.
// TODO: what happens if the end point is on a border?
Eigen::Vector3i last_voxel(floor(ray_end[0] / voxel_size),
floor(ray_end[1] / voxel_size),
floor(ray_end[2] / voxel_size));
// In which direction the voxel ids are incremented.
int stepX = (ray[0] >= 0) ? 1 : -1; // correct
int stepY = (ray[1] >= 0) ? 1 : -1; // correct
int stepZ = (ray[2] >= 0) ? 1 : -1; // correct
// Distance along the ray to the next voxel border from the current position (tMaxX, tMaxY, tMaxZ).
double next_voxel_boundary_x = (vx + stepX) * voxel_size; // correct
double next_voxel_boundary_y = (vy + stepY) * voxel_size; // correct
double next_voxel_boundary_z = (vz + stepZ) * voxel_size; // correct
// tMaxX, tMaxY, tMaxZ -- distance until next intersection with voxel-border
// the value of t at which the ray crosses the first vertical voxel boundary
double tMaxX = (ray[0] != 0) ? (next_voxel_boundary_x - ray_start[0]) / ray[0] : DBL_MAX; //
double tMaxY = (ray[1] != 0) ? (next_voxel_boundary_y - ray_start[1]) / ray[1] : DBL_MAX; //
double tMaxZ = (ray[2] != 0) ? (next_voxel_boundary_z - ray_start[2]) / ray[2] : DBL_MAX; //
// tDeltaX, tDeltaY, tDeltaZ --
// how far along the ray we must move for the horizontal component to equal the width of a voxel
// the direction in which we traverse the grid
// can only be FLT_MAX if we never go in that direction
double tDeltaX = (ray[0] != 0) ? voxel_size / ray[0] * stepX : DBL_MAX;
double tDeltaY = (ray[1] != 0) ? voxel_size / ray[1] * stepY : DBL_MAX;
double tDeltaZ = (ray[2] != 0) ? voxel_size / ray[2] * stepZ : DBL_MAX;
// Note: I am not sure why there is a need to do this, but I am keeping it for now
// possibly explained by: https://github.com/francisengelmann/fast_voxel_traversal/issues/6
Eigen::Vector3i diff(0, 0, 0);
bool neg_ray = false;
if (vx != last_voxel[0] && ray[0] < 0) {
diff[0]--;
neg_ray = true;
}
if (vy != last_voxel[1] && ray[1] < 0) {
diff[1]--;
neg_ray = true;
}
if (vz != last_voxel[2] && ray[2] < 0) {
diff[2]--;
neg_ray = true;
}
visited_voxels.push_back(current_voxel);
if (neg_ray) {
current_voxel += diff;
visited_voxels.push_back(current_voxel);
}
// ray casting loop
bool truncated = false;
while (current_voxel != last_voxel) {
if (tMaxX < tMaxY) {
if (tMaxX < tMaxZ) {
vx += stepX;
truncated = (vx < xmin || vx >= xmax);
tMaxX += tDeltaX;
} else {
vz += stepZ;
truncated = (vz < zmin || vz >= zmax);
tMaxZ += tDeltaZ;
}
} else {
if (tMaxY < tMaxZ) {
vy += stepY;
truncated = (vy < ymin || vy >= ymax);
tMaxY += tDeltaY;
} else {
vz += stepZ;
truncated = (vz < zmin || vz >= zmax);
tMaxZ += tDeltaZ;
}
}
if (truncated)
break;
visited_voxels.push_back(current_voxel);
}
}
Eigen::MatrixXf rgb_traversability_map(
const Eigen::MatrixXf& points, /* Nx5 ndarray, [x, y, z, intensity, obstacle] */
const Eigen::VectorXf lidar_range, /* (6,) ndarray, [xmin, xmax, ymin, ymax, zmin, zmax] */
double sensor_height, /* lidar mounted height */
double bev_res /* meters per pixel*/)
{
auto xmin = lidar_range[0];
auto xmax = lidar_range[1];
auto ymin = lidar_range[2];
auto ymax = lidar_range[3];
auto zmin = lidar_range[4];
auto zmax = lidar_range[5];
int img_w = int((xmax - xmin) / bev_res);
int img_h = int((ymax - ymin) / bev_res);
// bev_map has 5 channels: intensity, height, density, inferenced state, initial state
// cell state code, 0: unknow, 1: obstacle, 2: free space
Eigen::MatrixXf bev_map = Eigen::MatrixXf::Zero(img_h * img_w, 5);
std::vector<ssize_t> valid_ids;
for (ssize_t n = 0; n < points.rows(); n++) {
auto x = points(n, 0);
if (x < xmin || x > xmax)
continue;
auto y = points(n, 1);
if (y < ymin || y > ymax)
continue;
auto z = points(n, 2);
if (z < zmin || z > zmax)
continue;
valid_ids.push_back(n);
auto i = points(n, 3);
auto o = points(n, 4);
// convert to ego-car coordinate
int px = floor((x - xmin) / bev_res);
int py = floor((ymax - y) / bev_res);
double h = (z - zmin) / (zmax - zmin);
px = std::min(px, img_w - 1);
py = std::min(py, img_h - 1);
int idx = py * img_w + px;
bev_map(idx, 0) += i;
if (h > bev_map(idx, 1))
bev_map(idx, 1) = h;
bev_map(idx, 2) += 1;
if (o == 1)
bev_map(idx, 4) = 1;
else
bev_map(idx, 4) = 2;
bev_map(idx, 3) = bev_map(idx, 4);
}
for (ssize_t py = 0; py < img_h; py++) {
for (ssize_t px = 0; px < img_w; px++) {
int idx = py * img_w + px;
auto c = bev_map(idx, 2);
if (c > 0) {
bev_map(idx, 0) /= c;
}
bev_map(idx, 2) = std::min(1.0, log(c + 1) / log(64));
}
}
Eigen::Vector3d origin(0, 0, sensor_height);
// compute visibility
for (auto n : valid_ids) {
Eigen::Vector3d point = points.row(n).head(3).cast<double>();
std::vector<Eigen::Vector3i> visited_voxels;
_voxel_traversal(visited_voxels, origin, point, lidar_range, bev_res);
const int M = visited_voxels.size();
for (int j = 0; j < M; ++j) {
int vx = int(visited_voxels[j][0] - xmin / bev_res);
int vy = int(ymax / bev_res - visited_voxels[j][1]);
int vidx = vy * img_w + vx;
if (bev_map(vidx, 3) != 0)
continue;
bev_map(vidx, 3) = 2; // free
} // M
}
return bev_map;
}
Eigen::MatrixXf rgb_map(
const Eigen::MatrixXf& points, /* Nx4 ndarray */
const Eigen::VectorXf lidar_range, /* (6,) ndarray, [xmin, xmax, ymin, ymax, zmin, zmax] */
double bev_res /* m per pixel*/)
{
auto xmin = lidar_range[0];
auto xmax = lidar_range[1];
auto ymin = lidar_range[2];
auto ymax = lidar_range[3];
auto zmin = lidar_range[4];
auto zmax = lidar_range[5];
int img_w = int((xmax - xmin) / bev_res);
int img_h = int((ymax - ymin) / bev_res);
Eigen::MatrixXf bev_map = Eigen::MatrixXf::Zero(img_h * img_w, 3);
for (ssize_t n = 0; n < points.rows(); n++) {
auto x = points(n, 0);
if (x < xmin || x > xmax)
continue;
auto y = points(n, 1);
if (y < ymin || y > ymax)
continue;
auto z = points(n, 2);
if (z < zmin || z > zmax)
continue;
auto i = points(n, 3);
// convert to ego-car coordinate
int px = floor((x - xmin) / bev_res);
int py = floor((ymax - y) / bev_res);
double h = (z - zmin) / (zmax - zmin);
px = std::min(px, img_w - 1);
py = std::min(py, img_h - 1);
int idx = py * img_w + px;
bev_map(idx, 0) += i;
if (h > bev_map(idx, 1))
bev_map(idx, 1) = h;
bev_map(idx, 2) += 1;
}
for (ssize_t py = 0; py < img_h; py++) {
for (ssize_t px = 0; px < img_w; px++) {
int idx = py * img_w + px;
auto c = bev_map(idx, 2);
if (c > 0) {
bev_map(idx, 0) /= c;
}
bev_map(idx, 2) = std::min(1.0, log(c + 1) / log(64));
}
}
return bev_map;
}
Eigen::MatrixXf height_map(
const Eigen::MatrixXf& points, /* Nx4 ndarray */
const Eigen::VectorXf lidar_range, /* (6,) ndarray, [xmin, xmax, ymin, ymax, zmin, zmax] */
double bev_res /* m per pixel*/)
{
auto xmin = lidar_range[0];
auto xmax = lidar_range[1];
auto ymin = lidar_range[2];
auto ymax = lidar_range[3];
auto zmin = lidar_range[4];
auto zmax = lidar_range[5];
int img_w = int((xmax - xmin) / bev_res);
int img_h = int((ymax - ymin) / bev_res);
int nz = floor((zmax - zmin) / bev_res) + 1;
Eigen::MatrixXf bev_map = Eigen::MatrixXf::Zero(img_h * img_w, nz);
std::vector<int> density_map(img_h * img_w);
for (ssize_t n = 0; n < points.rows(); n++) {
auto x = points(n, 0);
if (x < xmin || x > xmax)
continue;
auto y = points(n, 1);
if (y < ymin || y > ymax)
continue;
auto z = points(n, 2);
if (z < zmin || z > zmax)
continue;
auto i = points(n, 3);
// convert to ego-car coordinate
int px = floor((x - xmin) / bev_res);
int py = floor((ymax - y) / bev_res);
int pz = floor((z - zmin) / bev_res);
px = std::min(px, img_w - 1);
py = std::min(py, img_h - 1);
pz = std::min(pz, nz - 2);
int idx = py * img_w + px;
bev_map(idx, pz) = 1;
bev_map(idx, nz - 1) += i;
density_map[idx] += 1;
}
for (ssize_t py = 0; py < img_h; py++) {
for (ssize_t px = 0; px < img_w; px++) {
int idx = py * img_w + px;
auto c = density_map[idx];
if (c > 0) {
bev_map(idx, nz - 1) /= c;
}
}
}
return bev_map;
}
PYBIND11_MODULE(bev, m)
{
m.doc() = "Create BEV map from lidar points";
m.def("rgb_map",
&rgb_map,
py::arg("points"),
py::arg("lidar_range"),
py::arg("bev_res"));
m.def("height_map",
&height_map,
py::arg("points"),
py::arg("lidar_range"),
py::arg("bev_res"));
m.def("rgb_traversability_map",
&rgb_traversability_map,
py::arg("points"),
py::arg("lidar_range"),
py::arg("sensor_height"),
py::arg("bev_res"));
}
| 33.085165 | 103 | 0.542307 | [
"vector"
] |
e2378dce0febf1ea1827eb3d82128bc78f40dae8 | 805 | cpp | C++ | leetcode_archived_cpp/LeetCode_56.cpp | Sean10/Algorithm_code | 46ff1cb5b81400cbcc324dabdf4298bf7a55e5eb | [
"BSD-3-Clause"
] | null | null | null | leetcode_archived_cpp/LeetCode_56.cpp | Sean10/Algorithm_code | 46ff1cb5b81400cbcc324dabdf4298bf7a55e5eb | [
"BSD-3-Clause"
] | 7 | 2021-03-19T04:41:21.000Z | 2021-10-19T15:46:36.000Z | leetcode_archived_cpp/LeetCode_56.cpp | Sean10/Algorithm_code | 46ff1cb5b81400cbcc324dabdf4298bf7a55e5eb | [
"BSD-3-Clause"
] | null | null | null | /**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
public:
vector<Interval> merge(vector<Interval>& intervals) {
if(intervals.empty())
return vector<Interval>{};
vector<Interval> ans;
sort(intervals.begin(), intervals.end(), [](Interval a, Interval b){return a.start < b.start;});
ans.push_back(intervals[0]);
for(int i = 1;i < intervals.size(); i++)
{
if (ans.back().end < intervals[i].start)
ans.push_back(intervals[i]);
else
ans.back().end = max(ans.back().end, intervals[i].end);
}
return ans;
}
};
| 25.15625 | 104 | 0.519255 | [
"vector"
] |
e23ad2f6272b35e0603e28582b9bb6af315e7050 | 1,312 | cpp | C++ | Extensions/ResourceIO/src/XMLRemovedBuildingSerializer.cpp | bkmsstudio/minecraftserver | fd42ab6e4cc986d32b31f3a13d6200778570bf51 | [
"MIT"
] | null | null | null | Extensions/ResourceIO/src/XMLRemovedBuildingSerializer.cpp | bkmsstudio/minecraftserver | fd42ab6e4cc986d32b31f3a13d6200778570bf51 | [
"MIT"
] | null | null | null | Extensions/ResourceIO/src/XMLRemovedBuildingSerializer.cpp | bkmsstudio/minecraftserver | fd42ab6e4cc986d32b31f3a13d6200778570bf51 | [
"MIT"
] | null | null | null | #include SAMPEDGENGINE_EXT_RESOURCEIO_PCH
#include <SAMP-EDGEngine/Ext/ResourceIO/XMLRemovedBuildingSerializer.hpp>
#include <SAMP-EDGEngine/Ext/ResourceIO/XMLHelperFunctions.hpp>
#include <SAMP-EDGEngine/Ext/ResourceIO/XMLNames.hpp>
namespace samp_edgengine::ext::resource_io
{
//////////////////////////////////////////////////////////////////////////////
bool XMLRemovedBuildingSerializer::serialize() const
{
xml::xml_node<>& node = *parentNode.document()->allocate_node(xml::node_element, XMLNames::RemovedBuildingNode);
parentNode.append_node(&node);
{
const_a modelIndex = removedBuilding.model;
const_a radius = removedBuilding.radius.value;
const_a origin = removedBuilding.origin;
xml_helper::setAttribute(node, XMLNames::Attributes::ModelIndex, std::to_string(modelIndex), xml_helper::AllocValue);
xml_helper::setAttribute(node, XMLNames::Attributes::Radius, std::to_string(radius), xml_helper::AllocValue);
xml_helper::setAttribute(node, XMLNames::Attributes::OriginX, std::to_string(origin.x), xml_helper::AllocValue);
xml_helper::setAttribute(node, XMLNames::Attributes::OriginY, std::to_string(origin.y), xml_helper::AllocValue);
xml_helper::setAttribute(node, XMLNames::Attributes::OriginZ, std::to_string(origin.z), xml_helper::AllocValue);
}
return true;
}
}
| 41 | 119 | 0.740091 | [
"model"
] |
e23e71fa535a0732b8c970fba654a4e5aed075ea | 5,373 | cpp | C++ | cs1400/projects/lionheart/Action.cpp | McKayRansom/CourseMaterials | 976552ffca4d9d6e822c74a19bc108f3435bdab1 | [
"MIT"
] | 6 | 2017-04-07T17:57:48.000Z | 2020-02-01T22:26:43.000Z | cs1400/projects/lionheart/Action.cpp | McKayRansom/CourseMaterials | 976552ffca4d9d6e822c74a19bc108f3435bdab1 | [
"MIT"
] | 20 | 2017-03-29T22:26:47.000Z | 2019-12-01T05:58:12.000Z | cs1400/projects/lionheart/Action.cpp | McKayRansom/CourseMaterials | 976552ffca4d9d6e822c74a19bc108f3435bdab1 | [
"MIT"
] | 91 | 2017-03-29T00:23:21.000Z | 2021-01-10T14:19:02.000Z | #include "Action.hpp"
#include <algorithm>
#include <cassert>
namespace lionheart
{
std::ostream &serialize(std::ostream &os, const Placement &placement)
{
return os << placement.row << " " << placement.col;
}
std::istream &deserialize(std::istream &is, Placement &placement)
{
is >> placement.row;
is >> placement.col;
return is;
}
class MoveImpl : public ActionImpl
{
public:
MoveImpl(int d)
: ActionImpl()
, dist(d)
{
}
std::unique_ptr<ActionImpl> clone() const override
{
return std::unique_ptr<ActionImpl>(new MoveImpl(dist));
}
bool apply(std::shared_ptr<const Map> const &map,
Unit &actor,
std::vector<std::shared_ptr<Unit>> &allies,
std::vector<std::shared_ptr<Unit>> &enemies) override
{
if (dist > actor.getMoveSpeed())
{
dist = actor.getMoveSpeed();
}
auto actLocation = actor.getLocation();
Placement curLoc{ actLocation.row, actLocation.col };
// verify move is legal (no intervening rocks or units)
for (auto i = 0; i < dist; ++i)
{
auto nextLoc = getNext(curLoc, actor);
// check for rocks
if ((*map)[map->at(nextLoc.row, nextLoc.col)] == lionheart::Tile::ROCK)
{
break;
}
auto sameLocation = [&](std::shared_ptr<Unit> const &u)
{ return u->getLocation() == map->at(nextLoc.row, nextLoc.col); };
// check for allies
auto aiter = std::find_if(allies.begin(), allies.end(), sameLocation);
if (aiter != allies.end())
{
break;
}
// check for enemies
auto eiter = std::find_if(enemies.begin(), enemies.end(), sameLocation);
if (eiter != enemies.end())
{
break;
}
// current location okay, iterate to check next location
curLoc = nextLoc;
}
return actor.move(map->at(curLoc.row, curLoc.col));
}
int getDistance() const
{
return dist;
}
void serialize(std::ostream & os) const override
{
os << 1 << " " << dist;
}
private:
Placement getNext(Placement const &old, Unit const &actor)
{
auto result = old;
switch (actor.getFacing())
{
case Direction::NORTH:
--result.row;
break;
case Direction::SOUTH:
++result.row;
break;
case Direction::EAST:
++result.col;
break;
case Direction::WEST:
--result.col;
break;
}
return result;
}
int dist;
};
class TurnImpl : public ActionImpl
{
public:
TurnImpl(Direction d)
: ActionImpl()
, dir(d)
{
}
std::unique_ptr<ActionImpl> clone() const
{
return std::unique_ptr<ActionImpl>(new TurnImpl(dir));
}
bool apply(std::shared_ptr<const Map> const &,
Unit &actor,
std::vector<std::shared_ptr<Unit>> &,
std::vector<std::shared_ptr<Unit>> &) override
{
actor.turn(dir);
return true;
}
Direction getDirection() const
{
return dir;
}
void serialize(std::ostream & os) const override
{
os << 2 << " ";
lionheart::serialize(os,dir);
}
private:
Direction dir;
};
class AttackImpl : public ActionImpl
{
public:
AttackImpl(Placement p)
: ActionImpl()
, target(p)
{
}
std::unique_ptr<ActionImpl> clone() const
{
return std::unique_ptr<ActionImpl>(new AttackImpl(target));
}
bool apply(std::shared_ptr<const Map> const &,
Unit &actor,
std::vector<std::shared_ptr<Unit>> &,
std::vector<std::shared_ptr<Unit>> &enemies) override
{
// find legal target
auto eIter = std::find_if(enemies.begin(),
enemies.end(),
[&](std::shared_ptr<Unit> const & u)->bool
{
auto loc = u->getLocation();
if ((loc.row == target.row) && (loc.col == target.col))
return true;
return false;
});
if (eIter != enemies.end())
{
auto &enemy = *eIter;
if (actor.inRange(enemy->getLocation()))
{
actor.attack(*enemy);
return true;
}
}
return false;
}
void serialize(std::ostream & os) const override
{
assert(!"Attack actions should not be serialized to maps");
os << 0 << " ";
}
private:
Placement target;
};
}
lionheart::Action lionheart::turn(Direction d)
{
return Action(std::unique_ptr<TurnImpl>(new TurnImpl(d)));
}
lionheart::Action lionheart::move(int distance)
{
return Action(std::unique_ptr<MoveImpl>(new MoveImpl(distance)));
}
lionheart::Action lionheart::wait()
{
// Return default constructed action (do nothing)
return Action();
}
lionheart::Action lionheart::attack(Placement p)
{
return Action(std::unique_ptr<AttackImpl>(new AttackImpl(p)));
}
std::ostream & ::lionheart::serialize(std::ostream &os, const Action &action)
{
if (action.pImpl)
{
action.pImpl->serialize(os);
}
else
{
os << 0 << " ";
}
return os;
}
std::istream & ::lionheart::deserialize(std::istream &is, Action &placement)
{
int type;
is >> type;
switch (type)
{
case 0:
placement = Action(NULL);
break;
case 1:
int dist;
is >> dist;
placement = move(dist);
break;
case 2:
Direction dir;
deserialize(is, dir);
placement = turn(dir);
break;
default:
throw "Attempted to deserialize an action that isn't a movement or turn.";
break;
}
return is;
}
| 21.841463 | 78 | 0.591476 | [
"vector"
] |
e241af38b382395524b4da8cc6dd3aa1f07a7c27 | 1,533 | cpp | C++ | assignment2/MeshGenerators/cube_generator.cpp | MichaelReiter/CSC305 | 37e52be3a82c990032d9113747d1cf1db5125b07 | [
"MIT"
] | null | null | null | assignment2/MeshGenerators/cube_generator.cpp | MichaelReiter/CSC305 | 37e52be3a82c990032d9113747d1cf1db5125b07 | [
"MIT"
] | null | null | null | assignment2/MeshGenerators/cube_generator.cpp | MichaelReiter/CSC305 | 37e52be3a82c990032d9113747d1cf1db5125b07 | [
"MIT"
] | null | null | null | #include "cube_generator.h"
namespace MeshGenerators {
CubeGenerator::CubeGenerator() {}
CubeGenerator::~CubeGenerator() {}
void CubeGenerator::write_to_file(std::ofstream& file) const
{
file << "# cube" << std::endl;
std::vector<OpenGP::Vec3> vertices {
{-1, -1, 1},
{1, -1, 1},
{-1, 1, 1},
{1, 1, 1},
{-1, 1, -1},
{1, 1, -1},
{-1, -1, -1},
{1, -1, -1}
};
write_vertices(file, vertices);
std::vector<OpenGP::Vec3> vertex_indices {
{1, 2, 3},
{3, 2, 4},
{3, 4, 5},
{5, 4, 6},
{5, 6, 7},
{7, 6, 8},
{7, 8, 1},
{1, 8, 2},
{2, 8, 4},
{4, 8, 6},
{7, 1, 5},
{5, 1, 3}
};
std::vector<OpenGP::Vec3> normals {
{0, 0, 1},
{0, 1, 0},
{0, 0, -1},
{0, -1, 0},
{1, 0, 0},
{-1, 0, 0}
};
std::vector<OpenGP::Vec3> normal_indices {
{1, 1, 1},
{1, 1, 1},
{2, 2, 2},
{2, 2, 2},
{3, 3, 3},
{3, 3, 3},
{4, 4, 4},
{4, 4, 4},
{5, 5, 5},
{5, 5, 5},
{6, 6, 6},
{6, 6, 6}
};
write_vertex_normals(file, normals);
write_faces(file, vertex_indices, normal_indices, vertex_indices);
}
}
| 24.725806 | 74 | 0.332029 | [
"vector"
] |
e24840b8b7ed3ddfa9977c926b64cc49c4b3ab18 | 441 | cpp | C++ | impl/jamtemplate/common/tilemap/tilemap_helpers.cpp | Thunraz/JamTemplateCpp | ee516d8a57dcfa6e7997585ab9bd7ff7df3640ea | [
"CC0-1.0"
] | null | null | null | impl/jamtemplate/common/tilemap/tilemap_helpers.cpp | Thunraz/JamTemplateCpp | ee516d8a57dcfa6e7997585ab9bd7ff7df3640ea | [
"CC0-1.0"
] | null | null | null | impl/jamtemplate/common/tilemap/tilemap_helpers.cpp | Thunraz/JamTemplateCpp | ee516d8a57dcfa6e7997585ab9bd7ff7df3640ea | [
"CC0-1.0"
] | null | null | null | #include "tilemap_helpers.hpp"
#include "drawable_helpers.hpp"
#include "shape.hpp"
namespace jt {
namespace tilemap {
std::shared_ptr<jt::DrawableInterface> createShapeFrom(InfoRect const& info)
{
std::shared_ptr<jt::Shape> shape = jt::dh::createShapeRect(info.size);
shape->setRotation(-info.rotation);
shape->setPosition(info.position);
shape->update(0.1f);
return shape;
}
} // namespace tilemap
} // namespace jt
| 23.210526 | 76 | 0.718821 | [
"shape"
] |
e24a8a273d96ef8b2a221ffe6a5300580094ffaf | 3,339 | hpp | C++ | tests/unit/ExampleNetwork.hpp | IPetr0v/compromutator | 6e1c34b5238a78f7f2f1628504103edfcb145523 | [
"Apache-2.0"
] | null | null | null | tests/unit/ExampleNetwork.hpp | IPetr0v/compromutator | 6e1c34b5238a78f7f2f1628504103edfcb145523 | [
"Apache-2.0"
] | null | null | null | tests/unit/ExampleNetwork.hpp | IPetr0v/compromutator | 6e1c34b5238a78f7f2f1628504103edfcb145523 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "../../src/NetworkSpace.hpp"
#include "../../src/network/Network.hpp"
#include <memory>
class ExampleNetwork
{
protected:
using B = BitMask;
using M = Match;
using H = HeaderSpace;
using N = NetworkSpace;
virtual void initNetwork() = 0;
virtual void destroyNetwork() = 0;
std::shared_ptr<Network> network;
};
class SimpleTwoSwitchNetwork : public ExampleNetwork
{
protected:
void initNetwork() override {
network = std::make_shared<Network>();
std::vector<PortInfo> ports{{1,0}, {2,0}};
sw1 = network->addSwitch(SwitchInfo(1, 2, ports));
sw2 = network->addSwitch(SwitchInfo(2, 1, ports));
port11 = sw1->port(1);
port12 = sw1->port(2);
port21 = sw2->port(1);
port22 = sw2->port(2);
rule1 = network->addRule(1, 0, 1, 0x0, M(1, B("0000xxxx")),
ActionsBase::portAction(2));
table_miss1 = network->getSwitch(1)->table(0)->tableMissRule();
rule2 = network->addRule(2, 0, 1, 0x0, M(1, B("000000xx")),
ActionsBase::portAction(2));
table_miss2 = network->getSwitch(2)->table(0)->tableMissRule();
}
void destroyNetwork() override {
network.reset();
}
SwitchPtr sw1, sw2;
PortPtr port11, port12, port21, port22;
RulePtr rule1, rule2;
RulePtr table_miss1, table_miss2;
};
class TwoSwitchNetwork : public ExampleNetwork
{
protected:
void initNetwork() override {
network = std::make_shared<Network>();
std::vector<PortInfo> ports{{1,0}, {2,0}};
sw1 = network->addSwitch(SwitchInfo(1, 2, ports));
sw2 = network->addSwitch(SwitchInfo(2, 1, ports));
port11 = sw1->port(1);
port12 = sw1->port(2);
port21 = sw2->port(1);
port22 = sw2->port(2);
rule1 = network->addRule(1, 0, 3, 0x0, M(1, B("00000000")),
ActionsBase::tableAction(1));
rule2 = network->addRule(1, 0, 2, 0x0, M(1, B("0000xxxx")),
ActionsBase::portAction(2));
link = network->addLink({1,2}, {2,1}).first;
rule3 = network->addRule(1, 0, 2, 0x0, M(1, B("0011xxxx")),
ActionsBase::portAction(2));
rule4 = network->addRule(1, 0, 2, 0x0, M(B("11111111")),
ActionsBase::dropAction());
rule5 = network->addRule(1, 0, 1, 0x0, M(B("1111xxxx")),
ActionsBase::portAction(2));
table_miss = network->getSwitch(1)->table(0)->tableMissRule();
rule11 = network->addRule(1, 1, 1, 0x0, M(1, B("00xxxxxx")),
ActionsBase::portAction(2));
table_miss1 = network->getSwitch(1)->table(1)->tableMissRule();
rule1_sw2 = network->addRule(2, 0, 1, 0x0, M(1, B("00000000")),
ActionsBase::portAction(2));
table_miss_sw2 = network->getSwitch(2)->table(0)->tableMissRule();
}
void destroyNetwork() override {
network.reset();
}
SwitchPtr sw1, sw2;
PortPtr port11, port12, port21, port22;
Link link;
RulePtr rule1, rule2, rule3, rule4, rule5, table_miss;
RulePtr rule11, table_miss1;
RulePtr rule1_sw2, table_miss_sw2;
};
| 32.105769 | 74 | 0.557353 | [
"vector"
] |
f4760fa6d7fb53fa9864a7b7a11cff328a88c5e9 | 3,023 | cpp | C++ | acmp.ru/0614/614.cpp | mstrechen/cp | ffac439840a71f70580a0ef197e47479e167a0eb | [
"MIT"
] | null | null | null | acmp.ru/0614/614.cpp | mstrechen/cp | ffac439840a71f70580a0ef197e47479e167a0eb | [
"MIT"
] | null | null | null | acmp.ru/0614/614.cpp | mstrechen/cp | ffac439840a71f70580a0ef197e47479e167a0eb | [
"MIT"
] | null | null | null | #include<iostream>
#include<fstream>
#include<string>
#include<cassert>
#include<iomanip>
#include<vector>
using namespace std;
const int BASE = 1000 * 1000 * 1000;
const int BASE_LEN = 3 + 3 + 3;
struct UInt
{
vector<int> dig;
UInt(int a = 0)
{
while(a)
{
dig.push_back(a%BASE);
a/=BASE;
}
}
int size() const
{
return dig.size();
}
int & operator [](int i)
{
assert(i>=0);
if(i>=(int)dig.size())
dig.resize(i+1, 0);
return dig[i];
}
int operator [](int i) const
{
assert(i>=0);
if(i>=(int)dig.size())
return 0;
return dig[i];
}
};
ostream & operator << (ostream & out, const UInt & toWrite)
{
if(toWrite.size())
{
out << toWrite[toWrite.size() - 1];
out.fill('0');
for(int i = toWrite.size() - 2; i>=0; i--)
out << setw(BASE_LEN) << toWrite[i];
}
else
{
out << 0;
}
return out;
}
UInt & operator += (UInt & left, const UInt & right)
{
if(&left == &right)
return left;
int carry = 0;
for(int i = 0; i<right.size() || carry; i++)
{
carry+=right[i]+left[i];
left[i] = carry % BASE;
carry/=BASE;
}
return left;
}
UInt & operator += (UInt & left, int right)
{
assert(right<BASE);
int carry = right;
for(int i = 0; i<carry; i++)
{
carry+=left[i];
left[i] = carry % BASE;
carry/=BASE;
}
return left;
}
struct Solution
{
string s;
mutable vector<vector<UInt> > mem;
mutable vector<vector<char> > used;
Solution(istream & in)
{
in >> s;
mem.assign(s.size() + 1, vector<UInt>(s.size()+ 1));
used.assign(s.size() + 1, vector<char>(s.size()+ 1, 0));
}
UInt smallSolve(int pos, int balance) const
{
if(pos>=0)
{
if(used[pos][balance])
return mem[pos][balance];
}
UInt ans;
if(balance == 0)
ans+=1;
if(balance)
{
int posClose = s.find(')', pos+1);
if(posClose!=string::npos)
ans+=smallSolve(posClose, balance - 1);
}
int posOpen = s.find('(', pos+1);
if(posOpen!=string::npos)
ans+=smallSolve(posOpen, balance + 1);
if(pos>=0)
{
used[pos][balance] = 1;
mem[pos][balance] = ans;
}
return ans;
}
UInt fullSolve() const
{
return smallSolve(-1, 0);
}
};
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
//ifstream in("brackets.in");
//ofstream out("brackets.out");
Solution solution(cin);
cout << solution.fullSolve();
return 0;
}
| 18.432927 | 65 | 0.447569 | [
"vector"
] |
f477b9b50f4a3b7547aacea385c6ea88d8bc3352 | 25,318 | cpp | C++ | src/printer/CPPPrinter.cpp | shiruizhao/swift | 2026acce35f0717c7a3e9dc522ff1c69f8dc3227 | [
"BSD-4-Clause-UC",
"BSD-4-Clause"
] | 22 | 2016-07-11T15:34:14.000Z | 2021-04-19T04:11:13.000Z | src/printer/CPPPrinter.cpp | shiruizhao/swift | 2026acce35f0717c7a3e9dc522ff1c69f8dc3227 | [
"BSD-4-Clause-UC",
"BSD-4-Clause"
] | 14 | 2016-07-11T14:28:42.000Z | 2017-01-27T02:59:24.000Z | src/printer/CPPPrinter.cpp | shiruizhao/swift | 2026acce35f0717c7a3e9dc522ff1c69f8dc3227 | [
"BSD-4-Clause-UC",
"BSD-4-Clause"
] | 7 | 2016-10-03T10:05:06.000Z | 2021-05-31T00:58:35.000Z | #include "CPPPrinter.h"
#include <cassert>
#include "../code/Code.h"
namespace swift {
namespace printer {
CPPPrinter::CPPPrinter(std::string str) :
Printer(str), isforward(false), isheader(false) {
}
CPPPrinter::~CPPPrinter() {
}
std::string CPPPrinter::OpConvert(code::OpKind op) {
using code::OpKind;
switch (op) {
case OpKind::UO_CMPT:
return "~"; // complement
case OpKind::UO_NEG:
return "!"; // negate
case OpKind::UO_PLUS:
return "+"; // unary plus
case OpKind::UO_MINUS:
return "-"; // unary minus
case OpKind::UO_INC:
return "++"; // increment
case OpKind::UO_DEC:
return "--"; // decrement
case OpKind::UO_ADDR:
return "&"; // address of
case OpKind::UO_DEREF:
return "*"; // deference of
case OpKind::UO_NEW:
return "new "; // new or malloc
case OpKind::UO_DEL:
return "delete "; // delete or dispose
case OpKind::UO_ARRAY_DEL:
return "delete[] "; // delete or dispose
case OpKind::BO_ASSIGN:
return "="; // Assignment
case OpKind::BO_FIELD:
return "."; // reference to a field
case OpKind::BO_RANGE:
return ": "; // range operator
case OpKind::BO_LSHGT:
return "<<"; // binary left shift
case OpKind::BO_RSHGT:
return ">>"; // binary right shift
case OpKind::BO_BAND:
return "&"; // binary and
case OpKind::BO_BOR:
return "|"; // binary or
case OpKind::BO_AND:
return "&&"; // and
case OpKind::BO_OR:
return "||"; // or
case OpKind::BO_XOR:
return "^"; // binary xor
case OpKind::BO_EQU:
return "=="; // equal
case OpKind::BO_NEQ:
return "!="; // not equal
case OpKind::BO_LT:
return "<"; // less than
case OpKind::BO_GT:
return ">"; // greater than
case OpKind::BO_LEQ:
return "<="; // less then or equal
case OpKind::BO_GEQ:
return ">="; // greater then or equal
case OpKind::BO_PLUS:
return "+"; // plus
case OpKind::BO_MINUS:
return "-"; // minus
case OpKind::BO_MUL:
return "*"; // multiply
case OpKind::BO_DIV:
return "/"; // divide
case OpKind::BO_MOD:
return "%"; // module
case OpKind::BO_SPLUS:
return "+="; // self plus
case OpKind::BO_SMINUS:
return "-="; // self minus
case OpKind::BO_SMUL:
return "*="; // self multiply
case OpKind::BO_SDIV:
return "/="; // self divide
case OpKind::BO_SMOD:
return "%="; // self module
case OpKind::BO_POINTER:
return "->"; // pointer to a field
case OpKind::BO_SCOPE:
return "::";
case OpKind::BO_COMMA:
return ",";
default:
assert(false);
return "";
}
}
std::pair<int, int> CPPPrinter::OpPrec(code::Expr* expr) {
if (expr == NULL) return std::make_pair<int, int>(-1,0);
auto b = dynamic_cast<code::BinaryOperator*>(expr);
if (b == NULL) return std::make_pair<int,int>(0,0);
using code::OpKind;
auto op = b->getOp();
switch (op) {
case OpKind::BO_POW:
return std::make_pair<int, int>(0,0);
case OpKind::BO_FIELD:
case OpKind::BO_POINTER:
case OpKind::BO_SCOPE:
return std::make_pair<int, int>(1,0);
case OpKind::UO_INC:
case OpKind::UO_DEC:
if (b->getLeft() != NULL)
return std::make_pair<int, int>(1,0);
case OpKind::UO_CMPT:
case OpKind::UO_NEG:
case OpKind::UO_PLUS:
case OpKind::UO_MINUS:
case OpKind::UO_ADDR:
case OpKind::UO_DEREF:
return std::make_pair<int, int>(2,1);
case OpKind::UO_NEW:
case OpKind::UO_DEL:
case OpKind::UO_ARRAY_DEL:
return std::make_pair<int, int>(3,1);
case OpKind::BO_MUL:
if (b->getLeft() == NULL)
return std::make_pair<int, int>(2,1);
case OpKind::BO_DIV:
case OpKind::BO_MOD:
return std::make_pair<int, int>(4,0);
case OpKind::BO_PLUS:
case OpKind::BO_MINUS:
if (b->getLeft() == NULL)
return std::make_pair<int, int>(2,1);
else
return std::make_pair<int, int>(5,0);
case OpKind::BO_LSHGT:
case OpKind::BO_RSHGT:
return std::make_pair<int, int>(6,0);
case OpKind::BO_LT:
case OpKind::BO_GT:
case OpKind::BO_LEQ:
case OpKind::BO_GEQ:
return std::make_pair<int, int>(7,0);
case OpKind::BO_EQU:
case OpKind::BO_NEQ:
return std::make_pair<int, int>(8,0);
case OpKind::BO_BAND:
if (b->getLeft() == NULL)
return std::make_pair<int, int>(2,1);
else
return std::make_pair<int, int>(9,0);
case OpKind::BO_XOR:
return std::make_pair<int, int>(10,0);
case OpKind::BO_BOR:
return std::make_pair<int, int>(11,0);
case OpKind::BO_AND:
return std::make_pair<int, int>(12,0);
case OpKind::BO_OR:
return std::make_pair<int, int>(13,0);
case OpKind::BO_ASSIGN:
case OpKind::BO_SPLUS:
case OpKind::BO_SMINUS:
case OpKind::BO_SMUL:
case OpKind::BO_SDIV:
case OpKind::BO_SMOD:
return std::make_pair<int, int>(15,1);
case OpKind::BO_COMMA:
return std::make_pair<int, int>(16,0);
case OpKind::BO_RANGE:
return std::make_pair<int, int>(17,0);
default:
assert(false);
return std::make_pair<int,int>(18,0);
}
}
void CPPPrinter::printPrefix() {
for (auto p : prefix) {
fprintf(file, "%s::", p.c_str());
}
}
void CPPPrinter::addHeader(std::string h) {
if(h.size() == 0) return;
if(h[0]!='<' && h[0]!='\"') h="\""+h;
if(h[h.size()-1]!='>' && h[h.size()-1]!='\"') h.push_back('\"');
header.push_back(h);
}
void CPPPrinter::print(code::Code* prog) {
/*
stmt contains all the includes, using and defines
Note: standard includes will be printed automatically
decl contains the body of the program
*/
indent = 0;
newline = true;
prefix.clear();
isforward = false;
isheader = false;
// output include
fprintf(file, "#include <iostream>\n");
fprintf(file, "#include <fstream>\n");
fprintf(file, "#include <sstream>\n");
fprintf(file, "#include <cstdio>\n");
fprintf(file, "#include <cstdlib>\n");
fprintf(file, "#include <cstring>\n");
fprintf(file, "#include <cmath>\n");
fprintf(file, "#include <cassert>\n");
fprintf(file, "#include <algorithm>\n");
fprintf(file, "#include <vector>\n");
fprintf(file, "#include <set>\n");
fprintf(file, "#include <map>\n");
fprintf(file, "#include <unordered_map>\n");
fprintf(file, "#include <chrono>\n");
fprintf(file, "#include <random>\n");
fprintf(file, "#include <numeric>\n");
fprintf(file, "#include <string>\n");
fprintf(file, "#include <memory>\n");
fprintf(file, "#include <functional>\n");
fprintf(file, "#include <utility>\n");
fprintf(file, "#include \"random/Bernoulli.h\"\n");
fprintf(file, "#include \"random/Beta.h\"\n");
fprintf(file, "#include \"random/Binomial.h\"\n");
fprintf(file, "#include \"random/BooleanDistrib.h\"\n");
fprintf(file, "#include \"random/Categorical.h\"\n");
fprintf(file, "#include \"random/Exponential.h\"\n");
fprintf(file, "#include \"random/Gaussian.h\"\n");
fprintf(file, "#include \"random/Gamma.h\"\n");
fprintf(file, "#include \"random/Geometric.h\"\n");
fprintf(file, "#include \"random/InvGamma.h\"\n");
fprintf(file, "#include \"random/Laplace.h\"\n");
fprintf(file, "#include \"random/Poisson.h\"\n");
fprintf(file, "#include \"random/TruncatedGauss.h\"\n");
fprintf(file, "#include \"random/UniformChoice.h\"\n");
fprintf(file, "#include \"random/UniformInt.h\"\n");
fprintf(file, "#include \"random/UniformReal.h\"\n");
fprintf(file, "#include \"util/Hist.h\"\n");
fprintf(file, "#include \"util/util.h\"\n");
fprintf(file, "#include \"util/DynamicTable.h\"\n");
// output costumized include
for (auto h : header)
fprintf(file, "#include %s\n", h.c_str());
// print special include/statements
for (auto s : prog->getAllMacros())
s->print(this);
printLine();
// Check for Special Printing Option
for (auto s : prog->getAllOptions()) {
if (s == "matrix") {
// Support Matrix
fprintf(file, "\n// Matrix Library included\n");
fprintf(file, "#include \"armadillo\"\n");
fprintf(file, "#include \"random/DiagGaussian.h\"\n");
fprintf(file, "#include \"random/Dirichlet.h\"\n");
fprintf(file, "#include \"random/Discrete.h\"\n");
fprintf(file, "#include \"random/InvWishart.h\"\n");
fprintf(file, "#include \"random/MultivarGaussian.h\"\n");
fprintf(file, "#include \"random/MultivarGaussianIndep.h\"\n");
fprintf(file, "#include \"random/Multinomial.h\"\n");
fprintf(file, "#include \"random/PrecisionGaussian.h\"\n");
fprintf(file, "#include \"random/UniformVector.h\"\n");
fprintf(file, "#include \"util/Hist_matrix.h\"\n");
fprintf(file, "#include \"util/util_matrix.h\"\n");
fprintf(file, "using namespace arma;\n\n");
} else
if (s == "MCMC" || s == "mcmc") {
// Support MCMC algorithms (Parental-MH, Gibbs)
fprintf(file, "\n// MCMC Library included\n");
fprintf(file, "#include \"util/MCMC.h\"\n");
fprintf(file, "#include \"util/util_MCMC.h\"\n");
}
}
//fprintf(file, "#define bool char\n"); // currently a hack for bool type, since elements in vector<bool> cannot be referenced
fprintf(file, "using namespace std;\n");
fprintf(file, "using namespace swift::random;\n");
printLine();
// print forward declaration
isforward = true; isheader = false;
for (auto p : prog->getAllDecls())
p->print(this);
printLine();
// print header declaration
isforward = false; isheader = true;
for (auto p : prog->getAllDecls())
p->print(this);
printLine();
// print main body
isforward = false; isheader = false;
for (auto p : prog->getAllDecls())
p->print(this);
}
void CPPPrinter::print(code::ArraySubscriptExpr* term) {
printIndent();
bool backup = newline;
newline = false;
// Note: [] operator
if (term->getLeft() != NULL) {
auto l_prec = OpPrec(term->getLeft());
if (l_prec.first > 1)
fprintf(file, "(");
term->getLeft()->print(this);
if (l_prec.first > 1)
fprintf(file, ")");
}
fprintf(file, "[");
if (term->getRight() != NULL)
term->getRight()->print(this);
fprintf(file, "]");
newline = backup;
if (backup)
fprintf(file, ";");
printLine();
}
void CPPPrinter::print(code::BinaryOperator* term) {
printIndent();
bool backup = newline;
newline = false;
auto l_prec = OpPrec(term->getLeft()).first;
auto r_prec = OpPrec(term->getRight()).first;
if (term->getOp() == code::OpKind::BO_POW) {
fprintf(file, "std::pow(");
term->getLeft()->print(this);
fprintf(file, ",");
term->getRight()->print(this);
fprintf(file, ")");
} else {
std::string op = OpConvert(term->getOp());
auto op_prec = OpPrec(term);
if (term->getLeft() != NULL) {
if (l_prec > op_prec.first || (l_prec == op_prec.first && op_prec.second == 1))
fprintf(file, "(");
term->getLeft()->print(this);
if (l_prec > op_prec.first || (l_prec == op_prec.first && op_prec.second == 1))
fprintf(file, ")");
}
fprintf(file, "%s", op.c_str());
if (term->getRight() != NULL) {
if (r_prec > op_prec.first || (r_prec == op_prec.first && op_prec.second == 0))
fprintf(file, "(");
term->getRight()->print(this);
if (r_prec > op_prec.first || (r_prec == op_prec.first && op_prec.second == 0))
fprintf(file, ")");
}
}
newline = backup;
if (backup)
fprintf(file, ";");
printLine();
}
void CPPPrinter::print(code::BooleanLiteral* term) {
printIndent();
if (term->getVal())
fprintf(file, "true");
else
fprintf(file, "false");
if (newline)
fprintf(file, ";");
printLine();
}
void CPPPrinter::print(code::BreakStmt* term) {
printIndent();
fprintf(file, "break;");
printLine();
}
void CPPPrinter::print(code::CallExpr* term) {
printIndent();
bool backup = newline;
newline = false;
// Note: () operatorƒf
auto f_prec = OpPrec(term->getFunc());
if (f_prec.first > 1)
fprintf(file, "(");
term->getFunc()->print(this);
if (f_prec.first > 1)
fprintf(file, ")");
fprintf(file, "(");
bool not_first = false;
for (auto p : term->getArgs()) {
if (not_first)
fprintf(file, ",");
else
not_first = true;
p->print(this);
}
fprintf(file, ")");
newline = backup;
if (backup)
fprintf(file, ";");
printLine();
}
void CPPPrinter::print(code::NewExpr* term) {
printIndent();
bool backup = newline;
newline = false;
fprintf(file, "new ");
term->getExpr()->print(this);
newline = backup;
if (backup)
fprintf(file, ";");
printLine();
}
void CPPPrinter::print(code::TemplateExpr* term) {
printIndent();
bool backup = newline;
newline = false;
// Note: () operatorƒf
auto f_prec = OpPrec(term->getVar());
if (f_prec.first > 1)
fprintf(file, "(");
term->getVar()->print(this);
if (f_prec.first > 1)
fprintf(file, ")");
bool not_first = false;
fprintf(file, "<");
for (auto p : term->getArgs()) {
if (not_first)
fprintf(file, ",");
else
not_first = true;
p->print(this);
}
fprintf(file, ">");
newline = backup;
if (backup)
fprintf(file, ";");
printLine();
}
void CPPPrinter::print(code::CaseStmt* term) {
decIndent();
printIndent();
fprintf(file, "case ");
bool backup = newline;
newline = false;
term->getVal()->print(this);
newline = backup;
fprintf(file, ":");
printLine();
incIndent();
if (term != NULL)
term->getSub()->print(this);
}
void CPPPrinter::print(code::ClassDecl* term) {
if (isforward) { // print forward decl of the class
printIndent();
fprintf(file, "class %s;", term->getName().c_str());
printLine();
} else
if (isheader) { // print everything except body of FunctionDecl
printIndent();
fprintf(file, "class %s", term->getName().c_str());
// inheritance
if (term->getInherit().size() > 0) {
bool backup = newline;
newline = false;
auto& h = term->getInherit();
for (size_t i = 0; i < h.size(); ++i) {
if (i == 0)
fprintf(file, ":");
else
fprintf(file, ",");
fprintf(file, " public ");
h[i].print(this);
}
newline = backup;
}
fprintf(file, " {");
printLine();
printIndent();
fprintf(file, "public:");
printLine();
incIndent();
for (auto p : term->getAllDecls())
p->print(this);
decIndent();
printIndent();
fprintf(file, "};");
printLine();
} else { // print body of FunctionDecl
prefix.push_back(term->getName());
for (auto p : term->getAllDecls())
p->print(this);
prefix.pop_back();
}
}
void CPPPrinter::print(code::CompoundStmt* term) {
printIndent();
fprintf(file, "{");
auto backup = newline;
newline = true;
if (term->getAll().size() > 0)
printLine();
incIndent();
for (auto p : term->getAll())
p->print(this);
decIndent();
if (term->getAll().size() > 0) // Otherwise it is just an empty block, no indent/newline needed
printIndent();
fprintf(file, "}");
newline = backup;
printLine();
}
void CPPPrinter::print(code::ContinueStmt* term) {
printIndent();
fprintf(file, "continue;");
printLine();
}
void CPPPrinter::print(code::DeclStmt* term) {
// We assume now isforward == false && isheader == false
assert(isforward == false && isheader == false);
isforward = true; isheader = false;
term->getDecl()->print(this);
isforward = false; isheader = true;
term->getDecl()->print(this);
isforward = false; isheader = false;
term->getDecl()->print(this);
}
void CPPPrinter::print(code::FieldDecl* term) {
print((code::VarDecl*) term);
}
void CPPPrinter::print(code::FloatingLiteral* term) {
printIndent();
// Special Case!
// Generally Here we keep 8 digits after decimal point
if (term->getVal() < 1e-6)
fprintf(file, "%s", std::to_string(term->getVal()).c_str());
else {
fprintf(file, "%.8lf", term->getVal());
}
if (newline)
fprintf(file, ";");
printLine();
}
void CPPPrinter::print(code::ForStmt* term) {
printIndent();
fprintf(file, "for (");
bool backup = newline;
newline = false;
if (term->isRange()) {
fprintf(file, "auto ");
term->getInit()->print(this);
} else {
if (term->getInit() != NULL)
term->getInit()->print(this);
fprintf(file, ";");
if (term->getCond() != NULL)
term->getCond()->print(this);
fprintf(file, ";");
if (term->getStep() != NULL)
term->getStep()->print(this);
}
fprintf(file, ")");
newline = backup;
if (term->getBody() != NULL) { // at least a pair of brackets will be printed
printLine();
term->getBody()->print(this);
}
else // Body is empty
fprintf(file, ";");
printLine();
}
void CPPPrinter::print(code::FunctionDecl* term) {
print(term, true);
}
void CPPPrinter::print(code::FunctionDecl* term, bool hasRetType) {
if (isforward) return ;
bool backup;
if (isheader) {
printIndent();
backup = newline;
newline = false;
if (term->isInline())
fprintf(file, "inline ");
if (hasRetType) {
term->getType().print(this);
fprintf(file, " ");
}
fprintf(file, "%s(", term->getName().c_str());
bool not_first = false;
for (auto p : term->getParams()) {
if (not_first)
fprintf(file, ",");
else
not_first = true;
p->print(this);
}
fprintf(file, ");");
newline = backup;
printLine();
} else {
printIndent();
backup = newline;
newline = false;
if (term->isInline())
fprintf(file, "inline ");
if (hasRetType) {
term->getType().print(this);
fprintf(file, " ");
}
printPrefix();
fprintf(file, "%s(", term->getName().c_str());
bool not_first = false;
for (auto p : term->getParams()) {
if (not_first)
fprintf(file, ", ");
else
not_first = true;
p->print(this);
}
fprintf(file, ")");
newline = backup;
printLine();
for (auto&d : term->getAllDecls()) {
d->print(this);
}
term->getBody().print(this);
}
}
void CPPPrinter::print(code::IfStmt* term) {
printIndent();
fprintf(file, "if (");
bool backup = newline;
newline = false;
term->getCond()->print(this);
fprintf(file, ")");
newline = backup;
if (term->getThen() != NULL) {
printLine();
incIndent();
term->getThen()->print(this);
decIndent();
}
if (term->getElse() != NULL) {
printIndent();
fprintf(file, "else");
printLine();
incIndent();
term->getElse()->print(this);
decIndent();
}
}
void CPPPrinter::print(code::IntegerLiteral* term) {
printIndent();
fprintf(file, "%d", term->getVal());
if (newline)
fprintf(file, ";");
printLine();
}
void CPPPrinter::print(code::NullLiteral* term) {
fprintf(file, "nullptr");
if (newline) {
fprintf(file, ";");
printLine();
}
}
void CPPPrinter::print(code::NamespaceDecl* term) {
if (isforward || isheader)
return;
printIndent();
fprintf(file, "namespace %s {", term->getName().c_str());
printLine();
printLine();
// print forward declaration
isforward = true; isheader = false;
for (auto p : term->getAllDecls())
p->print(this);
printLine();
// print header declaration
isforward = false; isheader = true;
for (auto p : term->getAllDecls())
p->print(this);
printLine();
// print body
isforward = false; isheader = false;
for (auto p : term->getAllDecls())
p->print(this);
printLine();
printIndent();
fprintf(file, "}");
printLine();
}
void CPPPrinter::print(code::ParamVarDecl* term) {
if (isforward) return ;
// assume newline == false
assert(newline == false);
bool backup = newline;
newline = false;
if (isheader) {
term->getType().print(this);
if (term->getValue() != NULL) {
fprintf(file, "=");
term->getValue()->print(this);
}
} else {
term->getType().print(this);
fprintf(file, " %s", term->getId().c_str());
}
newline = backup;
}
void CPPPrinter::print(code::ReturnStmt* term) {
printIndent();
fprintf(file, "return ");
if (term->getExpr() != NULL) {
bool backup = newline;
newline = false;
term->getExpr()->print(this);
newline = backup;
}
fprintf(file, ";");
printLine();
}
void CPPPrinter::print(code::SpecialMacro* term) {
// Note: No need to print ';' here!
printIndent();
fprintf(file, "%s", term->getMacro().c_str());
printLine();
}
void CPPPrinter::print(code::StringLiteral* term) {
printIndent();
fprintf(file, "\"%s\"", term->getVal().c_str());
if (newline)
fprintf(file, ";");
printLine();
}
void CPPPrinter::print(code::SwitchStmt* term) {
printIndent();
fprintf(file, "switch (");
bool backup = newline;
newline = false;
term->getCond()->print(this);
newline = backup;
fprintf(file, ")");
printLine();
term->getBody()->print(this);
}
void CPPPrinter::print(code::Type* term) {
// assume newline == false;
assert(newline == false);
if (term->isConst())
fprintf(file, "const ");
if (term->hasScope()) {
for (auto & nm : term->getScope()) {
fprintf(file, "%s::", nm.c_str());
}
}
fprintf(file, "%s", term->getName().c_str());
if (term->getTypeArgs().size() > 0) {
fprintf(file, "<");
auto it = term->getTypeArgs().begin();
it->print(this);
for (it++; it != term->getTypeArgs().end(); it++) {
fprintf(file, ",");
it->print(this);
}
fprintf(file, ">");
}
if (term->isRef())
fprintf(file, "&");
if (term->isPtr())
fprintf(file, "*");
}
void CPPPrinter::print(code::VarDecl* term) {
if (!isheader)
return;
printIndent();
bool backup = newline;
newline = false;
term->getType().print(this);
fprintf(file, " %s", term->getId().c_str());
if (term->getArrArgs().size() > 0) {
for (auto p : term->getArrArgs()) {
fprintf(file, "[");
p->print(this);
fprintf(file, "]");
}
}
if (term->getValue() != NULL) {
fprintf(file, " = ");
term->getValue()->print(this);
}
newline = backup;
if (backup)
fprintf(file, ";"); // Note: VarDecl can be in a ForStmt
printLine();
}
void CPPPrinter::print(code::Identifier* term) {
printIndent();
fprintf(file, "%s", term->getId().c_str());
if (newline)
fprintf(file, ";");
printLine();
}
//void CPPPrinter::print(code::DeleteStmt* term) {
// printIndent();
// if (term->isArray()) {
// fprintf(file, "delete[] ");
// } else {
// fprintf(file, "delete ");
// }
// bool backup = newline;
// newline = false;
// term->getVar()->print(this);
// newline = backup;
// fprintf(file, ";");
// printLine();
//}
//void CPPPrinter::print(code::NewExpr* term) {
// fprintf(file, "new ");
// if (term->isArray()) {
// term->getType().print(this);
// fprintf(file, "[");
// term->getExpr()->print(this);
// fprintf(file, "]");
// } else {
// term->getExpr()->print(this);
// }
//}
void CPPPrinter::print(code::DeclContext* term) {
// note should not reach here!!
term->print(this);
}
void CPPPrinter::print(code::ListInitExpr* term) {
fprintf(file, "{");
print(term->getArgs());
fprintf(file, "}");
}
std::string CPPPrinter::getLambdaKindStr(code::LambdaKind kind) {
using code::LambdaKind;
switch (kind) {
case LambdaKind::NA:
return "";
case LambdaKind::REF:
return "&";
case LambdaKind::COPY:
return "=";
case LambdaKind::THIS:
return "this";
default: return "";
}
}
void CPPPrinter::print(code::LambdaExpr* term) {
printIndent();
bool backup = newline;
newline = false;
fprintf(file, "[%s]",getLambdaKindStr(term->getKind()).c_str());
fprintf(file, "(");
bool isFirst = true;
for (auto p : term->getParams()) {
if (!isFirst) fprintf(file, ", ");
else isFirst = false;
p->print(this);
}
fprintf(file, ")");
term->getBody().print(this);
newline = backup;
if (backup)
fprintf(file, ";");
printLine();
}
void CPPPrinter::print(std::vector<code::Expr*>& exprs) {
bool first = true;
for (auto ex : exprs) {
if (!first) {
fprintf(file, ", ");
} else {
first = false;
}
ex->print(this);
}
}
void CPPPrinter::print(code::ClassConstructor* term) {
if (isforward) return;
bool backup;
if (isheader) {
printIndent();
backup = newline;
newline = false;
fprintf(file, "%s(", term->getName().c_str());
bool not_first = false;
for (auto p : term->getParams()) {
if (not_first)
fprintf(file, ",");
else
not_first = true;
p->print(this);
}
fprintf(file, ");");
newline = backup;
printLine();
}
else {
printIndent();
backup = newline;
newline = false;
printPrefix();
fprintf(file, "%s(", term->getName().c_str());
bool not_first = false;
for (auto p : term->getParams()) {
if (not_first)
fprintf(file, ", ");
else
not_first = true;
p->print(this);
}
fprintf(file, ")");
// print initial expression
if (term->getInitExpr() != NULL) {
fprintf(file, ":");
term->getInitExpr()->print(this);
}
newline = backup;
printLine();
term->getBody().print(this);
}
}
void CPPPrinter::print(code::CallClassConstructor* term) {
term->getType().print(this);
fprintf(file, "(");
print(term->getArgs());
fprintf(file, ")");
}
}
}
| 24.438224 | 128 | 0.593451 | [
"vector"
] |
f47990d4319aa1660f83c3f98b7554ec24e465f3 | 3,858 | cpp | C++ | nerarith-c++/day5/5a.cpp | joelfak/advent_of_code_2019 | d5031078c53c181835b4bf86458b360542f0122e | [
"Apache-2.0"
] | 9 | 2019-12-01T14:52:40.000Z | 2020-12-16T14:24:19.000Z | nerarith-c++/day5/5a.cpp | joelfak/advent_of_code_2019 | d5031078c53c181835b4bf86458b360542f0122e | [
"Apache-2.0"
] | null | null | null | nerarith-c++/day5/5a.cpp | joelfak/advent_of_code_2019 | d5031078c53c181835b4bf86458b360542f0122e | [
"Apache-2.0"
] | 51 | 2019-11-26T14:49:05.000Z | 2021-12-01T20:53:41.000Z | #include <bits/stdc++.h>
#include "prettyprint.hpp"
using namespace std;
const int MAX_NUM_PARAMETERS = 3;
set<int> known_opcodes = {1, 2, 3, 4, 99};
map<int, int> num_parameters_for_opcode = {
{1, 3},
{2, 3},
{3, 1},
{4, 1},
{99, 0}
};
vector<int> memory;
int memory_size;
int memory_get (int address) {
if (0 <= address && address < memory_size)
return memory[address];
else {
cerr << "error: out of bounds with address " << address << endl;
return -1;
}
}
void memory_set (int address, int value) {
if (0 <= address && address < memory_size)
memory[address] = value;
else
cerr << "error: out of bounds with address " << address << endl;
}
pair<int, vector<int>> extract_opcode_parameter_modes (int address) {
int combined = memory_get(address);
int opcode = combined % 100;
combined /= 100;
vector<int> parameter_modes (3);
for (int i=0; i < MAX_NUM_PARAMETERS; i++) {
parameter_modes[i] = combined % 10;
combined /= 10;
}
return {opcode, parameter_modes};
}
const int PARAMETER_MODE_POSITION = 0;
const int PARAMETER_MODE_IMMEDIATE = 1;
vector<int> get_parameters (int address, int num_parameters, vector<int> parameter_modes) {
vector<int> parameter_addresses (num_parameters);
for (int i=0; i < num_parameters; i++) {
switch (parameter_modes[i]) {
case PARAMETER_MODE_POSITION:
{
parameter_addresses[i] = memory_get(address+i);
break;
}
case PARAMETER_MODE_IMMEDIATE:
{
parameter_addresses[i] = address+i;
break;
}
}
}
return parameter_addresses;
}
const int OPCODE_ADD = 1;
const int OPCODE_MULTIPLY = 2;
const int OPCODE_INPUT = 3;
const int OPCODE_OUTPUT = 4;
const int OPCODE_HALT = 99;
int execute_operation(int opcode, vector<int> parameter_addresses) {
switch (opcode) {
case OPCODE_ADD:
{
int term1 = memory_get(parameter_addresses[0]);
int term2 = memory_get(parameter_addresses[1]);
int output_address = parameter_addresses[2];
int output = term1 + term2;
memory_set(output_address, output);
break;
}
case OPCODE_MULTIPLY:
{
int factor1 = memory_get(parameter_addresses[0]);
int factor2 = memory_get(parameter_addresses[1]);
int output_address = parameter_addresses[2];
int output = factor1 * factor2;
memory_set(output_address, output);
break;
}
case OPCODE_INPUT:
{
int output_address = parameter_addresses[0];
int input;
cin >> input;
memory_set(output_address, input);
break;
}
case OPCODE_OUTPUT:
{
int input_address = parameter_addresses[0];
int output = memory_get(input_address);
cout << output << endl;
break;
}
case OPCODE_HALT:
{
return -1;
}
}
return 0;
}
int main() {
int code;
char comma;
while (cin >> code) {
memory.push_back(code);
if (cin.peek() == ',')
cin >> comma;
else
break;
}
memory_size = memory.size();
int address = 0;
while (address < memory_size) {
auto [opcode, parameter_modes] = extract_opcode_parameter_modes(address);
vector<int> parameter_addresses = get_parameters(address+1, num_parameters_for_opcode[opcode], parameter_modes);
if (execute_operation(opcode, parameter_addresses) == -1)
break;
address += 1+num_parameters_for_opcode[opcode];
}
}
| 27.755396 | 120 | 0.572836 | [
"vector"
] |
f47c5d13ef03e6bef56d2e30cd264e82e3a893dd | 3,786 | cpp | C++ | engine/framework/nodes/vector_operator_node.cpp | wight-snake/Twilight | 836abb43c9920b9245e4f08520746c088dbf6172 | [
"MIT"
] | 1 | 2021-12-06T16:17:19.000Z | 2021-12-06T16:17:19.000Z | engine/framework/nodes/vector_operator_node.cpp | wight-snake/Twilight | 836abb43c9920b9245e4f08520746c088dbf6172 | [
"MIT"
] | null | null | null | engine/framework/nodes/vector_operator_node.cpp | wight-snake/Twilight | 836abb43c9920b9245e4f08520746c088dbf6172 | [
"MIT"
] | null | null | null | #include "vector_operator_node.h"
#include "node_graph.h"
const std::vector<std::string> VectorOperatorNode::operationNames = {
"normalize",
"invert",
"multiply",
"devide",
"add",
"subtract",
"dot",
"cross",
"rotate_axis",
"rotate",
"lerp",
"transform"
};
void VectorOperatorNode::InitializeSlots()
{
pNodeGraph->AddSlot(this, { "lhs", Slot::Type::stINPUT, Slot::ValueType::svVECTOR });
pNodeGraph->AddSlot(this, { "rhs", Slot::Type::stINPUT, Slot::ValueType::svVECTOR });
pNodeGraph->AddSlot(this, { "scalar", Slot::Type::stINPUT, Slot::ValueType::svFLOAT });
pNodeGraph->AddSlot(this, { "matrix", Slot::Type::stINPUT, Slot::ValueType::svMATRIX });
pNodeGraph->AddSlot(this, { "result", Slot::Type::stOUTPUT, Slot::ValueType::svVECTOR });
}
void VectorOperatorNode::Update(double deltaSeconds)
{
switch (operationIndex)
{
case 0:
data[outputs[0].valueKey] = data.value(inputs[0].valueKey, Vector()).GetNormalized3();
break;
case 1:
data[outputs[0].valueKey] = -data.value(inputs[0].valueKey, Vector());
break;
case 2:
data[outputs[0].valueKey] = data.value(inputs[0].valueKey, Vector()) * data.value(inputs[2].valueKey, 0.0f);
break;
case 3:
data[outputs[0].valueKey] = data.value(inputs[0].valueKey, Vector()) / data.value(inputs[2].valueKey, 0.0f);
break;
case 4:
data[outputs[0].valueKey] = data.value(inputs[0].valueKey, Vector()) + data.value(inputs[1].valueKey, Vector());
break;
case 5:
data[outputs[0].valueKey] = data.value(inputs[0].valueKey, Vector()) - data.value(inputs[1].valueKey, Vector());
break;
case 6:
data[outputs[0].valueKey] = data.value(inputs[0].valueKey, Vector()).Dot3(data[inputs[1].valueKey]);
break;
case 7:
data[outputs[0].valueKey] = data.value(inputs[0].valueKey, Vector()).Cross3(data[inputs[1].valueKey]);
break;
case 8:
data[outputs[0].valueKey] = data.value(inputs[0].valueKey, Vector()) * Matrix::RotationAxis(data[inputs[1].valueKey], data[inputs[2].valueKey]);
break;
case 9:
data[outputs[0].valueKey] = data.value(inputs[0].valueKey, Vector()) * Matrix::Rotation(data[inputs[1].valueKey]);
break;
case 10:
data[outputs[0].valueKey] = data.value(inputs[0].valueKey, Vector()).Lerp(data[inputs[1].valueKey], data[inputs[2].valueKey]);
break;
case 11:
data[outputs[0].valueKey] = data.value(inputs[0].valueKey, Vector()) * data.value(inputs[3].valueKey, Matrix::Identity());
break;
}
}
JSON VectorOperatorNode::ToJson() const
{
JSON json;
json["operationIndex"] = operationIndex;
return json;
}
void VectorOperatorNode::FromJson(const JSON& json)
{
operationIndex = json["operationIndex"];
}
void VectorOperatorNode::DrawWidget()
{
imnodes::BeginNode(GetUID(), "Vector Operation", { 136, 220, 170, 255 });
{
ImGui::SetNextItemWidth(imnodes::defaultNodeWidth - ImGui::CalcTextSize("operation").x);
if (ImGui::BeginCombo("operation", operationNames[operationIndex].c_str()))
{
for (uint32_t i = 0; i < operationNames.size(); i++)
{
if (ImGui::Selectable(operationNames[i].c_str()))
{
operationIndex = i;
for (auto& input : inputs)
{
input.RemoveConnection();
}
}
}
ImGui::EndCombo();
}
imnodes::InputAttribute(inputs[0].GetUID(), inputs[0].valueKey.c_str());
if (operationIndex >= 4 && operationIndex != 11)
{
imnodes::InputAttribute(inputs[1].GetUID(), inputs[1].valueKey.c_str());
}
if (operationIndex == 2 || operationIndex == 3 || operationIndex == 8 || operationIndex == 10)
{
imnodes::InputAttribute(inputs[2].GetUID(), inputs[2].valueKey.c_str());
}
if (operationIndex == 11)
{
imnodes::InputAttribute(inputs[3].GetUID(), inputs[3].valueKey.c_str());
}
imnodes::OutputAttribute(outputs[0].GetUID(), outputs[0].valueKey.c_str());
}
imnodes::EndNode();
} | 30.047619 | 146 | 0.677496 | [
"vector",
"transform"
] |
f4823533b55feb4ece31f07f31332b8dca733d52 | 1,668 | cpp | C++ | C++/15-3Sum.cpp | Auful01/Hacktoberfest-2021 | 0039fd26f8f3b97a9748a4fc76e7d77157fed56a | [
"MIT"
] | 38 | 2021-09-02T22:02:34.000Z | 2021-10-02T19:33:34.000Z | C++/15-3Sum.cpp | Auful01/Hacktoberfest-2021 | 0039fd26f8f3b97a9748a4fc76e7d77157fed56a | [
"MIT"
] | 188 | 2021-09-30T08:16:25.000Z | 2021-10-03T14:11:37.000Z | C++/15-3Sum.cpp | Auful01/Hacktoberfest-2021 | 0039fd26f8f3b97a9748a4fc76e7d77157fed56a | [
"MIT"
] | 131 | 2021-09-20T17:01:11.000Z | 2021-10-03T07:34:14.000Z | /*Link Of Question : https://leetcode.com/problems/3sum/
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Note: The solution set must not contain duplicate triplets.
*/
//Solution
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>>ans;
int n= nums.size();
sort(nums.begin(),nums.end());
/* Now fix the first element one by one and find the
other two elements */
for(int i=0;i<n-2;i++)
{
/* To find the other two elements, start two index
variables from two corners of the vector and move
them toward each other */
int l=i+1,
r=n-1;
if (i > 0 && nums[i] == nums[i - 1]) /* Skipping as we will get same set of solutions */
continue;
while(l<r)
{
if(nums[i]+nums[l]+nums[r]==0)
{
ans.push_back(vector<int>{nums[i],nums[l],nums[r]});
while(l<r && nums[l]==nums[l+1])l++;/* Skipping as we will get same set of solutions */
while(l<r && nums[r]==nums[r-1])r--;/* Skipping as we will get same set of solutions */
l++;
r--;
}
else if(nums[i]+nums[l]+nums[r]<0)l++;
else r--;
}
}
return ans;
}
};
/*
Sample Input : nums = [-1,0,1,2,-1,-4]
Sample output : [[-1,-1,2],[-1,0,1]]
Time Complexity : O(N*N)
Space Complexity : O(1)
*/
| 34.040816 | 156 | 0.489808 | [
"vector"
] |
f482b7a6f685cca251c1a8600b8ccd1553100c04 | 1,461 | hpp | C++ | src/string/test_dict_search.hpp | RamchandraApte/OmniTemplate | f150f451871b0ab43ac39a798186278106da1527 | [
"MIT"
] | 14 | 2019-04-23T21:44:12.000Z | 2022-03-04T22:48:59.000Z | src/string/test_dict_search.hpp | RamchandraApte/OmniTemplate | f150f451871b0ab43ac39a798186278106da1527 | [
"MIT"
] | 3 | 2019-04-25T10:45:32.000Z | 2020-08-05T22:40:39.000Z | src/string/test_dict_search.hpp | RamchandraApte/OmniTemplate | f150f451871b0ab43ac39a798186278106da1527 | [
"MIT"
] | 1 | 2020-07-16T22:16:33.000Z | 2020-07-16T22:16:33.000Z | #include "dict_search.hpp"
namespace string_tools::test {
template <typename Trie_Type> void test_dict_search_impl() {
auto trie = new Trie_Type{};
const vector<string> good_words{"hello", "world", "hell", "water", "wo", "lop",
"l", "er", "y", "yyy", "yyyy"};
const vector<string> bad_words{"help", "think", "codeforces", "mike", "wor",
"worl", "w", "hel", "helloworld"};
for (const auto &word : good_words) {
trie->insert(word);
}
for (const auto &word : good_words) {
assert(trie->find_leaf(word));
}
for (const auto &word : bad_words) {
assert(!trie->find_leaf(word));
}
auto hello = trie->find_node("hello");
assert(hello->go('p') == trie->find_node("lop"));
assert(hello->go('c') == trie);
assert(trie->find_node("lop")->exit_link() == nullptr);
assert(trie->find_node("lo")->exit_link() == nullptr);
assert(trie->find_node("water")->exit_link() == trie->find_node("er"));
const string str = "zhelloperzzasdfnpokncopdeforcesofoajcodeforcessyyyyyyyyyzzz";
decltype(trie->search({})) expected;
fo(j, str.size()) {
fo(i, j) {
for (const auto &word : good_words) {
if (str.substr(i, j - i) == word) {
expected.push_back({{i, j}, trie->find_leaf(word)});
}
}
}
}
assert(trie->search(str) == expected);
}
void test_dict_search() {
test_dict_search_impl<Trie<>>();
test_dict_search_impl<Trie<'\0', 256>>();
}
} // namespace string_tools::test
using namespace string_tools::test;
| 33.976744 | 82 | 0.637919 | [
"vector"
] |
f48ac2bf330f4ac565d1b267781a0b3303290115 | 2,486 | cpp | C++ | Flag.cpp | zacharytay1994/NotSoSuperMario | e0828f4cb2231f2e5993a71a492a25892744e129 | [
"CC-BY-3.0"
] | 2 | 2019-11-22T06:04:43.000Z | 2019-12-05T13:29:17.000Z | Flag.cpp | zacharytay1994/NotSoSuperMario | e0828f4cb2231f2e5993a71a492a25892744e129 | [
"CC-BY-3.0"
] | null | null | null | Flag.cpp | zacharytay1994/NotSoSuperMario | e0828f4cb2231f2e5993a71a492a25892744e129 | [
"CC-BY-3.0"
] | null | null | null | #include "Flag.h"
#include "CollisionDetectionComponent.h"
#include "Vec2.h"
#include "Scene.h"
#include "LevelOne.h"
Flag::Flag(ColliderManager& cm, const Vec2<float>& position, GameObject& mario, Scene& scene)
:
GameObject("pictures\\" + theme + "\\flagPole.png", 32, 640, 1, D3DXVECTOR2(position.x_, position.y_)),
flagflag_(new Sprite("pictures\\" + theme + "\\flagflag.png", 64, 64, 1)),
mario_(&mario),
scene_(&scene)
{
touch = false;
flagdown = false;
initialFlagHeight = sprite_->GetHeight() * 0.95 - flagflag_->GetHeight();
flagrelativeposition = 1;
}
void Flag::Update(const float& frametime) {
GameObject::Update(frametime);
float const flagbottom = position_.y + sprite_->GetHeight() / 2;
if (!touch) {
float const marioleft = mario_->GetPosition().x - mario_->sprite_->GetWidth() / 2;
float const marioright = mario_->GetPosition().x + mario_->sprite_->GetWidth() / 2;
float const mariotop = mario_->GetPosition().y - mario_->sprite_->GetHeight() / 2;
float const mariobottom = mario_->GetPosition().y + mario_->sprite_->GetHeight() / 2;
float const flagleft = position_.x - sprite_->GetWidth() / 2;
float const flagright = position_.x + sprite_->GetWidth() / 2;
float const flagtop = position_.y - sprite_->GetHeight() / 2;
if (!(marioleft > flagright || marioright < flagleft || mariotop > flagbottom || mariobottom < flagtop)){
contactdistance = flagbottom - mariobottom;
touch = true;
}
}
if (touch && !flagdown) {
flagrelativeposition -= 1.5 * frametime;
mario_->SetPosition(mario_->GetPosition().x, flagbottom - (contactdistance * flagrelativeposition));
dynamic_cast<PhysicsComponent*>(mario_->GetComponent("PhysicsComponent"))->SetVelocity(Vec2<float>(0.0f, 0.0f));
if (flagrelativeposition <= 0) {
flagdown = true;
dynamic_cast<PhysicsComponent*>(mario_->GetComponent("PhysicsComponent"))->SetVelocity(Vec2<float>(1.0f, -1.0f) * 300);
dynamic_cast<LevelOne*>(scene_)->levelCompleted = true;
}
}
flagflag_->GetImage().setY(flagbottom - (initialFlagHeight * flagrelativeposition) - flagflag_->GetHeight());
}
void Flag::Render(){
flagflag_->Draw();
GameObject::Render();
}
void Flag::ChildInitialize(Graphics& gfx){
GameObject::ChildInitialize(gfx);
flagflag_->Initialize(gfx);
flagflag_->GetImage().setScale(CAMERA_ZOOM);
flagflag_->GetImage().setX(position_.x - flagflag_->GetWidth());
flagflag_->GetImage().setY(position_.y + (sprite_->GetHeight()/2) - initialFlagHeight);
}
| 34.054795 | 122 | 0.703138 | [
"render"
] |
f48c35a6e26dd4b0f66a402dc28db911e7627aaa | 2,401 | cpp | C++ | hi_tools/mcl_editor/code_editor/CaretComponent.cpp | Matt-Dub/HISE | ae2dd1653e1c8d749a9088edcd573de6252b0b96 | [
"Intel"
] | null | null | null | hi_tools/mcl_editor/code_editor/CaretComponent.cpp | Matt-Dub/HISE | ae2dd1653e1c8d749a9088edcd573de6252b0b96 | [
"Intel"
] | null | null | null | hi_tools/mcl_editor/code_editor/CaretComponent.cpp | Matt-Dub/HISE | ae2dd1653e1c8d749a9088edcd573de6252b0b96 | [
"Intel"
] | null | null | null | /** ============================================================================
*
* MCL Text Editor JUCE module
*
* Copyright (C) Jonathan Zrake, Christoph Hart
*
* You may use, distribute and modify this code under the terms of the GPL3
* license.
* =============================================================================
*/
namespace mcl
{
using namespace juce;
//==============================================================================
mcl::CaretComponent::CaretComponent(const TextDocument& document) : document(document)
{
setInterceptsMouseClicks(false, false);
startTimerHz(20);
}
void mcl::CaretComponent::setViewTransform(const AffineTransform& transformToUse)
{
transform = transformToUse;
repaint();
}
void mcl::CaretComponent::updateSelections()
{
phase = 0.f;
repaint();
}
void mcl::CaretComponent::paint(Graphics& g)
{
auto colour = getParentComponent()->findColour(juce::CaretComponent::caretColourId);
UnblurryGraphics ug(g, *this);
bool drawCaretLine = document.getNumSelections() == 1 && document.getSelections().getFirst().isSingular();
for (const auto &r : getCaretRectangles())
{
g.setColour(colour.withAlpha(squareWave(phase)));
auto rf = ug.getRectangleWithFixedPixelWidth(r, 2);
g.fillRect(rf);
if (drawCaretLine)
{
g.setColour(Colours::white.withAlpha(0.04f));
g.fillRect(r.withX(0.0f).withWidth(getWidth()));
}
}
}
float mcl::CaretComponent::squareWave(float wt) const
{
if (isTimerRunning())
{
auto f = 0.5f * std::sin(wt) + 0.5f;
if (f > 0.3f)
return f;
return 0.0f;
}
return 0.6f;
}
void mcl::CaretComponent::timerCallback()
{
phase += 3.2e-1;
for (const auto &r : getCaretRectangles())
repaint(r.getSmallestIntegerContainer().expanded(3));
}
Array<Rectangle<float>> mcl::CaretComponent::getCaretRectangles() const
{
Array<Rectangle<float>> rectangles;
for (const auto& selection : document.getSelections())
{
if (document.getFoldableLineRangeHolder().isFolded(selection.head.x))
continue;
auto b = document.getGlyphBounds(selection.head, GlyphArrangementArray::ReturnBeyondLastCharacter);
b = b.removeFromLeft(CURSOR_WIDTH).withSizeKeepingCentre(CURSOR_WIDTH, document.getRowHeight());
rectangles.add(b.translated(selection.head.y == 0 ? 0 : -0.5f * CURSOR_WIDTH, 0.f)
.transformedBy(transform)
.expanded(0.f, 1.f));
}
return rectangles;
}
}
| 21.827273 | 107 | 0.641399 | [
"transform"
] |
f48fa89399de54a157f457445cd2382806fd513f | 2,737 | cpp | C++ | KTLT/lab3/Bai 3_11.cpp | trannguyenhan01092000/WorkspaceAlgorithm | 6ad3f12d55c7675184a8c15c5388ee8422e15a16 | [
"MIT"
] | 8 | 2020-11-26T03:36:49.000Z | 2020-11-28T14:33:07.000Z | KTLT/lab3/Bai 3_11.cpp | trannguyenhan/WorkspaceAlgorithm | 6ad3f12d55c7675184a8c15c5388ee8422e15a16 | [
"MIT"
] | null | null | null | KTLT/lab3/Bai 3_11.cpp | trannguyenhan/WorkspaceAlgorithm | 6ad3f12d55c7675184a8c15c5388ee8422e15a16 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
const int MAX = 10000;
int n, r;
int price[MAX][MAX];
int x[MAX];
bool visited[MAX];
vector<int> vt;
int min_price;
int sum_price;
int start, destination, numberOfPoint;
void input(){
cin >> n >> r;
for(int i=0; i<n; i++)
for(int j=0; j<n; j++){
cin >> price[i][j];
}
}
bool check(int a, int i){
if(visited[vt[i]]) return false;
if(price[x[a-1]][vt[i]] == 0) return false;
return true;
}
void solution(){
if(price[x[numberOfPoint-2]][destination] == 0) return;
min_price = min(min_price, sum_price + price[x[numberOfPoint-2]][destination]);
}
void TRY(int a){
for(int i=1; i<numberOfPoint-1; i++){
if(check(a, i)){
visited[vt[i]] = true;
sum_price += price[x[a-1]][vt[i]];
x[a] = vt[i];
if(a == numberOfPoint-2) solution();
else TRY(a+1);
visited[vt[i]] = false;
sum_price -= price[x[a-1]][vt[i]];
}
}
}
int main(){
string str;
input(); getline(cin,str);
while(r > 0){
min_price = INT_MAX;
sum_price = 0;
getline(cin, str);
// Tach str thanh cac so va ghi vao vector vt
/*
int pre = 0;
for(int i=0; i<str.length(); i++){
if(str[i] == ' '){
string tmp = str.substr(pre,i);
pre = i + 1;
stringstream convert(tmp);
int tmp_int = 0;
convert >> tmp_int;
vt.push_back(tmp_int - 1);
}
}
string tmp = str.substr(pre,str.length());
stringstream convert(tmp);
int tmp_int = 0;
convert >> tmp_int;
vt.push_back(tmp_int - 1);
*/
while (!str.empty()){
stringstream convert(str.substr(0, str.find(" ")));
int tmp = 0;
convert >> tmp;
vt.push_back(tmp - 1);
if (str.find(" ") > str.size()){
break;
} else {
str.erase(0, str.find(" ") + 1); // Update string
}
}
// Bat dau khoi tao cac du lieu can thiet truoc khi quay lui
start = vt[0]; // diem bat dau dau
destination = vt[vt.size()-1]; // diem dich
numberOfPoint = vt.size(); // so diem phai di qua
x[0] = start; x[numberOfPoint-1] = destination;
for(int i=0; i<n; i++)
visited[i] = false;
TRY(1);
// In ra ket qua
if(min_price == INT_MAX) cout << "0" << endl;
else cout << min_price << endl;
// Xoa vector va chuyen sang khach tiep theo
vt.erase(vt.begin(), vt.end());
r--;
}
}
| 24.881818 | 83 | 0.479357 | [
"vector"
] |
f4b8d05b5050fe253458152d51cee7725278d218 | 1,510 | cpp | C++ | main.cpp | silentWatcher3/Ludo-The_Game | 03576725241fe89dfd7cc74110971877663086b0 | [
"MIT"
] | null | null | null | main.cpp | silentWatcher3/Ludo-The_Game | 03576725241fe89dfd7cc74110971877663086b0 | [
"MIT"
] | null | null | null | main.cpp | silentWatcher3/Ludo-The_Game | 03576725241fe89dfd7cc74110971877663086b0 | [
"MIT"
] | null | null | null | #include <iostream>
#include "game.hpp"
static int numGamePlays = 0;
using std::clog;
int main(int argc, char const *argv[])
{
game newGame;
//GamePlay starts
try
{
short playConsent = 1;
do
{
if (!newGame.InitGame(playConsent))
{
std::cerr << "Couldn't initiate the game... Exiting" << std::endl;
return -1;
}
newGame.play();
std::cout << "Enter 1 if you want to play again and reset\nEnter 2 if you want to play with same players\nAnything else to say GoodBye :-)\nYour Consent : ";
playConsent = std::getchar();
} while (playConsent == 1 || playConsent == 2);
std::cout << "Khelne ke liye Dhanyawaad :-D" << std::endl;
}
catch (endApplication &e)
{
std::cerr << e.what() << std::endl;
return 0;
}
catch (std::exception &e)
{
std::cerr << e.what();
return 0;
}
return 0;
}
/*[LEARNT] - In C++ if an object is const, then it is totally CONSTANT, not like Java, where we can change contents of object, even with const reference -
* In C++, 'const' is like a promise to be kept, but can be broken using pointers sometimes, as needed
const Class* n; //Can't change the 'content' of what the pointer points to (ie. members 'shouldn't' be modified), but can make it point to a different location
Class const* n; //Same as above, just the astericks is at different position
Class* const n; //Java like, Can modfify the content, but can't make it point to something else
const Class* const n; //TOTALLY Constant by every mean
*/
| 27.454545 | 165 | 0.660927 | [
"object"
] |
f4b93626d0fdfb5657f035dfbbc30b63d87124e5 | 6,734 | cpp | C++ | plugins/archive/dmzMBRAPluginArchiveSupport.cpp | dmzgroup/mbra | d6749472f7c5463863ca93a8faff37f2afc9d1df | [
"MIT"
] | 1 | 2015-11-05T03:03:43.000Z | 2015-11-05T03:03:43.000Z | plugins/archive/dmzMBRAPluginArchiveSupport.cpp | dmzgroup/mbra | d6749472f7c5463863ca93a8faff37f2afc9d1df | [
"MIT"
] | null | null | null | plugins/archive/dmzMBRAPluginArchiveSupport.cpp | dmzgroup/mbra | d6749472f7c5463863ca93a8faff37f2afc9d1df | [
"MIT"
] | null | null | null | #include "dmzMBRAPluginArchiveSupport.h"
#include <dmzObjectAttributeMasks.h>
#include <dmzObjectModule.h>
#include <dmzQtModuleMap.h>
#include <dmzRuntimeConfigToNamedHandle.h>
#include <dmzRuntimeConfigToTypesBase.h>
#include <dmzRuntimeData.h>
#include <dmzRuntimePluginFactoryLinkSymbol.h>
#include <dmzRuntimePluginInfo.h>
#include <dmzTypesVector.h>
dmz::MBRAPluginArchiveSupport::MBRAPluginArchiveSupport (
const PluginInfo &Info,
Config &local) :
Plugin (Info),
ObjectObserverUtil (Info, local),
ArchiveObserverUtil (Info, local),
_log (Info),
_undo (Info),
_map (0),
_offsetX (0.5),
_offsetY (0.5),
_defaultAttrHandle (0),
_threatAttrHandle (0),
_vulAttrHandle (0), // Vulnerability
_ecAttrHandle (0), // Elimination Cost
_pcAttrHandle (0), // Prevention Cost
_toggleHandle (0),
_toggleTargetHandle (0),
_storeObjects (False),
_version (-1) {
_init (local);
}
dmz::MBRAPluginArchiveSupport::~MBRAPluginArchiveSupport () {
}
// Plugin Interface
void
dmz::MBRAPluginArchiveSupport::update_plugin_state (
const PluginStateEnum State,
const UInt32 Level) {
if (State == PluginStateInit) {
}
else if (State == PluginStateStart) {
}
else if (State == PluginStateStop) {
}
else if (State == PluginStateShutdown) {
}
}
void
dmz::MBRAPluginArchiveSupport::discover_plugin (
const PluginDiscoverEnum Mode,
const Plugin *PluginPtr) {
if (Mode == PluginDiscoverAdd) {
if (!_map) { _map = QtModuleMap::cast (PluginPtr); }
}
else if (Mode == PluginDiscoverRemove) {
if (_map && (_map == QtModuleMap::cast (PluginPtr))) { _map = 0; }
}
}
// Object Observer Interface
void
dmz::MBRAPluginArchiveSupport::create_object (
const UUID &Identity,
const Handle ObjectHandle,
const ObjectType &Type,
const ObjectLocalityEnum Locality) {
if (_storeObjects && _typeSet.contains_type (Type)) {
_objects.add (ObjectHandle);
}
}
void
dmz::MBRAPluginArchiveSupport::update_object_scalar (
const UUID &Identity,
const Handle ObjectHandle,
const Handle AttributeHandle,
const Float64 Value,
const Float64 *PreviousValue) {
if (AttributeHandle == _ecAttrHandle) {
ObjectModule *objMod = get_object_module ();
if (objMod && _pcAttrHandle) {
objMod->store_scalar (ObjectHandle, _pcAttrHandle, Value);
objMod->remove_attribute (ObjectHandle, _ecAttrHandle, ObjectScalarMask);
_ecObjects.add (ObjectHandle);
}
}
}
// Archive Observer Interface
void
dmz::MBRAPluginArchiveSupport::pre_process_archive (
const Handle ArchiveHandle,
const Int32 Version) {
if (Version <= _version) {
_objects.clear ();
_storeObjects = True;
}
_ecObjects.clear ();
}
void
dmz::MBRAPluginArchiveSupport::post_process_archive (
const Handle ArchiveHandle,
const Int32 Version) {
ObjectModule *objMod = get_object_module ();
if (objMod && _storeObjects) {
if (_objects.get_count () > 0) {
Float64 minx = 1.0e32, miny = 1.0e32, maxx = -1.0e32, maxy = -1.0e32;
HandleContainerIterator it;
Handle object (0);
while (_objects.get_next (it, object)) {
Vector pos;
if (objMod->lookup_position (object, _defaultAttrHandle, pos)) {
const Float64 XX = pos.get_x ();
const Float64 YY = pos.get_z ();
if (XX < minx) { minx = XX; }
if (XX > maxx) { maxx = XX; }
if (YY < miny) { miny = YY; }
if (YY > maxy) { maxy = YY; }
}
}
const Float64 OffsetX = minx + ((maxx - minx) * 0.5);
const Float64 OffsetY = miny + ((maxy - miny) * 0.5);
const Float64 Scale = is_zero64 (maxx - minx) ? 1.0 : 0.6 / (maxx - minx);
it.reset ();
while (_objects.get_next (it, object)) {
Vector pos;
if (objMod->lookup_position (object, _defaultAttrHandle, pos)) {
pos.set_x ((pos.get_x () - OffsetX) * Scale);
pos.set_z ((pos.get_z () - OffsetY) * Scale);
objMod->store_position (object, _defaultAttrHandle, pos);
}
}
if (_map) {
_map->center_on (0.0, 0.0);
_map->set_zoom (10);
Data out;
out.store_boolean (_toggleHandle, 0, False);
_toggleMapMessage.send (_toggleTargetHandle, &out);
}
_undo.reset ();
}
}
if (objMod) {
HandleContainerIterator it;
Handle object (0);
while (_ecObjects.get_next (it, object)) {
Float64 value (0.0);
if (!objMod->lookup_scalar (object, _threatAttrHandle, value)) {
objMod->store_scalar (object, _threatAttrHandle, 1.0);
}
if (!objMod->lookup_scalar (object, _vulAttrHandle, value)) {
objMod->store_scalar (object, _vulAttrHandle, 1.0);
}
}
}
_storeObjects = False;
}
void
dmz::MBRAPluginArchiveSupport::_init (Config &local) {
RuntimeContext *context = get_plugin_runtime_context ();
init_archive (local);
_defaultAttrHandle = activate_default_object_attribute (ObjectCreateMask);
_ecAttrHandle = activate_object_attribute (
config_to_string ("elimination-cost.name", local, "NA_Node_Elimination_Cost"),
ObjectScalarMask);
_typeSet = config_to_object_type_set ("object-type-list", local, context);
if (_typeSet.get_count () == 0) {
_typeSet.add_object_type ("na_node", context);
}
_toggleMapMessage = config_create_message (
"message.toggle-map.name",
local,
"ToggleMapMessage",
context,
&_log);
_threatAttrHandle = config_to_named_handle (
"threat.name",
local,
"NA_Node_Threat",
context);
_vulAttrHandle = config_to_named_handle (
"vulnerability.name",
local,
"NA_Node_Vulnerability",
context);
_pcAttrHandle = config_to_named_handle (
"prevention-cost.name",
local,
"NA_Node_Prevention_Cost",
context);
_toggleHandle = config_to_named_handle ("toggle.name", local, "toggle", context);
_toggleTargetHandle = config_to_named_handle (
"toggle-target.name",
local,
"dmzQtPluginMapProperties",
context);
}
extern "C" {
DMZ_PLUGIN_FACTORY_LINK_SYMBOL dmz::Plugin *
create_dmzMBRAPluginArchiveSupport (
const dmz::PluginInfo &Info,
dmz::Config &local,
dmz::Config &global) {
return new dmz::MBRAPluginArchiveSupport (Info, local);
}
};
| 23.22069 | 84 | 0.621473 | [
"object",
"vector"
] |
f4bef07955fac22b734a90392b20504cd3954bc8 | 1,668 | cc | C++ | apps/run.cc | CS126SP20/Math-Expression-OCR | d2172ad90c4504f0d986ab95c8a7f5f46e667c39 | [
"MIT"
] | null | null | null | apps/run.cc | CS126SP20/Math-Expression-OCR | d2172ad90c4504f0d986ab95c8a7f5f46e667c39 | [
"MIT"
] | null | null | null | apps/run.cc | CS126SP20/Math-Expression-OCR | d2172ad90c4504f0d986ab95c8a7f5f46e667c39 | [
"MIT"
] | null | null | null | // Copyright (c) 2020 [Your Name]. All rights reserved.
#include <cinder/app/App.h>
#include <cinder/app/RendererGl.h>
#include <gflags/gflags.h>
#include "my_app.h"
using cinder::app::App;
using cinder::app::RendererGl;
namespace myapp {
DEFINE_string(training_images, "../../../../../../assets/training/", "path to the training images");
DEFINE_string(training_labels, "../../../../../../assets/train_labels.txt", "path to the training labels");
DEFINE_string(model_save_path,"../../../../../../assets/my_model.xml", "Path to save model after training");
DEFINE_bool(train, false, "Include this flag if you want to train a new model");
DEFINE_string(equation, "../../../../../../assets/equations/addition.png", "Path to the image to evaluate");
DEFINE_string(model, "../../../../../../assets/my_model.xml", "Path to the model to use to evaluate the image");
const int kSamples = 8;
const int kWidth = 800;
const int kHeight = 500;
void ParseArgs(vector<string>* args) {
gflags::SetUsageMessage(
"Evaluate an image of a mathematical expression. "
"Pass --helpshort for options.");
int argc = static_cast<int>(args->size());
vector<char*> argvs;
for (string& str : *args) {
argvs.push_back(&str[0]);
}
char** argv = argvs.data();
gflags::ParseCommandLineFlags(&argc, &argv, true);
}
void SetUp(App::Settings* settings) {
vector<string> args = settings->getCommandLineArgs();
ParseArgs(&args);
settings->setWindowSize(kWidth, kHeight);
settings->setTitle("My CS 126 Application");
}
} // namespace myapp
CINDER_APP(myapp::MyApp,
RendererGl(RendererGl::Options().msaa(myapp::kSamples)),
myapp::SetUp)
| 34.75 | 112 | 0.675659 | [
"vector",
"model"
] |
f4ca7512fc1f81b304884d60d2706f878269fb0c | 2,098 | hpp | C++ | include/dal.hpp | FelipeCRamos/adt-dict | 7c3d79cb386513c80b47b11ff65d4b911623e80d | [
"MIT"
] | 1 | 2019-03-19T22:10:13.000Z | 2019-03-19T22:10:13.000Z | include/dal.hpp | FelipeCRamos/adt-dict | 7c3d79cb386513c80b47b11ff65d4b911623e80d | [
"MIT"
] | null | null | null | include/dal.hpp | FelipeCRamos/adt-dict | 7c3d79cb386513c80b47b11ff65d4b911623e80d | [
"MIT"
] | null | null | null | #ifndef _DAL_HPP_
#define _DAL_HPP_
#define debug false
#include <iostream>
#include <string>
#include <functional>
template <class Key, class Data, class KeyComparator = std::less<int> >
class DAL{
protected:
// using Key = int; // Key alias
// using Data = std::string; // Data Alias
struct NodeAL{ // Node alias, containing the pair key-data
Key id;
Data info;
NodeAL(Key _id = Key(), Data _info = Data()): id(_id), info(_info){};
};
// KeyComparator compare; // comparator function
static const int SIZE=50; // Default size of the list
int mi_Lenght; // Actual size of the list
int mi_Capacity; // Actual capacity of the list
NodeAL *mpt_Data; // Data vector, dinamically allocated
int _search( const Key & _x ) const; // Auxiliar search method
public:
/** Default constructor of DAL class. */
// DAL( void );
DAL( int _MaxSz = SIZE );
virtual ~DAL(){ if(mpt_Data) delete [] mpt_Data; };
/** Removes an item from the list. */
bool remove( const Key & _x, Data & _s );
/** Search for an item in the list. */
bool search( const Key & _x, Data & _s ) const;
/** Insert an item on the list. */
bool insert( const Key & _newKey, const Data & _newInfo );
/** Reserve _sizeNeeded elements */
bool reserve( size_t _sizeNeeded );
/** Retrieves the minimal key from the dictionary */
Key min() const;
/** Retrieves the maximum key from the dictionary */
Key max() const;
/** Retrieves on `_y` the next key to `_x`, if exists (true) */
bool successor( const Key & _x, Key & _y ) const;
/** Retrieves on `_y` the prev key to `_x`, if exists (true) */
bool predecessor( const Key & _x, Key & _y ) const;
// sends back to the output stream an ASCII representation for the list
inline friend
std::ostream &operator<<( std::ostream & _os, const DAL & _oList ){
_os << "[\n";
for( int i = 0; i < _oList.mi_Lenght; i++ ){
_os << i << ":\t{" << _oList.mpt_Data[i].id << ",\t'"
<< _oList.mpt_Data[i].info << "'}\n";
}
_os << "]";
return _os;
}
};
#include "dal.inl"
#endif
| 28.351351 | 73 | 0.627741 | [
"vector"
] |
f4d45c3291f337a415341587fee6b73bf87869fe | 717 | cpp | C++ | Questions Level-Wise/Easy/verifying-an-alien-dictionary.cpp | PrakharPipersania/LeetCode-Solutions | ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7 | [
"MIT"
] | 2 | 2021-03-05T22:32:23.000Z | 2021-03-05T22:32:29.000Z | Questions Level-Wise/Easy/verifying-an-alien-dictionary.cpp | PrakharPipersania/LeetCode-Solutions | ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7 | [
"MIT"
] | null | null | null | Questions Level-Wise/Easy/verifying-an-alien-dictionary.cpp | PrakharPipersania/LeetCode-Solutions | ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7 | [
"MIT"
] | null | null | null | class Solution {
public:
bool compare(string &x,string &y,unordered_map<char,short> &pattern)
{
short len=min(x.size(),y.size());
for(int i=0;i<len;i++)
{
if(pattern[x[i]]>pattern[y[i]])
return 0;
else if(pattern[x[i]]<pattern[y[i]])
return 1;
}
return (x.size()>y.size()?0:1);
}
bool isAlienSorted(vector<string>& words, string order)
{
unordered_map<char,short> pattern;
for(int i=0;i<order.size();i++)
pattern[order[i]]=i;
for(int i=1;i<words.size();i++)
if(!compare(words[i-1],words[i],pattern))
return 0;
return 1;
}
}; | 28.68 | 72 | 0.490934 | [
"vector"
] |
f4da66328242b34be6526c9f4350d87482e3904e | 14,222 | cc | C++ | content/child/indexed_db/indexed_db_dispatcher.cc | xzhan96/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-01-07T18:51:03.000Z | 2021-01-07T18:51:03.000Z | content/child/indexed_db/indexed_db_dispatcher.cc | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/child/indexed_db/indexed_db_dispatcher.cc | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/child/indexed_db/indexed_db_dispatcher.h"
#include <utility>
#include "base/format_macros.h"
#include "base/lazy_instance.h"
#include "base/strings/stringprintf.h"
#include "base/threading/thread_local.h"
#include "content/child/indexed_db/indexed_db_key_builders.h"
#include "content/child/indexed_db/webidbcursor_impl.h"
#include "content/child/indexed_db/webidbdatabase_impl.h"
#include "content/child/thread_safe_sender.h"
#include "content/common/indexed_db/indexed_db_messages.h"
#include "ipc/ipc_channel.h"
#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBDatabaseCallbacks.h"
#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBDatabaseError.h"
#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBDatabaseException.h"
#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBObservation.h"
#include "third_party/WebKit/public/platform/modules/indexeddb/WebIDBValue.h"
using blink::WebBlobInfo;
using blink::WebData;
using blink::WebIDBCallbacks;
using blink::WebIDBCursor;
using blink::WebIDBDatabase;
using blink::WebIDBDatabaseCallbacks;
using blink::WebIDBDatabaseError;
using blink::WebIDBKey;
using blink::WebIDBMetadata;
using blink::WebIDBObservation;
using blink::WebIDBObserver;
using blink::WebIDBValue;
using blink::WebString;
using blink::WebVector;
using base::ThreadLocalPointer;
namespace content {
static base::LazyInstance<ThreadLocalPointer<IndexedDBDispatcher> >::Leaky
g_idb_dispatcher_tls = LAZY_INSTANCE_INITIALIZER;
namespace {
IndexedDBDispatcher* const kHasBeenDeleted =
reinterpret_cast<IndexedDBDispatcher*>(0x1);
} // unnamed namespace
IndexedDBDispatcher::IndexedDBDispatcher(ThreadSafeSender* thread_safe_sender)
: thread_safe_sender_(thread_safe_sender) {
g_idb_dispatcher_tls.Pointer()->Set(this);
}
IndexedDBDispatcher::~IndexedDBDispatcher() {
// Clear any pending callbacks - which may result in dispatch requests -
// before marking the dispatcher as deleted.
pending_callbacks_.Clear();
DCHECK(pending_callbacks_.IsEmpty());
in_destructor_ = true;
mojo_owned_callback_state_.clear();
mojo_owned_database_callback_state_.clear();
g_idb_dispatcher_tls.Pointer()->Set(kHasBeenDeleted);
}
IndexedDBDispatcher* IndexedDBDispatcher::ThreadSpecificInstance(
ThreadSafeSender* thread_safe_sender) {
if (g_idb_dispatcher_tls.Pointer()->Get() == kHasBeenDeleted) {
NOTREACHED() << "Re-instantiating TLS IndexedDBDispatcher.";
g_idb_dispatcher_tls.Pointer()->Set(NULL);
}
if (g_idb_dispatcher_tls.Pointer()->Get())
return g_idb_dispatcher_tls.Pointer()->Get();
IndexedDBDispatcher* dispatcher = new IndexedDBDispatcher(thread_safe_sender);
if (WorkerThread::GetCurrentId())
WorkerThread::AddObserver(dispatcher);
return dispatcher;
}
void IndexedDBDispatcher::WillStopCurrentWorkerThread() {
delete this;
}
std::vector<WebIDBObservation> IndexedDBDispatcher::ConvertObservations(
const std::vector<IndexedDBMsg_Observation>& idb_observations) {
std::vector<WebIDBObservation> web_observations;
for (const auto& idb_observation : idb_observations) {
WebIDBObservation web_observation;
web_observation.objectStoreId = idb_observation.object_store_id;
web_observation.type = idb_observation.type;
web_observation.keyRange =
WebIDBKeyRangeBuilder::Build(idb_observation.key_range);
// TODO(palakj): Assign value to web_observation.
web_observations.push_back(std::move(web_observation));
}
return web_observations;
}
void IndexedDBDispatcher::OnMessageReceived(const IPC::Message& msg) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(IndexedDBDispatcher, msg)
IPC_MESSAGE_HANDLER(IndexedDBMsg_CallbacksSuccessCursorAdvance,
OnSuccessCursorContinue)
IPC_MESSAGE_HANDLER(IndexedDBMsg_CallbacksSuccessCursorContinue,
OnSuccessCursorContinue)
IPC_MESSAGE_HANDLER(IndexedDBMsg_CallbacksSuccessCursorPrefetch,
OnSuccessCursorPrefetch)
IPC_MESSAGE_HANDLER(IndexedDBMsg_CallbacksSuccessValue, OnSuccessValue)
IPC_MESSAGE_HANDLER(IndexedDBMsg_CallbacksSuccessInteger, OnSuccessInteger)
IPC_MESSAGE_HANDLER(IndexedDBMsg_CallbacksError, OnError)
IPC_MESSAGE_HANDLER(IndexedDBMsg_DatabaseCallbacksChanges,
OnDatabaseChanges)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
// If a message gets here, IndexedDBMessageFilter already determined that it
// is an IndexedDB message.
DCHECK(handled) << "Didn't handle a message defined at line "
<< IPC_MESSAGE_ID_LINE(msg.type());
}
bool IndexedDBDispatcher::Send(IPC::Message* msg) {
return thread_safe_sender_->Send(msg);
}
int32_t IndexedDBDispatcher::RegisterObserver(
std::unique_ptr<WebIDBObserver> observer) {
return observers_.Add(observer.release());
}
void IndexedDBDispatcher::RemoveObservers(
const std::vector<int32_t>& observer_ids_to_remove) {
for (int32_t id : observer_ids_to_remove)
observers_.Remove(id);
}
void IndexedDBDispatcher::RequestIDBCursorAdvance(
unsigned long count,
WebIDBCallbacks* callbacks_ptr,
int32_t ipc_cursor_id,
int64_t transaction_id) {
// Reset all cursor prefetch caches except for this cursor.
ResetCursorPrefetchCaches(transaction_id, ipc_cursor_id);
std::unique_ptr<WebIDBCallbacks> callbacks(callbacks_ptr);
int32_t ipc_callbacks_id = pending_callbacks_.Add(callbacks.release());
Send(new IndexedDBHostMsg_CursorAdvance(
ipc_cursor_id, CurrentWorkerId(), ipc_callbacks_id, count));
}
void IndexedDBDispatcher::RequestIDBCursorContinue(
const IndexedDBKey& key,
const IndexedDBKey& primary_key,
WebIDBCallbacks* callbacks_ptr,
int32_t ipc_cursor_id,
int64_t transaction_id) {
// Reset all cursor prefetch caches except for this cursor.
ResetCursorPrefetchCaches(transaction_id, ipc_cursor_id);
std::unique_ptr<WebIDBCallbacks> callbacks(callbacks_ptr);
int32_t ipc_callbacks_id = pending_callbacks_.Add(callbacks.release());
Send(new IndexedDBHostMsg_CursorContinue(
ipc_cursor_id, CurrentWorkerId(), ipc_callbacks_id, key, primary_key));
}
void IndexedDBDispatcher::RequestIDBCursorPrefetch(
int n,
WebIDBCallbacks* callbacks_ptr,
int32_t ipc_cursor_id) {
std::unique_ptr<WebIDBCallbacks> callbacks(callbacks_ptr);
int32_t ipc_callbacks_id = pending_callbacks_.Add(callbacks.release());
Send(new IndexedDBHostMsg_CursorPrefetch(
ipc_cursor_id, CurrentWorkerId(), ipc_callbacks_id, n));
}
void IndexedDBDispatcher::RequestIDBCursorPrefetchReset(int used_prefetches,
int unused_prefetches,
int32_t ipc_cursor_id) {
Send(new IndexedDBHostMsg_CursorPrefetchReset(
ipc_cursor_id, used_prefetches, unused_prefetches));
}
void IndexedDBDispatcher::RegisterCursor(int32_t ipc_cursor_id,
WebIDBCursorImpl* cursor) {
DCHECK(!base::ContainsKey(cursors_, ipc_cursor_id));
cursors_[ipc_cursor_id] = cursor;
}
void IndexedDBDispatcher::CursorDestroyed(int32_t ipc_cursor_id) {
cursors_.erase(ipc_cursor_id);
}
void IndexedDBDispatcher::RegisterMojoOwnedCallbacks(
IndexedDBCallbacksImpl::InternalState* callbacks) {
mojo_owned_callback_state_[callbacks] = base::WrapUnique(callbacks);
}
void IndexedDBDispatcher::UnregisterMojoOwnedCallbacks(
IndexedDBCallbacksImpl::InternalState* callbacks) {
if (in_destructor_)
return;
auto it = mojo_owned_callback_state_.find(callbacks);
DCHECK(it != mojo_owned_callback_state_.end());
it->second.release();
mojo_owned_callback_state_.erase(it);
}
void IndexedDBDispatcher::RegisterMojoOwnedDatabaseCallbacks(
blink::WebIDBDatabaseCallbacks* callbacks) {
mojo_owned_database_callback_state_[callbacks] = base::WrapUnique(callbacks);
}
void IndexedDBDispatcher::UnregisterMojoOwnedDatabaseCallbacks(
blink::WebIDBDatabaseCallbacks* callbacks) {
if (in_destructor_)
return;
auto it = mojo_owned_database_callback_state_.find(callbacks);
DCHECK(it != mojo_owned_database_callback_state_.end());
it->second.release();
mojo_owned_database_callback_state_.erase(it);
}
// Populate some WebIDBValue members (data & blob info) from the supplied
// value message (IndexedDBMsg_Value or one that includes it).
template <class IndexedDBMsgValueType>
static void PrepareWebValue(const IndexedDBMsgValueType& value,
WebIDBValue* web_value) {
if (value.bits.empty())
return;
web_value->data.assign(&*value.bits.begin(), value.bits.size());
blink::WebVector<WebBlobInfo> local_blob_info(value.blob_or_file_info.size());
for (size_t i = 0; i < value.blob_or_file_info.size(); ++i) {
const IndexedDBMsg_BlobOrFileInfo& info = value.blob_or_file_info[i];
if (info.is_file) {
local_blob_info[i] = WebBlobInfo(
WebString::fromUTF8(info.uuid.c_str()), info.file_path,
info.file_name, info.mime_type, info.last_modified, info.size);
} else {
local_blob_info[i] = WebBlobInfo(WebString::fromUTF8(info.uuid.c_str()),
info.mime_type, info.size);
}
}
web_value->webBlobInfo.swap(local_blob_info);
}
static void PrepareReturnWebValue(const IndexedDBMsg_ReturnValue& value,
WebIDBValue* web_value) {
PrepareWebValue(value, web_value);
web_value->primaryKey = WebIDBKeyBuilder::Build(value.primary_key);
web_value->keyPath = WebIDBKeyPathBuilder::Build(value.key_path);
}
void IndexedDBDispatcher::OnSuccessValue(
const IndexedDBMsg_CallbacksSuccessValue_Params& params) {
DCHECK_EQ(params.ipc_thread_id, CurrentWorkerId());
WebIDBCallbacks* callbacks =
pending_callbacks_.Lookup(params.ipc_callbacks_id);
if (!callbacks)
return;
WebIDBValue web_value;
PrepareReturnWebValue(params.value, &web_value);
if (params.value.primary_key.IsValid()) {
web_value.primaryKey = WebIDBKeyBuilder::Build(params.value.primary_key);
web_value.keyPath = WebIDBKeyPathBuilder::Build(params.value.key_path);
}
callbacks->onSuccess(web_value);
pending_callbacks_.Remove(params.ipc_callbacks_id);
}
void IndexedDBDispatcher::OnSuccessInteger(int32_t ipc_thread_id,
int32_t ipc_callbacks_id,
int64_t value) {
DCHECK_EQ(ipc_thread_id, CurrentWorkerId());
WebIDBCallbacks* callbacks = pending_callbacks_.Lookup(ipc_callbacks_id);
if (!callbacks)
return;
callbacks->onSuccess(value);
pending_callbacks_.Remove(ipc_callbacks_id);
}
void IndexedDBDispatcher::OnSuccessCursorContinue(
const IndexedDBMsg_CallbacksSuccessCursorContinue_Params& p) {
DCHECK_EQ(p.ipc_thread_id, CurrentWorkerId());
int32_t ipc_callbacks_id = p.ipc_callbacks_id;
int32_t ipc_cursor_id = p.ipc_cursor_id;
const IndexedDBKey& key = p.key;
const IndexedDBKey& primary_key = p.primary_key;
if (cursors_.find(ipc_cursor_id) == cursors_.end())
return;
WebIDBCallbacks* callbacks = pending_callbacks_.Lookup(ipc_callbacks_id);
if (!callbacks)
return;
WebIDBValue web_value;
PrepareWebValue(p.value, &web_value);
callbacks->onSuccess(WebIDBKeyBuilder::Build(key),
WebIDBKeyBuilder::Build(primary_key), web_value);
pending_callbacks_.Remove(ipc_callbacks_id);
}
void IndexedDBDispatcher::OnSuccessCursorPrefetch(
const IndexedDBMsg_CallbacksSuccessCursorPrefetch_Params& p) {
DCHECK_EQ(p.ipc_thread_id, CurrentWorkerId());
int32_t ipc_callbacks_id = p.ipc_callbacks_id;
int32_t ipc_cursor_id = p.ipc_cursor_id;
std::vector<WebIDBValue> values(p.values.size());
for (size_t i = 0; i < p.values.size(); ++i)
PrepareWebValue(p.values[i], &values[i]);
std::map<int32_t, WebIDBCursorImpl*>::const_iterator cur_iter =
cursors_.find(ipc_cursor_id);
if (cur_iter == cursors_.end())
return;
cur_iter->second->SetPrefetchData(p.keys, p.primary_keys, values);
WebIDBCallbacks* callbacks = pending_callbacks_.Lookup(ipc_callbacks_id);
DCHECK(callbacks);
cur_iter->second->CachedContinue(callbacks);
pending_callbacks_.Remove(ipc_callbacks_id);
}
void IndexedDBDispatcher::OnError(int32_t ipc_thread_id,
int32_t ipc_callbacks_id,
int code,
const base::string16& message) {
DCHECK_EQ(ipc_thread_id, CurrentWorkerId());
WebIDBCallbacks* callbacks = pending_callbacks_.Lookup(ipc_callbacks_id);
if (!callbacks)
return;
if (message.empty())
callbacks->onError(WebIDBDatabaseError(code));
else
callbacks->onError(WebIDBDatabaseError(code, message));
pending_callbacks_.Remove(ipc_callbacks_id);
}
void IndexedDBDispatcher::OnDatabaseChanges(
int32_t ipc_thread_id,
const IndexedDBMsg_ObserverChanges& changes) {
DCHECK_EQ(ipc_thread_id, CurrentWorkerId());
std::vector<WebIDBObservation> observations(
ConvertObservations(changes.observations));
for (auto& it : changes.observation_index) {
WebIDBObserver* observer = observers_.Lookup(it.first);
// An observer can be removed from the renderer, but still exist in the
// backend. Moreover, observer might have recorded some changes before being
// removed from the backend and thus, have its id be present in changes.
if (!observer)
continue;
observer->onChange(observations, std::move(it.second));
}
}
void IndexedDBDispatcher::ResetCursorPrefetchCaches(
int64_t transaction_id,
int32_t ipc_exception_cursor_id) {
typedef std::map<int32_t, WebIDBCursorImpl*>::iterator Iterator;
for (Iterator i = cursors_.begin(); i != cursors_.end(); ++i) {
if (i->first == ipc_exception_cursor_id ||
i->second->transaction_id() != transaction_id)
continue;
i->second->ResetPrefetchCache();
}
}
} // namespace content
| 37.230366 | 89 | 0.750668 | [
"vector"
] |
f4de61ffce25c1a7a591edb1b8b73a05d83692cd | 800 | cpp | C++ | src/container-with-most-water.cpp | Liuchang0812/leetcode | d71f87b0035e661d0009f4382b39c4787c355f89 | [
"MIT"
] | 9 | 2015-09-09T20:28:31.000Z | 2019-05-15T09:13:07.000Z | src/container-with-most-water.cpp | liuchang0812/leetcode | d71f87b0035e661d0009f4382b39c4787c355f89 | [
"MIT"
] | 1 | 2015-02-25T13:10:09.000Z | 2015-02-25T13:10:09.000Z | src/container-with-most-water.cpp | liuchang0812/leetcode | d71f87b0035e661d0009f4382b39c4787c355f89 | [
"MIT"
] | 1 | 2016-08-31T19:14:52.000Z | 2016-08-31T19:14:52.000Z | #include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
int maxArea(vector<int> &height) {
int ans = 0;
int l, r;
l = 0;
r = height.size()-1;
while( l < r)
{
while (l < r && height[l] >= height[r])
{
ans = max(ans, (r-l) * height[r]);
r -- ;
}
while (l < r && height[l] <= height[r])
{
ans = max(ans, (r-l) * height[l]);
l++;
}
}
return ans;
}
};
int main(){
Solution s;
vector<int> height;
height.push_back(1);
height.push_back(5);
height.push_back(2);
height.push_back(3);
height.push_back(2);
cout << s.maxArea(height) << endl;
return 0;
}
| 19.512195 | 50 | 0.43875 | [
"vector"
] |
f4de8250101785f9dc05cc3db7442b7934dea052 | 9,756 | cpp | C++ | smalldrop/smalldrop_robot_arm/src/controllers/gravity_compensation_real_controller.cpp | blackchacal/Master-Thesis----Software | 9a9858ede3086eee99d1fc969e32b4fb13278f00 | [
"MIT"
] | 1 | 2020-08-16T14:37:09.000Z | 2020-08-16T14:37:09.000Z | smalldrop/smalldrop_robot_arm/src/controllers/gravity_compensation_real_controller.cpp | blackchacal/Master-Thesis----Software | 9a9858ede3086eee99d1fc969e32b4fb13278f00 | [
"MIT"
] | 1 | 2020-06-26T09:14:45.000Z | 2020-07-18T08:46:50.000Z | smalldrop/smalldrop_robot_arm/src/controllers/gravity_compensation_real_controller.cpp | blackchacal/smalldrop | 9a9858ede3086eee99d1fc969e32b4fb13278f00 | [
"MIT"
] | null | null | null | // Copyright (c) 2019-2020 Ricardo Tonet
// Use of this source code is governed by the MIT license, see LICENSE
#include "smalldrop_robot_arm/gravity_compensation_real_controller.h"
namespace smalldrop
{
namespace smalldrop_robot_arm
{
/*****************************************************************************************
* Public methods
*****************************************************************************************/
bool GravityCompensationRealController::init(hardware_interface::RobotHW *robot_hw, ros::NodeHandle &nh)
{
// Verify robot
std::cout << "Verifying robot id" << std::endl;
std::string arm_id;
if (!nh.getParam("/gravity_compensation_real_controller/arm_id", arm_id))
{
ROS_ERROR("GravityCompensationRealController: Could not read the parameter 'arm_id'.");
return false;
}
// Verify number of joints
std::cout << "Verifying number of joints" << std::endl;
std::vector<std::string> joint_names;
if (!nh.getParam("/gravity_compensation_real_controller/joints", joint_names) || joint_names.size() != 7)
{
ROS_ERROR("GravityCompensationRealController: Invalid or no joint_names parameters "
"provided, aborting controller init!");
return false;
}
// Verify robot model interface
std::cout << "Verifying robot model interface" << std::endl;
auto* model_interface = robot_hw->get<franka_hw::FrankaModelInterface>();
if (model_interface == nullptr) {
ROS_ERROR_STREAM(
"GravityCompensationExampleController: Error getting model interface from hardware");
return false;
}
try {
model_handle_ = std::make_unique<franka_hw::FrankaModelHandle>(
model_interface->getHandle(arm_id + "_model"));
} catch (hardware_interface::HardwareInterfaceException& ex) {
ROS_ERROR_STREAM(
"GravityCompensationExampleController: Exception getting model handle from interface: "
<< ex.what());
return false;
}
// Verify robot state interface
std::cout << "Verifying robot state interface" << std::endl;
auto* state_interface = robot_hw->get<franka_hw::FrankaStateInterface>();
if (state_interface == nullptr) {
ROS_ERROR_STREAM(
"GravityCompensationExampleController: Error getting state interface from hardware");
return false;
}
try {
state_handle_ = std::make_unique<franka_hw::FrankaStateHandle>(
state_interface->getHandle(arm_id + "_robot"));
} catch (hardware_interface::HardwareInterfaceException& ex) {
ROS_ERROR_STREAM(
"GravityCompensationExampleController: Exception getting state handle from interface: "
<< ex.what());
return false;
}
// Verify effort joint interface
std::cout << "Verifying effort joint interface" << std::endl;
auto *effort_joint_interface = robot_hw->get<hardware_interface::EffortJointInterface>();
if (effort_joint_interface == nullptr)
{
ROS_ERROR_STREAM("GravityCompensationRealController: Error getting effort joint "
"interface from hardware");
return false;
}
// Verify joint handles
std::cout << "Verifying joint handles" << std::endl;
for (size_t i = 0; i < 7; ++i)
{
try
{
joint_handles_.push_back(effort_joint_interface->getHandle(joint_names[i]));
}
catch (const hardware_interface::HardwareInterfaceException &ex)
{
ROS_ERROR_STREAM("GravityCompensationRealController: Exception getting joint handles: " << ex.what());
return false;
}
}
// Load joint model from urdf to get joint limits
urdf::Model model;
if (model.initParam("/robot_description"))
{
robot_joints_ = model.joints_;
}
else
{
ROS_ERROR("Unable to read the robot model from URDF.");
}
setupPublishersAndSubscribers(nh);
// ---------------------------------------------------------------------------
// Init Values
// ---------------------------------------------------------------------------
T0ee_.setZero();
max_joint_limits_ << robot_joints_[joint_handles_[0].getName()].get()->limits.get()->upper,
robot_joints_[joint_handles_[1].getName()].get()->limits.get()->upper,
robot_joints_[joint_handles_[2].getName()].get()->limits.get()->upper,
robot_joints_[joint_handles_[3].getName()].get()->limits.get()->upper,
robot_joints_[joint_handles_[4].getName()].get()->limits.get()->upper,
robot_joints_[joint_handles_[5].getName()].get()->limits.get()->upper,
robot_joints_[joint_handles_[6].getName()].get()->limits.get()->upper;
min_joint_limits_ << robot_joints_[joint_handles_[0].getName()].get()->limits.get()->lower,
robot_joints_[joint_handles_[1].getName()].get()->limits.get()->lower,
robot_joints_[joint_handles_[2].getName()].get()->limits.get()->lower,
robot_joints_[joint_handles_[3].getName()].get()->limits.get()->lower,
robot_joints_[joint_handles_[4].getName()].get()->limits.get()->lower,
robot_joints_[joint_handles_[5].getName()].get()->limits.get()->lower,
robot_joints_[joint_handles_[6].getName()].get()->limits.get()->lower;
return true;
}
void GravityCompensationRealController::starting(const ros::Time &time)
{
// We want to start the controller by setting as the desired position
// the actual position. This avoids problems associated with sending the robot
// to a specified position right away. That can cause bounces and instabillities.
// Read the robot state
franka::RobotState initial_state = state_handle_->getRobotState();
// Get transformation from end-effector to base T0ee_d
T0ee_ = Eigen::Matrix4d::Map(initial_state.O_T_EE.data());
Eigen::Affine3d transform(T0ee_);
Eigen::Vector3d X0ee_ = transform.translation();
Eigen::Matrix3d R0ee_ = transform.rotation();
}
void GravityCompensationRealController::update(const ros::Time &time, const ros::Duration &period)
{
// Get robot state
franka::RobotState robot_state = state_handle_->getRobotState();
// Obtain joint positions (q), velocities (qdot) and efforts (effort) from hardware interface
q_ = Eigen::Matrix<double, 7, 1>::Map(robot_state.q.data());
qdot_ = Eigen::Matrix<double, 7, 1>::Map(robot_state.dq.data());
// Desired link-side joint torque sensor signals without gravity. Unit: [Nm]
Eigen::Map<Eigen::Matrix<double, 7, 1>> tau_J_d(robot_state.tau_J_d.data());
// Calculate X = f(q) using forward kinematics (FK)
T0ee_ = Eigen::Matrix4d::Map(robot_state.O_T_EE.data());
Eigen::Affine3d transform(T0ee_);
Eigen::Vector3d X0ee_(transform.translation());
Eigen::Matrix3d R0ee_(transform.rotation());
// Publish current pose
publishCurrentPose(X0ee_, R0ee_);
// ---------------------------------------------------------------------------
// Calculate the dynamic parameters
// ---------------------------------------------------------------------------
// Calculate Jacobian
std::array<double, 42> jacobian_array = model_handle_->getZeroJacobian(franka::Frame::kEndEffector);
J = Eigen::Matrix<double, 6, 7>::Map(jacobian_array.data());
// Calculate the dynamics: inertia, coriolis and gravity matrices
M = Eigen::Matrix<double, 7, 7>::Map(model_handle_->getMass().data());
C = Eigen::Matrix<double, 7, 1>::Map(model_handle_->getCoriolis().data());
g = Eigen::Matrix<double, 7, 1>::Map(model_handle_->getGravity().data());
// Calculate Lambda which is the Mass Matrix of the task space
// Λ(q) = (J * M(q)−1 * JT)−1
Eigen::Matrix<double, 6, 6> lambda;
lambda = (J * M.inverse() * J.transpose()).inverse();
// Calculate the Dynamically consistent generalized inverse of the jacobian
// J# = M(q)−1 * JT * Λ(q)
Jhash = M.inverse() * J.transpose() * lambda;
// ---------------------------------------------------------------------------
// compute control
// ---------------------------------------------------------------------------
// Declare variables
// tau_d = [0, 0, 0, 0, 0, 0, 0]
Eigen::VectorXd tau_d(7);
// Calculate final torque
tau_d << 0, 0, 0, 0, 0, 0, 0;
// Saturate torque rate to avoid discontinuities
tau_d << saturateTorqueRate(tau_d, tau_J_d);
// Publish wrenches and tracking errors
publishWrenches();
publishTrackingErrors();
// Set desired torque to each joint
for (size_t i = 0; i < 7; ++i)
joint_handles_[i].setCommand(tau_d(i));
}
/**
* \brief Clamps the joint torques if they go beyond the defined limits.
*/
Eigen::Matrix<double, 7, 1> GravityCompensationRealController::saturateTorqueRate(
const Eigen::Matrix<double, 7, 1> &tau_d, const Eigen::Matrix<double, 7, 1> &tau_J_d)
{
Eigen::Matrix<double, 7, 1> tau_d_saturated;
for (size_t i = 0; i < 7; i++)
{
double difference = tau_d[i] - tau_J_d[i];
tau_d_saturated[i] = tau_J_d[i] + std::max(std::min(difference, delta_tau_max_), -delta_tau_max_);
}
return tau_d_saturated;
}
/**
* \brief Publishes the robot external wrenches to a topic.
*/
void GravityCompensationRealController::publishWrenches(void)
{
geometry_msgs::Wrench wrench_msg;
// Prepare force msg
franka::RobotState state = state_handle_->getRobotState();
std::array<double, 6> wrench = state.O_F_ext_hat_K;
wrench_msg.force.x = wrench[0];
wrench_msg.force.y = wrench[1];
wrench_msg.force.z = wrench[2];
wrench_msg.torque.x = wrench[3];
wrench_msg.torque.y = wrench[4];
wrench_msg.torque.z = wrench[5];
wrench_pub_.publish(wrench_msg);
}
} // namespace smalldrop_robot_arm
} // namespace smalldrop
PLUGINLIB_EXPORT_CLASS(smalldrop::smalldrop_robot_arm::GravityCompensationRealController, controller_interface::ControllerBase) | 38.561265 | 127 | 0.644834 | [
"vector",
"model",
"transform"
] |
f4e768ec506e5d87c7848c9982429237a46c0986 | 12,445 | cpp | C++ | app/src/main/cpp/VideoProcessor.cpp | suhail-mir/EVMHR | 64b90601b6d212150bfdabb70ddec421a60cdd1c | [
"MIT"
] | 2 | 2016-10-10T15:32:23.000Z | 2019-07-22T00:51:23.000Z | app/src/main/cpp/VideoProcessor.cpp | suhail-mir/EVMHR | 64b90601b6d212150bfdabb70ddec421a60cdd1c | [
"MIT"
] | null | null | null | app/src/main/cpp/VideoProcessor.cpp | suhail-mir/EVMHR | 64b90601b6d212150bfdabb70ddec421a60cdd1c | [
"MIT"
] | 3 | 2019-06-17T08:21:31.000Z | 2019-10-21T07:37:51.000Z | // Yet anther C++ implementation of EVM, based on OpenCV and Qt.
// Copyright (C) 2014 Joseph Pan <cs.wzpan@gmail.com>
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
// 02110-1301 USA
//
#include "VideoProcessor.h"
VideoProcessor::VideoProcessor(){
delay = -1;
rate = 0;
fnumber = 0;
length = 0;
stop = true;
modify = false;
curPos = 0;
curIndex = 0;
curLevel = 0;
digits = 0;
extension = ".avi";
levels = 4;
alpha = 50; // 放大倍数
lambda_c = 80;
fl = 0.83; // 下限频率
fh = 1; // 上限频率
chromAttenuation = 0.1;
delta = 0;
exaggeration_factor = 2.0;
lambda = 0;
}
/**
* getFrameRate - return the frame rate
*
*
* @return the frame rate
*/
double VideoProcessor::getFrameRate()
{
double r = capture.get(CV_CAP_PROP_FPS);
return r;
}
/**
* getLengthMS - return the video length in milliseconds
*
*
* @return the length of length in milliseconds
*/
double VideoProcessor::getLengthMS()
{
double l = 1000.0 * length / rate;
return l;
}
/**
* spatialFilter - spatial filtering an image
*
* @param src - source image
* @param pyramid - destinate pyramid
*/
bool VideoProcessor::spatialFilter(const cv::Mat &src, std::vector<cv::Mat> &pyramid)
{
switch (spatialType) {
case LAPLACIAN: // laplacian pyramid
return buildLaplacianPyramid(src, levels, pyramid);
break;
case GAUSSIAN: // gaussian pyramid
return buildGaussianPyramid(src, levels, pyramid);
break;
default:
return false;
break;
}
}
/**
* temporalFilter - temporal filtering an image
*
* @param src - source image
* @param dst - destinate image
*/
void VideoProcessor::temporalFilter(const cv::Mat &src,
cv::Mat &dst)
{
switch (temporalType) {
case IIR: // IIR bandpass filter
temporalIIRFilter(src, dst);
break;
case IDEAL: // Ideal bandpass filter
temporalIdealFilter(src, dst);
break;
default:
break;
}
return;
}
/**
* temporalIIRFilter - temporal IIR filtering an image
* (thanks to Yusuke Tomoto)
* @param pyramid - source image
* @param filtered - filtered result
*
*/
void VideoProcessor::temporalIIRFilter(const cv::Mat &src,
cv::Mat &dst)
{
cv::Mat temp1 = (1 - fh)*lowpass1[curLevel] + fh*src;
cv::Mat temp2 = (1 - fl)*lowpass2[curLevel] + fl*src;
lowpass1[curLevel] = temp1;
lowpass2[curLevel] = temp2;
dst = lowpass1[curLevel] - lowpass2[curLevel];
}
/**
* temporalIdalFilter - temporal IIR filtering an image pyramid of concat-frames
* (Thanks to Daniel Ron & Alessandro Gentilini)
*
* @param pyramid - source pyramid of concatenate frames
* @param filtered - concatenate filtered result
*
*/
void VideoProcessor::temporalIdealFilter(const cv::Mat &src,
cv::Mat &dst)
{
cv::Mat channels[3];
// split into 3 channels
cv::split(src, channels);
for (int i = 0; i < 3; ++i){
cv::Mat current = channels[i]; // current channel
cv::Mat tempImg;
int width = cv::getOptimalDFTSize(current.cols);
int height = cv::getOptimalDFTSize(current.rows);
cv::copyMakeBorder(current, tempImg,
0, height - current.rows,
0, width - current.cols,
cv::BORDER_CONSTANT, cv::Scalar::all(0));
// do the DFT
cv::dft(tempImg, tempImg, cv::DFT_ROWS | cv::DFT_SCALE);
// construct the filter
cv::Mat filter = tempImg.clone();
createIdealBandpassFilter(filter, fl, fh, rate);
// apply filter
cv::mulSpectrums(tempImg, filter, tempImg, cv::DFT_ROWS);
// do the inverse DFT on filtered image
cv::idft(tempImg, tempImg, cv::DFT_ROWS | cv::DFT_SCALE);
// copy back to the current channel
tempImg(cv::Rect(0, 0, current.cols, current.rows)).copyTo(channels[i]);
}
// merge channels
cv::merge(channels, 3, dst);
// normalize the filtered image
cv::normalize(dst, dst, 0, 1, CV_MINMAX);
}
/**
* amplify - ampilfy the motion
*
* @param filtered - motion image
*/
void VideoProcessor::amplify(const cv::Mat &src, cv::Mat &dst)
{
float currAlpha;
switch (spatialType) {
case LAPLACIAN:
//compute modified alpha for this level
currAlpha = lambda / delta / 8 - 1;
currAlpha *= exaggeration_factor;
if (curLevel == levels || curLevel == 0) // ignore the highest and lowest frequency band
dst = src * 0;
else
dst = src * cv::min(alpha, currAlpha);
break;
case GAUSSIAN:
dst = src * alpha;
break;
default:
break;
}
}
/**
* concat - concat all the frames into a single large Mat
* where each column is a reshaped single frame
*
* @param frames - frames of the video sequence
* @param dst - destinate concatnate image
*/
void VideoProcessor::concat(const std::vector<cv::Mat> &frames,
cv::Mat &dst)
{
cv::Size frameSize = frames.at(0).size();
cv::Mat temp(frameSize.width*frameSize.height, length - 1, CV_32FC3);
for (int i = 0; i < length - 1; ++i) {
// get a frame if any
cv::Mat input = frames.at(i);
// reshape the frame into one column
// 像素总数不变,但row变成总数,意味着column为1
cv::Mat reshaped = input.reshape(3, input.cols*input.rows).clone();
cv::Mat line = temp.col(i);
// save the reshaped frame to one column of the destinate big image
reshaped.copyTo(line);
}
temp.copyTo(dst);
std::cout << "ok";
}
/**
* deConcat - de-concat the concatnate image into frames
*
* @param src - source concatnate image
* @param framesize - frame size
* @param frames - destinate frames
*/
void VideoProcessor::deConcat(const cv::Mat &src,
const cv::Size &frameSize,
std::vector<cv::Mat> &frames)
{
for (int i = 0; i < length - 1; ++i) { // get a line if any
cv::Mat line = src.col(i).clone();
cv::Mat reshaped = line.reshape(3, frameSize.height).clone();
frames.push_back(reshaped);
}
}
/**
* createIdealBandpassFilter - create a 1D ideal band-pass filter
*
* @param filter - destinate filter
* @param fl - low cut-off
* @param fh - high cut-off
* @param rate - sampling rate(i.e. video frame rate)
*/
void VideoProcessor::createIdealBandpassFilter(cv::Mat &filter, double fl, double fh, double rate)
{
int width = filter.cols;
int height = filter.rows;
fl = 2 * fl * width / rate;
fh = 2 * fh * width / rate;
double response;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
// filter response
if (j >= fl && j <= fh)
response = 1.0f;
else
response = 0.0f;
filter.at<float>(i, j) = response;
}
}
}
/**
* setInput - set the name of the expected video file
*
* @param fileName - the name of the video file
*
* @return True if success. False otherwise
*/
bool VideoProcessor::setInput(const std::string &fileName)
{
fnumber = 0;
tempFile = fileName;
// In case a resource was already
// associated with the VideoCapture instance
if (isOpened()){
capture.release();
}
// Open the video file
if (capture.open(fileName)){
// read parameters
length = capture.get(CV_CAP_PROP_FRAME_COUNT);
rate = getFrameRate();
//cv::Mat input;
// show first frame
//getNextFrame(input);
//emit showFrame(input);
//emit updateBtn();
return true;
}
else {
return false;
}
}
/**
* setSpatialFilter - set the spatial filter
*
* @param type - spatial filter type. Could be:
* 1. LAPLACIAN: laplacian pyramid
* 2. GAUSSIAN: gaussian pyramid
*/
void VideoProcessor::setSpatialFilter(spatialFilterType type)
{
spatialType = type;
}
/**
* setTemporalFilter - set the temporal filter
*
* @param type - temporal filter type. Could be:
* 1. IIR: second order(IIR) filter
* 2. IDEAL: ideal bandpass filter
*/
void VideoProcessor::setTemporalFilter(temporalFilterType type)
{
temporalType = type;
}
/**
* close - close the video
*
*/
void VideoProcessor::close()
{
rate = 0;
length = 0;
modify = 0;
capture.release();
writer.release();
tempWriter.release();
}
/**
* isStop - Is the processing stop
*
*
* @return True if not processing/playing. False otherwise
*/
bool VideoProcessor::isStop()
{
return stop;
}
/**
* isOpened - Is the player opened?
*
*
* @return True if opened. False otherwise
*/
bool VideoProcessor::isOpened()
{
return capture.isOpened();
}
/**
* getNextFrame - get the next frame if any
*
* @param frame - the expected frame
*
* @return True if success. False otherwise
*/
bool VideoProcessor::getNextFrame(cv::Mat &frame)
{
return capture.read(frame);
}
/**
* findPeaks - find peaks in the curve
*
*/
int findPeaks(std::vector<double> smoothedData) {
double diff;
std::vector<int> sign;
for (int i = 1; i < smoothedData.size(); ++i) {
diff = smoothedData[i] - smoothedData[i - 1];
if (diff > 0) {
sign.push_back(1);
}
else if (diff < 0) {
sign.push_back(-1);
}
else {
sign.push_back(0);
}
}
int peaks = 0;
for (int j = 1; j < sign.size(); j++) {
diff = sign[j] - sign[j - 1];
if (diff < 0) {
peaks++;
}
}
return peaks;
}
/**
* smooth - smooth the curve with Moving Average Filtering
*
*/
void smooth(std::vector<double> input_data, unsigned int len, std::vector<double> & output_data, unsigned int span) {
unsigned int i = 0, j = 0;
unsigned int pn = 0, n = 0;
double sum = 0.0;
if (span % 2 == 1) {
n = (span - 1) / 2;
}
else{
n = (span - 2) / 2;
}
for (i = 0; i < len; ++i) {
pn = n;
if (i < n) {
pn = i;
}
else if ((len - 1 - i) < n) {
pn = len - i - 1;
}
sum = 0.0;
for (j = i - pn; j <= i + pn; ++j) {
sum += input_data[j];
}
output_data.push_back(sum / (pn * 2 + 1));
}
}
/**
* colorMagnify - color magnification
*
*/
int VideoProcessor::colorMagnify()
{
// set filter
setSpatialFilter(GAUSSIAN);
setTemporalFilter(IDEAL);
// create a temp file
// createTemp();
// current frame
cv::Mat input;
// output frame
cv::Mat output;
// motion image
cv::Mat motion;
// temp image
cv::Mat temp;
// video frames
std::vector<cv::Mat> frames;
// down-sampled frames
std::vector<cv::Mat> downSampledFrames;
// filtered frames
std::vector<cv::Mat> filteredFrames;
// concatenate image of all the down-sample frames
cv::Mat videoMat;
// concatenate filtered image
cv::Mat filtered;
// if no capture device has been set
if (!isOpened())
return 0;
// set the modify flag to be true
modify = true;
// is processing
stop = false;
// 1. spatial filtering
while (getNextFrame(input) && !isStop()) {
input.convertTo(temp, CV_32FC3);
frames.push_back(temp.clone());
// spatial filtering
std::vector<cv::Mat> pyramid;
spatialFilter(temp, pyramid);
downSampledFrames.push_back(pyramid.at(levels - 1));
}
// 2. concat all the frames into a single large Mat
// where each column is a reshaped single frame
// (for processing convenience)
concat(downSampledFrames, videoMat);
// 3. temporal filtering
temporalFilter(videoMat, filtered);
// 4. amplify color motion
amplify(filtered, filtered);
// 5. de-concat the filtered image into filtered frames
deConcat(filtered, downSampledFrames.at(0).size(), filteredFrames);
cv::Mat cl[3];
std::vector<double> markdata;
// 6. amplify each frame
// by adding frame image and motions
// and write into video
fnumber = 0;
for (int i = 0; i<length - 1 && !isStop(); ++i) {
// up-sample the motion image
upsamplingFromGaussianPyramid(filteredFrames.at(i), levels, motion);
resize(motion, motion, frames.at(i).size());
temp = frames.at(i) + motion;
output = temp.clone();
double minVal, maxVal;
minMaxLoc(output, &minVal, &maxVal); //find minimum and maximum intensities
output.convertTo(output, CV_8UC3, 255.0 / (maxVal - minVal),
-minVal * 255.0 / (maxVal - minVal));
cv::split(output, cl);
cv::Scalar mean = cv::mean(cl[1]);
markdata.push_back(mean[0]);
}
// Smooth the curve
std::vector<double> smoothedData;
smooth(markdata, markdata.size(), smoothedData, 11);
// Find Peaks
return findPeaks(smoothedData);
}
| 22.383094 | 117 | 0.657613 | [
"vector"
] |
f4eaa939563739a84626d2929e0200d2f4f0643a | 5,304 | cpp | C++ | app/src/particlesource.cpp | DaveeFTW/infinity | 6a4f269f8abcf65696064cad94ba9ac8b845bd74 | [
"MIT"
] | 137 | 2019-11-10T16:12:16.000Z | 2022-03-27T23:32:15.000Z | app/src/particlesource.cpp | DaveeFTW/infinity | 6a4f269f8abcf65696064cad94ba9ac8b845bd74 | [
"MIT"
] | 12 | 2019-11-11T20:37:05.000Z | 2021-11-14T17:18:56.000Z | app/src/particlesource.cpp | DaveeFTW/infinity | 6a4f269f8abcf65696064cad94ba9ac8b845bd74 | [
"MIT"
] | 49 | 2019-11-15T02:37:05.000Z | 2022-03-28T20:04:49.000Z | /*
Copyright (C) 2015, David "Davee" Morgan
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 "particlesource.h"
#include "vertextype.h"
#include <pspgu.h>
#include <pspgum.h>
#include <limits.h>
#include <time.h>
namespace
{
float getRandomLinearPosition(auto ctx, float p, float length)
{
if (length == 0.f)
return p;
float rnd = sceKernelUtilsMt19937UInt(ctx) / (double)0xFFFFFFFF;
return p + rnd * length;
}
} // anonymous namespace
ParticleSource::ParticleSource(float x, float y, int max)
: ParticleSource(Rectangle(x, y, 0, 0), max)
{
}
ParticleSource::ParticleSource(Rectangle spawnArea, int max)
: m_spawnArea(spawnArea)
, m_decayCoefficient(2.5f)
, m_velocityCoefficient(50.f)
, m_repeat(true)
, m_opacity(1.f)
{
sceKernelUtilsMt19937Init(&m_ctx, time(NULL));
m_particles.reserve(max);
m_particles.resize(max);
regenerateParticles();
}
void ParticleSource::setSpawnArea(float x, float y)
{
m_spawnArea = Rectangle(x, y, 0, 0);
}
void ParticleSource::setSpawnArea(Rectangle spawnArea)
{
m_spawnArea = spawnArea;
}
void ParticleSource::setDecayCoefficient(float decay)
{
m_decayCoefficient = decay;
regenerateParticles();
}
float ParticleSource::decayCoefficient(void) const
{
return m_decayCoefficient;
}
void ParticleSource::setVelocityCoefficient(float velocity)
{
m_velocityCoefficient = velocity;
regenerateParticles();
}
float ParticleSource::velocityCoefficient(void) const
{
return m_velocityCoefficient;
}
void ParticleSource::setRepeat(bool repeat)
{
m_repeat = repeat;
}
bool ParticleSource::repeat(void) const
{
return m_repeat;
}
void ParticleSource::setOpacity(float opacity)
{
m_opacity = opacity;
}
float ParticleSource::opacity(void) const
{
return m_opacity;
}
void ParticleSource::update(float dt)
{
for (auto i = (unsigned)0; i < m_particles.size(); ++i)
{
if (m_particles[i].decay <= 0.f && m_repeat)
{
m_particles[i].decay = 1.f;
m_particles[i].x =
getRandomLinearPosition(&m_ctx, m_spawnArea.x(), m_spawnArea.width());
m_particles[i].y =
getRandomLinearPosition(&m_ctx, m_spawnArea.y(), m_spawnArea.height());
}
else
{
m_particles[i].decay -= m_particles[i].decayRate * dt;
m_particles[i].x += m_particles[i].direction.x * dt;
m_particles[i].y += m_particles[i].direction.y * dt;
}
}
}
void ParticleSource::render(void)
{
auto particles = static_cast<Vertex*>(sceGuGetMemory(m_particles.size() * sizeof(Vertex)));
for (auto i = 0u; i < m_particles.size(); ++i)
{
int particleAlpha = (m_particles[i].decay * 0xFF);
if (particleAlpha < 0)
particleAlpha = 0;
else if (particleAlpha > 0xFF)
particleAlpha = 0xFF;
particles[i].colour = 0x00FFFFFF | ((int)(particleAlpha * m_opacity) << 24);
particles[i].x = m_particles[i].x;
particles[i].y = m_particles[i].y;
particles[i].z = 0.f;
}
sceGumDrawArray(GU_POINTS,
GU_COLOR_8888 | GU_VERTEX_32BITF | GU_TRANSFORM_3D,
m_particles.size(),
0,
particles);
}
void ParticleSource::regenerateParticles(void)
{
for (auto i = (unsigned)0; i < m_particles.size(); ++i)
{
m_particles[i].decay = (float)i / (float)m_particles.size();
// if the spawn area has a width, place randomly along this line
m_particles[i].x = getRandomLinearPosition(&m_ctx, m_spawnArea.x(), m_spawnArea.width());
// likewise place randomly along height line
m_particles[i].y = getRandomLinearPosition(&m_ctx, m_spawnArea.y(), m_spawnArea.height());
float rnd = sceKernelUtilsMt19937UInt(&m_ctx) / (double)0xFFFFFFFF;
m_particles[i].decayRate = rnd / decayCoefficient() + 0.000001f;
float vx = sceKernelUtilsMt19937UInt(&m_ctx) / (double)0xFFFFFFFF;
float vy = sceKernelUtilsMt19937UInt(&m_ctx) / (double)0xFFFFFFFF;
m_particles[i].direction.x = ((2.f * vx) - 1.f) * velocityCoefficient();
m_particles[i].direction.y = ((2.f * vy) - 1.f) * velocityCoefficient();
}
}
| 28.363636 | 98 | 0.669495 | [
"render"
] |
f4eb892559abbda855dfcf2cefd134d1efd10429 | 861 | cpp | C++ | src/CaptureFile/BufferOutputStream.cpp | tufeigunchu/orbit | 407354cf7c9159ff7e3177c603a6850b95509e3a | [
"BSD-2-Clause"
] | 1,847 | 2020-03-24T19:01:42.000Z | 2022-03-31T13:18:57.000Z | src/CaptureFile/BufferOutputStream.cpp | tufeigunchu/orbit | 407354cf7c9159ff7e3177c603a6850b95509e3a | [
"BSD-2-Clause"
] | 1,100 | 2020-03-24T19:41:13.000Z | 2022-03-31T14:27:09.000Z | src/CaptureFile/BufferOutputStream.cpp | tufeigunchu/orbit | 407354cf7c9159ff7e3177c603a6850b95509e3a | [
"BSD-2-Clause"
] | 228 | 2020-03-25T05:32:08.000Z | 2022-03-31T11:27:39.000Z | // Copyright (c) 2021 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "CaptureFile/BufferOutputStream.h"
#include <algorithm>
#include <cstring>
#include "OrbitBase/File.h"
namespace orbit_capture_file {
bool BufferOutputStream::Write(const void* data, int size) {
CHECK(data != nullptr);
CHECK(size >= 0);
absl::MutexLock lock{&mutex_};
size_t old_size = buffer_.size();
size_t new_size = old_size + size;
CHECK(new_size > old_size);
buffer_.resize(new_size);
std::memcpy(buffer_.data() + old_size, data, size);
return true;
}
std::vector<unsigned char> BufferOutputStream::TakeBuffer() {
absl::MutexLock lock{&mutex_};
auto output_buffer = std::move(buffer_);
return output_buffer;
}
} // namespace orbit_capture_file | 23.27027 | 73 | 0.722416 | [
"vector"
] |
f4ef6fc1dc44e33b413be533618540a1d62b9cbb | 4,087 | cc | C++ | PYTHIA8/pythia8243/examples/main121.cc | mpoghos/AliRoot | e81490f640ad6f2a6189f679de96b07a94304b58 | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | PYTHIA8/pythia8243/examples/main121.cc | mpoghos/AliRoot | e81490f640ad6f2a6189f679de96b07a94304b58 | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | PYTHIA8/pythia8243/examples/main121.cc | mpoghos/AliRoot | e81490f640ad6f2a6189f679de96b07a94304b58 | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | // main121.cc is a part of the PYTHIA event generator.
// Copyright (C) 2019 Torbjorn Sjostrand.
// PYTHIA is licenced under the GNU GPL v2 or later, see COPYING for details.
// Please respect the MCnet Guidelines, see GUIDELINES for details.
// Illustrate how to set up automatic uncertainty band calculations.
#include "Pythia8/Pythia.h"
using namespace Pythia8;
//--------------------------------------------------------------------------
// Small helper function to get variation names.
string weightLabel(string weightString) {
// Strip leading whitespace
weightString.erase(0,weightString.find_first_not_of(" \t\n\r\f\v"));
// Find first blank and use this to isolate weight label.
int iBlank = weightString.find(" ", 0);
return weightString.substr(0, iBlank);
}
//--------------------------------------------------------------------------
int main() {
// Initialize Pythia.
Pythia pythia;
pythia.readFile("main121.cmnd");
pythia.init();
// Define multiple histograms, one for each variation.
int nWeights = pythia.info.nWeights();
vector<double> sumOfWeights;
vector<Hist> pTtop, nCh;
vector<string> names;
vector<string> weightStrings = pythia.settings.wvec("UncertaintyBands:List");
// Loop through weights to initialize the histograms.
for (int iWeight=0; iWeight < nWeights; ++iWeight) {
names.push_back( (iWeight==0)
? "baseline" : weightLabel(weightStrings[iWeight-1]));
pTtop.push_back ( Hist("top transverse momentum", 100, 0., 200.));
nCh.push_back ( Hist("charged particle multiplicity", 100, -1., 399.));
sumOfWeights.push_back(0.);
}
// Event generation loop.
int nEvent = pythia.mode("Main:numberOfEvents");
for (int iEvent=0; iEvent < nEvent; ++iEvent) {
// Generate next event. Break out of event loop if at end of an LHE file.
if ( !pythia.next() ) {
if ( pythia.info.atEndOfFile() ) break;
else continue;
}
// Find last top in event record and count number of charged particles.
int iTop = 0;
int nChg = 0;
for (int i=0; i < pythia.event.size(); ++i) {
if (pythia.event[i].id() == 6) iTop = i;
if (pythia.event[i].isFinal() && pythia.event[i].isCharged()) ++nChg;
}
// Get top pT.
double pT = pythia.event[iTop].pT();
// Fill histograms with variation weights.
for (int iWeight = 0; iWeight < nWeights; ++iWeight) {
// Get weight
double w = pythia.info.weight(iWeight);
// Add the weight of the current event to the wsum of weights.
sumOfWeights[iWeight] += w;
// Fill histograms.
pTtop[iWeight].fill(pT, w);
nCh[iWeight].fill(nChg, w);
}
}
// Print cross section information.
pythia.stat();
// Normalize histograms and print data tables. Also, construct a simple
// gnuplot command to plot the histograms.
stringstream gnuplotCommand;
gnuplotCommand << "gnuplot -e \"plot";
for (int iWeight=0; iWeight < nWeights; ++iWeight) {
cout << "Normalize histogram for weight " << names[iWeight] << " to "
<< scientific << setprecision(8) << sumOfWeights[iWeight] << endl;
pTtop[iWeight] *= pythia.info.sigmaGen() / sumOfWeights[iWeight]
/ 2.; // ... and divide by bin width.
nCh[iWeight] *= pythia.info.sigmaGen() / sumOfWeights[iWeight]
/ 4.; // ... and divide by bin width.
// Print data tables.
ofstream write;
write.open( ("pTtop-" + names[iWeight] + ".dat").c_str());
pTtop[iWeight].table(write);
write.close();
write.open( ("nCh-" + names[iWeight] + ".dat").c_str());
nCh[iWeight].table(write);
write.close();
// Construct gnuplot command.
gnuplotCommand << " \'pTtop-" << names[iWeight]
<< ".dat\' using 1:2 w steps title \'" << names[iWeight] << "\',";
}
gnuplotCommand.seekp(-1, std::ios_base::end);
gnuplotCommand << "; pause -1\"";
// Print suggested gnuplot command.
cout << "You can plot the variation by e.g. using the command:" << endl;
cout << gnuplotCommand.str() << endl << endl;
// Done.
return 0;
}
| 34.635593 | 79 | 0.619036 | [
"vector"
] |
760e4c889facb07b9a41bfcd0ae7b70ccd33d8ff | 3,016 | cc | C++ | poj/3/3945.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | 1 | 2015-04-17T09:54:23.000Z | 2015-04-17T09:54:23.000Z | poj/3/3945.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | null | null | null | poj/3/3945.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
static const int INF = 10000000;
struct cube
{
int x, y, t, n, e, i;
cube(int a, int b, int c, int d, int e_, int f)
: x(a), y(b), t(c), n(d), e(e_), i(f)
{}
int top() const { return t; }
int bottom() const { return t^1; }
int north() const { return n; }
int south() const { return n^1; }
int east() const { return e; }
int west() const { return e^1; }
char color() const
{
static const char tbl[] = "rcgmby";
return tbl[top()];
}
};
int bfs(const vector<string>& grid, const string& route, int x, int y)
{
const int H = grid.size();
const int W = grid[0].size();
static int dist[30][30][6][6][6];
for (int i = 0; i < H; i++) {
for (int j = 0; j < W; j++) {
for (int t = 0; t < 6; t++) {
for (int n = 0; n < 6; n++) {
fill_n(dist[i][j][t][n], 6, INF);
}
}
}
}
queue<cube> q;
q.push(cube(x, y, 0, 2, 4, 0));
dist[x][y][0][2][0] = 0;
int ans = INF;
while (!q.empty()) {
const cube c = q.front();
q.pop();
const int dd = dist[c.x][c.y][c.t][c.n][c.i];
for (int d = 0; d < 4; d++) {
cube cc(c);
static const int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1};
cc.x += dx[d];
cc.y += dy[d];
if (0 <= cc.x && cc.x < H && 0 <= cc.y && cc.y < W && grid[cc.x][cc.y] != 'k') {
switch (d) {
case 0: // north
cc.n = c.top();
cc.t = c.south();
break;
case 1: // south
cc.n = c.bottom();
cc.t = c.north();
break;
case 2: // west
cc.e = c.bottom();
cc.t = c.east();
break;
case 3: // east
cc.e = c.top();
cc.t = c.west();
break;
}
if (grid[cc.x][cc.y] != 'w') {
if (grid[cc.x][cc.y] == route[cc.i] && grid[cc.x][cc.y] == cc.color()) {
++cc.i;
if (cc.i == 6) {
ans = min(ans, dd+1);
} else {
int& ddd = dist[cc.x][cc.y][cc.t][cc.n][cc.i];
if (dd+1 < ddd) {
ddd = dd+1;
q.push(cc);
}
}
}
} else {
int& ddd = dist[cc.x][cc.y][cc.t][cc.n][cc.i];
if (dd+1 < ddd) {
ddd = dd+1;
q.push(cc);
}
}
}
}
}
return ans;
}
int main()
{
ios::sync_with_stdio(false);
int W, H;
while (cin >> W >> H && W != 0) {
vector<string> grid(H);
int x, y;
for (int i = 0; i < H; i++) {
cin >> grid[i];
for (int j = 0; j < W; j++) {
if (grid[i][j] == '#') {
x = i;
y = j;
grid[i][j] = 'w';
}
}
}
string route;
cin >> route;
const int ans = bfs(grid, route, x, y);
if (ans == INF) {
cout << "unreachable" << endl;
} else {
cout << ans << endl;
}
}
return 0;
}
| 23.748031 | 86 | 0.395225 | [
"vector"
] |
760e79cf230e11a5a0554254b3140ed8553f4eab | 1,794 | hpp | C++ | 3space-studio/src/canvas_painter.hpp | gifted-nguvu/darkstar-dts-converter | aa17a751a9f3361ca9bbb400ee4c9516908d1297 | [
"MIT"
] | 2 | 2020-03-18T18:23:27.000Z | 2020-08-02T15:59:16.000Z | 3space-studio/src/canvas_painter.hpp | gifted-nguvu/darkstar-dts-converter | aa17a751a9f3361ca9bbb400ee4c9516908d1297 | [
"MIT"
] | 5 | 2019-07-07T16:47:47.000Z | 2020-08-10T16:20:00.000Z | 3space-studio/src/canvas_painter.hpp | gifted-nguvu/darkstar-dts-converter | aa17a751a9f3361ca9bbb400ee4c9516908d1297 | [
"MIT"
] | 1 | 2020-03-18T18:23:30.000Z | 2020-03-18T18:23:30.000Z | #ifndef DARKSTARDTSCONVERTER_DTS_WIDGET_HPP
#define DARKSTARDTSCONVERTER_DTS_WIDGET_HPP
#include "views/graphics_view.hpp"
namespace studio
{
auto canvas_painter(const std::shared_ptr<wxWindow>& parent, const std::shared_ptr<sf::RenderWindow>& window, ImGuiContext& gui_context, std::shared_ptr<views::graphics_view> handler)
{
sf::Clock clock;
auto callbacks = handler->get_callbacks();
handler->setup_view(*parent, *window, gui_context);
return [parent, window, gui_context = &gui_context, handler, clock, callbacks](auto& wx_event) mutable {
wxPaintDC Dc(parent.get());
sf::Event event{};
ImGui::SetCurrentContext(gui_context);
while (window->pollEvent(event))
{
ImGui::SFML::ProcessEvent(event);
if (event.type == sf::Event::KeyPressed && (event.key.code != sf::Keyboard::Escape))
{
const auto callback = callbacks.find(event.key.code);
if (callback != callbacks.end())
{
callback->second(event);
}
}
if (event.type == sf::Event::Closed)
{
window->close();
}
if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))
{
window->close();
}
}
handler->render_gl(*parent, *window, *gui_context);
window->pushGLStates();
ImGui::SFML::Update(*window, clock.restart());
handler->render_ui(*parent, *window, *gui_context);
ImGui::SFML::Render(*window);
window->popGLStates();
window->display();
};
}
}
#endif//DARKSTARDTSCONVERTER_DTS_WIDGET_HPP
| 28.47619 | 185 | 0.566332 | [
"render"
] |
760ec6cef7ec282cbe7d4e9b9d070261f5211052 | 17,233 | cpp | C++ | trots_lib/TROTSEntry.cpp | felliu/Optimization-Benchmarks | 384c3d8c5f526a1b5a9392e80d8e67ffe410a0a2 | [
"BSD-3-Clause"
] | null | null | null | trots_lib/TROTSEntry.cpp | felliu/Optimization-Benchmarks | 384c3d8c5f526a1b5a9392e80d8e67ffe410a0a2 | [
"BSD-3-Clause"
] | null | null | null | trots_lib/TROTSEntry.cpp | felliu/Optimization-Benchmarks | 384c3d8c5f526a1b5a9392e80d8e67ffe410a0a2 | [
"BSD-3-Clause"
] | null | null | null | #include <algorithm>
#include <cassert>
#include <cmath>
#include <memory>
#include <numeric>
#include <unordered_set>
#include <vector>
#include <matio.h>
#ifdef USE_MKL
#include "MKL_sparse_matrix.h"
#endif
#include "TROTSEntry.h"
#include "util.h"
namespace {
const char* func_type_names[] = {"Min", "Max", "Mean", "Quadratic", "gEUD", "LTCP", "DVH", "Chain"};
/*FunctionType get_linear_function_type(int dataID, bool minimise, const std::string& roi_name, matvar_t* matrix_struct) {
const int zero_indexed_dataID = dataID - 1;
std::cerr << "Reading name field\n";
//The times when the function type is mean, the data.matrix struct should have an entry at dataID with the name "<ROI_name> + (mean)"...
matvar_t* matrix_entry_name_var = Mat_VarGetStructFieldByName(matrix_struct, "Name", zero_indexed_dataID);
check_null(matrix_entry_name_var, "Failed to read name field of matrix entry\n.");
const bool is_mean =
return minimise ? FunctionType::Max : FunctionType::Min;
}*/
FunctionType get_nonlinear_function_type(int type_id) {
assert(type_id >= 2);
//The type ID is one-indexed, so need to subtract one for that.
//Then add two since type_id one maps to three different possible function types.
return static_cast<FunctionType>(type_id + 1);
}
}
TROTSEntry::TROTSEntry(matvar_t* problem_struct_entry, matvar_t* matrix_struct,
const std::vector<std::variant<std::unique_ptr<SparseMatrix<double>>,
std::vector<double>>
>& mat_refs) :
rhs{0}, weight{0}, c{0}
{
assert(problem_struct_entry->class_type == MAT_C_STRUCT);
//Try to ensure that the structure is a scalar (1x1) struct.
assert(problem_struct_entry->rank == 2);
assert(problem_struct_entry->dims[0] == 1 && problem_struct_entry->dims[1] == 1);
matvar_t* name_var = Mat_VarGetStructFieldByName(problem_struct_entry, "Name", 0);
check_null(name_var, "Cannot find name variable in problem entry.");
assert(name_var->class_type == MAT_C_CHAR);
this->roi_name = get_name_str(name_var);
std::cerr << "Name: " << this->roi_name << "\n";
//Matlab stores numeric values as doubles by default, which seems to be the type
//used by TROTS as well even for integral values. Do some casting here to convert the data to
//more intuitive types.
matvar_t* id_var = Mat_VarGetStructFieldByName(problem_struct_entry, "dataID", 0);
check_null(id_var, "Could not read id field from struct\n");
this->id = cast_from_double<int>(id_var);
matvar_t* minimise_var = Mat_VarGetStructFieldByName(problem_struct_entry, "Minimise", 0);
check_null(minimise_var, "Could not read Minimise field from struct\n");
this->minimise = cast_from_double<bool>(minimise_var);
matvar_t* active_var = Mat_VarGetStructFieldByName(problem_struct_entry, "Active", 0);
check_null(active_var, "Could not read Active field from struct\n");
this->active = cast_from_double<bool>(active_var);
//The IsConstraint field goes against the trend of using doubles, and is actually a MATLAB logical val,
//which matio has as a MAT_C_UINT8
matvar_t* is_cons_var = Mat_VarGetStructFieldByName(problem_struct_entry, "IsConstraint", 0);
check_null(is_cons_var, "Could not read IsConstraint field from struct\n");
this->is_cons = *static_cast<bool*>(is_cons_var->data);
matvar_t* objective_var = Mat_VarGetStructFieldByName(problem_struct_entry, "Objective", 0);
check_null(objective_var, "Could not read Objective field from struct\n");
this->rhs = *static_cast<double*>(objective_var->data);
matvar_t* function_type = Mat_VarGetStructFieldByName(problem_struct_entry, "Type", 0);
check_null(function_type, "Could not read the \"Type\" field from the problem struct\n");
int TROTS_type = cast_from_double<int>(function_type);
//An index of 1 means a "linear" function, which in reality can be one of three possibilities. Min, max and mean.
//Determine which one it is.
if (TROTS_type == 1) {
if (std::holds_alternative<std::vector<double>>(mat_refs[this->id - 1]))
this->type = FunctionType::Mean;
else {
this->type = this->minimise ? FunctionType::Max : FunctionType::Min;
}
}
else
this->type = get_nonlinear_function_type(TROTS_type);
if (this->type == FunctionType::Mean) {
this->matrix_ref = nullptr;
this->mean_vec_ref = &std::get<std::vector<double>>(mat_refs[this->id - 1]);
} else {
this->mean_vec_ref = nullptr;
this->matrix_ref = std::get<std::unique_ptr<SparseMatrix<double>>>(mat_refs[this->id - 1]).get();
}
matvar_t* weight_var = Mat_VarGetStructFieldByName(problem_struct_entry, "Weight", 0);
check_null(weight_var, "Could not read the \"Weight\" field from the problem struct.\n");
this->weight = *static_cast<double*>(weight_var->data);
//We use a square difference approximation:
//account for this when weighting objectives by squaring the weight too.
/*if (this->type == FunctionType::Min || this->type == FunctionType::Max)
this->weight = this->weight * this->weight;*/
matvar_t* parameters_var = Mat_VarGetStructFieldByName(problem_struct_entry, "Parameters", 0);
check_null(parameters_var, "Could not read the \"Parameters\" field from the problem struct.\n");
const size_t num_elems = parameters_var->dims[0] * parameters_var->dims[1];
if (num_elems > 0) {
assert(parameters_var->dims[0] == 1); //The parameter array should be a row vector
const double* elems = static_cast<double*>(parameters_var->data);
for (int i = 0; i < num_elems; ++i) {
this->func_params.push_back(*elems++);
}
}
//A lot of the objective functions require a temporary y vector to hold the dose. To avoid allocating that space for each
//call to compute the objective value, we pre-allocate storage for it in this->y_vec.
if (this->type != FunctionType::Mean) {
const auto num_rows = this->matrix_ref->get_rows();
const auto num_cols = this->matrix_ref->get_cols();
this->y_vec.resize(num_rows);
this->grad_tmp.resize(num_rows);
this->num_vars = num_cols;
} else {
const auto num_cols = this->mean_vec_ref->size();
this->num_vars = num_cols;
}
if (this->type == FunctionType::Quadratic) {
matvar_t* c_var = Mat_VarGetStructFieldByName(matrix_struct, "c", this->id - 1);
assert(c_var->data_type == MAT_T_SINGLE);
this->c = static_cast<double>(*static_cast<float*>(c_var->data));
}
this->grad_nonzero_idxs = this->calc_grad_nonzero_idxs();
//Sanity check: the mean function type should have a collapsed dose matrix (i.e. a vector)
// other function types should have a matrix. Check that the other type is nullptr for each.
assert((this->type == FunctionType::Mean && this->matrix_ref == nullptr)
|| (this->type != FunctionType::Mean && this->mean_vec_ref == nullptr));
}
std::vector<double> TROTSEntry::calc_sparse_grad(const double* x, bool cached_dose) const {
std::vector<double> dense_grad(this->num_vars);
this->calc_gradient(x, &dense_grad[0], cached_dose);
std::vector<double> sparse_grad;
sparse_grad.reserve(this->grad_nonzero_idxs.size());
for (int idx : this->grad_nonzero_idxs) {
sparse_grad.push_back(dense_grad[idx]);
}
return sparse_grad;
}
double TROTSEntry::calc_value(const double* x, bool cached_dose) const {
double val = 0.0;
switch (this->type) {
case FunctionType::Quadratic:
val = this->calc_quadratic(x);
break;
case FunctionType::Max:
val = this->quadratic_penalty_max(x, cached_dose);
break;
case FunctionType::Min:
val = this->quadratic_penalty_min(x, cached_dose);
break;
case FunctionType::Mean:
val = this->calc_mean(x);
//val = this->quadratic_penalty_mean(x);
break;
case FunctionType::gEUD:
val = this->calc_gEUD(x, cached_dose);
break;
case FunctionType::LTCP:
val = this->calc_LTCP(x, cached_dose);
break;
default:
break;
}
//If this is a constraint, we need to take care to include the RHS.
if (this->is_constraint()) {
//When using quadratic penalties, the rhs is already taken care of implicitly in the function value
const double rhs_val = (this->type == FunctionType::Max || this->type == FunctionType::Min)
? 0.0
: this->rhs;
val = val - rhs_val;
}
return val;
}
double TROTSEntry::calc_quadratic(const double* x) const {
return 0.5 * this->matrix_ref->quad_mul(x, &this->y_vec[0]) + this->c;
}
double TROTSEntry::calc_max(const double* x) const {
this->matrix_ref->vec_mul(x, &this->y_vec[0]);
const double max_elem = *std::max_element(this->y_vec.cbegin(), this->y_vec.cend());
return max_elem;
}
double TROTSEntry::calc_min(const double* x) const {
this->matrix_ref->vec_mul(x, &this->y_vec[0]);
const double min_elem = *std::min_element(this->y_vec.cbegin(), this->y_vec.cend());
return min_elem;
}
double TROTSEntry::calc_mean(const double* x) const {
double val = 0.0;
#ifdef USE_MKL
val = cblas_ddot(this->mean_vec_ref->size(), x, 1, &(*this->mean_vec_ref)[0], 1);
#else
#pragma omp parallel for schedule(static)
for (int i = 0; i < this->mean_vec_ref->size(); ++i) {
val += (*this->mean_vec_ref)[i] * x[i];
}
#endif
return val;
}
double TROTSEntry::calc_LTCP(const double* x, bool cached_dose) const {
if (!cached_dose)
this->matrix_ref->vec_mul(x, &this->y_vec[0]);
const double prescribed_dose = this->func_params[0];
const double alpha = this->func_params[1];
double sum = 0.0;
const auto num_voxels = this->y_vec.size();
for (int i = 0; i < num_voxels; ++i) {
sum += std::exp(-alpha * (this->y_vec[i] - prescribed_dose));
}
const double val = sum / static_cast<double>(num_voxels);
return val;
}
double TROTSEntry::calc_gEUD(const double* x, bool cached_dose) const {
if (!cached_dose)
this->matrix_ref->vec_mul(x, &this->y_vec[0]);
const auto num_voxels = this->y_vec.size();
const double a = this->func_params[0];
double sum = 0.0;
for (int i = 0; i < num_voxels; ++i) {
sum += std::pow(this->y_vec[i], a);
}
const double val = std::pow(sum / static_cast<double>(num_voxels), 1/a);
return val;
}
/*double TROTSEntry::quadratic_penalty_mean(const double* x) const {
const double mean = cblas_ddot(this->mean_vec_ref->size(), x, 1, &(*this->mean_vec_ref)[0], 1);
const double diff = this->minimise ?
std::max(mean - this->rhs, 0.0) :
std::min(mean - this->rhs, 0.0);
return diff * diff;
}*/
double TROTSEntry::quadratic_penalty_min(const double* x, bool cached_dose) const {
if (!cached_dose)
this->matrix_ref->vec_mul(x, &this->y_vec[0]);
double sq_diff = 0.0;
const size_t num_voxels = this->y_vec.size();
for (int i = 0; i < num_voxels; ++i) {
double clamped_diff = std::min(this->y_vec[i] - this->rhs, 0.0);
sq_diff += clamped_diff * clamped_diff;
}
return sq_diff / static_cast<double>(num_voxels);
}
double TROTSEntry::quadratic_penalty_max(const double* x, bool cached_dose) const {
if (!cached_dose)
this->matrix_ref->vec_mul(x, &this->y_vec[0]);
double sq_diff = 0.0;
const size_t num_voxels = this->y_vec.size();
for (int i = 0; i < num_voxels; ++i) {
double clamped_diff = std::max(this->y_vec[i] - this->rhs, 0.0);
sq_diff += clamped_diff * clamped_diff;
}
return sq_diff / static_cast<double>(num_voxels);
}
void TROTSEntry::calc_gradient(const double* x, double* grad, bool cached_dose) const {
switch (this->type) {
case FunctionType::Quadratic:
quad_grad(x, grad);
break;
case FunctionType::Max:
quad_max_grad(x, grad, cached_dose);
break;
case FunctionType::Min:
quad_min_grad(x, grad, cached_dose);
break;
case FunctionType::Mean:
mean_grad(x, grad);
//quad_mean_grad(x, grad);
break;
case FunctionType::gEUD:
gEUD_grad(x, grad, cached_dose);
break;
case FunctionType::LTCP:
LTCP_grad(x, grad, cached_dose);
break;
default:
//std::fill(grad, grad + this->num_vars, 0.0);
break;
}
}
std::vector<int> TROTSEntry::calc_grad_nonzero_idxs() const {
std::vector<int> non_zeros;
if (this->function_type() != FunctionType::Mean) {
int nnz = this->matrix_ref->get_nnz();
const int* col_inds = this->matrix_ref->get_col_inds();
std::unordered_set<int> non_zero_cols;
for (int i = 0; i < nnz; ++i) {
non_zero_cols.insert(col_inds[i]);
}
non_zeros.reserve(non_zero_cols.size());
//Convert to vector before returning
std::copy(non_zero_cols.cbegin(), non_zero_cols.cend(), std::back_inserter(non_zeros));
}
else {
//The gradient is just the "average vector" so find the nonzeros there
for (int i = 0; i < this->mean_vec_ref->size(); ++i) {
double entry = (*this->mean_vec_ref)[i];
if (entry >= 1e-20) {
non_zeros.push_back(i);
}
}
}
std::sort(non_zeros.begin(), non_zeros.end());
return non_zeros;
}
void TROTSEntry::mean_grad(const double* x, double* grad) const {
std::copy(this->mean_vec_ref->cbegin(), this->mean_vec_ref->cend(), grad);
}
/*void TROTSEntry::quad_mean_grad(const double* x, double* grad) const {
const double mean = cblas_ddot(this->mean_vec_ref->size(), x, 1, &(*this->mean_vec_ref)[0], 1);
for (int i = 0; i < num_vars; ++i) {
const double tmp = this->minimise ? std::max(mean - this->rhs, 0.0) :
std::min(mean - this->rhs, 0.0);
grad[i] = 2.0 * (*this->mean_vec_ref)[i] * tmp;
}
}*/
void TROTSEntry::LTCP_grad(const double* x, double* grad, bool cached_dose) const {
const auto num_voxels = this->matrix_ref->get_rows();
if (!cached_dose) {
this->matrix_ref->vec_mul(x, &this->y_vec[0]);
}
const double prescribed_dose = this->func_params[0];
const double alpha = this->func_params[1];
for (int i = 0; i < num_voxels; ++i) {
this->grad_tmp[i] =
-alpha / static_cast<double>(num_voxels) * std::exp(-alpha * (this->y_vec[i] - prescribed_dose));
}
this->matrix_ref->vec_mul_transpose(&this->grad_tmp[0], grad);
}
void TROTSEntry::gEUD_grad(const double* x, double* grad, bool cached_dose) const {
const auto num_voxels = this->matrix_ref->get_rows();
if (!cached_dose) {
this->matrix_ref->vec_mul(x, &this->y_vec[0]);
}
const double a = this->func_params[0];
//Calculate the factor that all entries have in common, namely m^a * (\sum d_i(x)^a)^(1/a - 1)
double common_factor = 0.0;
for (int i = 0; i < num_voxels; ++i) {
common_factor += std::pow(this->y_vec[i], a);
}
common_factor = std::pow(common_factor, (1 / a) - 1);
common_factor *= std::pow(num_voxels, -1/a);
for (int i = 0; i < this->grad_tmp.size(); ++i) {
this->grad_tmp[i] = std::pow(this->y_vec[i], a - 1) * common_factor;
}
this->matrix_ref->vec_mul_transpose(&this->grad_tmp[0], grad);
}
void TROTSEntry::quad_min_grad(const double* x, double* grad, bool cached_dose) const {
//Sometimes, this->y_vec will already contain the current dose vector, no need to recompute in this case
if (!cached_dose) {
this->matrix_ref->vec_mul(x, &this->y_vec[0]);
}
const auto num_vars = this->grad_tmp.size();
for (int i = 0; i < num_vars; ++i) {
this->grad_tmp[i] = 2 * std::min(this->y_vec[i] - this->rhs, 0.0)
/ static_cast<double>(num_vars);
}
this->matrix_ref->vec_mul_transpose(&this->grad_tmp[0], grad);
}
void TROTSEntry::quad_max_grad(const double* x, double* grad, bool cached_dose) const {
//Sometimes, this->y_vec will already contain the current dose vector, no need to recompute in this case
if (!cached_dose) {
this->matrix_ref->vec_mul(x, &this->y_vec[0]);
}
const auto num_vars = this->grad_tmp.size();
for (int i = 0; i < num_vars; ++i) {
this->grad_tmp[i] = 2 * std::max(this->y_vec[i] - this->rhs, 0.0)
/ static_cast<double>(num_vars);
}
this->matrix_ref->vec_mul_transpose(&this->grad_tmp[0], grad);
}
void TROTSEntry::quad_grad(const double* x, double* grad) const {
this->matrix_ref->vec_mul(x, grad);
}
| 38.900677 | 144 | 0.632043 | [
"vector"
] |
76150a80b007b50b2965bcc131c1cfc8afbbae42 | 2,098 | cpp | C++ | lumino/Runtime/src/Engine/CoreApplication.cpp | lriki/Lumino | 1a80430f4a83dbdfbe965b3d5b16064991b3edb0 | [
"MIT"
] | 30 | 2016-01-24T05:35:45.000Z | 2020-03-03T09:54:27.000Z | lumino/Runtime/src/Engine/CoreApplication.cpp | lriki/Lumino | 1a80430f4a83dbdfbe965b3d5b16064991b3edb0 | [
"MIT"
] | 35 | 2016-04-18T06:14:08.000Z | 2020-02-09T15:51:58.000Z | lumino/Runtime/src/Engine/CoreApplication.cpp | lriki/Lumino | 1a80430f4a83dbdfbe965b3d5b16064991b3edb0 | [
"MIT"
] | 5 | 2016-04-03T02:52:05.000Z | 2018-01-02T16:53:06.000Z | #include "Internal.hpp"
#include <LuminoEngine/Reflection/TypeInfo.hpp>
#include <LuminoEngine/Engine/EngineContext2.hpp>
#include <LuminoEngine/Engine/CoreApplication.hpp>
namespace ln {
//==============================================================================
// CoreApplication
LN_OBJECT_IMPLEMENT(CoreApplication, Object) {}
CoreApplication* CoreApplication::s_instance = nullptr;
CoreApplication::CoreApplication() {
if (LN_ASSERT(!s_instance)) return;
s_instance = this;
}
CoreApplication::~CoreApplication() {
if (s_instance == this) {
s_instance = nullptr;
}
}
void CoreApplication::configure() {
}
//bool CoreApplication::updateEngine() {
// return true;
//}
//void CoreApplication::renderEngine() {
//}
//
//void CoreApplication::terminateEngine() {
//}
//
//Result CoreApplication::initializeInternal() {
// return ok();
//}
//
//bool CoreApplication::updateInertnal() {
// return updateEngine();
//}
//
//void CoreApplication::renderInertnal() {
// renderEngine();
//}
//
//void CoreApplication::terminateInternal() {
// terminateEngine();
//}
//==============================================================================
// AppIntegration
//Ref<CoreApplication> AppIntegration::s_app;
//Result AppIntegration::initialize(CoreApplication* app) {
// return app->initializeInternal();
//}
//
//bool AppIntegration::update(CoreApplication* app) {
// return app->updateInertnal();
//}
//
//void AppIntegration::render(CoreApplication* app) {
// app->renderInertnal();
//}
//
//void AppIntegration::terminate(CoreApplication* app) {
// app->terminateInternal();
//}
//void AppIntegration::run(ConfigureApp configureApp, InitializeEngine initializeEngine, CreateAppInstance createAppInstance) {
// configureApp();
//
// if (!initializeEngine()) {
// return;
// }
//
// s_app = Ref<CoreApplication>(createAppInstance(), false);
//
// initialize(s_app);
// while (update(s_app)) {
// render(s_app);
// }
// terminate(s_app);
//
// s_app = nullptr;
//}
//
} // namespace ln
| 21.854167 | 127 | 0.621544 | [
"render",
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.